IT-xiaoXiong 2021-11-14 15:29:16 +08:00
parent 26d4ac26ef
commit 90b6efa231
188 changed files with 53269 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

66
aiyh/utils/ApiResult.java Normal file
View File

@ -0,0 +1,66 @@
package aiyh.utils;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/27 0027 10:21
* api
*/
public class ApiResult {
private final int code;
private final String msg;
private final Object data;
public ApiResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static String successNoData(){
return ApiResult.success(null, 200, "请求成功!");
}
public static String success(Object data){
return ApiResult.success(data, 200, "请求成功!");
}
public static String success(Object data, String msg){
return ApiResult.success(data, 200, msg);
}
public static String success(Object data, int code, String msg){
return JSON.toJSONString(new ApiResult(code, msg, data));
}
public static String error(){
return ApiResult.error(0, "服务器异常!");
}
public static String error(String msg){
return ApiResult.error(0, msg);
}
public static String error(int code, String msg){
return JSON.toJSONString(new ApiResult(code, msg, null));
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
}

View File

@ -0,0 +1,74 @@
package aiyh.utils;
import aiyh.utils.zwl.common.ToolUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/25 0025 10:53
*
*/
public class HotDeployToolUtil extends ClassLoader {
ToolUtil toolUtil = new ToolUtil();
private final String classpath;
private final String className;
public HotDeployToolUtil(String classpath, String className) {
this.classpath = classpath;
this.className = className;
}
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> loadedClass = findLoadedClass(name);
// 需要我自己去加载
if (loadedClass == null) {
loadedClass = findClass(name);
if (loadedClass != null) {
return loadedClass;
}
}
return super.loadClass(name, resolve);
}
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
if (name.startsWith("java.")) {
return getSystemClassLoader().loadClass(name);
}
byte[] data;
String classPath = name.replace(".", System.getProperties().getProperty("file.separator")) + ".class";
try {
data = this.loadClassData(classPath);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return this.defineClass(name, data, 0, data.length);
}
public byte[] loadClassData(String name) throws Exception {
FileInputStream inputStream;
try {
toolUtil.writeDebuggerLog(classpath + name);
inputStream = new FileInputStream(classpath + name);
// 定义字节数组输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b = 0;
while ((b = inputStream.read()) != -1) {
baos.write(b);
}
inputStream.close();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
throw new ClassNotFoundException();
}
}
}

1356
aiyh/utils/Util.java Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
package aiyh.utils.annotation;
import java.lang.annotation.*;
/**
* @author EBU7-dev1-ay
* @date 2021/9/3 0003 16:02
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface DateFormatAn {
String value() default "yyyy-MM-dd HH:mm:ss";
}

View File

@ -0,0 +1,44 @@
package aiyh.utils.dao;
import aiyh.utils.Util;
import aiyh.utils.entity.ApiConfigDetailDTO;
import aiyh.utils.entity.ApiConfigMainDTO;
import aiyh.utils.entity.MultiLanguageDTO;
import weaver.conn.RecordSet;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/14 0014 12:09
*
*/
public class UtilDao {
private final RecordSet rs = new RecordSet();
public ApiConfigMainDTO getApiConfigMain(String id) {
String query = "select id,workflow_type,api_url,api_name from uf_api_param_config where id = ?";
rs.executeQuery(query, id);
return Util.recordeSet2Entity(rs, ApiConfigMainDTO.class, true);
}
public List<ApiConfigDetailDTO> getApiConfigDetail(int mainId) {
String query = "select dt.id,dt.line_num,dt.param_name,dt.param_type,dt.object_child,dt.parent_line,dt.change_rule, " +
"dt.param_value,wf.fieldname workflow_field,wf.tablename tablename,dt.array_sql " +
"from uf_api_param_config_dt1 dt " +
"left join workflow_field_table_view wf on wf.id = dt.workflow_field " +
"where mainid = ? and (are_use is null or are_use = 1)";
rs.executeQuery(query, mainId);
return Util.recordeSet2Array(rs, ApiConfigDetailDTO.class, true);
}
public List<MultiLanguageDTO> queryLanguage(int groupId) {
String query = "select * from uf_multi_language_dt1 where mainid = ?";
rs.executeQuery(query, groupId);
return Util.recordeSet2Array(rs, MultiLanguageDTO.class, true);
}
}

View File

@ -0,0 +1,31 @@
package aiyh.utils.entity;
import java.io.InputStream;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/25 0025 18:00
* inputStream
*/
public class AInputStream {
private String fileName;
private InputStream inputStream;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}

View File

@ -0,0 +1,64 @@
package aiyh.utils.entity;
import org.jetbrains.annotations.NotNull;
import weaver.file.FileUpload;
import weaver.system.SystemComInfo;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.zip.ZipOutputStream;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/25 0025 17:38
* zipoutputstaream
*/
public class AZipOutputStream extends ZipOutputStream {
private ZipOutputStream zipOutputStream;
public static String filePath;
private OutputStream out;
static {
filePath = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
filePath += "zip" + File.separator + System.currentTimeMillis() + UUID.randomUUID() + ".zip";
}
public AZipOutputStream(@NotNull OutputStream out) {
super(out);
this.out = out;
}
public AZipOutputStream(@NotNull OutputStream out, @NotNull Charset charset) {
super(out, charset);
this.out = out;
}
@Override
public void close() throws IOException {
try {
Files.deleteIfExists(Paths.get(AZipOutputStream.filePath));
} catch (IOException e) {
e.printStackTrace();
}finally {
out.flush();
super.flush();
super.close();
out.close();
}
}
public ZipOutputStream getZipOutputStream() {
return zipOutputStream;
}
public void setZipOutputStream(ZipOutputStream zipOutputStream) {
this.zipOutputStream = zipOutputStream;
}
}

View File

@ -0,0 +1,123 @@
package aiyh.utils.entity;
public class ApiConfigDetailDTO extends BaseTree<ApiConfigDetailDTO>{
private int id;
private int lineNum;
private String paramName;
private int paramType;
private int objectChild;
private int parentLine;
private int changeRule;
private String paramValue;
private String workflowField;
private String tablename;
private String arraySql;
public void setId(int id){
this.id = id;
}
public void setLineNum(int lineNum){
this.lineNum = lineNum;
}
public void setParamName(String paramName){
this.paramName = paramName;
}
public void setParamType(int paramType){
this.paramType = paramType;
}
public void setObjectChild(int objectChild){
this.objectChild = objectChild;
}
public void setParentLine(int parentLine){
this.parentLine = parentLine;
}
public void setChangeRule(int changeRule){
this.changeRule = changeRule;
}
public void setParamValue(String paramValue){
this.paramValue = paramValue;
}
public void setWorkflowField(String workflowField){
this.workflowField = workflowField;
}
public void setTablename(String tablename){
this.tablename = tablename;
}
public void setArraySql(String arraySql){
this.arraySql = arraySql;
}
public int getId(){
return this.id;
}
public int getLineNum(){
return this.lineNum;
}
public String getParamName(){
return this.paramName;
}
public int getParamType(){
return this.paramType;
}
public int getObjectChild(){
return this.objectChild;
}
public int getParentLine(){
return this.parentLine;
}
public int getChangeRule(){
return this.changeRule;
}
public String getParamValue(){
return this.paramValue;
}
public String getWorkflowField(){
return this.workflowField;
}
public String getTablename(){
return this.tablename;
}
public String getArraySql(){
return this.arraySql;
}
@Override
public String toString() {
return "ApiConfigDetailDTO{" +
"id='" + id + '\'' +
", lineNum='" + lineNum + '\'' +
", paramName='" + paramName + '\'' +
", paramType='" + paramType + '\'' +
", objectChild='" + objectChild + '\'' +
", parentLine='" + parentLine + '\'' +
", changeRule='" + changeRule + '\'' +
", paramValue='" + paramValue + '\'' +
", workflowField='" + workflowField + '\'' +
", tablename='" + tablename + '\'' +
", arraySql='" + arraySql + '\'' +
'}';
}
}

View File

@ -0,0 +1,65 @@
package aiyh.utils.entity;
import java.util.List;
public class ApiConfigMainDTO {
private int id;
private int workflowType;
private String apiUrl;
private String apiName;
private List<ApiConfigDetailDTO> details;
public List<ApiConfigDetailDTO> getDetails() {
return details;
}
public void setDetails(List<ApiConfigDetailDTO> details) {
this.details = details;
}
public void setId(int id){
this.id = id;
}
public void setWorkflowType(int workflowType){
this.workflowType = workflowType;
}
public void setApiUrl(String apiUrl){
this.apiUrl = apiUrl;
}
public void setApiName(String apiName){
this.apiName = apiName;
}
public int getId(){
return this.id;
}
public int getWorkflowType(){
return this.workflowType;
}
public String getApiUrl(){
return this.apiUrl;
}
public String getApiName(){
return this.apiName;
}
@Override
public String toString() {
return "ApiConfigMainDTO{" +
"id=" + id +
", workflowType=" + workflowType +
", apiUrl='" + apiUrl + '\'' +
", apiName='" + apiName + '\'' +
", details=" + details +
'}';
}
}

View File

@ -0,0 +1,22 @@
package aiyh.utils.entity;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/12 0012 14:04
*
*/
public class BaseTree<T> {
private List<T> children;
public List<T> getChildren() {
return children;
}
public void setChildren(List<T> children) {
this.children = children;
}
}

View File

@ -0,0 +1,363 @@
package aiyh.utils.entity;
public class FnainvoiceinterfaceDTO {
private int id;
private int type;
private String interfaceurl;
private int status;
private int interfaceType;
private String userName;
private String password;
private String lastmodify;
private String weightPercent;
private String tokenurl;
private String openIDurl;
private String client_id;
private String client_secret;
private String sqm;
private String Client;
private String GTAXID;
private String imageCatalog;
private int noNeedCheck;
private String noNeedCheckAmount;
private String account;
private String corpName;
private String cid;
private String synInvoiceUrl;
private String synBillingInfoUrl;
private String synDocUrl;
private String subIds;
private int subIdStatus;
private String jsUrl;
private String createAppUrl;
private String appName;
private String checkUrl;
private String javaUrl;
private String oaUrl;
private String webUrl;
private String aesKey;
public void setId(int id){
this.id = id;
}
public void setType(int type){
this.type = type;
}
public void setInterfaceurl(String interfaceurl){
this.interfaceurl = interfaceurl;
}
public void setStatus(int status){
this.status = status;
}
public void setInterfaceType(int interfaceType){
this.interfaceType = interfaceType;
}
public void setUserName(String userName){
this.userName = userName;
}
public void setPassword(String password){
this.password = password;
}
public void setLastmodify(String lastmodify){
this.lastmodify = lastmodify;
}
public void setWeightPercent(String weightPercent){
this.weightPercent = weightPercent;
}
public void setTokenurl(String tokenurl){
this.tokenurl = tokenurl;
}
public void setOpenIDurl(String openIDurl){
this.openIDurl = openIDurl;
}
public void setClientId(String client_id){
this.client_id = client_id;
}
public void setClientSecret(String client_secret){
this.client_secret = client_secret;
}
public void setSqm(String sqm){
this.sqm = sqm;
}
public void setClient(String Client){
this.Client = Client;
}
public void setGTAXID(String GTAXID){
this.GTAXID = GTAXID;
}
public void setImageCatalog(String imageCatalog){
this.imageCatalog = imageCatalog;
}
public void setNoNeedCheck(int noNeedCheck){
this.noNeedCheck = noNeedCheck;
}
public void setNoNeedCheckAmount(String noNeedCheckAmount){
this.noNeedCheckAmount = noNeedCheckAmount;
}
public void setAccount(String account){
this.account = account;
}
public void setCorpName(String corpName){
this.corpName = corpName;
}
public void setCid(String cid){
this.cid = cid;
}
public void setSynInvoiceUrl(String synInvoiceUrl){
this.synInvoiceUrl = synInvoiceUrl;
}
public void setSynBillingInfoUrl(String synBillingInfoUrl){
this.synBillingInfoUrl = synBillingInfoUrl;
}
public void setSynDocUrl(String synDocUrl){
this.synDocUrl = synDocUrl;
}
public void setSubIds(String subIds){
this.subIds = subIds;
}
public void setSubIdStatus(int subIdStatus){
this.subIdStatus = subIdStatus;
}
public void setJsUrl(String jsUrl){
this.jsUrl = jsUrl;
}
public void setCreateAppUrl(String createAppUrl){
this.createAppUrl = createAppUrl;
}
public void setAppName(String appName){
this.appName = appName;
}
public void setCheckUrl(String checkUrl){
this.checkUrl = checkUrl;
}
public void setJavaUrl(String javaUrl){
this.javaUrl = javaUrl;
}
public void setOaUrl(String oaUrl){
this.oaUrl = oaUrl;
}
public void setWebUrl(String webUrl){
this.webUrl = webUrl;
}
public void setAesKey(String aesKey){
this.aesKey = aesKey;
}
public int getId(){
return this.id;
}
public int getType(){
return this.type;
}
public String getInterfaceurl(){
return this.interfaceurl;
}
public int getStatus(){
return this.status;
}
public int getInterfaceType(){
return this.interfaceType;
}
public String getUserName(){
return this.userName;
}
public String getPassword(){
return this.password;
}
public String getLastmodify(){
return this.lastmodify;
}
public String getWeightPercent(){
return this.weightPercent;
}
public String getTokenurl(){
return this.tokenurl;
}
public String getOpenIDurl(){
return this.openIDurl;
}
public String getClientId(){
return this.client_id;
}
public String getClientSecret(){
return this.client_secret;
}
public String getSqm(){
return this.sqm;
}
public String getClient(){
return this.Client;
}
public String getGTAXID(){
return this.GTAXID;
}
public String getImageCatalog(){
return this.imageCatalog;
}
public int getNoNeedCheck(){
return this.noNeedCheck;
}
public String getNoNeedCheckAmount(){
return this.noNeedCheckAmount;
}
public String getAccount(){
return this.account;
}
public String getCorpName(){
return this.corpName;
}
public String getCid(){
return this.cid;
}
public String getSynInvoiceUrl(){
return this.synInvoiceUrl;
}
public String getSynBillingInfoUrl(){
return this.synBillingInfoUrl;
}
public String getSynDocUrl(){
return this.synDocUrl;
}
public String getSubIds(){
return this.subIds;
}
public int getSubIdStatus(){
return this.subIdStatus;
}
public String getJsUrl(){
return this.jsUrl;
}
public String getCreateAppUrl(){
return this.createAppUrl;
}
public String getAppName(){
return this.appName;
}
public String getCheckUrl(){
return this.checkUrl;
}
public String getJavaUrl(){
return this.javaUrl;
}
public String getOaUrl(){
return this.oaUrl;
}
public String getWebUrl(){
return this.webUrl;
}
public String getAesKey(){
return this.aesKey;
}
@Override
public String toString() {
return "FnainvoiceinterfaceDTO{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
", interfaceurl='" + interfaceurl + '\'' +
", status='" + status + '\'' +
", interfaceType='" + interfaceType + '\'' +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", lastmodify='" + lastmodify + '\'' +
", weightPercent='" + weightPercent + '\'' +
", tokenurl='" + tokenurl + '\'' +
", openIDurl='" + openIDurl + '\'' +
", client_id='" + client_id + '\'' +
", client_secret='" + client_secret + '\'' +
", sqm='" + sqm + '\'' +
", Client='" + Client + '\'' +
", GTAXID='" + GTAXID + '\'' +
", imageCatalog='" + imageCatalog + '\'' +
", noNeedCheck='" + noNeedCheck + '\'' +
", noNeedCheckAmount='" + noNeedCheckAmount + '\'' +
", account='" + account + '\'' +
", corpName='" + corpName + '\'' +
", cid='" + cid + '\'' +
", synInvoiceUrl='" + synInvoiceUrl + '\'' +
", synBillingInfoUrl='" + synBillingInfoUrl + '\'' +
", synDocUrl='" + synDocUrl + '\'' +
", subIds='" + subIds + '\'' +
", subIdStatus='" + subIdStatus + '\'' +
", jsUrl='" + jsUrl + '\'' +
", createAppUrl='" + createAppUrl + '\'' +
", appName='" + appName + '\'' +
", checkUrl='" + checkUrl + '\'' +
", javaUrl='" + javaUrl + '\'' +
", oaUrl='" + oaUrl + '\'' +
", webUrl='" + webUrl + '\'' +
", aesKey='" + aesKey + '\'' +
'}';
}
}

View File

@ -0,0 +1,50 @@
package aiyh.utils.entity;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/25 0025 17:29
*
*/
public class ListZipEntity {
private String directory;
private boolean isDirectory;
private List<AInputStream> aInputStreamList;
private List<ListZipEntity> fileList;
{
this.isDirectory = false;
}
public boolean isDirectory() {
return isDirectory;
}
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.isDirectory = true;
this.directory = directory;
}
public List<ListZipEntity> getFileList() {
return fileList;
}
public void setFileList(List<ListZipEntity> fileList) {
this.fileList = fileList;
}
public List<AInputStream> getaInputStreamList() {
return aInputStreamList;
}
public void setaInputStreamList(List<AInputStream> aInputStreamList) {
this.aInputStreamList = aInputStreamList;
}
}

View File

@ -0,0 +1,73 @@
package aiyh.utils.entity;
public class MultiLanguageDTO {
private int id;
private int mainid;
private String bswyz;
private String znCh;
private String enUs;
private String znHk;
public void setId(int id){
this.id = id;
}
public void setMainid(int mainid){
this.mainid = mainid;
}
public void setBswyz(String bswyz){
this.bswyz = bswyz;
}
public void setZnCh(String znCh){
this.znCh = znCh;
}
public void setEnUs(String enUs){
this.enUs = enUs;
}
public void setZnHk(String znHk){
this.znHk = znHk;
}
public int getId(){
return this.id;
}
public int getMainid(){
return this.mainid;
}
public String getBswyz(){
return this.bswyz;
}
public String getZnCh(){
return this.znCh;
}
public String getEnUs(){
return this.enUs;
}
public String getZnHk(){
return this.znHk;
}
@Override
public String toString() {
return "MultiLanguageDTO{" +
"id='" + id + '\'' +
", mainid='" + mainid + '\'' +
", bswyz='" + bswyz + '\'' +
", znCh='" + znCh + '\'' +
", enUs='" + enUs + '\'' +
", znHk='" + znHk + '\'' +
'}';
}
}

View File

@ -0,0 +1,44 @@
package aiyh.utils.fileUtil;
/**
* @author EBU7-dev1-ayh
* @date 2021/9/8 0008 14:02
* watermark point
*/
public class WatermarkPoint {
private Integer X;
private Integer Y;
private WatermarkPointEnum location;
public WatermarkPoint(Integer x, Integer y) {
this.X = x;
this.Y = y;
}
public WatermarkPoint(WatermarkPointEnum location) {
this.location = location;
}
public WatermarkPointEnum getLocation() {
return location;
}
public Integer getX() {
return X;
}
public Integer getY() {
return Y;
}
@Override
public String toString() {
return "WatermarkPoint{" +
"X=" + X +
", Y=" + Y +
", location=" + location +
'}';
}
}

View File

@ -0,0 +1,30 @@
package aiyh.utils.fileUtil;
/**
* @author @author EBU7-dev1-ay
* @date 2021/9/8 0008 14:16
* watermarkPointEnum
*/
public enum WatermarkPointEnum {
/**
*
*/
CENTER,
/**
*
*/
LEFT_TOP,
/**
*
*/
LEFT_BOTTOM,
/**
*
*/
RIGHT_TOP,
/**
*
*/
RIGHT_BOTTOM
}

View File

@ -0,0 +1,803 @@
package aiyh.utils.fileUtil;
import weaver.conn.RecordSet;
import weaver.file.FileUpload;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.system.SystemComInfo;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;
/**
* @author EBU7-dev1-ayh
* @date 2021/9/2 0002 16:59
*
*/
public class WritWatermark {
/**
* id
*
* @param imageId id
* @param pressText
* @param color
* @param fontName PLAIN BOLD ITALIC
* @param fontStyle
* @param fontSize
* @param watermarkPoint
* @param degree
* @param alpha 0-1
* @param lineSpacing
* @return ID
* @throws IOException io
*/
public static int addTextWatermarkById(int imageId, String pressText, Color color, String fontName, int fontStyle
, int fontSize, WatermarkPoint watermarkPoint, double degree, float alpha, double lineSpacing) throws IOException {
ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(imageId);
if(inputStreamById == null){
throw new RuntimeException("Failed to obtain the image to which a watermark is to be added. " +
"Check whether the file exists in the system and ensure that the file is in the image format.");
}
// 将输入流读取为图片
Image image = ImageIO.read(inputStreamById);
int width = image.getWidth(null);
int height = image.getHeight(null);
double lineHeight = fontSize * lineSpacing;
// 创建bufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
// 设置对线段的锯齿状边缘处理
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, width, height, null);
Font font = new Font(fontName, fontStyle, fontSize);
graphics.setColor(color);
graphics.setFont(font);
// 设置旋转角度
graphics.rotate(Math.toRadians(degree), (double) width / 2, (double) height / 2);
// 设置透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
String[] pressTexts = pressText.split("\n");
String maxStr = "";
int max = 0;
// 求出最大长度值
for (String press : pressTexts) {
if (press.length() > max) {
max = press.length();
maxStr = press;
}
}
int X;
int Y;
int fontWidth = graphics.getFontMetrics(graphics.getFont()).charsWidth(maxStr.toCharArray(), 0, max);
int fontsHeight = (int) Math.round(lineHeight) * pressTexts.length;
if (watermarkPoint.getLocation() == null) {
X = watermarkPoint.getX();
Y = watermarkPoint.getY();
} else {
// 水印放在中间
if (watermarkPoint.getLocation().equals(WatermarkPointEnum.CENTER)) {
X = (width / 2) - (fontWidth / 2);
Y = (height / 2) - (fontsHeight / 2);
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.LEFT_TOP)) {
// 水印放在左上
X = 10;
Y = 10;
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.LEFT_BOTTOM)) {
// 水印放在左下
X = 10;
Y = height - fontsHeight - 10;
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.RIGHT_TOP)) {
// 水印放在右上
X = width - fontWidth - 10;
Y = 10;
} else {
// 水印放在右下
X = width - fontWidth - 10;
Y = height - fontsHeight - 10;
}
}
for (int i = 0; i < pressTexts.length; i++) {
// 防止重叠需要对Y进行特殊处理
graphics.drawString(pressTexts[i], X, Y + ((int) Math.round(lineHeight) * (i + 1)));
}
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
// 获取图片后缀
String query = "select imagefilename from imagefile where imagefileid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, imageId);
String suffix = "jpg";
String imageFileName = "";
if (rs.next()) {
imageFileName = Util.null2String(rs.getString(1));
suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
}
String createDir = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
// 防止高并发下文件名重复导致文件覆盖的问题
String tempPath = createDir + imageFileName + System.currentTimeMillis() + UUID.randomUUID() + "." + suffix;
File file = new File(tempPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 输出到临时目录
FileOutputStream outputStreamTem = new FileOutputStream(URLDecoder.decode(tempPath, "utf-8"));
ImageIO.write(bufferedImage, suffix, outputStreamTem);
outputStreamTem.close();
// 保存生成的水印图片到压缩包
int i = imageFileManager.saveImageFileByInputStream(new FileInputStream(tempPath), imageFileName);
// 建议虚拟机进行一次垃圾回收,防止临时文件被其他文件流保存而无法删除临时文件
System.gc();
// 删除临时文件, 防止文件删除失败,设置一个自旋操作,加大文件删除的几率
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
Files.delete(Paths.get(tempPath));
deleteFlag = false;
} catch (Exception e) {
// 设置线程沉睡500毫秒等待jvm进行垃圾回收将持有临时文件的流对象回收确保临时文件能删除
try {
Thread.sleep(500);
} catch (InterruptedException interruptedException) {
return i;
}
if (n > 5) {
deleteFlag = false;
}
}
}
return i;
}
/**
* id
*
* @param imageId id
* @param picId id
* @param watermarkPoint
* @param degree
* @param alpha 0-1
* @return ID
* @throws IOException io
*/
public static int addPicWatermarkById(int imageId, int picId
, WatermarkPoint watermarkPoint, double degree, float alpha) throws IOException {
ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(imageId);
if(inputStreamById == null){
throw new RuntimeException("Failed to obtain the image to which a watermark is to be added. " +
"Check whether the file exists in the system and ensure that the file is in the image format.");
}
// 将输入流读取为图片
Image image = ImageIO.read(inputStreamById);
int width = image.getWidth(null);
int height = image.getHeight(null);
// 创建bufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
// 设置对线段的锯齿状边缘处理
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, width, height, null);
// 设置旋转角度
graphics.rotate(Math.toRadians(degree), (double) width / 2, (double) height / 2);
// 设置透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 获取水印图片
InputStream inputStreamImgIcon = ImageFileManager.getInputStreamById(picId);
if(inputStreamImgIcon == null){
throw new RuntimeException("The obtained watermark logo image is empty");
}
Image logoImg = ImageIO.read(inputStreamImgIcon);
int logoWidth = logoImg.getWidth(null);
int logoHeight = logoImg.getHeight(null);
int X;
int Y;
if (watermarkPoint.getLocation() == null) {
X = watermarkPoint.getX();
Y = watermarkPoint.getY();
} else {
// 水印放在中间
if (watermarkPoint.getLocation().equals(WatermarkPointEnum.CENTER)) {
X = (width / 2) - (logoWidth / 2);
Y = (height / 2) - (logoHeight / 2);
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.LEFT_TOP)) {
// 水印放在左上
X = 10;
Y = 10;
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.LEFT_BOTTOM)) {
// 水印放在左下
X = 10;
Y = height - logoHeight - 10;
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.RIGHT_TOP)) {
// 水印放在右上
X = width - logoWidth - 10;
Y = 10;
} else {
// 水印放在右下
X = width - logoWidth - 10;
Y = height - logoHeight - 10;
}
}
graphics.drawImage(logoImg, X, Y, null);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
// 获取图片后缀
String query = "select imagefilename from imagefile where imagefileid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, imageId);
String suffix = "jpg";
String imageFileName = "";
if (rs.next()) {
imageFileName = Util.null2String(rs.getString(1));
suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
}
String createDir = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
// 防止高并发下文件名重复导致文件覆盖的问题
String tempPath = createDir + imageFileName + System.currentTimeMillis() + UUID.randomUUID() + "." + suffix;
File file = new File(tempPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 输出到临时目录
FileOutputStream outputStreamTem = new FileOutputStream(URLDecoder.decode(tempPath, "utf-8"));
ImageIO.write(bufferedImage, suffix, outputStreamTem);
outputStreamTem.close();
// 保存生成的水印图片到压缩包
int i = imageFileManager.saveImageFileByInputStream(new FileInputStream(tempPath), imageFileName);
// 建议虚拟机进行一次垃圾回收,防止临时文件被其他文件流保存而无法删除临时文件
System.gc();
// 删除临时文件, 防止文件删除失败,设置一个自旋操作,加大文件删除的几率
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
Files.delete(Paths.get(tempPath));
deleteFlag = false;
} catch (Exception e) {
// 设置线程沉睡500毫秒等待jvm进行垃圾回收将持有临时文件的流对象回收确保临时文件能删除
try {
Thread.sleep(500);
} catch (InterruptedException interruptedException) {
return i;
}
if (n > 5) {
deleteFlag = false;
}
}
}
return i;
}
/**
* id
*
* @param imageId id
* @param logoInput
* @param watermarkPoint
* @param degree
* @param alpha 0-1
* @return ID
* @throws IOException io
*/
public static int addPicWatermarkById(int imageId, InputStream logoInput
, WatermarkPoint watermarkPoint, double degree, float alpha) throws IOException {
ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(imageId);
if(inputStreamById == null){
throw new RuntimeException("Failed to obtain the image to which a watermark is to be added. " +
"Check whether the file exists in the system and ensure that the file is in the image format.");
}
// 将输入流读取为图片
Image image = ImageIO.read(inputStreamById);
int width = image.getWidth(null);
int height = image.getHeight(null);
// 创建bufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
// 设置对线段的锯齿状边缘处理
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, width, height, null);
// 设置旋转角度
graphics.rotate(Math.toRadians(degree), (double) width / 2, (double) height / 2);
// 设置透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
if(logoInput == null){
throw new RuntimeException("The obtained watermark logo image is empty");
}
// 获取水印图片
ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(logoInput));
Image logoImg = logoImgIcon.getImage();
int logoWidth = logoImg.getWidth(null);
int logoHeight = logoImg.getHeight(null);
int X;
int Y;
if (watermarkPoint.getLocation() == null) {
X = watermarkPoint.getX();
Y = watermarkPoint.getY();
} else {
// 水印放在中间
if (watermarkPoint.getLocation().equals(WatermarkPointEnum.CENTER)) {
X = (width / 2) - (logoWidth / 2);
Y = (height / 2) - (logoHeight / 2);
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.LEFT_TOP)) {
// 水印放在左上
X = 10;
Y = 10;
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.LEFT_BOTTOM)) {
// 水印放在左下
X = 10;
Y = height - logoHeight - 10;
} else if (watermarkPoint.getLocation().equals(WatermarkPointEnum.RIGHT_TOP)) {
// 水印放在右上
X = width - logoWidth - 10;
Y = 10;
} else {
// 水印放在右下
X = width - logoWidth - 10;
Y = height - logoHeight - 10;
}
}
graphics.drawImage(logoImg, X, Y, null);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
// 获取图片后缀
String query = "select imagefilename from imagefile where imagefileid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, imageId);
String suffix = "jpg";
String imageFileName = "";
if (rs.next()) {
imageFileName = Util.null2String(rs.getString(1));
suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
}
String createDir = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
// 防止高并发下文件名重复导致文件覆盖的问题
String tempPath = createDir + imageFileName + System.currentTimeMillis() + UUID.randomUUID() + "." + suffix;
File file = new File(tempPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 输出到临时目录
FileOutputStream outputStreamTem = new FileOutputStream(URLDecoder.decode(tempPath, "utf-8"));
ImageIO.write(bufferedImage, suffix, outputStreamTem);
outputStreamTem.close();
// 保存生成的水印图片到压缩包
int i = imageFileManager.saveImageFileByInputStream(new FileInputStream(tempPath), imageFileName);
// 建议虚拟机进行一次垃圾回收,防止临时文件被其他文件流保存而无法删除临时文件
System.gc();
// 删除临时文件, 防止文件删除失败,设置一个自旋操作,加大文件删除的几率
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
Files.delete(Paths.get(tempPath));
deleteFlag = false;
} catch (Exception e) {
// 设置线程沉睡500毫秒等待jvm进行垃圾回收将持有临时文件的流对象回收确保临时文件能删除
try {
Thread.sleep(500);
} catch (InterruptedException interruptedException) {
return i;
}
if (n > 5) {
deleteFlag = false;
}
}
}
return i;
}
/**
*
* @param imageId id
* @param pressText
* @param color
* @param fontName
* @param fontStyle
* @param fontSize
* @param degree
* @param alpha
* @param lineSpacing
* @param moveX X
* @param moveY Y
* @param randomX X
* @return id
* @throws IOException io
*/
public static int addTextTileWatermarkById(int imageId, String pressText, Color color, String fontName, int fontStyle
, int fontSize, double degree, float alpha, double lineSpacing, int moveX, int moveY, int randomX) throws IOException {
ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(imageId);
if(inputStreamById == null){
throw new RuntimeException("Failed to obtain the image to which a watermark is to be added. " +
"Check whether the file exists in the system and ensure that the file is in the image format.");
}
// 将输入流读取为图片
Image image = ImageIO.read(inputStreamById);
int width = image.getWidth(null);
int height = image.getHeight(null);
double lineHeight = fontSize * lineSpacing;
// 创建bufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
// 设置对线段的锯齿状边缘处理
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, width, height, null);
Font font = new Font(fontName, fontStyle, fontSize);
graphics.setColor(color);
graphics.setFont(font);
// 设置旋转角度
graphics.rotate(Math.toRadians(degree), (double) width / 2, (double) height / 2);
// 设置透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
String[] pressTexts = pressText.split("\n");
String maxStr = "";
int max = 0;
// 求出最大长度值
for (String press : pressTexts) {
if (press.length() > max) {
max = press.length();
maxStr = press;
}
}
int X;
int Y;
int fontWidth = graphics.getFontMetrics(graphics.getFont()).charsWidth(maxStr.toCharArray(), 0, max);
int fontsHeight = (int) Math.round(lineHeight) * pressTexts.length;
int mustX = fontWidth;
int mustY = fontsHeight;
int start = - (width + height);
int end = width + height;
X = start;
Y = start;
int random = 0;
// 循环Y每次偏移防止重叠的最小偏移量加上自定义的偏移量
for (; Y <= end; Y = Y + moveY + mustY ){
// 循环X,每次偏移防止重叠的最小偏移量加上自定义偏移量
for (; X <= end; X = X + moveX + mustX){
for (int i = 0; i < pressTexts.length; i ++){
// 防止重叠对Y做文字偏移
graphics.drawString(pressTexts[i], X + random, Y + (int) Math.ceil(lineHeight) * (i + 1) );
}
}
X = start;
if(random == 0){
random = - randomX;
}else {
random = 0;
}
}
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
// 获取图片后缀
String query = "select imagefilename from imagefile where imagefileid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, imageId);
String suffix = "jpg";
String imageFileName = "";
if (rs.next()) {
imageFileName = Util.null2String(rs.getString(1));
suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
}
String createDir = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
// 防止高并发下文件名重复导致文件覆盖的问题
String tempPath = createDir + imageFileName + System.currentTimeMillis() + UUID.randomUUID() + "." + suffix;
File file = new File(tempPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 输出到临时目录
FileOutputStream outputStreamTem = new FileOutputStream(URLDecoder.decode(tempPath, "utf-8"));
ImageIO.write(bufferedImage, suffix, outputStreamTem);
outputStreamTem.close();
// 保存生成的水印图片到压缩包
int i = imageFileManager.saveImageFileByInputStream(new FileInputStream(tempPath), imageFileName);
// 建议虚拟机进行一次垃圾回收,防止临时文件被其他文件流保存而无法删除临时文件
System.gc();
// 删除临时文件, 防止文件删除失败,设置一个自旋操作,加大文件删除的几率
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
Files.delete(Paths.get(tempPath));
deleteFlag = false;
} catch (Exception e) {
// 设置线程沉睡500毫秒等待jvm进行垃圾回收将持有临时文件的流对象回收确保临时文件能删除
try {
Thread.sleep(500);
} catch (InterruptedException interruptedException) {
return i;
}
if (n > 5) {
deleteFlag = false;
}
}
}
return i;
}
/**
*
* @param imageId id
* @param picId id
* @param degree
* @param alpha
* @param moveX X
* @param moveY Y
* @param randomX X
* @return id
* @throws IOException io
*/
public static int addPicTileWatermarkById(int imageId, int picId
, double degree, float alpha, int moveX, int moveY, int randomX) throws IOException {
ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(imageId);
if(inputStreamById == null){
throw new RuntimeException("Failed to obtain the image to which a watermark is to be added. " +
"Check whether the file exists in the system and ensure that the file is in the image format.");
}
// 将输入流读取为图片
Image image = ImageIO.read(inputStreamById);
int width = image.getWidth(null);
int height = image.getHeight(null);
// 创建bufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
// 设置对线段的锯齿状边缘处理
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, width, height, null);
// 设置旋转角度
graphics.rotate(Math.toRadians(degree), (double) width / 2, (double) height / 2);
// 设置透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 获取水印图片
InputStream inputStreamImgIcon = ImageFileManager.getInputStreamById(picId);
if(inputStreamImgIcon == null){
throw new RuntimeException("The obtained watermark logo image is empty");
}
ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(inputStreamImgIcon));
Image logoImg = logoImgIcon.getImage();
int logoWidth = logoImg.getWidth(null);
int logoHeight = logoImg.getHeight(null);
int X;
int Y;
int mustX = logoWidth;
int mustY = logoHeight;
int start = - (width + height);
int end = width + height;
X = start;
Y = start;
int random = 0;
// 循环Y每次偏移防止重叠的最小偏移量加上自定义的偏移量
for (; Y <= end; Y = Y + moveY + mustY ){
// 循环X,每次偏移防止重叠的最小偏移量加上自定义偏移量
for (; X <= end; X = X + moveX + mustX){
graphics.drawImage(logoImg, X + random, Y, null);
}
X = start;
if(random == 0){
random = - randomX;
}else {
random = 0;
}
}
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
// 获取图片后缀
String query = "select imagefilename from imagefile where imagefileid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, imageId);
String suffix = "jpg";
String imageFileName = "";
if (rs.next()) {
imageFileName = Util.null2String(rs.getString(1));
suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
}
String createDir = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
// 防止高并发下文件名重复导致文件覆盖的问题
String tempPath = createDir + imageFileName + System.currentTimeMillis() + UUID.randomUUID() + "." + suffix;
File file = new File(tempPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 输出到临时目录
FileOutputStream outputStreamTem = new FileOutputStream(URLDecoder.decode(tempPath, "utf-8"));
ImageIO.write(bufferedImage, suffix, outputStreamTem);
outputStreamTem.close();
// 保存生成的水印图片到压缩包
int i = imageFileManager.saveImageFileByInputStream(new FileInputStream(tempPath), imageFileName);
// 建议虚拟机进行一次垃圾回收,防止临时文件被其他文件流保存而无法删除临时文件
System.gc();
// 删除临时文件, 防止文件删除失败,设置一个自旋操作,加大文件删除的几率
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
Files.delete(Paths.get(tempPath));
deleteFlag = false;
} catch (Exception e) {
// 设置线程沉睡500毫秒等待jvm进行垃圾回收将持有临时文件的流对象回收确保临时文件能删除
try {
Thread.sleep(500);
} catch (InterruptedException interruptedException) {
return i;
}
if (n > 5) {
deleteFlag = false;
}
}
}
return i;
}
/**
*
* @param imageId id
* @param logoInput
* @param degree
* @param alpha
* @param moveX X
* @param moveY Y
* @param randomX X
* @return id
* @throws IOException io
*/
public static int addPicTileWatermarkById(int imageId, InputStream logoInput
, double degree, float alpha, int moveX, int moveY, int randomX) throws IOException {
ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(imageId);
if(inputStreamById == null){
throw new RuntimeException("Failed to obtain the image to which a watermark is to be added. " +
"Check whether the file exists in the system and ensure that the file is in the image format.");
}
// 将输入流读取为图片
Image image = ImageIO.read(inputStreamById);
int width = image.getWidth(null);
int height = image.getHeight(null);
// 创建bufferedImage
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = bufferedImage.createGraphics();
// 设置对线段的锯齿状边缘处理
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, width, height, null);
// 设置旋转角度
graphics.rotate(Math.toRadians(degree), (double) width / 2, (double) height / 2);
// 设置透明度
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
if(logoInput == null){
throw new RuntimeException("The obtained watermark logo image is empty");
}
// 获取水印图片
ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(logoInput));
Image logoImg = logoImgIcon.getImage();
int logoWidth = logoImg.getWidth(null);
int logoHeight = logoImg.getHeight(null);
int X;
int Y;
int mustX = logoWidth;
int mustY = logoHeight;
int start = - (width + height);
int end = width + height;
X = start;
Y = start;
int random = 0;
// 循环Y每次偏移防止重叠的最小偏移量加上自定义的偏移量
for (; Y <= end; Y = Y + moveY + mustY ){
// 循环X,每次偏移防止重叠的最小偏移量加上自定义偏移量
for (; X <= end; X = X + moveX + mustX){
graphics.drawImage(logoImg, X + random, Y, null);
}
X = start;
if(random == 0){
random = - randomX;
}else {
random = 0;
}
}
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
// 获取图片后缀
String query = "select imagefilename from imagefile where imagefileid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, imageId);
String suffix = "jpg";
String imageFileName = "";
if (rs.next()) {
imageFileName = Util.null2String(rs.getString(1));
suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
}
String createDir = FileUpload.getCreateDir(new SystemComInfo().getFilesystem()) + "tempfile" + File.separator;
// 防止高并发下文件名重复导致文件覆盖的问题
String tempPath = createDir + imageFileName + System.currentTimeMillis() + UUID.randomUUID() + "." + suffix;
File file = new File(tempPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// 输出到临时目录
FileOutputStream outputStreamTem = new FileOutputStream(URLDecoder.decode(tempPath, "utf-8"));
ImageIO.write(bufferedImage, suffix, outputStreamTem);
outputStreamTem.close();
// 保存生成的水印图片到压缩包
int i = imageFileManager.saveImageFileByInputStream(new FileInputStream(tempPath), imageFileName);
// 建议虚拟机进行一次垃圾回收,防止临时文件被其他文件流保存而无法删除临时文件
System.gc();
// 删除临时文件, 防止文件删除失败,设置一个自旋操作,加大文件删除的几率
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
Files.delete(Paths.get(tempPath));
deleteFlag = false;
} catch (Exception e) {
// 设置线程沉睡500毫秒等待jvm进行垃圾回收将持有临时文件的流对象回收确保临时文件能删除
try {
Thread.sleep(500);
} catch (InterruptedException interruptedException) {
return i;
}
if (n > 5) {
deleteFlag = false;
}
}
}
return i;
}
}

View File

@ -0,0 +1,12 @@
package aiyh.utils.function;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/12 0012 14:17
*
*/
@FunctionalInterface
public interface FindChildren<T> {
boolean findChildren(T t,T t1);
}

View File

@ -0,0 +1,12 @@
package aiyh.utils.function;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/12 0012 14:17
*
*/
@FunctionalInterface
public interface VerifyParent<T> {
boolean verifyParent(T t);
}

View File

@ -0,0 +1,39 @@
package aiyh.utils.httpUtil;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
/**
* IOIOUtilscloseQuietly
*
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
*/
public class ExtendedIOUtils {
public static void flush(Flushable... resources) throws IOException {
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
}
}
}
}
}

View File

@ -0,0 +1,26 @@
package aiyh.utils.httpUtil;
/**
* @author @author EBU7-dev1-ay
* @date 2021/9/1 0001 10:52
* httpposttype
*/
public class HttpArgsType {
/**
* put
*/
public static final String HTTP_POST_PUT = "PUT";
/**
* post
*/
public static final String HTTP_POST_POST = "POST";
public static final String HTTP_HTTPS = "https";
public static final String HTTP_HTTP = "http";
public static final String DEFAULT_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";
public static final String X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
public static final String APPLICATION_JSON = "application/json;charset=utf-8";
}

View File

@ -0,0 +1,87 @@
package aiyh.utils.httpUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.ssl.SSLContextBuilder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
/**
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
**/
public class HttpManager {
/**
*
*/
private static final int CONNECT_TIMEOUT = 30000;
private static final int CONNECTION_REQUEST_TIMEOUT = 10000;
private static final int SOCKET_TIMEOUT = 30000;
private static final int MAX_TOTAL = 500;
private static final int MAX_PRE_ROUTE = 500;
/**
*
*/
static RequestConfig requestConfig = RequestConfig.custom()
//网络请求的超时时间
.setConnectTimeout(CONNECT_TIMEOUT)
//连接池去获取连接的超时时间
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
//设置socket超时时间
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
static {
// 配置最大的连接数
manager.setMaxTotal(MAX_TOTAL);
// 每个路由最大连接数路由是根据host来管理的大小不好控制
manager.setDefaultMaxPerRoute(MAX_PRE_ROUTE);
}
/**
* urlhttp / https
* @param url
* @return
*/
public static CloseableHttpClient getHttpConnection(String url){
if(url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())){
SSLContext sslContext;
SSLConnectionSocketFactory sslsf = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> {
// 绕过所有验证
return true;
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
sslsf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
e.printStackTrace();
}
return HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(manager)
.setConnectionManagerShared(true)
.setDefaultRequestConfig(requestConfig)
.build();
}else{
return HttpClients.custom()
.setConnectionManager(manager)
.setDefaultRequestConfig(requestConfig)
.setConnectionManagerShared(true)
.build();
}
}
}

View File

@ -0,0 +1,110 @@
package aiyh.utils.httpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/31 0031 17:16
* http
*/
public class ResponeVo {
/**
*
*/
int code;
/**
*
*/
String entityString;
/**
*
*/
@JSONField(serialize = false)
Header[] allHeaders;
Locale locale;
public int getCode() {
return code;
}
/**
* map
* @return map
* @throws JsonProcessingException JSON
*/
public Map<String, Object> getEntityMap() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(this.getEntityString(), Map.class);
}
/**
*
* @param clazz
* @param <T>
* @return
* @throws JsonProcessingException JSON
*/
public <T> T getEntity(Class<T> clazz) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(this.getEntityString(), clazz);
}
/**
*
* @param clazz
* @param <T>
* @return
*/
public <T> List<T> getEntityArray(Class<T> clazz) {
return JSON.parseArray(this.getEntityString(), clazz);
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public void setCode(int code) {
this.code = code;
}
public Header[] getAllHeaders() {
return allHeaders;
}
public void setAllHeaders(Header[] allHeaders) {
this.allHeaders = allHeaders;
}
public String getEntityString() {
return entityString;
}
public void setEntityString(String entityString) {
this.entityString = entityString;
}
@Override
public String toString() {
return "ResponeVo{" +
"code=" + code +
", entityString='" + entityString + '\'' +
", locale=" + locale +
'}';
}
}

View File

@ -0,0 +1,54 @@
package aiyh.utils.httpUtil.httpAsync;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import aiyh.utils.httpUtil.ExtendedIOUtils;
import aiyh.utils.httpUtil.ResponeVo;
import java.util.Locale;
import java.util.concurrent.Callable;
/**
* @author EBU7-dev1-ayh
* @date 2021/9/2 0002 22:55
* async
*/
public class HttpAsyncThread implements Callable<ResponeVo> {
private final CloseableHttpClient httpClient;
private final HttpUriRequest request;
private String DEFAULT_ENCODING = "UTF-8";
public HttpAsyncThread(CloseableHttpClient httpClient, HttpUriRequest request, String DEFAULT_ENCODING) {
this.httpClient = httpClient;
this.request = request;
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
@Override
public ResponeVo call() throws Exception {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
Header[] allHeaders = response.getAllHeaders();
Locale locale = response.getLocale();
responeVo.setLocale(locale);
responeVo.setAllHeaders(allHeaders);
responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING));
responeVo.setCode(response.getStatusLine().getStatusCode());
} catch (Exception e) {
throw e;
}
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
}

View File

@ -0,0 +1,40 @@
package aiyh.utils.httpUtil.httpAsync;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import aiyh.utils.httpUtil.ExtendedIOUtils;
import java.util.function.Consumer;
/**
* @author EBU7-dev1-ayh
* @date 2021/9/2 0002 23:18
* callback
*/
public class HttpAsyncThreadCallBack implements Runnable{
private final CloseableHttpClient httpClient;
private final HttpUriRequest request;
private final Consumer<CloseableHttpResponse> consumer;
public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer){
this.httpClient = httpClient;
this.request = request;
this.consumer = consumer;
}
@Override
public void run() {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
consumer.accept(response);
} catch (Exception e) {
consumer.accept(null);
}
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
}

View File

@ -0,0 +1,24 @@
package aiyh.utils.httpUtil.staticUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
*/
public class GlobalStaticCache {
/**
*
*/
public static Map<String,String> header = new HashMap<>();
/**
*
*/
public static Map<String,String> paramMap = new HashMap<>();
}

View File

@ -0,0 +1,836 @@
package aiyh.utils.httpUtil.staticUtil;
import aiyh.utils.httpUtil.util.CloseThread;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.http.Header;
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.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.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import aiyh.utils.httpUtil.ExtendedIOUtils;
import aiyh.utils.httpUtil.HttpArgsType;
import aiyh.utils.httpUtil.HttpManager;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack;
import aiyh.utils.zwl.common.ToolUtil;
import weaver.file.ImageFileManager;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/31 0031 17:16
* http
*/
public class HttpStaticUtils {
// 默认编码
public static String DEFAULT_ENCODING = "UTF-8";
private static final ToolUtil toolUtil = new ToolUtil();
// 线程池
public static final ThreadPoolExecutor executorService;
static {
// private final ExecutorService executorService = Executors.newFixedThreadPool(3);
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
ThreadFactory threadFactory = threadFactoryBuilder.setNameFormat("xxx-pool-%d").build();
executorService = new ThreadPoolExecutor(5, 200, 0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
}
public static HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
public static HttpGet getHttpGet(String url) {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
return httpGet;
}
/**
* get
* @param url
* @return
* @throws IOException io
*/
public static ResponeVo apiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
/**
* delete
* @param url
* @return
* @throws IOException io
*/
public static ResponeVo apiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
/**
* get
* @param url
* @param headers
* @return
* @throws IOException io
*/
public static ResponeVo apiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
/**
* delete
* @param url
* @param headers
* @return
* @throws IOException io
*/
public static ResponeVo apiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
public static ResponeVo apiGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
public static ResponeVo apiDelete(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
/**
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void apiGet(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
System.out.println(getUrl);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
callBackRequest(httpConnection, httpGet, consumer);
}
/**
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void apiDelete(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
callBackRequest(httpConnection, httpDelete, consumer);
}
/**
* post
* @param url
* @param params
* @return
* @throws IOException io
*/
public static ResponeVo apiPost(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiPut(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
/**
* post
* @param url
* @param params
* @param headers
* @return
* @throws IOException io
*/
public static ResponeVo apiPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiPut(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
public static ResponeVo apiUploadFile(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiUploadFile(String url,File file, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiUploadFileById(String url,int id, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public static HttpPost uploadFileByInputStream(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey,inputStream, ContentType.MULTIPART_FORM_DATA,fileName);
for (Map.Entry<String,String> param : params.entrySet()){
StringBody stringBody = new StringBody(param.getValue(),ContentType.MULTIPART_FORM_DATA);
builder.addPart(param.getKey(),stringBody);
}
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if("Content-Type".equalsIgnoreCase(entry.getKey())){
continue;
}
httpPost.setHeader(entry.getKey(), entry.getValue());
}
httpPost.setHeader("Content-Type", "multipart/form-data");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
public static HttpPost uploadFileByInputStream(String url,File file, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey,file, ContentType.MULTIPART_FORM_DATA,fileName);
for (Map.Entry<String,String> param : params.entrySet()){
StringBody stringBody = new StringBody(param.getValue(),ContentType.MULTIPART_FORM_DATA);
builder.addPart(param.getKey(),stringBody);
}
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if("Content-Type".equalsIgnoreCase(entry.getKey())){
continue;
}
httpPost.setHeader(entry.getKey(), entry.getValue());
}
httpPost.setHeader("Content-Type", "multipart/form-data");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
/**
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void apiPost(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPost, consumer);
}
/**
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void apiPut(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPut, consumer);
}
/**
*
* @param httpClient httpclient
* @param request
* @param consumer
* @throws IOException io
*/
private static void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
consumer.accept(response);
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
}
// new CloseThread(httpClient,response).run();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
/**
*
* @param httpClient httpclient
* @param request
* @return
* @throws IOException io
*/
public static ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
Header[] allHeaders = response.getAllHeaders();
Locale locale = response.getLocale();
responeVo.setLocale(locale);
responeVo.setAllHeaders(allHeaders);
responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING));
responeVo.setCode(response.getStatusLine().getStatusCode());
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
}
// new CloseThread(httpClient,response).run();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
/**
* get
*
* @param url
* @return Future
* @throws IOException io
*/
public static Future<ResponeVo> asyncApiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiUploadFile(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiUploadFile(String url,File file, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiUploadFileById(String url,int id, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
/**
* delete
*
* @param url
* @return Future
* @throws IOException io
*/
public static Future<ResponeVo> asyncApiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
/**
* get
*
* @param url
* @param headers
* @return
* @throws IOException io
*/
public static Future<ResponeVo> asyncApiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiDelete(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void asyncApiGet(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer));
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void asyncApiDelete(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer));
}
public static Future<ResponeVo> asyncApiPost(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiPut(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiPut(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void asyncApiPost(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer));
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public static void asyncApiPut(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer));
}
/**
* post
* @param url
* @param headerMap
* @param paramsMap
* @return
* @throws UnsupportedEncodingException
*/
private static HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, String> paramsMap) throws UnsupportedEncodingException {
String contentType = "";
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
contentType = entry.getValue();
}
}
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap));
httpPost.setEntity(stringEntity);
}
return httpPost;
}
private static HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, String> paramsMap) throws UnsupportedEncodingException {
String contentType = "";
HttpPut httpPut = new HttpPut(url.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
contentType = entry.getValue();
}
}
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap));
httpPut.setEntity(stringEntity);
}
return httpPut;
}
private static String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
toolUtil.writeErrorLog(e.getLocalizedMessage() + "\n" + e);
}
return total.toString();
}
/**
*
* @param headers
* @return
*/
public static Map<String, String> headersHandle(Map<String, String> headers) {
Map<String, String> map = new HashMap<>();
if (headers != null && headers.size() > 0) {
if (GlobalStaticCache.header != null && GlobalStaticCache.header.size() > 0) {
map.putAll(GlobalStaticCache.header);
}
map.putAll(headers);
} else {
map.putAll(GlobalStaticCache.header);
}
return map;
}
/**
*
* @param params
* @return
*/
public static Map<String, String> paramsHandle(Map<String, String> params) {
Map<String, String> map = new HashMap<>();
if (params != null && params.size() > 0) {
if (GlobalStaticCache.paramMap != null && GlobalStaticCache.paramMap.size() > 0) {
map.putAll(GlobalStaticCache.paramMap);
}
map.putAll(params);
} else {
map.putAll(GlobalStaticCache.paramMap);
}
return map;
}
/**
* urlget
* @param url
* @param params
* @return url
*/
public static String urlHandle(String url, Map<String, String> params) {
if(params == null || params.size() <= 0){
return url;
}
String serializeParams = serializeParams(params);
String getUrl;
if (!url.contains("?")) {
if (url.endsWith("/")) {
getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams;
} else {
getUrl = url + "?" + serializeParams;
}
} else {
if (url.endsWith("?")) {
getUrl = url + serializeParams;
} else {
getUrl = url + "&" + serializeParams;
}
}
return getUrl;
}
/**
*
* @param params
* @return
*/
private static String serializeParams(Map<String, String> params) {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.append("&");
builder.append(entry.getKey());
builder.append("=");
builder.append(entry.getValue());
}
return removeSeparator(builder);
}
return "";
}
private static String removeSeparator(StringBuilder sqlBuilder) {
String str = sqlBuilder.toString().trim();
String removeSeparator = "&";
if (str.endsWith(removeSeparator)) {
// 如果以分&号结尾,则去除&号
str = str.substring(0, str.length() - 1);
}
if (str.trim().startsWith(removeSeparator)) {
// 如果以&开头,则去除&
str = str.substring(1);
}
return str;
}
}

View File

@ -0,0 +1,34 @@
package aiyh.utils.httpUtil.util;
import aiyh.utils.httpUtil.ExtendedIOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
/**
* @author EBU7-dev1-ayh
* @create 2021/11/5 0005 16:09
*/
public class CloseThread implements Runnable {
private CloseableHttpClient httpClient;
private CloseableHttpResponse response;
public CloseThread(CloseableHttpClient httpClient, CloseableHttpResponse response) {
this.httpClient = httpClient;
this.response = response;
}
@Override
public void run() {
try {
Thread.sleep(1000 * 60);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
}
}

View File

@ -0,0 +1,42 @@
package aiyh.utils.httpUtil.util;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
*/
public class GlobalCache {
/**
*
*/
public Map<String,String> header = new HashMap<>();
/**
*
*/
public Map<String,Object> paramMap = new HashMap<>();
public Map<String,String> uptHeader(String key, String value){
header.put(key,value);
return header;
}
public Map<String,Object> uptParam(String key, Object value){
paramMap.put(key,value);
return paramMap;
}
public void clearHeader(){
header.clear();
}
public void clearParam(){
paramMap.clear();
}
}

View File

@ -0,0 +1,772 @@
package aiyh.utils.httpUtil.util;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.http.Header;
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.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.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import aiyh.utils.httpUtil.ExtendedIOUtils;
import aiyh.utils.httpUtil.HttpArgsType;
import aiyh.utils.httpUtil.HttpManager;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack;
import aiyh.utils.zwl.common.ToolUtil;
import weaver.file.ImageFileManager;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/31 0031 17:16
* http HttpStaticUtils使HttpStaticUtils
*/
public class HttpUtils {
// 默认编码
private String DEFAULT_ENCODING = "UTF-8";
private final ToolUtil toolUtil = new ToolUtil();
private final GlobalCache globalCache = new GlobalCache();
// 线程池
private final ThreadPoolExecutor executorService;
{
// private final ExecutorService executorService = Executors.newFixedThreadPool(3);
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
ThreadFactory threadFactory = threadFactoryBuilder.setNameFormat("xxx-pool-%d").build();
executorService = new ThreadPoolExecutor(5, 200, 0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
}
public HttpUtils() {
}
public GlobalCache getGlobalCache() {
return globalCache;
}
public void setDEFAULT_ENCODING() {
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
public HttpUtils(String DEFAULT_ENCODING) {
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
public HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
public HttpGet getHttpGet(String url) {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
return httpGet;
}
/**
* get
*
* @param url
* @return
* @throws IOException io
*/
public ResponeVo apiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
/**
* delete
*
* @param url
* @return
* @throws IOException io
*/
public ResponeVo apiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
/**
* get
*
* @param url
* @param headers
* @return
* @throws IOException io
*/
public ResponeVo apiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
public ResponeVo apiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
public ResponeVo apiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
public ResponeVo apiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiGet(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
callBackRequest(httpConnection, httpGet, consumer);
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiDelete(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
callBackRequest(httpConnection, httpDelete, consumer);
}
public ResponeVo apiPost(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
public ResponeVo apiUploadFile(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiUploadFile(String url,File file, String fileKey,String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiUploadFileById(String url,int id, String fileKey,String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPost, consumer);
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPut, consumer);
}
private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
consumer.accept(response);
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
}
// new CloseThread(httpClient,response).run();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
Header[] allHeaders = response.getAllHeaders();
Locale locale = response.getLocale();
responeVo.setLocale(locale);
responeVo.setAllHeaders(allHeaders);
responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING));
responeVo.setCode(response.getStatusLine().getStatusCode());
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
}
// new CloseThread(httpClient,response).run();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
/**
* get
*
* @param url
* @return
* @throws IOException io
*/
public Future<ResponeVo> asyncApiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
/**
* delete
*
* @param url
* @return
* @throws IOException io
*/
public Future<ResponeVo> asyncApiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
/**
* get
*
* @param url
* @param headers
* @return
* @throws IOException io
*/
public Future<ResponeVo> asyncApiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer));
}
/**
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer));
}
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer));
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer));
}
private HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
String contentType = "";
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
contentType = entry.getValue();
}
}
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
// } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
} else{
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap),DEFAULT_ENCODING);
httpPost.setEntity(stringEntity);
}
return httpPost;
}
public HttpPost uploadFileByInputStream(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, Object> params, Map<String, String> headers){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey,inputStream, ContentType.MULTIPART_FORM_DATA,fileName);
ContentType contentType= ContentType.create("text/plain",StandardCharsets.UTF_8);
for (Map.Entry<String,Object> param : params.entrySet()){
StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType);
builder.addPart(param.getKey(),stringBody);
}
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if("Content-Type".equalsIgnoreCase(entry.getKey())){
continue;
}
httpPost.setHeader(entry.getKey(), entry.getValue());
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
public HttpPost uploadFileByInputStream(String url,File file, String fileKey,String fileName,
Map<String, Object> params, Map<String, String> headers){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey,file, ContentType.MULTIPART_FORM_DATA,fileName);
for (Map.Entry<String,Object> param : params.entrySet()){
StringBody stringBody = new StringBody(String.valueOf(param.getValue()),ContentType.MULTIPART_FORM_DATA);
builder.addPart(param.getKey(),stringBody);
}
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if("Content-Type".equalsIgnoreCase(entry.getKey())){
continue;
}
httpPost.setHeader(entry.getKey(), entry.getValue());
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
private HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
String contentType = "";
HttpPut httpPut = new HttpPut(url.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
contentType = entry.getValue();
}
}
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap),DEFAULT_ENCODING);
httpPut.setEntity(stringEntity);
}
return httpPut;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
toolUtil.writeErrorLog(e.getLocalizedMessage() + "\n" + e);
}
return total.toString();
}
public Map<String, String> headersHandle(Map<String, String> headers) {
Map<String, String> map = new HashMap<>();
if (headers != null && headers.size() > 0) {
if (globalCache.header != null && globalCache.header.size() > 0) {
map.putAll(globalCache.header);
}
map.putAll(headers);
} else {
map.putAll(globalCache.header);
}
return map;
}
public Map<String, Object> paramsHandle(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
if (params != null && params.size() > 0) {
if (globalCache.paramMap != null && globalCache.paramMap.size() > 0) {
map.putAll(globalCache.paramMap);
}
map.putAll(params);
} else {
map.putAll(globalCache.paramMap);
}
return map;
}
public String urlHandle(String url, Map<String, Object> params) {
if (params == null || params.size() <= 0) {
return url;
}
String serializeParams = serializeParams(params);
String getUrl;
if (!url.contains("?")) {
if (url.endsWith("/")) {
getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams;
} else {
getUrl = url + "?" + serializeParams;
}
} else {
if (url.endsWith("?")) {
getUrl = url + serializeParams;
} else {
getUrl = url + "&" + serializeParams;
}
}
return getUrl;
}
private String serializeParams(Map<String, Object> params) {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.append("&");
builder.append(entry.getKey());
builder.append("=");
builder.append(entry.getValue());
}
return removeSeparator(builder);
}
return "";
}
private String removeSeparator(StringBuilder sqlBuilder) {
String str = sqlBuilder.toString().trim();
String removeSeparator = "&";
if (str.endsWith(removeSeparator)) {
// 如果以分&号结尾,则去除&号
str = str.substring(0, str.length() - 1);
}
if (str.trim().startsWith(removeSeparator)) {
// 如果以&开头,则去除&
str = str.substring(1);
}
return str;
}
}

View File

@ -0,0 +1,24 @@
package aiyh.utils.mapUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/19 0019 19:40
* map
*/
public class ParaMap extends HashMap<String, Object> implements Map<String, Object> {
public static ParaMap create() {
return new ParaMap();
}
@Override
public ParaMap put(String name, Object value) {
super.put(name, value);
return this;
}
}

View File

@ -0,0 +1,42 @@
package aiyh.utils.mapUtil;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/19 0019 19:45
* utilMap
*/
public class UtilHashMap<K, V> extends HashMap<K, V> implements Map<K, V> {
public UtilHashMap(){
super();
}
public UtilHashMap<K,V> uPut(K key, V value) {
this.put(key,value);
return this;
}
public UtilHashMap<K,V> uPutAll(Map<? extends K, ? extends V> m) {
super.putAll(m);
return this;
}
public UtilHashMap<K,V> uReplace(K key, V value) {
super.replace(key, value);
return this;
}
public UtilHashMap<K,V> filter(UtilMapFilter<? super K, ? super V> predicate){
UtilHashMap<K,V> newMap = new UtilHashMap<>();
for (Entry<K,V> entry : this.entrySet()){
if(predicate.test(entry.getKey(), entry.getValue())){
newMap.put(entry.getKey(),entry.getValue());
}
}
return newMap;
}
}

View File

@ -0,0 +1,43 @@
package aiyh.utils.mapUtil;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 15:06
* LinkedHashMap
*/
public class UtilLinkedHashMap<K, V> extends LinkedHashMap<K, V> implements Map<K, V> {
public UtilLinkedHashMap() {
super();
}
public UtilLinkedHashMap<K, V> uPut(K key, V value) {
this.put(key, value);
return this;
}
public UtilLinkedHashMap<K, V> uPutAll(Map<? extends K, ? extends V> m) {
super.putAll(m);
return this;
}
public UtilLinkedHashMap<K, V> uReplace(K key, V value) {
super.replace(key, value);
return this;
}
public UtilLinkedHashMap<K, V> filter(UtilMapFilter<? super K, ? super V> predicate) {
UtilLinkedHashMap<K, V> newMap = new UtilLinkedHashMap<>();
for (Entry<K, V> entry : this.entrySet()) {
if (predicate.test(entry.getKey(), entry.getValue())) {
newMap.put(entry.getKey(), entry.getValue());
}
}
return newMap;
}
}

View File

@ -0,0 +1,11 @@
package aiyh.utils.mapUtil;
/**
* @author @author EBU7-dev1-ay
* @date 2021/8/19 0019 21:18
* utilMapFilter
*/
public interface UtilMapFilter<K,V> {
boolean test(K k,V v);
}

View File

@ -0,0 +1,86 @@
package aiyh.utils.service;
import aiyh.utils.dao.UtilDao;
import aiyh.utils.entity.ApiConfigDetailDTO;
import aiyh.utils.entity.ApiConfigMainDTO;
import aiyh.utils.entity.MultiLanguageDTO;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/14 0014 12:21
* service
*/
public class UtilService {
private final UtilDao utilDao = new UtilDao();
public ApiConfigMainDTO getApiConfigMain(String id){
ApiConfigMainDTO apiConfigMain = utilDao.getApiConfigMain(id);
List<ApiConfigDetailDTO> apiConfigDetails = utilDao.getApiConfigDetail(apiConfigMain.getId());
apiConfigMain.setDetails(apiConfigDetails);
return apiConfigMain;
}
public ApiConfigMainDTO getApiConfigMainTree(String id){
ApiConfigMainDTO apiConfigMain = utilDao.getApiConfigMain(id);
List<ApiConfigDetailDTO> apiConfigDetails = utilDao.getApiConfigDetail(apiConfigMain.getId());
List<ApiConfigDetailDTO> apiConfigDetailTreeList = list2Tree(apiConfigDetails);
apiConfigMain.setDetails(apiConfigDetailTreeList);
return apiConfigMain;
}
private List<ApiConfigDetailDTO> list2Tree(List<ApiConfigDetailDTO> list) {
List<ApiConfigDetailDTO> treeList = new ArrayList<>();
for (ApiConfigDetailDTO apiConfigDetailDTO : list) {
if (apiConfigDetailDTO.getObjectChild() == 0) {
ApiConfigDetailDTO child = findChild(list, apiConfigDetailDTO);
treeList.add(child);
}
}
return treeList;
}
private ApiConfigDetailDTO findChild(List<ApiConfigDetailDTO> list, ApiConfigDetailDTO apiConfigDetailDTO) {
if (apiConfigDetailDTO.getParamType() != 3) {
return apiConfigDetailDTO;
}
for (ApiConfigDetailDTO ddConfigDetailDTO : list) {
if (ddConfigDetailDTO.getParentLine() == apiConfigDetailDTO.getLineNum()) {
// 子项
if (apiConfigDetailDTO.getChildren() == null) {
apiConfigDetailDTO.setChildren(new ArrayList<>());
}
apiConfigDetailDTO.getChildren().add(findChild(list, ddConfigDetailDTO));
}
}
return apiConfigDetailDTO;
}
public Map<String, String> queryLanguage(int groupId, int languageId){
List<MultiLanguageDTO> multiLanguageDTOS = utilDao.queryLanguage(groupId);
Map<String, String> languageResult = new HashMap<>();
if(languageId == 9){
// 中文繁体
for (MultiLanguageDTO multiLanguageDTO : multiLanguageDTOS) {
languageResult.put(multiLanguageDTO.getBswyz(),multiLanguageDTO.getZnHk());
}
}else if(languageId == 8){
// 英文
for (MultiLanguageDTO multiLanguageDTO : multiLanguageDTOS) {
languageResult.put(multiLanguageDTO.getBswyz(),multiLanguageDTO.getEnUs());
}
}else {
// 中文简体
for (MultiLanguageDTO multiLanguageDTO : multiLanguageDTOS) {
languageResult.put(multiLanguageDTO.getBswyz(),multiLanguageDTO.getZnCh());
}
}
return languageResult;
}
}

View File

@ -0,0 +1,24 @@
package aiyh.utils.sqlUtil.builderSql;
import aiyh.utils.sqlUtil.sqlResult.SqlResult;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.impl.WhereImpl;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author EBU7-dev1-ay
* @date 2021/8/23 0023 14:27
* Builder sql
*/
public interface BuilderSql {
SqlResult insertSql(String tableName, Map<String,Object> map);
SqlResult insertBatchSql(String tableName, List<LinkedHashMap<String, Object>> mapList);
SqlResult updateSql(String tableName, Map<String,Object> map, Where where);
SqlResult updateBatchSql(String tableName, List<LinkedHashMap<String, Object>> map, List<Where> whereList);
String insertSqlForString(String tableName, Map<String,Object> map);
String updateSqlForString(String tableName, Map<String,Object> map, WhereImpl where);
}

View File

@ -0,0 +1,450 @@
package aiyh.utils.sqlUtil.builderSql.impl;
import aiyh.utils.Util;
import aiyh.utils.mapUtil.UtilHashMap;
import aiyh.utils.mapUtil.UtilLinkedHashMap;
import aiyh.utils.sqlUtil.builderSql.BuilderSql;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.impl.WhereImpl;
import weaver.conn.RecordSet;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 14:45
*/
public class BuilderSqlImpl implements BuilderSql {
private String DB_TYPE;
{
// 获取当前数据库的类型
this.DB_TYPE = (new RecordSet()).getDBType();
}
/**
*
* @param tableName
* @param mapConfig
* @return SQL
*/
@Override
public PrepSqlResultImpl insertSql(String tableName, Map<String, Object> mapConfig) {
UtilHashMap<String, Object> map = this.verifyMap(mapConfig);
List<Object> args = new ArrayList<>();
StringBuilder sqlBuilder = new StringBuilder("insert into ");
sqlBuilder.append(tableName);
StringBuilder fieldBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
map.forEach((field, value) -> {
fieldBuilder.append(field);
fieldBuilder.append(", ");
valueBuilder.append(" ?, ");
args.add(value);
});
sqlBuilder.append(" ( ");
sqlBuilder.append(Util.removeSeparator(fieldBuilder));
sqlBuilder.append(" ) values ( ");
sqlBuilder.append(Util.removeSeparator(valueBuilder));
sqlBuilder.append(" )");
return new PrepSqlResultImpl(sqlBuilder.toString(), args);
}
public <T> PrepSqlResultImpl insertSqlByEntity(String tableName, T t){
List<Object> args = new ArrayList<>();
StringBuilder sqlBuilder = new StringBuilder("insert into ");
sqlBuilder.append(tableName);
StringBuilder fieldBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(t.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor proper : propertyDescriptors) {
String name = proper.getName();
Method readMethod = proper.getReadMethod();
Object invoke = readMethod.invoke(t);
// System.out.println(name);
// System.out.println(invoke);
if(invoke == null){
continue;
}
fieldBuilder.append(name);
fieldBuilder.append(", ");
valueBuilder.append(" ?, ");
args.add(invoke);
}
} catch (Exception e) {
e.printStackTrace();
}
sqlBuilder.append(" ( ");
sqlBuilder.append(Util.removeSeparator(fieldBuilder));
sqlBuilder.append(" ) values ( ");
sqlBuilder.append(Util.removeSeparator(valueBuilder));
sqlBuilder.append(" )");
return new PrepSqlResultImpl(sqlBuilder.toString(), args);
}
/**
* SQL
* @param tableName
* @param mapListConfig list
* @return SQL
*/
@Override
public BatchSqlResultImpl insertBatchSql(String tableName, List<LinkedHashMap<String, Object>> mapListConfig) {
List<UtilLinkedHashMap<String, Object>> mapList = this.verifyMapList(mapListConfig);
StringBuilder sqlBuilder = new StringBuilder("insert into ");
sqlBuilder.append(tableName);
StringBuilder fieldBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
List<List> args = new ArrayList<>();
AtomicInteger i = new AtomicInteger();
mapList.forEach(item -> {
List<Object> arg = new ArrayList<>();
item.forEach((field, value) -> {
if (i.get() == 0) {
fieldBuilder.append(field);
fieldBuilder.append(", ");
valueBuilder.append(" ?, ");
}
arg.add(value);
});
args.add(arg);
i.getAndIncrement();
});
sqlBuilder.append(" ( ");
sqlBuilder.append(Util.removeSeparator(fieldBuilder));
sqlBuilder.append(" ) values ( ");
sqlBuilder.append(Util.removeSeparator(valueBuilder));
sqlBuilder.append(" )");
return new BatchSqlResultImpl(sqlBuilder.toString(), args);
}
public <T> BatchSqlResultImpl insertBatchSqlByEntity(String tableName, List<T> list) {
StringBuilder sqlBuilder = new StringBuilder("insert into ");
sqlBuilder.append(tableName);
StringBuilder fieldBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
List<List> args = new ArrayList<>();
AtomicInteger i = new AtomicInteger();
list.forEach(item -> {
List<Object> arg = new ArrayList<>();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(item.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor proper : propertyDescriptors) {
String name = proper.getName();
Method readMethod = proper.getReadMethod();
Object invoke = readMethod.invoke(item);
if(invoke == null){
continue;
}
if (i.get() == 0) {
fieldBuilder.append(name);
fieldBuilder.append(", ");
valueBuilder.append(" ?, ");
}
arg.add(invoke);
}
} catch (Exception e) {
e.printStackTrace();
}
args.add(arg);
i.getAndIncrement();
});
sqlBuilder.append(" ( ");
sqlBuilder.append(Util.removeSeparator(fieldBuilder));
sqlBuilder.append(" ) values ( ");
sqlBuilder.append(Util.removeSeparator(valueBuilder));
sqlBuilder.append(" )");
return new BatchSqlResultImpl(sqlBuilder.toString(), args);
}
/**
*
* @param tableName
* @param mapConfig
* @param where
* @return SQL
*/
@Override
public PrepSqlResultImpl updateSql(String tableName, Map<String, Object> mapConfig, Where where) {
UtilHashMap<String, Object> map = this.verifyMap(mapConfig);
this.verifyWhere(where);
StringBuilder sqlBuilder = new StringBuilder("update ");
StringBuilder fieldValue = new StringBuilder();
List<Object> args = new ArrayList<>();
sqlBuilder.append(tableName);
sqlBuilder.append(" set ");
map.forEach((field, value) -> {
fieldValue.append(field);
fieldValue.append(" = ?, ");
args.add(value);
});
sqlBuilder.append(Util.removeSeparator(fieldValue));
sqlBuilder.append(" ");
sqlBuilder.append(where.getSql());
if (where.getArgs() != null && where.getArgs().size() > 0) {
args.addAll(where.getArgs());
}
return new PrepSqlResultImpl(sqlBuilder.toString(), args);
}
public <T> PrepSqlResultImpl updateSqlByEntity(String tableName, T t, Where where){
this.verifyWhere(where);
StringBuilder sqlBuilder = new StringBuilder("update ");
StringBuilder fieldValue = new StringBuilder();
List<Object> args = new ArrayList<>();
sqlBuilder.append(tableName);
sqlBuilder.append(" set ");
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(t.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor proper : propertyDescriptors) {
String name = proper.getName();
Method readMethod = proper.getReadMethod();
Object invoke = readMethod.invoke(t);
if(invoke == null){
continue;
}
fieldValue.append(name);
fieldValue.append(" = ?, ");
args.add(invoke);
}
} catch (Exception e) {
e.printStackTrace();
}
sqlBuilder.append(Util.removeSeparator(fieldValue));
sqlBuilder.append(" ");
sqlBuilder.append(where.getSql());
if (where.getArgs() != null && where.getArgs().size() > 0) {
args.addAll(where.getArgs());
}
return new PrepSqlResultImpl(sqlBuilder.toString(), args);
}
/**
* @param tableName
* @param mapListConfig
* @param whereList
* @return id= ?,id
*/
@Override
public BatchSqlResultImpl updateBatchSql(String tableName, List<LinkedHashMap<String, Object>> mapListConfig, List<Where> whereList) {
List<UtilLinkedHashMap<String, Object>> mapList = this.verifyMapList(mapListConfig);
this.verifyWhereList(whereList);
if (mapList.size() != whereList.size()) {
throw new RuntimeException("mapList与whereList长度不一致mapList size and whereList size Not the same!");
}
StringBuilder sqlBuilder = new StringBuilder("update ");
StringBuilder fieldValue = new StringBuilder();
sqlBuilder.append(tableName);
sqlBuilder.append(" set ");
List<List> args = new ArrayList<>();
AtomicInteger i = new AtomicInteger();
mapList.forEach(item -> {
List<Object> arg = new ArrayList<>();
item.forEach((field, value) -> {
if (i.get() == 0) {
fieldValue.append(field);
fieldValue.append(" = ?, ");
}
arg.add(value);
});
if (whereList.get(i.get()).getArgs() != null && whereList.get(i.get()).getArgs().size() > 0) {
arg.addAll(whereList.get(i.get()).getArgs());
}
args.add(arg);
i.getAndIncrement();
});
sqlBuilder.append(Util.removeSeparator(fieldValue));
sqlBuilder.append(" ");
sqlBuilder.append(whereList.get(0).getSql());
return new BatchSqlResultImpl(sqlBuilder.toString(), args);
}
public <T> BatchSqlResultImpl updateBatchSqlByEntity(String tableName, List<T> list, List<Where> whereList) {
this.verifyWhereList(whereList);
if (list.size() != whereList.size()) {
throw new RuntimeException("List与whereList长度不一致mapList size and whereList size Not the same!");
}
StringBuilder sqlBuilder = new StringBuilder("update ");
StringBuilder fieldValue = new StringBuilder();
sqlBuilder.append(tableName);
sqlBuilder.append(" set ");
List<List> args = new ArrayList<>();
AtomicInteger i = new AtomicInteger();
list.forEach(item -> {
List<Object> arg = new ArrayList<>();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(item.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor proper : propertyDescriptors) {
String name = proper.getName();
Method readMethod = proper.getReadMethod();
Object invoke = readMethod.invoke(item);
if(invoke == null){
continue;
}
if (i.get() == 0) {
fieldValue.append(name);
fieldValue.append(" = ?, ");
}
arg.add(invoke);
}
} catch (Exception e) {
e.printStackTrace();
}
if (whereList.get(i.get()).getArgs() != null && whereList.get(i.get()).getArgs().size() > 0) {
arg.addAll(whereList.get(i.get()).getArgs());
}
args.add(arg);
i.getAndIncrement();
});
sqlBuilder.append(Util.removeSeparator(fieldValue));
sqlBuilder.append(" ");
sqlBuilder.append(whereList.get(0).getSql());
return new BatchSqlResultImpl(sqlBuilder.toString(), args);
}
/**
* SQL
* @param tableName
* @param mapConfig
* @return SQL
*/
@Override
public String insertSqlForString(String tableName, Map<String, Object> mapConfig) {
UtilHashMap<String, Object> map = this.verifyMap(mapConfig);
StringBuilder sqlBuilder = new StringBuilder("insert into ");
sqlBuilder.append(tableName);
StringBuilder fieldBuilder = new StringBuilder();
StringBuilder valueBuilder = new StringBuilder();
map.forEach((field, value) -> {
fieldBuilder.append(field);
fieldBuilder.append(", ");
valueBuilder.append("'");
valueBuilder.append(value);
valueBuilder.append("'");
valueBuilder.append(", ");
});
sqlBuilder.append(" ( ");
sqlBuilder.append(Util.removeSeparator(fieldBuilder));
sqlBuilder.append(" ) values ( ");
sqlBuilder.append(Util.removeSeparator(valueBuilder));
sqlBuilder.append(" )");
return sqlBuilder.toString();
}
/**
* SQL
* @param tableName
* @param mapConfig
* @return SQL
*/
@Override
public String updateSqlForString(String tableName, Map<String, Object> mapConfig, WhereImpl where) {
UtilHashMap<String, Object> map = this.verifyMap(mapConfig);
this.verifyWhere(where);
StringBuilder sqlBuilder = new StringBuilder("update ");
StringBuilder fieldValue = new StringBuilder();
sqlBuilder.append(tableName);
sqlBuilder.append(" set ");
map.forEach((field, value) -> {
fieldValue.append(field);
fieldValue.append(" = ");
fieldValue.append("'");
fieldValue.append(value);
fieldValue.append("'");
fieldValue.append(", ");
});
sqlBuilder.append(Util.removeSeparator(fieldValue));
sqlBuilder.append(" ");
sqlBuilder.append(where.getSql());
return sqlBuilder.toString();
}
/**
* SQLnull
* @param map SQLmap
* @return UtilHashMap
*/
public UtilHashMap<String, Object> verifyMap(Map<String, Object> map) {
UtilHashMap<String, Object> filterMap = Util.createUtilHashMap()
.uPutAll(map)
.filter((key, value) -> !Objects.isNull(key) && !Objects.isNull(value));
if (Util.mapIsNullOrEmpty(filterMap)) {
throw new RuntimeException("map为空或没有数据 map is null or empty!");
}
return filterMap;
}
/**
* SQL
* @param mapList SQL
* @return
*/
public List<UtilLinkedHashMap<String, Object>> verifyMapList(List<LinkedHashMap<String, Object>> mapList) {
if (Objects.isNull(mapList)) {
throw new RuntimeException("mapList为nullmapList is null!");
}
List<UtilLinkedHashMap<String, Object>> collect = mapList.stream().map(item ->
Util.createUtilLinkedHashMap()
.uPutAll(item)
.filter((key, value) -> !Objects.isNull(key) && !Objects.isNull(value))
).collect(Collectors.toList());
if (mapList.size() == 0) {
throw new RuntimeException("mapList没有数据mapList is empty!");
}
return collect;
}
/**
* where
* @param where where
*/
private void verifyWhere(Where where) {
if (where == null) {
throw new RuntimeException("where为null where is null!");
}
}
/**
* where
* @param whereList where
*/
private void verifyWhereList(List<Where> whereList) {
if (whereList == null) {
throw new RuntimeException("whereList为null whereList is null!");
}
whereList.forEach(item->{
if(item == null){
throw new RuntimeException("whereList中数据为null whereDate is null in whereList!");
}
});
}
}

View File

@ -0,0 +1,9 @@
package aiyh.utils.sqlUtil.sqlResult;
/**
* @author EBU7-dev1-ay
* @date 2021/8/23 0023 14:41
*/
public interface SqlResult {
}

View File

@ -0,0 +1,28 @@
package aiyh.utils.sqlUtil.sqlResult.impl;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/12 0012 16:57
* sql
*/
public class BatchSqlResultImpl implements aiyh.utils.sqlUtil.sqlResult.SqlResult {
private final String sqlStr;
private final List<List> batchList;
public BatchSqlResultImpl(String sqlStr, List<List> batchList) {
this.sqlStr = sqlStr;
this.batchList = batchList;
}
public String getSqlStr() {
return sqlStr;
}
public List<List> getBatchList() {
return batchList;
}
}

View File

@ -0,0 +1,30 @@
package aiyh.utils.sqlUtil.sqlResult.impl;
import aiyh.utils.sqlUtil.sqlResult.SqlResult;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 14:39
* prepSqlResult
*/
public class PrepSqlResultImpl implements SqlResult {
private final String sqlStr;
private final List<Object> args;
public PrepSqlResultImpl(String sqlStr, List<Object> args) {
this.sqlStr = sqlStr;
this.args = args;
}
public String getSqlStr() {
return sqlStr;
}
public List<Object> getArgs() {
return args;
}
}

View File

@ -0,0 +1,14 @@
package aiyh.utils.sqlUtil.whereUtil;
/**
* @author EBU7-dev1-ay
* @date 2021/8/23 0023 22:14
* inner where
*/
public interface InnerWhere {
InnerWhereOperator whereAnd(String key);
InnerWhereOperator whereOr(String key);
Where endInnerWhere();
}

View File

@ -0,0 +1,56 @@
package aiyh.utils.sqlUtil.whereUtil;
import java.util.List;
/**
* @author EBU7-dev1-ay
* @date 2021/8/23 0023 22:15
*/
public interface InnerWhereOperator {
InnerWhere whereNull();
InnerWhere whereNotNull();
InnerWhere whereEqual(Object value);
InnerWhere whereNotEqual(Object value);
InnerWhere greaterThan(Object value);
InnerWhere lessThan(Object value);
InnerWhere greaterOrEqual(Object value);
InnerWhere lessThanOrEqual(Object value);
InnerWhere BetweenAnd(Object start, Object end);
InnerWhere whereIn(Object... values);
InnerWhere whereInList(List<Object> list);
InnerWhere whereNotIn(Object... values);
InnerWhere whereNotInList(List<Object> list);
InnerWhere inSql(Object sql);
InnerWhere notInSql(Object sql);
InnerWhere whereLike(Object value);
InnerWhere whereNotLike(Object value);
InnerWhere whereExists(Object... values);
InnerWhere whereNotExists(Object... values);
InnerWhere whereExistsList(List<Object> list);
InnerWhere whereNotExistsList(List<Object> list);
InnerWhere whereExistsSql(Object sql);
InnerWhere whereNotExistsSql(Object sql);
}

View File

@ -0,0 +1,23 @@
package aiyh.utils.sqlUtil.whereUtil;
import java.util.List;
/**
* @author EBU7-dev1-ay
* @date 2021/8/23 0023 12:58
* SQL
*/
public interface Where {
WhereOperator whereAnd(String key);
WhereOperator whereOr(String key);
InnerWhereOperator andInnerWhere(String key);
InnerWhereOperator orInnerWhere(String key);
String getSql();
List<Object> getArgs();
}

View File

@ -0,0 +1,57 @@
package aiyh.utils.sqlUtil.whereUtil;
import java.util.List;
/**
* @author EBU7-dev1-ay
* @date 2021/8/23 0023 13:00
* wherevalue
*/
public interface WhereOperator {
Where whereNull();
Where whereNotNull();
Where whereEqual(Object value);
Where whereNotEqual(Object value);
Where greaterThan(Object value);
Where lessThan(Object value);
Where greaterOrEqual(Object value);
Where lessThanOrEqual(Object value);
Where BetweenAnd(Object start, Object end);
Where whereIn(Object ...values);
Where whereInList(List<Object> list);
Where whereNotIn(Object... values);
Where whereNotInList(List<Object> list);
Where inSql(Object sql);
Where notInSql(Object sql);
Where whereLike(Object value);
Where whereNotLike(Object value);
Where whereExists(Object ...values);
Where whereNotExists(Object ...values);
Where whereExistsList(List<Object> list);
Where whereNotExistsList(List<Object> list);
Where whereExistsSql(Object sql);
Where whereNotExistsSql(Object sql);
}

View File

@ -0,0 +1,57 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.InnerWhere;
import aiyh.utils.sqlUtil.whereUtil.InnerWhereOperator;
import aiyh.utils.sqlUtil.whereUtil.Where;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 22:18
*/
public class InnerPrepWhereImpl implements InnerWhere {
private final InnerPrepWhereOperatorImpl whereOperator;
private final PrepWhereImpl prepWhere;
public InnerPrepWhereOperatorImpl getWhereOperator() {
return whereOperator;
}
{
this.whereOperator = new InnerPrepWhereOperatorImpl(this);
}
public InnerPrepWhereImpl(PrepWhereImpl prepWhere) {
this.prepWhere = prepWhere;
}
@Override
public InnerWhereOperator whereAnd(String key) {
this.whereAppend(" and ");
this.whereAppend(key);
return this.whereOperator;
}
@Override
public InnerWhereOperator whereOr(String key) {
this.whereAppend(" or ");
this.whereAppend(key);
return this.whereOperator;
}
@Override
public Where endInnerWhere() {
this.whereAppend(" ) ");
return this.prepWhere;
}
public void whereAppend(Object key) {
this.prepWhere.whereAppend(key);
}
public void addArgs(Object key) {
this.prepWhere.addArgs(key);
}
}

View File

@ -0,0 +1,241 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.InnerWhere;
import aiyh.utils.sqlUtil.whereUtil.InnerWhereOperator;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 22:20
*/
public class InnerPrepWhereOperatorImpl implements InnerWhereOperator {
private final InnerPrepWhereImpl innerPrepWhere;
public InnerPrepWhereOperatorImpl(InnerPrepWhereImpl innerPrepWhere) {
this.innerPrepWhere = innerPrepWhere;
}
@Override
public InnerWhere whereNull() {
this.innerPrepWhere.whereAppend(" is null ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotNull() {
this.innerPrepWhere.whereAnd(" is not null ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereEqual(Object value) {
this.innerPrepWhere.whereAppend(" = ? ");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotEqual(Object value) {
this.innerPrepWhere.whereAppend(" <> ? ");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere greaterThan(Object value) {
this.innerPrepWhere.whereAppend(" > ? ");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere lessThan(Object value) {
this.innerPrepWhere.whereAppend(" < ? ");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere greaterOrEqual(Object value) {
this.innerPrepWhere.whereAppend(" >= ? ");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere lessThanOrEqual(Object value) {
this.innerPrepWhere.whereAppend(" <= ? ");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere BetweenAnd(Object start, Object end) {
this.innerPrepWhere.whereAppend(" between ? ");
this.innerPrepWhere.addArgs(start);
this.innerPrepWhere.whereAppend(" and ? ");
this.innerPrepWhere.addArgs(end);
return this.innerPrepWhere;
}
@Override
public InnerWhere whereIn(Object... values) {
this.innerPrepWhere.whereAppend(" in ( ");
for (int i = 0; i < values.length; i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(values[i]);
if (i < values.length - 1) {
this.innerPrepWhere.whereAppend(",");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereInList(List<Object> list) {
this.innerPrepWhere.whereAppend(" in ( ");
for (int i = 0; i < list.size(); i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(list.get(i));
if (i < list.size() - 1) {
this.innerPrepWhere.whereAppend(",");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotIn(Object... values) {
this.innerPrepWhere.whereAppend(" not in ( ");
for (int i = 0; i < values.length; i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(values[i]);
if (i < values.length - 1) {
this.innerPrepWhere.whereAppend(",");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotInList(List<Object> list) {
this.innerPrepWhere.whereAppend(" not in ( ");
for (int i = 0; i < list.size(); i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(list.get(i));
if (i < list.size() - 1) {
this.innerPrepWhere.whereAppend(", ");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere inSql(Object sql) {
this.innerPrepWhere.whereAppend(" in ( ");
this.innerPrepWhere.whereAppend(sql);
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere notInSql(Object sql) {
this.innerPrepWhere.whereAppend(" not in ( ");
this.innerPrepWhere.whereAppend(sql);
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereLike(Object value) {
this.innerPrepWhere.whereAppend(" like ?");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotLike(Object value) {
this.innerPrepWhere.whereAppend(" not like ?");
this.innerPrepWhere.addArgs(value);
return this.innerPrepWhere;
}
@Override
public InnerWhere whereExists(Object... values) {
this.innerPrepWhere.whereAppend(" exists ( ");
for (int i = 0; i < values.length; i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(values[i]);
if (i < values.length - 1) {
this.innerPrepWhere.whereAppend(",");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotExists(Object... values) {
this.innerPrepWhere.whereAppend(" not exists ( ");
for (int i = 0; i < values.length; i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(values[i]);
if (i < values.length - 1) {
this.innerPrepWhere.whereAppend(",");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereExistsList(List<Object> list) {
this.innerPrepWhere.whereAppend(" exists ( ");
for (int i = 0; i < list.size(); i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(list.get(i));
if (i < list.size() - 1) {
this.innerPrepWhere.whereAppend(", ");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotExistsList(List<Object> list) {
this.innerPrepWhere.whereAppend(" not exists ( ");
for (int i = 0; i < list.size(); i++) {
this.innerPrepWhere.whereAppend(" ? ");
this.innerPrepWhere.addArgs(list.get(i));
if (i < list.size() - 1) {
this.innerPrepWhere.whereAppend(", ");
}
}
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereExistsSql(Object sql) {
this.innerPrepWhere.whereAppend(" exists ( ");
this.innerPrepWhere.whereAppend(sql);
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
@Override
public InnerWhere whereNotExistsSql(Object sql) {
this.innerPrepWhere.whereAppend(" not exists ( ");
this.innerPrepWhere.whereAppend(sql);
this.innerPrepWhere.whereAppend(" ) ");
return this.innerPrepWhere;
}
}

View File

@ -0,0 +1,55 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.InnerWhere;
import aiyh.utils.sqlUtil.whereUtil.InnerWhereOperator;
import aiyh.utils.sqlUtil.whereUtil.Where;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 13:18
*
*/
@Deprecated
public class InnerWhereImpl implements InnerWhere {
private final InnerWhereOperator whereOperator;
private final WhereImpl where;
{
this.whereOperator = new InnerWhereOperatorImpl(this);
}
public InnerWhereOperator getWhereOperator() {
return whereOperator;
}
public InnerWhereImpl(WhereImpl where) {
this.where = where;
}
@Override
public InnerWhereOperator whereAnd(String key) {
this.where.whereAppend(" and ");
this.where.whereAppend(key);
return this.whereOperator;
}
@Override
public InnerWhereOperator whereOr(String key) {
this.where.whereAppend(" or ");
this.where.whereAppend(key);
return this.whereOperator;
}
@Override
public Where endInnerWhere() {
this.where.whereAppend(" ) ");
return this.where;
}
public void whereAppend(Object key){
this.where.whereAppend(key);
}
}

View File

@ -0,0 +1,277 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.InnerWhere;
import aiyh.utils.sqlUtil.whereUtil.InnerWhereOperator;
import weaver.conn.RecordSet;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 13:23
*/
@Deprecated
public class InnerWhereOperatorImpl implements InnerWhereOperator {
private final InnerWhereImpl where;
private String DB_TYPE;
{
// 获取当前数据库的类型
this.DB_TYPE = (new RecordSet()).getDBType();
}
public InnerWhereOperatorImpl(InnerWhereImpl where) {
this.where = where;
}
@Override
public InnerWhere whereNull() {
this.where.whereAppend(" is null ");
return this.where;
}
@Override
public InnerWhere whereNotNull() {
this.where.whereAnd(" is not null ");
return this.where;
}
@Override
public InnerWhere whereEqual(Object value) {
this.where.whereAppend(" = ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere whereNotEqual(Object value) {
this.where.whereAppend(" <> ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere greaterThan(Object value) {
this.where.whereAppend(" > ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere lessThan(Object value) {
this.where.whereAppend(" < ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere greaterOrEqual(Object value) {
this.where.whereAppend(" >= ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere lessThanOrEqual(Object value) {
this.where.whereAppend(" <= ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere BetweenAnd(Object start, Object end) {
this.where.whereAppend(" between ");
this.where.whereAppend("'");
this.where.whereAppend(start);
this.where.whereAppend("'");
this.where.whereAppend(" and ");
this.where.whereAppend("'");
this.where.whereAppend(end);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere whereIn(Object... values) {
this.where.whereAppend(" in ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereInList(List<Object> list) {
this.where.whereAppend(" in ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereNotIn(Object... values) {
this.where.whereAppend(" not in ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereNotInList(List<Object> list) {
this.where.whereAppend(" not in ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere inSql(Object sql) {
this.where.whereAppend(" in ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere notInSql(Object sql) {
this.where.whereAppend(" not in ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereLike(Object value) {
this.where.whereAppend(" like ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere whereNotLike(Object value) {
this.where.whereAppend(" not like ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public InnerWhere whereExists(Object... values) {
this.where.whereAppend(" exists ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereNotExists(Object... values) {
this.where.whereAppend(" not exists ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereExistsList(List<Object> list) {
this.where.whereAppend(" exists ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereNotExistsList(List<Object> list) {
this.where.whereAppend(" not exists ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereExistsSql(Object sql) {
this.where.whereAppend(" exists ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public InnerWhere whereNotExistsSql(Object sql) {
this.where.whereAppend(" not exists ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
}

View File

@ -0,0 +1,77 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.InnerWhereOperator;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.WhereOperator;
import java.util.ArrayList;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 13:18
*
*/
public class PrepWhereImpl implements Where {
private final WhereOperator whereOperator;
private final StringBuilder sqlBuilder;
private final List<Object> args;
private final InnerPrepWhereImpl innerWhere;
{
this.whereOperator = new PrepWhereOperatorImpl(this);
this.sqlBuilder = new StringBuilder("where 1 = 1 ");
this.args = new ArrayList<>();
this.innerWhere = new InnerPrepWhereImpl(this);
}
@Override
public WhereOperator whereAnd(String key) {
this.sqlBuilder.append(" and ");
this.sqlBuilder.append(key);
return this.whereOperator;
}
@Override
public WhereOperator whereOr(String key) {
this.sqlBuilder.append(" or ");
this.sqlBuilder.append(key);
return this.whereOperator;
}
@Override
public InnerWhereOperator andInnerWhere(String key){
this.sqlBuilder.append(" and ( ");
this.sqlBuilder.append(key);
return this.innerWhere.getWhereOperator();
}
@Override
public InnerWhereOperator orInnerWhere(String key){
this.sqlBuilder.append(" or ( ");
this.sqlBuilder.append(key);
return this.innerWhere.getWhereOperator();
}
public void whereAppend(Object key){
this.sqlBuilder.append(key);
}
public void addArgs(Object value){
this.args.add(value);
}
@Override
public String getSql(){
return this.sqlBuilder.toString().replace(" 1 = 1 and", "").replace(" 1 = 1 or","");
}
@Override
public List<Object> getArgs() {
return this.args;
}
}

View File

@ -0,0 +1,220 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import org.jetbrains.annotations.NotNull;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.WhereOperator;
import weaver.conn.RecordSet;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 13:23
*/
public class PrepWhereOperatorImpl implements WhereOperator {
private final PrepWhereImpl where;
private String DB_TYPE;
{
// 获取当前数据库的类型
this.DB_TYPE = (new RecordSet()).getDBType();
}
public PrepWhereOperatorImpl(PrepWhereImpl where) {
this.where = where;
}
@Override
public Where whereNull() {
this.where.whereAppend(" is null ");
return this.where;
}
@Override
public Where whereNotNull() {
this.where.whereAnd(" is not null ");
return this.where;
}
@Override
public Where whereEqual(Object value) {
this.where.whereAppend(" = ? ");
this.where.addArgs(value);
return this.where;
}
@Override
public Where whereNotEqual(Object value) {
this.where.whereAppend(" <> ? ");
this.where.addArgs(value);
return this.where;
}
@Override
public Where greaterThan(Object value) {
this.where.whereAppend(" > ? ");
this.where.addArgs(value);
return this.where;
}
@Override
public Where lessThan(Object value) {
this.where.whereAppend(" < ? ");
this.where.addArgs(value);
return this.where;
}
@Override
public Where greaterOrEqual(Object value) {
this.where.whereAppend(" >= ? ");
this.where.addArgs(value);
return this.where;
}
@Override
public Where lessThanOrEqual(Object value) {
this.where.whereAppend(" <= ? ");
this.where.addArgs(value);
return this.where;
}
@Override
public Where BetweenAnd(Object start, Object end) {
this.where.whereAppend(" between ? ");
this.where.addArgs(start);
this.where.whereAppend(" and ? ");
this.where.addArgs(end);
return this.where;
}
@Override
public Where whereIn(Object... values) {
this.where.whereAppend(" in ( ");
return getWhere(values);
}
@NotNull
private Where getWhere(Object[] values) {
for (int i = 0; i < values.length; i++) {
this.where.whereAppend(" ? ");
this.where.addArgs(values[i]);
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereInList(List<Object> list) {
this.where.whereAppend(" in ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend(" ? ");
this.where.addArgs(list.get(i));
if (i < list.size() - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotIn(Object ...values) {
this.where.whereAppend(" not in ( ");
return getWhere(values);
}
@Override
public Where whereNotInList(List<Object> list) {
this.where.whereAppend(" not in ( ");
return getWhere(list);
}
@Override
public Where inSql(Object sql) {
this.where.whereAppend(" in ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where notInSql(Object sql) {
this.where.whereAppend(" not in ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereLike(Object value) {
this.where.whereAppend(" like ?");
this.where.addArgs(value);
return this.where;
}
@Override
public Where whereNotLike(Object value) {
this.where.whereAppend(" not like ?");
this.where.addArgs(value);
return this.where;
}
@Override
public Where whereExists(Object ...values) {
this.where.whereAppend(" exists ( ");
return getWhere(values);
}
@Override
public Where whereNotExists(Object ...values) {
this.where.whereAppend(" not exists ( ");
return getWhere(values);
}
@Override
public Where whereExistsList(List<Object> list) {
this.where.whereAppend(" exists ( ");
return getWhere(list);
}
@Override
public Where whereNotExistsList(List<Object> list) {
this.where.whereAppend(" not exists ( ");
return getWhere(list);
}
@NotNull
private Where getWhere(List<Object> list) {
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend(" ? ");
this.where.addArgs(list.get(i));
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereExistsSql(Object sql) {
this.where.whereAppend(" exists ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotExistsSql(Object sql) {
this.where.whereAppend(" not exists ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
}

View File

@ -0,0 +1,68 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.InnerWhereOperator;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.WhereOperator;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 13:18
*
*/
@Deprecated
public class WhereImpl implements Where {
private final WhereOperator whereOperator;
private final StringBuilder sqlBuilder;
private final InnerWhereImpl innerWhere;
{
this.whereOperator = new WhereOperatorImpl(this);
this.sqlBuilder = new StringBuilder("where 1 = 1 ");
this.innerWhere = new InnerWhereImpl(this);
}
@Override
public WhereOperator whereAnd(String key) {
this.sqlBuilder.append(" and ");
this.sqlBuilder.append(key);
return this.whereOperator;
}
@Override
public WhereOperator whereOr(String key) {
this.sqlBuilder.append(" or ");
this.sqlBuilder.append(key);
return this.whereOperator;
}
@Override
public InnerWhereOperator andInnerWhere(String key){
this.sqlBuilder.append(" and ( ");
this.sqlBuilder.append(key);
return innerWhere.getWhereOperator();
}
@Override
public InnerWhereOperator orInnerWhere(String key){
this.sqlBuilder.append(" or ( ");
this.sqlBuilder.append(key);
return innerWhere.getWhereOperator();
}
public void whereAppend(Object key){
this.sqlBuilder.append(key);
}
@Override
public String getSql(){
return this.sqlBuilder.toString().replace(" 1 = 1 and", "").replace(" 1 = 1 or","");
}
@Override
public List<Object> getArgs() {
return null;
}
}

View File

@ -0,0 +1,277 @@
package aiyh.utils.sqlUtil.whereUtil.impl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.sqlUtil.whereUtil.WhereOperator;
import weaver.conn.RecordSet;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/23 0023 13:23
*/
@Deprecated
public class WhereOperatorImpl implements WhereOperator {
private final WhereImpl where;
private String DB_TYPE;
{
// 获取当前数据库的类型
this.DB_TYPE = (new RecordSet()).getDBType();
}
public WhereOperatorImpl(WhereImpl where) {
this.where = where;
}
@Override
public Where whereNull() {
this.where.whereAppend(" is null ");
return this.where;
}
@Override
public Where whereNotNull() {
this.where.whereAnd(" is not null ");
return this.where;
}
@Override
public Where whereEqual(Object value) {
this.where.whereAppend(" = ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where whereNotEqual(Object value) {
this.where.whereAppend(" <> ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where greaterThan(Object value) {
this.where.whereAppend(" > ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where lessThan(Object value) {
this.where.whereAppend(" < ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where greaterOrEqual(Object value) {
this.where.whereAppend(" >= ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where lessThanOrEqual(Object value) {
this.where.whereAppend(" <= ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where BetweenAnd(Object start, Object end) {
this.where.whereAppend(" between ");
this.where.whereAppend("'");
this.where.whereAppend(start);
this.where.whereAppend("'");
this.where.whereAppend(" and ");
this.where.whereAppend("'");
this.where.whereAppend(end);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where whereIn(Object... values) {
this.where.whereAppend(" in ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereInList(List<Object> list) {
this.where.whereAppend(" in ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotIn(Object... values) {
this.where.whereAppend(" not in ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotInList(List<Object> list) {
this.where.whereAppend(" not in ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where inSql(Object sql) {
this.where.whereAppend(" in ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where notInSql(Object sql) {
this.where.whereAppend(" not in ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereLike(Object value) {
this.where.whereAppend(" like ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where whereNotLike(Object value) {
this.where.whereAppend(" not like ");
this.where.whereAppend("'");
this.where.whereAppend(value);
this.where.whereAppend("'");
return this.where;
}
@Override
public Where whereExists(Object... values) {
this.where.whereAppend(" exists ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotExists(Object... values) {
this.where.whereAppend(" not exists ( ");
for (int i = 0; i < values.length; i++) {
this.where.whereAppend("'");
this.where.whereAppend(values[i]);
this.where.whereAppend("'");
if (i < values.length - 1) {
this.where.whereAppend(",");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereExistsList(List<Object> list) {
this.where.whereAppend(" exists ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotExistsList(List<Object> list) {
this.where.whereAppend(" not exists ( ");
for (int i = 0; i < list.size(); i++) {
this.where.whereAppend("'");
this.where.whereAppend(list.get(i));
this.where.whereAppend("'");
if (i < list.size() - 1) {
this.where.whereAppend(", ");
}
}
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereExistsSql(Object sql) {
this.where.whereAppend(" exists ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
@Override
public Where whereNotExistsSql(Object sql) {
this.where.whereAppend(" not exists ( ");
this.where.whereAppend(sql);
this.where.whereAppend(" ) ");
return this.where;
}
}

View File

@ -0,0 +1,98 @@
package aiyh.utils.zwl.common;
import weaver.common.StringUtil;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
/**
* Action
* @author bleach
* @date 2019-10-09
* @version 1.0
*/
public abstract class CusBaseAction extends ToolUtil implements Action {
//当前类名称
private String className = this.getClass().getName();
protected RequestInfo requestInfo;//流程请求信息实体类
protected RecordSetTrans rsts = null;//流程操作事务数据集
protected String tablename;//当前流程表单名称
protected String requestId;//流程请求ID
protected String workflowId;//流程类型ID
protected User user = null;//当前用户
protected int creater = -1;//流程创建人ID
protected RequestManager reqManager = null;
protected String[] baseArray = new String[3];
protected abstract String handle();//Action 具体操作
/**
*
*
* @param requestInfo requestInfo
* @return string
*/
@Override
public String execute(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
this.rsts = requestInfo.getRsTrans();
if (this.rsts == null) {
rsts = new RecordSetTrans();
}
this.initParam();
return handle();
}
/**
*
*/
private void initParam() {
this.requestId = StringUtil.vString(requestInfo.getRequestid());
this.workflowId = StringUtil.vString(requestInfo.getWorkflowid());
this.reqManager = requestInfo.getRequestManager();
this.user = reqManager.getUser();
this.creater = reqManager.getCreater();
this.tablename = requestInfo.getRequestManager().getBillTableName();
//通过系统请求管理类获取表单名称失败,再次查询
if ("".equals(this.tablename)) {
tablename = getBillTableNameByWorkflowId(this.workflowId);
}
//获取流程基础数据
String select_base_sql = "select * from workflow_requestbase where requestid = ?";
try {
if (rsts == null) {
rsts = new RecordSetTrans();
}
String request_name = "";
String request_mark = "";
if (rsts.executeQuery(select_base_sql, requestId)) {
while (rsts.next()) {
request_name = Util.null2String(rsts.getString("requestname"));
request_mark = Util.null2String(rsts.getString("requestmark"));
}
}
baseArray[0] = this.requestId;
baseArray[1] = request_name;
baseArray[2] = request_mark;
this.writeNewDebuggerLog(className, "main_requestname:[" + request_name + "],main_requestmark:[" + request_mark + "],workflowid:[" + workflowId + "],requestid:[" + requestId + "],tablename:[" + tablename + "]");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
this.writeNewDebuggerLog(className, "get workflow dataset error:[" + e1.getMessage() + "/" + e1.toString() + "]");
}
}
}

View File

@ -0,0 +1,501 @@
package aiyh.utils.zwl.common;
import aiyh.utils.zwl.common.logging.Logger;
import aiyh.utils.zwl.common.logging.LoggerFactory;
import weaver.conn.ConnStatementDataSource;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;
import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* -
* @author bleach
* @date 2018-01-18
* @version 2.0 Modify By Weilin.Zhu 2018-12-05
* @version 3.0 Modify By Weilin.Zhu 使log4j 2020-03-10
*/
public class ToolUtil extends BaseBean {
Logger logger = LoggerFactory.getLogger("cus");
/**
*
*/
boolean isDebug = true;
/**
* 0[Debugger] 1[Warning] 2[Error]
*/
private int logLevel = 2;
private RecordSet rs = new RecordSet();
/**
*
*/
public ToolUtil() {
// TODO Auto-generated constructor stub
logger = LoggerFactory.getLogger("cus");
//是否开启日志模式
String isopen = getSystemParamValue("Debug_Mode");
//输出日志级别
logLevel = Util.getIntValue(getSystemParamValue("Logger_Level"),-1);
if("1".equals(isopen)){
isDebug = true;
}
}
/**
* ID
* @param workflowid ID
* @return
*/
public String getBillTableNameByWorkflowId(String workflowid){
String tablename = "";
if(!"".equals(workflowid)){
String select_data = "select tablename from workflow_bill where id in (select formid from workflow_base where id = ?)";
if(rs.executeQuery(select_data, workflowid)){
if(rs.next()){
tablename = Util.null2String(rs.getString(1));
}
}
}
return tablename;
}
/**
*
* @param likestr
* @return
*/
public Map<String,String> getSystemParamValueMap(String likestr){
return getSystemParamList(likestr);
}
/**
*
* @return
*/
public Map<String,String> getAllSystemParamValue(){
return getSystemParamList("");
}
/**
*
* @param likestr
* @return
*/
private Map<String,String> getSystemParamList(String likestr){
Map<String,String> param_map = new HashMap<String, String>();
String select_sql = "select uuid,paramvalue from uf_systemconfig";
RecordSet rs = new RecordSet();
if(!"".equals(likestr)){
select_sql += " where uuid like '%" + likestr + "%'";
}
if(rs.execute(select_sql)){
while(rs.next()){
String uuid = Util.null2String(rs.getString(1));
String paramvalue = Util.null2String(rs.getString(2));
param_map.put(uuid, paramvalue);
}
}
return param_map;
}
/**
*
* @param uuid
* @return
*/
public String getSystemParamValue(String uuid){
String paramvalue = "";
if(!"".equals(uuid)){
String select_sql = "select paramvalue from uf_systemconfig where uuid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(select_sql,uuid);
if(rs.next()){
paramvalue = Util.null2String(rs.getString(1));
}
}
return paramvalue;
}
/**
*
* @param cus_sql SQL
* @param value
* @return
*/
public String getValueByChangeRule(String cus_sql,String value){
return getValueByChangeRule(cus_sql,value,"");
}
/**
*
* @param cus_sql SQL
* @param value
* @param requestid ID
* @return
*/
public String getValueByChangeRule(String cus_sql,String value,String requestid){
return getValueByChangeRule(cus_sql,value,requestid,0);
}
/**
*
* @param cus_sql SQL
* @param value
* @param requestid ID
* @param detailKeyvalue
* @return
*/
public String getValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue){
return getValueByChangeRule(cus_sql,value,requestid,detailKeyvalue,null);
}
/**
*
* @param cus_sql SQL
* @param value
* @param requestid ID
* @param detailKeyvalue
* @param datasourceid ID
* @return
*/
public String getValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue,String datasourceid){
String endValue = "";
cus_sql = cus_sql.replace("&nbsp;", " ");
cus_sql = cus_sql.replace("{?dt.id}", String.valueOf(detailKeyvalue));
//参数进行替换
String sqlString = cus_sql.replace("{?requestid}", requestid);
sqlString = sqlString.replace("?", value);
sqlString = ToDBC(sqlString);
try {
if(datasourceid != null && !"".equals(datasourceid)){
ConnStatementDataSource csds = new ConnStatementDataSource(datasourceid);
csds.setStatementSql(sqlString);
csds.executeQuery();
if(csds.next()){
endValue = Util.null2String(csds.getString(1));
}
csds.close();
}else{
RecordSet rs = new RecordSet();
if(rs.executeQuery(sqlString)){
rs.next();
endValue = Util.null2String(rs.getString(1));
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return endValue;
}
/**
*
* @param cus_sql SQL
* @param value
* @return
*/
public String getValueByChangeRule_SingleParam(String cus_sql,String value){
String endValue = "";
cus_sql = cus_sql.replace("&nbsp;", " ");
RecordSet rs = new RecordSet();
if(rs.executeQuery(cus_sql,value)){
rs.next();
endValue = Util.null2String(rs.getString(1));
}
return endValue;
}
/**
*
* @param input
* @return
*/
public String ToDBC(String input) {
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
/**
* ID
* @param fieldid id
* @return
*/
public String getFieldNameByFieldid(int fieldid){
if(fieldid > 0){
return getFieldNameByFieldid(String.valueOf(fieldid));
}else{
return "";
}
}
/**
* ID
* @param fieldid id
* @return
*/
public String getFieldNameByFieldid(String fieldid){
String fieldname = "";
if(!"".equals(fieldid)){
if(fieldid.startsWith(",")){
fieldid = fieldid.substring(1);
}
if(fieldid.endsWith(",")){
fieldid =fieldid.substring(0,fieldid.length() - 1);
}
String select_sql = "select fieldname from workflow_billfield where id in (" + fieldid + ")";
RecordSet rs = new RecordSet();
if(rs.execute(select_sql)){
while(rs.next()){
fieldname += "," + Util.null2String(rs.getString(1));
}
}
}
if(fieldname.startsWith(",")){
fieldname = fieldname.substring(1);
}
return fieldname;
}
/**
*
* @param logstr
*/
public void writeDebuggerLog(String logstr){
if(logLevel >= 0){
logger.info(logstr);
}
}
/**
*
* @param className
* @param logstr
*/
public void writeDebuggerLog(String className,String logstr){
if(logLevel >= 0){
logger.info(logstr);
}
}
/**
*
* @param logstr
*/
public void writeWarningLog(String logstr){
if(logLevel >= 1){
logger.warn(logstr);
}
}
/**
*
* @param className
* @param logstr
*/
public void writeWarningLog(String className,String logstr){
if(logLevel >= 1){
logger.warn(logstr);
}
}
/**
*
* @param logstr
*/
public void writeErrorLog(String logstr){
logger.error(logstr);
}
/**
*
* @param className
* @param logstr
*/
public void writeErrorLog(String className,String logstr){
logger.error(logstr);
}
/**
*
* @param logstr
*/
public void writeDebugLog(Object logstr){
logger.info(logstr);
}
/**
*
* @param logstr
* @param o
*/
public void writeNewDebuggerLog(Object o,Object logstr){
logger.info(logstr);
}
/**
*
* @param o
* @param s
* @deprecated
*/
protected void writeNewLog(String o,String s){
try {
String filename = "cus_" + TimeUtil.getCurrentDateString() + "_ecology.log";
String folder = GCONST.getRootPath() + "log" + File.separatorChar + "cus";
//this.writeDebugLog("folder:[" + folder + "]");
File f = new File(folder);
// 创建文件夹
if (!f.exists()) {
f.mkdirs();
}
f = new File(folder + File.separatorChar + filename);
//文件不存在,则直接创建
if(!f.exists()){
f.createNewFile();
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, true)));
out.write("[" + o + "][" + TimeUtil.getCurrentTimeString() + "]:"+ s + "\r\n");
//关闭写入流
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
writeDebugLog("创建日志文件存在异常:[" + e.getMessage() + "/" + e.toString() + "]");
}
}
/**
* ID
* @param modeid ID
* @return
*/
public String getTableNameByModeID(int modeid){
String modeTableName = "";
if(modeid > 0){
String select_sql = "select tablename from modeinfo m left join workflow_bill wb on m.formid = wb.id " +
"left join ModeFormExtend me on me.formid = wb.id where m.id = ?";
RecordSet rs = new RecordSet();
if(rs.executeQuery(select_sql,modeid)){
if(rs.next()){
modeTableName = Util.null2String(rs.getString(1));
}
}
}
return modeTableName;
}
/**
* ID
* @param requestid id
* @return
*/
public String getTableNameByRequestID(int requestid) {
String billTableName = "";
if(requestid > 0) {
String select_sql = "select wbi.tablename from workflow_requestbase wr inner join workflow_base wb on wr.workflowid = wb.id "
+ "inner join workflow_bill wbi on wbi.id = wb.formid where wr.requestid = ?";
RecordSet rs = new RecordSet();
if(rs.executeQuery(select_sql,requestid)){
if(rs.next()){
billTableName = Util.null2String(rs.getString(1));
}
}
}
return billTableName;
}
/**
* @return the isDebug
*/
public boolean isDebug() {
return isDebug;
}
}

View File

@ -0,0 +1,89 @@
package aiyh.utils.zwl.common.logging;
/**
* log4j
* @date 2020-03-10
* @version 1.0
*/
public class Log4JLogger implements Logger {
private org.apache.log4j.Logger log;
//类名
private String classname;
@Override
public String getClassname() {
return classname;
}
@Override
public void setClassname(String classname) {
this.classname = classname;
}
@Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return log.isInfoEnabled();
}
@Override
public void debug(Object message) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.debug(classname+"."+method+"() - "+message);
}
@Override
public void debug(Object message, Throwable exception) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.debug(classname+"."+method+"() - "+message, exception);
}
@Override
public void info(Object message) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.info(classname+"."+method+"() - "+message);
}
@Override
public void info(Object message, Throwable exception) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.info(classname+"."+method+"() - "+message, exception);
}
@Override
public void warn(Object message) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.warn(classname+"."+method+"() - "+message);
}
@Override
public void warn(Object message, Throwable exception) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.warn(classname+"."+method+"() - "+message, exception);
}
@Override
public void error(Object message) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.error(classname+"."+method+"() - "+message);
}
@Override
public void error(Object message, Throwable exception) {
String method = Thread.currentThread().getStackTrace()[2].getMethodName();
log.error(classname+"."+method+"() - "+message, exception);
}
@Override
public void init(String name) {
if("".equals(name)) {
name = "cuslog";
}
log = org.apache.log4j.Logger.getLogger(name);
}
}

View File

@ -0,0 +1,78 @@
package aiyh.utils.zwl.common.logging;
/**
*
*
* @author zwl
* @date 2020-03-10
*/
public interface Logger {
public boolean isDebugEnabled();
/**
* debug
* @param message
*/
public void debug(Object message);
/**
* debug
* @param message
* @param exception
*/
public void debug(Object message, Throwable exception);
public boolean isInfoEnabled();
/**
* info
* @param message
*/
public void info(Object message);
/**
* info
* @param message
* @param exception
*/
public void info(Object message, Throwable exception);
/**
* warn
* @param message
*/
public void warn(Object message);
/**
* warn
* @param message
* @param exception
*/
public void warn(Object message, Throwable exception);
/**
* error
* @param message
*/
public void error(Object message);
/**
* error
* @param message
* @param exception
*/
public void error(Object message, Throwable exception);
public String getClassname();
public void setClassname(String classname);
/**
*
*
* @param name logger
*/
public void init(String name);
}

View File

@ -0,0 +1,49 @@
package aiyh.utils.zwl.common.logging;
/**
*
*
* @author zwl
* @date 2020-03-10
* @version 1.0
*/
public class LoggerFactory {
private static final String loggerName = "cus";
public static Logger getLogger(String LogName, String clazz) {
if("".equals(LogName)) {
LogName = loggerName;
}
Logger logger = new Log4JLogger();
logger.setClassname(clazz);
logger.init(LogName);
return logger;
}
/**
* logger
* @param clazz
* @return
*/
public static Logger getLogger(Class<?> clazz) {
return getLogger(loggerName,clazz.getCanonicalName());
}
/**
* logger
* @param className
* @return
*/
public static Logger getLogger(String className) {
return getLogger(loggerName,className);
}
/**
* logger
* @return
*/
public static Logger getLogger() {
String className = Thread.currentThread().getStackTrace()[2].getClassName();
return getLogger(loggerName, className);
}
}

BIN
com/.DS_Store vendored Normal file

Binary file not shown.

BIN
com/api/aiyh_guijiu.zip Normal file

Binary file not shown.

View File

@ -0,0 +1,212 @@
package com.api.aiyh_guijiu.dao;
import aiyh.utils.Util;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_guijiu.pojo.UfWorkflowConflicDt1DTO;
import com.api.aiyh_guijiu.pojo.WorkflowBaseInfoDTO;
import com.api.aiyh_guijiu.pojo.WorkflowConfigDTO;
import com.api.aiyh_guijiu.vo.ConfigInfoVo;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.workflow.workflow.WorkflowVersion;
import java.util.ArrayList;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/10 0010 11:27
*
*/
public class ConflictWorkflowDao {
RecordSet rs = new RecordSet();
ToolUtil toolUtil = new ToolUtil();
public List<WorkflowConfigDTO> queryConfig(String workflowId) {
String query = "select * from uf_workflow_conflic_dt1 " +
"where workflow_type in (select id from workflow_base " +
"where activeVersionID in (select activeVersionID " +
"from workflow_base where id = ?) or id = ?)";
rs.executeQuery(query, workflowId, workflowId);
UfWorkflowConflicDt1DTO ufWorkflowConflicDt1DTO = Util.recordeSet2Entity(rs, UfWorkflowConflicDt1DTO.class, true);
if (ufWorkflowConflicDt1DTO == null) {
return null;
}
// String ids = WorkflowVersion.getVersionStringByWfid(workflowId);
query = "select dt.id,dt.workflow_type,main.enable,wf.tablename,wf.fieldname start_date_field, " +
"wf1.fieldname start_time_field,wf2.fieldname end_date_field,wf4.fieldname hrm_field, " +
"wf3.fieldname end_time_field from uf_workflow_conflic main " +
"left join uf_workflow_conflic_dt1 dt on dt.mainid = main.id " +
"left join workflow_field_table_view wf on wf.id = dt.start_date_field " +
"left join workflow_field_table_view wf1 on wf1.id = dt.start_time_field " +
"left join workflow_field_table_view wf2 on wf2.id = dt.end_date_field " +
"left join workflow_field_table_view wf3 on wf3.id = dt.end_time_field " +
"left join workflow_field_table_view wf4 on wf4.id = dt.hrm_field " +
"where main.id = ? and main.enable = 0";
// and dt.workflow_type not in (" + ids + ")
rs.executeQuery(query, ufWorkflowConflicDt1DTO.getMainid());
return Util.recordeSet2Array(rs, WorkflowConfigDTO.class, true);
}
public List<WorkflowBaseInfoDTO> queryConflict(WorkflowConfigDTO workflowConfigDTO, String startTime
, String startDate, String endTime, String endDate, String hrmId, String requestId) {
// (a,b)(c,d) == > (2021-09-10 12:00:23 , 2021-09-10 20:00:23) (2021-09-10 15:00:23 , 2021-09-10 19:00:23)
// select * from table where (hrm = ? or hrm like "%?%") and a <= d and b >= c and requestid != requestId;
String query = "select id from " + workflowConfigDTO.getTablename() +
" where (',' || " + workflowConfigDTO.getHrmField() +" || ',') like ('%,' || '" + hrmId + "' || ',%') " +
" and requestid != " + requestId + " and " + workflowConfigDTO.getStartDateField() + " is not null " +
" and " + workflowConfigDTO.getEndDateField() + " is not null" +
(StringUtils.isNullOrEmpty(workflowConfigDTO.getStartTimeField()) ? "" : " and " + workflowConfigDTO.getStartTimeField() + " is not null") +
(StringUtils.isNullOrEmpty(workflowConfigDTO.getEndTimeField()) ? "" : " and " + workflowConfigDTO.getEndTimeField() + " is not null");
rs.executeQuery(query);
List<String> integers = Util.recordeSet2Array(rs, String.class);
String ids = String.join(",", integers);
if(StringUtils.isNullOrEmpty(ids)){
ids = "-1";
}
query = "select * from " +
workflowConfigDTO.getTablename() +
" where to_date(concat(" +
workflowConfigDTO.getStartDateField() +
" || ' ' ," +
(StringUtils.isNullOrEmpty(workflowConfigDTO.getStartTimeField()) ? "'00:00:00'" : workflowConfigDTO.getStartTimeField()) +
"), 'yyyy-mm-dd hh24:mi:ss') <= to_date('" +
endDate +
" " +
(StringUtils.isNullOrEmpty(endTime) ? "23:59:59" : endTime) +
"', 'yyyy-mm-dd hh24:mi:ss')" +
" and to_date(concat(" +
workflowConfigDTO.getEndDateField() +
" || ' ' ," +
(StringUtils.isNullOrEmpty(workflowConfigDTO.getEndTimeField()) ? "'23:59:59'" : workflowConfigDTO.getEndTimeField()) +
"), 'yyyy-mm-dd hh24:mi:ss') >= to_date('" +
startDate +
" " +
(StringUtils.isNullOrEmpty(startTime) ? "00:00:00" : startTime) +
"', 'yyyy-mm-dd hh24:mi:ss') " +
" and id in (" + ids + ")";
/*query = "select * from " +
workflowConfigDTO.getTablename() +
" where to_date(concat(" +
workflowConfigDTO.getStartDateField() +
" || ' ' ," +
(StringUtils.isNullOrEmpty(workflowConfigDTO.getStartTimeField()) ? "'00:00:00'" : workflowConfigDTO.getStartTimeField()) +
"), 'yyyy-mm-dd hh24:mi:ss') <= to_date('" +
endDate +
" " +
(StringUtils.isNullOrEmpty(endTime) ? "23:59:59" : endTime) +
"', 'yyyy-mm-dd hh24:mi:ss')" +
" and to_date(concat(" +
workflowConfigDTO.getEndDateField() +
" || ' ' ," +
(StringUtils.isNullOrEmpty(workflowConfigDTO.getEndTimeField()) ? "'23:59:59'" : workflowConfigDTO.getEndTimeField()) +
"), 'yyyy-mm-dd hh24:mi:ss') >= to_date('" +
startDate +
" " +
(StringUtils.isNullOrEmpty(startTime) ? "00:00:00" : startTime) +
"', 'yyyy-mm-dd hh24:mi:ss') " +
" and " + " (',' || " + workflowConfigDTO.getHrmField() + " || ',') like " + " ('%,' || '" + hrmId + "' || ',%') " +
" and requestid != " + requestId;*/
/*hrmId +
" in (select regexp_substr(hrm_str, '[^,]+', 1, level) " +
"from dual connect by regexp_substr(hrm_str, '[^,]+', 1, level) is not null)" +
" and requestid != " + requestId;*/
// toolUtil.writeErrorLog(query);
// System.out.println(query);
/*query = "select * from " + workflowConfigDTO.getTablename() + " where to_date(concat("
+ workflowConfigDTO.getStartDateField() + " || ' ' ," + workflowConfigDTO.getStartTimeField()
+ "), 'yyyy-mm-dd hh24:mi:ss') <= to_date(concat("
+ endDate + " " + endTime + "), 'yyyy-mm-dd hh24:mi:ss')"
+ " and " + workflowConfigDTO.getEndDateField() + " || ' ' ," + workflowConfigDTO.getEndTimeField()
+ "), 'yyyy-mm-dd hh24:mi:ss') >= to_date(concat("
+ startDate + " " + startTime + "), 'yyyy-mm-dd hh24:mi:ss') " + hrmId
+ " and in (select regexp_substr(hrm_str, '[^,]+', 1, level) " +
"from dual connect by regexp_substr(hrm_str, '[^,]+', 1, level) is not null)";*/
try {
rs.executeQuery(query);
}catch (Exception e){
toolUtil.writeErrorLog("查询重复的流程错误,错误信息:" + e);
}
List<WorkflowBaseInfoDTO> list = new ArrayList<>();
while(rs.next()){
// 存在时间段冲突的数据,查询冲突数据的流程信息
RecordSet rsT = new RecordSet();
requestId = Util.null2String(rs.getString("requestid"));
query = "select distinct wrb.requestid,wrb.workflowid,wrb.requestnamenew,wb.workflowname, " +
"(case when hr.lastname is null and wrb.creater != 1 then '未知' " +
"when wrb.creater = 1 then '系统管理员' else hr.lastname end) creater, " +
"wrb.createdate,wrb.createtime from workflow_requestbase wrb " +
"left join HrmResource hr on wrb.creater = hr.id " +
"left join workflow_base wb on wb.id = wrb.workflowid " +
"where wrb.requestid = ?";
rsT.executeQuery(query, requestId);
WorkflowBaseInfoDTO workflowBaseInfoDTO = Util.recordeSet2Entity(rsT, WorkflowBaseInfoDTO.class, true);
list.add(workflowBaseInfoDTO);
}
// if (rs.next()) {
// toolUtil.writeDebuggerLog("into next;");
//// 存在时间段冲突的数据,查询冲突数据的流程信息
// requestId = Util.null2String(rs.getString("requestid"));
// query = "select wrb.workflowid,wrb.requestid,wrb.requestnamenew,wb.workflowname, " +
// "(case when hr.lastname is null and wrb.creater != 1 then '未知' " +
// "when wrb.creater = 1 then '系统管理员' else hr.lastname end) creater, " +
// "wrb.createdate,wrb.createtime from workflow_requestbase wrb " +
// "left join HrmResource hr on wrb.creater = hr.id " +
// "left join workflow_base wb on wb.id = wrb.workflowid " +
// "where wrb.requestid = ?";
// rs.executeQuery(query, requestId);
// return Util.recordeSet2Entity(rs, WorkflowBaseInfoDTO.class, true);
// }
if(list.size() == 0){
return null;
}
return list;
}
public List<Integer> getWatermarkConfig(String workflowId) {
String query = "select id from workflow_base " +
"where activeVersionID in (select activeVersionID " +
"from workflow_base where id = ?) or id = ?";
rs.executeQuery(query, workflowId, workflowId);
return Util.recordeSet2Array(rs, Integer.class);
}
public WorkflowConfigDTO getWorkflowConfig(String workflowId){
String query = "select * from uf_workflow_conflic_dt1 " +
"where workflow_type in (select id from workflow_base " +
"where activeVersionID in (select activeVersionID " +
"from workflow_base where id = ?) or id = ?)";
rs.executeQuery(query, workflowId, workflowId);
UfWorkflowConflicDt1DTO ufWorkflowConflicDt1DTO = Util.recordeSet2Entity(rs, UfWorkflowConflicDt1DTO.class, true);
if (ufWorkflowConflicDt1DTO == null) {
return null;
}
String ids = WorkflowVersion.getVersionStringByWfid(workflowId);
query = "select dt.id,main.enable,wf.tablename,wf.fieldname start_date_field, " +
"wf1.fieldname start_time_field,wf2.fieldname end_date_field,wf4.fieldname hrm_field, " +
"wf3.fieldname end_time_field from uf_workflow_conflic main " +
"left join uf_workflow_conflic_dt1 dt on dt.mainid = main.id " +
"left join workflow_field_table_view wf on wf.id = dt.start_date_field " +
"left join workflow_field_table_view wf1 on wf1.id = dt.start_time_field " +
"left join workflow_field_table_view wf2 on wf2.id = dt.end_date_field " +
"left join workflow_field_table_view wf3 on wf3.id = dt.end_time_field " +
"left join workflow_field_table_view wf4 on wf4.id = dt.hrm_field " +
"where main.id = ? and main.enable = 0 and dt.workflow_type in (" + ids + ")";
rs.executeQuery(query, ufWorkflowConflicDt1DTO.getMainid());
return Util.recordeSet2Entity(rs,WorkflowConfigDTO.class,true);
}
public ConfigInfoVo getConfigInfo(String tableName,String workflowId){
String query = "select cf.workflow_type ,cf.workflow_node ,cf.enable ,wf.fieldname workflow_field from " + tableName +
" cf left join workflow_field_table_view wf on wf.id = cf.workflow_field " +
" where cf.workflow_type = ?";
rs.executeQuery(query,workflowId);
return Util.recordeSet2Entity(rs, ConfigInfoVo.class, true);
}
}

View File

@ -0,0 +1,83 @@
package com.api.aiyh_guijiu.pojo;
public class UfWorkflowConflicDt1DTO {
private int id;
private int mainid;
private int workflowType;
private String startDateField;
private String startTimeField;
private String endDateField;
private String endTimeField;
public void setId(int id){
this.id = id;
}
public void setMainid(int mainid){
this.mainid = mainid;
}
public void setWorkflowType(int workflowType){
this.workflowType = workflowType;
}
public void setStartDateField(String startDateField){
this.startDateField = startDateField;
}
public void setStartTimeField(String startTimeField){
this.startTimeField = startTimeField;
}
public void setEndDateField(String endDateField){
this.endDateField = endDateField;
}
public void setEndTimeField(String endTimeField){
this.endTimeField = endTimeField;
}
public int getId(){
return this.id;
}
public int getMainid(){
return this.mainid;
}
public int getWorkflowType(){
return this.workflowType;
}
public String getStartDateField(){
return this.startDateField;
}
public String getStartTimeField(){
return this.startTimeField;
}
public String getEndDateField(){
return this.endDateField;
}
public String getEndTimeField(){
return this.endTimeField;
}
@Override
public String toString() {
return "UfWorkflowConflicDt1DTO{" +
"id='" + id + '\'' +
", mainid='" + mainid + '\'' +
", workflowType='" + workflowType + '\'' +
", startDateField='" + startDateField + '\'' +
", startTimeField='" + startTimeField + '\'' +
", endDateField='" + endDateField + '\'' +
", endTimeField='" + endTimeField + '\'' +
'}';
}
}

View File

@ -0,0 +1,83 @@
package com.api.aiyh_guijiu.pojo;
public class WorkflowBaseInfoDTO {
private int workflowid;
private int requestid;
private String requestnamenew;
private String workflowname;
private String creater;
private String createdate;
private String createtime;
public void setWorkflowid(int workflowid){
this.workflowid = workflowid;
}
public void setRequestid(int requestid){
this.requestid = requestid;
}
public void setRequestnamenew(String requestnamenew){
this.requestnamenew = requestnamenew;
}
public void setWorkflowname(String workflowname){
this.workflowname = workflowname;
}
public void setCreater(String creater){
this.creater = creater;
}
public void setCreatedate(String createdate){
this.createdate = createdate;
}
public void setCreatetime(String createtime){
this.createtime = createtime;
}
public int getWorkflowid(){
return this.workflowid;
}
public int getRequestid(){
return this.requestid;
}
public String getRequestnamenew(){
return this.requestnamenew;
}
public String getWorkflowname(){
return this.workflowname;
}
public String getCreater(){
return this.creater;
}
public String getCreatedate(){
return this.createdate;
}
public String getCreatetime(){
return this.createtime;
}
@Override
public String toString() {
return "WorkflowBaseInfoDTO{" +
"workflowid='" + workflowid + '\'' +
", requestid='" + requestid + '\'' +
", requestnamenew='" + requestnamenew + '\'' +
", workflowname='" + workflowname + '\'' +
", creater='" + creater + '\'' +
", createdate='" + createdate + '\'' +
", createtime='" + createtime + '\'' +
'}';
}
}

View File

@ -0,0 +1,103 @@
package com.api.aiyh_guijiu.pojo;
public class WorkflowConfigDTO {
private int id;
private int enable;
private int workflowType;
private String tablename;
private String startDateField;
private String startTimeField;
private String endDateField;
private String endTimeField;
private String hrmField;
public int getWorkflowType() {
return workflowType;
}
public void setWorkflowType(int workflowType) {
this.workflowType = workflowType;
}
public String getHrmField() {
return hrmField;
}
public void setHrmField(String hrmField) {
this.hrmField = hrmField;
}
public void setId(int id){
this.id = id;
}
public void setEnable(int enable){
this.enable = enable;
}
public void setTablename(String tablename){
this.tablename = tablename;
}
public void setStartDateField(String startDateField){
this.startDateField = startDateField;
}
public void setStartTimeField(String startTimeField){
this.startTimeField = startTimeField;
}
public void setEndDateField(String endDateField){
this.endDateField = endDateField;
}
public void setEndTimeField(String endTimeField){
this.endTimeField = endTimeField;
}
public int getId(){
return this.id;
}
public int getEnable(){
return this.enable;
}
public String getTablename(){
return this.tablename;
}
public String getStartDateField(){
return this.startDateField;
}
public String getStartTimeField(){
return this.startTimeField;
}
public String getEndDateField(){
return this.endDateField;
}
public String getEndTimeField(){
return this.endTimeField;
}
@Override
public String toString() {
return "WorkflowConfigDTO{" +
"id=" + id +
", enable=" + enable +
", workflowType=" + workflowType +
", tablename='" + tablename + '\'' +
", startDateField='" + startDateField + '\'' +
", startTimeField='" + startTimeField + '\'' +
", endDateField='" + endDateField + '\'' +
", endTimeField='" + endTimeField + '\'' +
", hrmField='" + hrmField + '\'' +
'}';
}
}

View File

@ -0,0 +1,464 @@
package com.api.aiyh_guijiu.service;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.fileUtil.WatermarkPoint;
import aiyh.utils.fileUtil.WatermarkPointEnum;
import aiyh.utils.fileUtil.WritWatermark;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_guijiu.dao.ConflictWorkflowDao;
import com.api.aiyh_guijiu.pojo.WorkflowBaseInfoDTO;
import com.api.aiyh_guijiu.pojo.WorkflowConfigDTO;
import com.api.aiyh_guijiu.vo.ConfigInfoVo;
import com.api.aiyh_guijiu.vo.PicPsVO;
import com.api.workflow.constant.RequestAuthenticationConstant;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.engine.workflow.biz.requestForm.FileBiz;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocManager;
import weaver.file.ImageFileManager;
import weaver.hrm.User;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/7 0007 12:43
* workflow queue
*/
public class WorkflowQueueService {
ToolUtil toolUtil = new ToolUtil();
ObjectMapper mapper = new ObjectMapper();
ConflictWorkflowDao conflictWorkflowDao = new ConflictWorkflowDao();
/**
* ps
*
* @return
*/
public String getPicIsPsConfig(String workflowId) {
ConfigInfoVo ufPsNodeConfig = conflictWorkflowDao.getConfigInfo("uf_ps__node_config", workflowId);
if (ufPsNodeConfig == null) {
return ApiResult.successNoData();
}
return ApiResult.success(ufPsNodeConfig);
// String picPsWorkflowId = toolUtil.getSystemParamValue("PIC_PS_WORKFLOW_ID");
// if (StringUtils.isNullOrEmpty(picPsWorkflowId)) {
// return ApiResult.successNoData();
// }
// String nodeId = toolUtil.getSystemParamValue("PIC_PS_NODE_ID");
// String fieldName = toolUtil.getSystemParamValue("PIC_PS_FIELD_NAME");
// List<Integer> watermarkConfig = conflictWorkflowDao.getWatermarkConfig(picPsWorkflowId);
// Map<String, Object> map = new HashMap<>();
// map.put("workflowIds", watermarkConfig);
// map.put("nodeId", nodeId);
// map.put("fieldName", fieldName);
// return ApiResult.success(map);
}
/**
* ps
*
* @param imgIds id
* @return ps
*/
public String getPicIsPs(String imgIds) {
// 通过docId查询到物理文件的id
String query = "select imagefileid,imagefilename,docid from docimagefile where docid in ( " + imgIds + ")";
RecordSet rs = new RecordSet();
rs.executeQuery(query);
List<PicPsVO> list = new ArrayList<>();
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
int docId = rs.getInt(3);
PicPsVO picPsVO = PicPsVO.PicPsVOBuilder.aPicPsVO()
.docId(docId)
.fileId(id)
.fileName(name)
.build();
// 通过物理文件的id进行获取对应的输入流信息。
// ImageFileManager imageFileManager = new ImageFileManager();
// 通过文件id获取输入流
InputStream inputStreamById = ImageFileManager.getInputStreamById(id);
try {
// 获取媒体数据
Metadata metadata = ImageMetadataReader.readMetadata(inputStreamById);
// 遍历Directory对象每个对象里面包含标签
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
System.out.println(directory);
if ("Photoshop".equalsIgnoreCase(directoryName) || "Adobe JPEG".equalsIgnoreCase(directoryName)
|| directoryName.contains("Adobe")) {
if (picPsVO.getScore() > 90) {
continue;
}
picPsVO.setDescribe("图片经过Adobe Photoshop软件注意审核");
picPsVO.setScore(90);
}
String model = "";
for (Tag tag : directory.getTags()) {
System.out.println(tag);
if (tag.getDescription() != null && tag.getDescription().toLowerCase().contains("Adobe".toLowerCase())) {
picPsVO.setDescribe("图片经过Adobe Photoshop软件注意审核");
picPsVO.setScore(70);
if (picPsVO.getScore() > 70) {
continue;
}
}
if ("Software".equalsIgnoreCase(tag.getTagName())) {
if (tag.getDescription().toLowerCase().contains("Adobe".toLowerCase())
|| tag.getDescription().toLowerCase().contains("Photoshop".toLowerCase())) {
picPsVO.setDescribe("图片经过Adobe Photoshop软件注意审核");
picPsVO.setScore(100);
} else {
if (picPsVO.getScore() > 70) {
continue;
}
picPsVO.setDescribe("图片经过" + tag.getDescription() + "软件,注意审核!");
picPsVO.setScore(70);
}
if (!StringUtils.isNullOrEmpty(model) && picPsVO.getDescribe().contains(model)) {
picPsVO.setDescribe("");
picPsVO.setScore(-1);
}
}
if ("Model".equalsIgnoreCase(tag.getTagName())) {
model = tag.getDescription();
if (!StringUtils.isNullOrEmpty(picPsVO.getDescribe())) {
if (picPsVO.getDescribe().contains(tag.getDescription())) {
picPsVO.setDescribe("");
picPsVO.setScore(-1);
}
}
}
if ("User Comment".equalsIgnoreCase(tag.getTagName())) {
try {
if (picPsVO.getScore() > 80) {
continue;
}
com.alibaba.fastjson.JSONObject.parseObject(tag.getDescription());
picPsVO.setDescribe("图片经过手机端图片处理软件,软件未知!请注意审核!");
picPsVO.setScore(80);
} catch (Exception e) {
if (picPsVO.getScore() > 40) {
continue;
}
picPsVO.setDescribe("图片可能经过未知软件!请注意审核!");
picPsVO.setScore(40);
}
}
}
}
} catch (ImageProcessingException | IOException e) {
e.printStackTrace();
}
list.add(picPsVO);
}
List<PicPsVO> collect = list.stream().filter(item -> item.getScore() > 0).collect(Collectors.toList());
return ApiResult.success(collect);
}
public String getWorkflowQueue(Map<String, String> param) {
String workflowId = param.get("workflowId");
String requestId = param.get("requestId");
List<Integer> watermarkConfig = conflictWorkflowDao.getWatermarkConfig(workflowId);
List<WorkflowConfigDTO> workflowConfigDTOS = conflictWorkflowDao.queryConfig(workflowId);
if (workflowConfigDTOS == null || workflowConfigDTOS.size() == 0) {
return ApiResult.successNoData();
}
WorkflowConfigDTO nowConfig = workflowConfigDTOS.stream().filter(item -> {
AtomicBoolean flag = new AtomicBoolean(false);
watermarkConfig.forEach(id -> {
if (id == item.getWorkflowType()) {
flag.set(true);
}
});
return flag.get();
}).collect(Collectors.toList()).get(0);
// 获取当前流程填写的时间信息
String startTime = param.get("startTime");
String startDate = param.get("startDate");
String endTime = param.get("endTime");
String endDate = param.get("endDate");
String hrmStr = param.get("hrmStr");
// 如果当前的requestid不是创建节点则查询数据库信息作为对比条件
if (!"-1".equals(requestId)) {
String hrmField = Util.null2String(nowConfig.getHrmField());
String query = "select * from " + nowConfig.getTablename() + " where requestid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, requestId);
rs.next();
hrmStr = rs.getString(hrmField);
startDate = rs.getString(nowConfig.getStartDateField());
startTime = rs.getString(nowConfig.getStartTimeField());
endTime = rs.getString(nowConfig.getEndTimeField());
endDate = rs.getString(nowConfig.getEndDateField());
}
List<WorkflowBaseInfoDTO> list = new ArrayList<>();
// 循环查询流程中时间是否存在冲突
for (WorkflowConfigDTO workflowConfigDTO : workflowConfigDTOS) {
// 查询冲突的流程数据 TODO 流程相关人 查询数据库
toolUtil.writeErrorLog(hrmStr);
toolUtil.writeErrorLog(workflowConfigDTO.toString() + "\n");
for (String hrmId : hrmStr.split(",")) {
List<WorkflowBaseInfoDTO> workflowBaseInfoDTOList = conflictWorkflowDao.queryConflict(workflowConfigDTO, startTime,
startDate, endTime, endDate, hrmId, requestId);
toolUtil.writeErrorLog(workflowBaseInfoDTOList + "\n");
if (workflowBaseInfoDTOList != null) {
// toolUtil.writeErrorLog(workflowBaseInfoDTOList.toString());
list.addAll(workflowBaseInfoDTOList);
}
}
}
if (list.size() == 0) {
return ApiResult.successNoData();
}
ArrayList<WorkflowBaseInfoDTO> collect = list.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(WorkflowBaseInfoDTO::getRequestid))), ArrayList::new)
);
// 将查询到的信息进行返回给前端
return ApiResult.success(collect);
}
/**
*
*
* @param user user
* @param param
* @return
*/
public String addWaterMark(User user, Map<String, String> param) {
String fileIds = param.get("fileIds");
String location = param.get("location");
String time = param.get("time");
if (StringUtils.isNullOrEmpty(time)) {
time = Util.getTime("yyyy-MM-dd HH:mm:ss");
}
String pressText = "地点:" + location + "\n" + "时间:" + time;
String watermarkColor = toolUtil.getSystemParamValue("WATERMARK_COLOR");
if (StringUtils.isNullOrEmpty(watermarkColor)) {
watermarkColor = "0,0,0";
}
// 处理文字水印的RGB颜色
String[] RGBStr = watermarkColor.replace("", ",").split(",");
int[] RGB = Arrays.stream(RGBStr).mapToInt(Integer::parseInt).toArray();
if (RGB.length < 3) {
RGB = new int[]{0, 0, 0};
}
int R = RGB[0];
int G = RGB[1];
int B = RGB[2];
if (R < 0) {
R = 0;
}
if (R > 255) {
R = 255;
}
if (G < 0) {
G = 0;
}
if (G > 255) {
G = 255;
}
if (B < 0) {
B = 0;
}
if (B > 255) {
B = 255;
}
Color color = new Color(R, G, B);
String fontName = toolUtil.getSystemParamValue("FONT_NAME");
if (StringUtils.isNullOrEmpty(fontName)) {
fontName = "Microsoft YaHei";
}
int fontSize = Util.getIntValue(toolUtil.getSystemParamValue("FONT_SIZE"), 10);
StringBuilder newIds = new StringBuilder();
int index = 0;
//根据fileId 查询物理文件
String query = "select imagefileid from docimagefile where docid in ( " + fileIds + ")";
RecordSet rs = new RecordSet();
rs.executeQuery(query);
while (rs.next()) {
int id = rs.getInt(1);
int newId;
try {
newId = WritWatermark.addTextWatermarkById(id, pressText, color, fontName, Font.PLAIN, fontSize
, new WatermarkPoint(WatermarkPointEnum.RIGHT_BOTTOM), 0, 1, 1.3);
} catch (IOException e) {
return ApiResult.error("图片水印添加失败!");
}
if (index == 0) {
newIds.append(newId);
} else {
newIds.append(",").append(newId);
}
index++;
}
//复制原图的权限信息等
// 复制原来的文件信息,并将现有的信息进行绑定
DocManager docManager = new DocManager();
String[] picIdStrArr = fileIds.split(",");
String[] newImgArr = newIds.toString().split(",");
int[] picIdArr = Arrays.stream(picIdStrArr).mapToInt(Integer::parseInt).toArray();
StringBuilder newDocIds = new StringBuilder();
for (int i = 0; i < picIdArr.length; i++) {
docManager.setId(picIdArr[i]);
// 复制文件
int newId = 0;
try {
newId = docManager.copyDoc(false);
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog("file copy fail!");
}
if (i == 0) {
newDocIds.append(newId);
} else {
newDocIds.append(",").append(newId);
}
// 替换复制出来的数据的物理文件关联关系
PrepSqlResultImpl prepSqlResult = aiyh.utils.Util.createSqlBuilder().updateSql("docimagefile"
, ParaMap.create().put("imagefileid", newImgArr[i])
, aiyh.utils.Util.createPrepWhereImpl().whereAnd("docid").whereEqual(newId));
rs.executeUpdate(prepSqlResult.getSqlStr(), prepSqlResult.getArgs());
}
// 替换原来图片的字段
String isSaveResource = toolUtil.getSystemParamValue("SAVE_RESOURCE");
String sourceField = toolUtil.getSystemParamValue("RESOURCE_FIELD");
if (StringUtils.isNullOrEmpty(isSaveResource)) {
isSaveResource = "0";
}
String fieldName = param.get("fieldName");
String tableName = param.get("tableName");
String isWrite = param.get("isWrite");
// String sourceField = param.get("sourceField");
String requestId = param.get("requestId");
if ("true".equals(isWrite)) {
if ("0".equals(isSaveResource)) {
// 不保存原来的图片
String update = "update " +
tableName +
" set " +
fieldName +
" = " +
newDocIds +
" where " +
" requestid = ?";
rs.executeUpdate(update, requestId);
} else {
String update = "update " +
tableName +
" set " +
fieldName +
" = " +
newDocIds +
" , " +
sourceField +
" = " +
fileIds +
" where " +
" requestid = ?";
rs.executeUpdate(update, requestId);
}
}
// 查询新文件信息
String listType = Util.null2String(String.valueOf(param.get("listType")), "list");
int requestid = Util.getIntValue(Util.null2String(String.valueOf(param.get("requestid"))), -1);
int desrequestid = Util.getIntValue(Util.null2String(String.valueOf(param.get("desrequestid"))), -1);
int isprint = Util.getIntValue(Util.null2String(String.valueOf(param.get("isprint"))), 0);
int workflowid = Util.getIntValue(Util.null2String(String.valueOf(param.get("workflowid"))), 0);
String f_weaver_belongto_userid = Util.null2String(String.valueOf(param.get("f_weaver_belongto_userid")));
String f_weaver_belongto_usertype = Util.null2String(String.valueOf(param.get("f_weaver_belongto_usertype")));
String authStr = Util.null2String(String.valueOf(param.get(RequestAuthenticationConstant.AUTHORITY_STRING)));
String authSignatureStr = Util.null2String(String.valueOf(param.get(RequestAuthenticationConstant.AUTHORITY_SIGNATURESTRING)));
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("user", user);
Map<String, Object> retobj;
try {
retobj = FileBiz.getFileDatas(Util.null2String(newDocIds.toString()), listType, requestid, desrequestid,
isprint, f_weaver_belongto_userid, f_weaver_belongto_usertype, true, false, authStr, authSignatureStr, paramsMap);
} catch (Exception e) {
e.printStackTrace();
return ApiResult.error("查询附件信息失败:" + e);
}
Map<String, Object> result = new HashMap<>();
result.put("fileData", retobj);
result.put("fileIds", newDocIds.toString());
return ApiResult.success(result);
}
/**
* id
*
* @return
*/
public String getWatermarkConfig(String workflowId) {
ConfigInfoVo configInfo = conflictWorkflowDao.getConfigInfo("uf_watermark_cofig", workflowId);
if (configInfo == null) {
return ApiResult.successNoData();
}
return ApiResult.success(configInfo);
// Map<String, Object> map = new HashMap<>();
// String workflowId = toolUtil.getSystemParamValue("PIC_WATERMARK_WORKFLOW_ID");
// List<Integer> list = conflictWorkflowDao.getWatermarkConfig(workflowId);
// String picWatermarkField = toolUtil.getSystemParamValue("PIC_WATERMARK_FIELD_NAME");
// String nodeId = toolUtil.getSystemParamValue("PIC_WATERMARK_NODE_ID");
// map.put("fieldName", picWatermarkField);
// map.put("workflowIds", list);
// map.put("nodeId", nodeId);
// return ApiResult.success(map);
}
/**
* Collection Type
*
* @param collectionClass Collection
* @param elementClasses
* @return JavaType Java
*/
public JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/**
*
*
* @param workflowId id
* @return
*/
public String getWorkflowConflictConfig(String workflowId) {
Map<String, Object> map = new HashMap<>();
List<Integer> watermarkConfig = conflictWorkflowDao.getWatermarkConfig(workflowId);
WorkflowConfigDTO workflowConfig = conflictWorkflowDao.getWorkflowConfig(workflowId);
map.put("workflowIds", watermarkConfig);
map.put("workflowConfig", workflowConfig);
return ApiResult.success(map);
}
}

View File

@ -0,0 +1,67 @@
package com.api.aiyh_guijiu.vo;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/14 0014 21:28
* peizhi xinxi Vo
*/
public class ConfigInfoVo {
int workflowType;
String workflowField;
String workflowNode;
int enable;
public ConfigInfoVo() {
}
public ConfigInfoVo(int workflowType, String workflowField, String workflowNode, int enable) {
this.workflowType = workflowType;
this.workflowField = workflowField;
this.workflowNode = workflowNode;
this.enable = enable;
}
public int getWorkflowType() {
return workflowType;
}
public void setWorkflowType(int workflowType) {
this.workflowType = workflowType;
}
public String getWorkflowField() {
return workflowField;
}
public void setWorkflowField(String workflowField) {
this.workflowField = workflowField;
}
public String getWorkflowNode() {
return workflowNode;
}
public void setWorkflowNode(String workflowNode) {
this.workflowNode = workflowNode;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
@Override
public String toString() {
return "ConfigInfoVo{" +
"workflowType=" + workflowType +
", workflowField='" + workflowField + '\'' +
", workflowNode='" + workflowNode + '\'' +
", enable=" + enable +
'}';
}
}

View File

@ -0,0 +1,120 @@
package com.api.aiyh_guijiu.vo;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/10 0010 16:50
* pic ps vo
*/
public class PicPsVO {
private int docId;
private int fileId;
private String fileName;
private int score;
private String describe;
public PicPsVO(int docId, int fileId, String fileName, int score, String describe) {
this.docId = docId;
this.fileId = fileId;
this.fileName = fileName;
this.score = score;
this.describe = describe;
}
public int getDocId() {
return docId;
}
public void setDocId(int docId) {
this.docId = docId;
}
public int getFileId() {
return fileId;
}
public void setFileId(int fileId) {
this.fileId = fileId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public static final class PicPsVOBuilder {
private int docId;
private int fileId;
private String fileName;
private int score;
private String describe;
private PicPsVOBuilder() {
}
public static PicPsVOBuilder aPicPsVO() {
return new PicPsVOBuilder();
}
public PicPsVOBuilder docId(int docId) {
this.docId = docId;
return this;
}
public PicPsVOBuilder fileId(int fileId) {
this.fileId = fileId;
return this;
}
public PicPsVOBuilder fileName(String fileName) {
this.fileName = fileName;
return this;
}
public PicPsVOBuilder score(int score) {
this.score = score;
return this;
}
public PicPsVOBuilder describe(String describe) {
this.describe = describe;
return this;
}
public PicPsVO build() {
return new PicPsVO(docId, fileId, fileName, score, describe);
}
}
@Override
public String toString() {
return "PicPsVO{" +
"docId=" + docId +
", fileId=" + fileId +
", fileName='" + fileName + '\'' +
", score=" + score +
", describe='" + describe + '\'' +
'}';
}
}

View File

@ -0,0 +1,157 @@
package com.api.aiyh_guijiu.web;
import aiyh.utils.ApiResult;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_guijiu.service.WorkflowQueueService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/3 0003 12:08
*
*/
@Path("/change2Workflow")
public class ConflictWorkflowController {
private final WorkflowQueueService workflowQueueService = new WorkflowQueueService();
private final ToolUtil toolUtil = new ToolUtil();
private final String className = "QueryWorkflow";
/**
*
*
* @return
*/
@Path("/queryWatermark/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryWatermark(@PathParam("workflowId") String workflowId) {
try {
return workflowQueueService.getWatermarkConfig(workflowId);
}catch (Exception e){
toolUtil.writeErrorLog(className + "======> queryWatermark",e.toString());
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param request
* @param response
* @param param
* @return
*/
@Path("/addWatermark")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String addWatermark(@Context HttpServletRequest request, @Context HttpServletResponse response,
@RequestBody Map<String, String> param) {
User user = HrmUserVarify.getUser(request, response);
try {
return workflowQueueService.addWaterMark(user, param);
}catch (Exception e){
toolUtil.writeErrorLog(className + "======> addWatermark",e.toString());
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param workflowId id
* @return
*/
@Path("/queryWorkflow/config/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryWorkflowConfig(@PathParam("workflowId") String workflowId) {
try {
return workflowQueueService.getWorkflowConflictConfig(workflowId);
}catch (Exception e){
toolUtil.writeErrorLog(className + "======> queryWorkflowConfig",e.toString());
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param param
* @return
*/
@Path("/queryConflict")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryWorkflowQueue(@RequestBody Map<String, String> param) {
try {
return workflowQueueService.getWorkflowQueue(param);
}catch (Exception e){
toolUtil.writeErrorLog(className + "======> queryWorkflowQueue",e.toString());
e.printStackTrace();
return ApiResult.error(e.toString());
}
}
/**
* ps
*
* @param imgIds
* @return ps
*/
@Path("/picIsPs/{imgIds}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryPicIsPs(@PathParam("imgIds") String imgIds) {
try {
return workflowQueueService.getPicIsPs(imgIds);
}catch (Exception e){
toolUtil.writeErrorLog(className + "======> queryPicIsPs",e.toString());
return ApiResult.error(e.toString());
}
}
/**
* ps
*
* @return
*/
@Path("/queryPicPsConfig/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryPicPsConfig(@PathParam("workflowId") String workflowId) {
try {
return workflowQueueService.getPicIsPsConfig(workflowId);
}catch (Exception e){
toolUtil.writeErrorLog(className + "======> queryPicPsConfig",e.toString());
return ApiResult.error(e.toString());
}
}
}

View File

@ -0,0 +1,103 @@
package com.api.aiyh_kafang.dao;
import aiyh.utils.Util;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO;
import weaver.conn.RecordSet;
import weaver.workflow.workflow.WorkflowVersion;
import java.util.List;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/11/9 0009 14:38
*/
public class InvoiceMapping {
private RecordSet rs = new RecordSet();
private ToolUtil toolUtil = new ToolUtil();
private final String ModeTable = "uf_fpyzjb";
private final String ModeDetailTable = "uf_fpyzjb_dt1";
public UfInvoiceConfigDTO getConfigInfo(String workflowId) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String query = "select ic.id,ic.invoice_browse,ic.workflow_nodes,ic.workflow_type, " +
"dtv.tablename invoice_detail_table,ftv.fieldname invoice_field,ftv1.fieldname invoice_price " +
"from uf_invoice_config ic " +
"left join workflow_detail_table_view dtv on ic.invoice_detail_table = dtv.id " +
"left join workflow_field_table_view ftv on ic.invoice_field = ftv.id " +
"left join workflow_field_table_view ftv1 on ic.invoice_price = ftv1.id " +
" where workflow_type in (" + workflowId + " )";
rs.executeQuery(query);
UfInvoiceConfigDTO ufInvoiceConfigDTO = Util.recordeSet2Entity(rs, UfInvoiceConfigDTO.class, true);
if (ufInvoiceConfigDTO != null) {
ufInvoiceConfigDTO.setWorkflowType(versionStringByWfid);
}
return ufInvoiceConfigDTO;
}
public void saveInvoiceInfo(int dataId, String tableName, String requestId) {
// 主表数据
Map<String, Object> update = Util.createUtilHashMap()
.uPut("lc", requestId)
.uPut("sm", "发票扫描自动添加实体发票信息!");
Where where = Util.createPrepWhereImpl().whereAnd("id").whereEqual(dataId);
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(tableName, update, where);
toolUtil.writeErrorLog("SQL" + sqlResult.getSqlStr() + " ---->参数:" + sqlResult.getArgs());
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
}
public void saveInvoiceDetail(Map<String, Object> insert, String modeTable) {
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().insertSql(modeTable, insert);
toolUtil.writeErrorLog("SQL" + sqlResult.getSqlStr() + " ---->参数:" + sqlResult.getArgs());
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
}
public String getMainId(String requestId) {
String query = "select * from uf_fpyzjb where lc = ?";
rs.executeQuery(query, requestId);
rs.next();
return rs.getString("id");
}
public List<Map<String, Object>> selectModeInfo(String mainId) {
RecordSet rs = new RecordSet();
String query = "select * from " + ModeDetailTable + " where mainid = ?";
rs.executeQuery(query, mainId);
return Util.recordSet2MapList(rs);
}
public List<Map<String, Object>> selectWorkflowData(String workflowId, String requestId, UfInvoiceConfigDTO configInfo) {
// 根据流程id查询流程主表
String mainTable = Util.getMainTable(workflowId);
String query = "select * from " + mainTable + " where requestid = ?";
rs.executeQuery(query, requestId);
rs.next();
String mainId = rs.getString("id");
// 查询明细表数据
RecordSet rs = new RecordSet();
query = "select * from " + configInfo.getInvoiceDetailTable() + " where mainid = ?";
rs.executeQuery(query, mainId);
return Util.recordSet2MapList(rs);
}
public String getWorkflowCode(String workflowCodeId, String invoiceTable) {
String query = "select * from " + invoiceTable + " where id = ?";
rs.executeQuery(query, workflowCodeId);
if (rs.next()) {
return rs.getString("invoicenumber");
} else {
throw new RuntimeException("发票不存在!");
}
}
public boolean selectExist(String main, String number) {
rs.executeQuery("select * from " + ModeDetailTable + " where mainid = ? and fphm2 = ?",main,number);
return rs.next();
}
}

View File

@ -0,0 +1,93 @@
package com.api.aiyh_kafang.entity;
public class UfInvoiceConfigDTO {
private int id;
private int requestId;
private String workflowType;
private String workflowNodes;
private String invoiceField;
private String invoicePrice;
private int invoiceBrowse;
private String invoiceDetailTable;
public void setId(int id) {
this.id = id;
}
public void setRequestId(int requestId) {
this.requestId = requestId;
}
public void setWorkflowType(String workflowType) {
this.workflowType = workflowType;
}
public void setWorkflowNodes(String workflowNodes) {
this.workflowNodes = workflowNodes;
}
public void setInvoiceField(String invoiceField) {
this.invoiceField = invoiceField;
}
public void setInvoicePrice(String invoicePrice) {
this.invoicePrice = invoicePrice;
}
public void setInvoiceBrowse(int invoiceBrowse) {
this.invoiceBrowse = invoiceBrowse;
}
public void setInvoiceDetailTable(String invoiceDetailTable) {
this.invoiceDetailTable = invoiceDetailTable;
}
public int getId() {
return this.id;
}
public int getRequestId() {
return this.requestId;
}
public String getWorkflowType() {
return this.workflowType;
}
public String getWorkflowNodes() {
return this.workflowNodes;
}
public String getInvoiceField() {
return this.invoiceField;
}
public String getInvoicePrice() {
return this.invoicePrice;
}
public int getInvoiceBrowse() {
return this.invoiceBrowse;
}
public String getInvoiceDetailTable() {
return this.invoiceDetailTable;
}
@Override
public String toString() {
return "UfInvoiceConfigDTO{" +
"id='" + id + '\'' +
", requestId='" + requestId + '\'' +
", workflowType='" + workflowType + '\'' +
", workflowNodes='" + workflowNodes + '\'' +
", invoiceField='" + invoiceField + '\'' +
", invoicePrice='" + invoicePrice + '\'' +
", invoiceBrowse='" + invoiceBrowse + '\'' +
", invoiceDetailTable='" + invoiceDetailTable + '\'' +
'}';
}
}

View File

@ -0,0 +1,284 @@
package com.api.aiyh_kafang.service;
import aiyh.utils.Util;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_kafang.dao.InvoiceMapping;
import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO;
import com.engine.fna.util.FnaInvoiceUploadUtil;
import com.weaver.general.TimeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.fna.invoice.utils.HttpUtil;
import weaver.fna.invoice.utils.ImageUtil;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.hrm.User;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* @author EBU7-dev1-ayh
* @create 2021/11/2 0002 15:17
*
*/
public class InvoiceService {
private final InvoiceMapping invoiceMapping = new InvoiceMapping();
private final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance();
private final RecordSet rs = new RecordSet();
private final ToolUtil toolUtil = new ToolUtil();
private final String ModeTable = "uf_fpyzjb";
private final String ModeDetailTable = "uf_fpyzjb_dt1";
private final String ModeDetailTableErr = "uf_fpyzjb_dt3";
private String formModeId = "17";
private final String invoiceTable = "fnainvoiceledger";
public InvoiceService() {
String formModeId = toolUtil.getSystemParamValue("formModeId");
if(!StringUtils.isNullOrEmpty(formModeId)){
this.formModeId = formModeId;
}
}
/**
* OCR
*
* @param user
* @param fileId
* @return
* @throws IOException
*/
public JSONObject getInvoiceInfo(User user, int fileId) throws Exception {
// InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId);
// byte[] bytes;
// bytes = IOUtils.toByteArray(inputStreamById);
String fileData = FnaInvoiceUploadUtil.changeFileTobase64(fileId);
byte[] imageBytes = ImageUtil.transformImage(fileData);
JSONObject jsonObject = HttpUtil.postImage(imageBytes, user);
toolUtil.writeErrorLog(jsonObject.toString());
return jsonObject;
}
/**
*
*/
public Map<String, Object> contrastInvoiceInfo(Map<String, Object> params) {
// 获取到流程表中的明细数据,对比建模表中的发票信息,查验数量是否一致以及发票的钱
// List<String> fileIdList = (List<String>) params.get("fileIdList");
String requestId = Util.null2String(params.get("requestId"));
String workflowId = Util.null2String(params.get("workflowId"));
// 查询建模表数据
String mainId = invoiceMapping.getMainId(requestId);
List<Map<String, Object>> modeData = invoiceMapping.selectModeInfo(mainId);
// 查询配置表信息
UfInvoiceConfigDTO configInfo = invoiceMapping.getConfigInfo(workflowId);
// 查询流程中的发票数据
List<Map<String, Object>> workflowData = invoiceMapping.selectWorkflowData(workflowId, requestId, configInfo);
// 对比合同信息,查询出相差的发票
List<Map<String, Object>> priceNotEqual = new ArrayList<>();
List<Map<String, Object>> workflowDataRm = new ArrayList<>();
List<Map<String, Object>> modeDataRm = new ArrayList<>();
if (configInfo.getInvoiceBrowse() == 1) {
// 属于浏览框
for (Map<String, Object> workflowDatum : workflowData) {
String workflowCodeId = Util.null2String(workflowDatum.get(configInfo.getInvoiceField()));
String workflowCode = "";
String workflowInvoicePrice = Util.null2String(workflowDatum.get(configInfo.getInvoicePrice()));
try {
workflowCode = invoiceMapping.getWorkflowCode(workflowCodeId, invoiceTable);
workflowDatum.put(configInfo.getInvoiceField(),workflowCode);
workflowDatum.put("fphm2",workflowCode);
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog("发票不存在:" + e);
}
for (Map<String, Object> modeDatum : modeData) {
String modeCode = Util.null2String(modeDatum.get("fphm2"));
String modePrice = Util.null2String(modeDatum.get("fpje"));
if (workflowCode.equals(modeCode)) {
// 发票号码相等,校验发票金额
if (!workflowInvoicePrice.equals(modePrice)) {
// 金额不相等
// 添加校验失败数据到数组中
priceNotEqual.add(modeDatum);
}
// 求差集
workflowDataRm.add(workflowDatum);
modeDataRm.add(modeDatum);
break;
}
}
}
// 求差
// 建模表中多余的发票信息
modeData.removeAll(modeDataRm);
// 流程中有但是建模表中没有的发票信息
workflowData.removeAll(workflowDataRm);
} else {
// 不属于浏览框
for (Map<String, Object> workflowDatum : workflowData) {
String workflowCode = Util.null2String(workflowDatum.get(configInfo.getInvoiceField()));
String workflowInvoicePrice = Util.null2String(workflowDatum.get(configInfo.getInvoicePrice()));
for (Map<String, Object> modeDatum : modeData) {
String modeCode = Util.null2String(modeDatum.get("fphm2"));
String modePrice = Util.null2String(modeDatum.get("fpje"));
if (workflowCode.equals(modeCode)) {
// 发票号码相等,校验发票金额
if (!workflowInvoicePrice.equals(modePrice)) {
// 金额不相等
// 添加校验失败数据到数组中
priceNotEqual.add(modeDatum);
}
// 求差集
workflowDataRm.add(workflowDatum);
modeDataRm.add(modeDatum);
break;
}
}
}
// 求差
// 建模表中多余的发票信息
modeData.removeAll(modeDataRm);
// 流程中有但是建模表中没有的发票信息
workflowData.removeAll(workflowDataRm);
}
List<LinkedHashMap<String, Object>> insertList = new ArrayList<>();
// 将价格不一样的数据保存到建模表明细3中并标识错误原因为价格不一致
for (Map<String, Object> map : priceNotEqual) {
LinkedHashMap<String, Object> data = new LinkedHashMap<>();
data.put("fphm1", map.get("fphm2"));
data.put("sbyy","流程发票明细信息表中的发票与扫描识别发票的发票金额不一致!");
data.put("mainid", mainId);
insertList.add(data);
}
// 将建模表多的发票保存到建模表明细3中并标识错误原因为流程中不存在改发票信息
for (Map<String, Object> map : modeData) {
LinkedHashMap<String, Object> data = new LinkedHashMap<>();
data.put("fphm1", map.get("fphm2"));
data.put("sbyy", "流程中不存在该发票信息,但扫描发票中存在改发票!");
data.put("mainid", mainId);
insertList.add(data);
}
// 将流程中多的发票保存到建模表明细3中并标识错误原因为扫描发票中不存在改发票信息
for (Map<String, Object> map : workflowData) {
LinkedHashMap<String, Object> data = new LinkedHashMap<>();
data.put("fphm1", Util.null2String(map.get(configInfo.getInvoiceField())));
data.put("sbyy", "流程中存在改发票,但是扫描发票中没有发现该发票信息!");
data.put("mainid", mainId);
insertList.add(data);
}
RecordSet rs = new RecordSet();
BatchSqlResultImpl batchSqlResult = Util.createSqlBuilder().insertBatchSql(ModeDetailTableErr, insertList);
toolUtil.writeErrorLog("SQL" + batchSqlResult.getSqlStr() + " ---->参数:" + batchSqlResult.getBatchList());
System.out.println("SQL" + batchSqlResult.getSqlStr() + " ---->参数:" + batchSqlResult.getBatchList());
/* for (List list : batchSqlResult.getBatchList()) {
rs.executeUpdate(batchSqlResult.getSqlStr(),list);
}*/
try{
rs.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
}catch(Exception e){
e.printStackTrace();
}
Map<String, Object> result = new HashMap<>();
result.put("priceNotEqual", priceNotEqual);
result.put("workflowData", workflowData);
result.put("modeData", modeData);
return result;
}
/**
*
*
* @param workflowId
* @return
*/
public UfInvoiceConfigDTO getConfigInfo(String workflowId) {
return invoiceMapping.getConfigInfo(workflowId);
}
/**
*
*
* @param invoiceInfo
* @param requestId
*/
public void saveInvoiceInfo(JSONObject invoiceInfo, String requestId) {
// TODO 查询是否已经存在,不存在则新增,存在则更新
String query = "select * from " + ModeTable + " where lc = ?";
rs.executeQuery(query, requestId);
if (rs.next()) {
// 存在,往明细表中添加数据
saveInvoiceDetail(invoiceInfo, requestId, rs.getString("id"));
return;
}
// 添加主表数据,并且添加明细
int dataId = mdu.getModeDataNewId(ModeTable,
Util.getIntValue(formModeId, -1),
1, 0, TimeUtil.getCurrentDateString(),
TimeUtil.getOnlyCurrentTimeString());
// TODO 插入数据库信息
invoiceMapping.saveInvoiceInfo(dataId, ModeTable, requestId);
saveInvoiceDetail(invoiceInfo, requestId, String.valueOf(dataId));
ModeRightInfo mri = new ModeRightInfo();
mri.rebuildModeDataShareByEdit(1, Util.getIntValue(formModeId, -1), dataId);
}
/**
*
*
* @param invoiceInfo
* @param requestId
* @param mainId
*/
public void saveInvoiceDetail(JSONObject invoiceInfo, String requestId, String mainId) {
String main = mainId;
if (StringUtils.isNullOrEmpty(main)) {
// 查询主表数据
String query = "select * from " + ModeTable + " where lc = ?";
rs.executeQuery(query, requestId);
rs.next();
main = rs.getString("id");
}
// 保存明细表数据
JSONObject returnInfo = (JSONObject) invoiceInfo.get("returnInfo");
toolUtil.writeErrorLog("returnInfo" + returnInfo);
if(returnInfo == null){
throw new RuntimeException("发票数据获取失败:" + invoiceInfo);
}
JSONObject response = (JSONObject) returnInfo.get("response");
JSONObject data = (JSONObject) response.get("data");
JSONArray identifyResults = (JSONArray) data.get("identify_results");
for (int i = 0; i < identifyResults.size(); i++) {
JSONObject item = (JSONObject) identifyResults.get(i);
JSONObject details = (JSONObject) item.get("details");
// 查询是否存在该发票,不存在则添加
if(invoiceMapping.selectExist(main,Util.null2String(details.get("number")))){
return;
}
// 明细表数据
Map<String, Object> insert = Util.createUtilHashMap()
// 发票号码
.uPut("fphm2", details.get("number"))
// 费用日期
.uPut("fyrq", details.get("date"))
// 服务内容
.uPut("fwnr", details.get("item_names"))
// 发票金额
.uPut("fpje", details.get("total"))
.uPut("mainid", main);
toolUtil.writeErrorLog("insert" + insert);
invoiceMapping.saveInvoiceDetail(insert, ModeDetailTable);
}
}
}

View File

@ -0,0 +1,32 @@
package com.api.aiyh_kafang.service;
import aiyh.utils.zwl.common.ToolUtil;
import org.apache.axiom.util.base64.Base64Utils;
import weaver.file.ImageFileManager;
import java.util.Map;
import java.util.UUID;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/8 0008 13:36
*
*/
public class UploadByBase64Service {
public int uploadImage(Map<String, String> param) {
ToolUtil toolUtil = new ToolUtil();
String base64 = String.valueOf(param.get("base64"));
ImageFileManager fileManager = new ImageFileManager();
byte[] data = null;
data = Base64Utils.decode(base64);
fileManager.setData(data);
String fileName = "" + System.currentTimeMillis() + UUID.randomUUID() + ".jpg";
fileManager.setImagFileName(fileName);
int i = fileManager.saveImageFile();
toolUtil.writeErrorLog("生成的图片的id" + i);
return i;
}
}

View File

@ -0,0 +1,36 @@
package com.api.aiyh_kafang.web;
import aiyh.utils.ApiResult;
import com.api.aiyh_kafang.service.InvoiceService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/27 0027 10:29
*
*/
@Path("/kafang/invoiceCheck")
public class InvoiceController {
private InvoiceService invoiceService = new InvoiceService();
@Path("/check/contrast")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String check(@Context HttpServletRequest request, @Context HttpServletResponse response,
@RequestBody Map<String, Object> params) {
Map<String, Object> result = invoiceService.contrastInvoiceInfo(params);
return ApiResult.success(result);
}
}

View File

@ -0,0 +1,109 @@
package com.api.aiyh_kafang.web;
import aiyh.utils.ApiResult;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_kafang.entity.UfInvoiceConfigDTO;
import com.api.aiyh_kafang.service.InvoiceService;
import com.api.aiyh_kafang.service.UploadByBase64Service;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import weaver.file.ImageFileManager;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/27 0027 14:13
* upload invoice by base64 arr
*/
@Path("/kafang/upload")
public class UploadByBase64 {
private final ToolUtil toolUtil = new ToolUtil();
private final UploadByBase64Service uploadByBase64Service = new UploadByBase64Service();
private final InvoiceService invoiceService = new InvoiceService();
@Path("/uploadImage/byBase64")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String uploadImage(@Context HttpServletRequest request, @Context HttpServletResponse response,
@RequestBody Map<String, String> base64Map) {
int i = uploadByBase64Service.uploadImage(base64Map);
// TODO 上传完成过后,调用发票识别接口,将数据保存到建模表中
User user = HrmUserVarify.getUser(request, response);
JSONObject invoiceInfo = null;
try {
invoiceInfo = invoiceService.getInvoiceInfo(user, i);
if (invoiceInfo == null || "1".equals(String.valueOf(invoiceInfo.get("status")))) {
throw new RuntimeException(invoiceInfo == null ? "识别数据为空!" : invoiceInfo.toString());
}
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog("发票识别失败!" + e);
return ApiResult.error("发票识别失败!");
}
try {
invoiceService.saveInvoiceInfo(invoiceInfo, base64Map.get("requestId"));
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog("发票保存失败!" + e);
return ApiResult.error("发票保存失败!");
}
return ApiResult.success(i);
}
@Path("/getConfigInfo/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String getWorkflowId(@PathParam("workflowId") String workflowId) {
UfInvoiceConfigDTO configInfo = invoiceService.getConfigInfo(workflowId);
return ApiResult.success(configInfo);
}
@Path("/download/img/{fileId}")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("fileId") int fileId) throws IOException {
try {
InputStream inputStreamById = ImageFileManager.getInputStreamById(fileId);
byte[] bytes = IOUtils.toByteArray(inputStreamById);
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
outputStream.write(bytes);
// byte[] buffer = new byte[1024*10];
// int len = 0;
// while ((len = inputStreamById.read(buffer)) != -1) {
// outputStream.write(buffer, 0, len);
// }
outputStream.flush();
outputStream.close();
}
};
Response.ResponseBuilder header = Response.ok(output, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition",
"attachment; filename=image_from_server.jpg");
return header.build();
} catch (Exception e) {
return Response.ok(ApiResult.error("异常" + e), MediaType.APPLICATION_JSON).build();
}
// return ApiResult.success("成功");
}
}

View File

@ -0,0 +1,147 @@
package com.api.aiyh_pcn.async_organization;
import com.ibm.icu.text.SimpleDateFormat;
import km.org.apache.poi.hssf.usermodel.HSSFCellStyle;
import km.org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import weaver.aiyh_pcn.async_organization.model.Department;
import weaver.aiyh_pcn.async_organization.model.Employee;
import weaver.aiyh_pcn.async_organization.model.Position;
import weaver.aiyh_pcn.async_organization.result.GetOrganizationResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/8 0008 16:06
* api
*/
@Path("/asyncOrganization")
public class ExportExcel {
@GET
@Path("/exportExcel")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportExcel(@Context HttpServletRequest request, @Context HttpServletResponse response) {
GetOrganizationResult getOrganizationResult = new GetOrganizationResult();
List<Employee> employeeList = getOrganizationResult.getEmployeeList();
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();
CellStyle cellStyle = sxssfWorkbook.createCellStyle();
// 设置单元格居中对齐
cellStyle.setAlignment(HorizontalAlignment.forInt(HSSFCellStyle.ALIGN_CENTER));
Font font = sxssfWorkbook.createFont();
font.setColor(HSSFColor.RED.index);
cellStyle.setFont(font);
Sheet sheet = sxssfWorkbook.createSheet("人员信息");
Row desc = sheet.createRow(0);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 13));
Cell cell2 = desc.createCell(0);
cell2.setCellValue("员工信息表同步数据时按照岗位id进行排序同步");
cell2.setCellStyle(cellStyle);
Row th = sheet.createRow(1);
th.createCell(0).setCellValue("员工ID");
th.createCell(1).setCellValue("名(英文)");
th.createCell(2).setCellValue("姓(英文)");
th.createCell(3).setCellValue("中文姓名");
th.createCell(4).setCellValue("英文名");
th.createCell(5).setCellValue("员工编号");
th.createCell(6).setCellValue("岗位ID");
th.createCell(7).setCellValue("部门ID");
th.createCell(8).setCellValue("部门名称");
th.createCell(9).setCellValue("成本中心编码");
th.createCell(10).setCellValue("邮箱");
th.createCell(11).setCellValue("公司实体");
th.createCell(12).setCellValue("电话号");
th.createCell(13).setCellValue("座机号");
for (int i = 0; i < employeeList.size(); i++) {
Employee e = employeeList.get(i);
Row row = sheet.createRow(i + 2);
row.createCell(0).setCellValue(e.getUserID());
row.createCell(1).setCellValue(e.getFIRSTNAMEEN());
row.createCell(2).setCellValue(e.getLASTNAMEEN());
row.createCell(3).setCellValue(e.getUSERNAMECN());
row.createCell(4).setCellValue(e.getPreferred_Name());
row.createCell(5).setCellValue(e.getUSERCODE());
row.createCell(6).setCellValue(e.getJOBCODEID());
row.createCell(7).setCellValue(e.getDEPARTMENTID());
row.createCell(8).setCellValue(e.getDEPARTMENTNAME());
row.createCell(9).setCellValue(e.getCOSTCENTERCODE());
row.createCell(10).setCellValue(e.getEMAIL());
row.createCell(11).setCellValue(e.getORGANIZATION());
row.createCell(12).setCellValue(e.getMOBILENO());
row.createCell(13).setCellValue(e.getTEL());
}
List<Department> departmentList = getOrganizationResult.getDepartmentList();
Sheet depSheet = sxssfWorkbook.createSheet("部门信息");
Row depdesc = depSheet.createRow(0);
depSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
Cell cell1 = depdesc.createCell(0);
cell1.setCellValue("部门信息表同步数据时按照该上级部门id进行排序同步红色字体为根部门");
cell1.setCellStyle(cellStyle);
Row depTh = depSheet.createRow(1);
depTh.createCell(0).setCellValue("部门ID");
depTh.createCell(1).setCellValue("部门名称");
depTh.createCell(2).setCellValue("上级部门");
for (int i = 0; i < departmentList.size(); i++) {
Row row = depSheet.createRow(i + 2);
Department d = departmentList.get(i);
row.createCell(0).setCellValue(d.getDEPARTMENTID());
row.createCell(1).setCellValue(d.getDEPARTMENTNAME());
Cell cell = row.createCell(2);
cell.setCellValue(d.getPARENTDEPARTMENDID());
if (d.getPARENTDEPARTMENDID() == 0) {
cell.setCellStyle(cellStyle);
}
}
List<Position> positionList = getOrganizationResult.getPositionList();
Sheet posSheet = sxssfWorkbook.createSheet("职位信息");
Row posdesc = posSheet.createRow(0);
posSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));
Cell cell3 = posdesc.createCell(0);
cell3.setCellValue("职位信息表职位同步过程中以上级岗位id升序排序进行同步");
cell3.setCellStyle(cellStyle);
Row posTh = posSheet.createRow(1);
posTh.createCell(0).setCellValue("岗位编号");
posTh.createCell(1).setCellValue("岗位编号");
posTh.createCell(2).setCellValue("岗位描述");
posTh.createCell(3).setCellValue("上级岗位ID");
for (int i = 0; i < positionList.size(); i++) {
Row row = posSheet.createRow(i + 2);
Position p = positionList.get(i);
row.createCell(0).setCellValue(p.getJOBCODEID());
row.createCell(1).setCellValue(p.getJOBCODE());
row.createCell(2).setCellValue(p.getJOBFUNCTION());
row.createCell(3).setCellValue(p.getSUPERIORJOBCODEID());
}
SimpleDateFormat newsdf = new SimpleDateFormat("yyyy-MM-dd-HHmmss");
String date = newsdf.format(new Date());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
sxssfWorkbook.write(bos);
return Response.ok(bos.toByteArray(), "application/msexcel;charset=UTF-8")
.header("Content-Disposition", "attachment;filename=\""
+ new String(("CMS人员同步接口数据" + date + ".xlsx").getBytes("GBK"),
"ISO8859_1") + "\"")
.build();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,104 @@
package com.api.aiyh_pcn.copy_attachment.dao;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_pcn.copy_attachment.model.ConfigEmpty;
import weaver.conn.RecordSet;
import weaver.general.Util;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/26 0026 18:21
* config
*/
public class ConfigTableData {
public static ConfigEmpty getConfig(String workflowId) {
ToolUtil toolUtil = new ToolUtil();
RecordSet rs = new RecordSet();
// 查询配置表,获取配置数据
String querySql = "select ufta.id,ufta.workflow_type,wftva.fieldname as template_field, " +
"wftvb.fieldname as attachment_field,wftv.fieldname as show_field, wftvb.id as attachment_field_id, " +
"ufta.is_template_show,ufta.model_table_name, ufta.model_field,wsl.selectvalue as show_value, " +
"wftv.tablename as show_table_name,wftva.tablename as template_table_name,wftvb.tablename as attachment_table_name, " +
"wsla.selectvalue as hidden_value from uf_temp_attachment as ufta " +
"left join workflow_selectitem as wsl on wsl.id = ufta.show_value " +
"left join workflow_selectitem as wsla on wsla.id = ufta.hidden_value " +
"left join workflow_field_table_view as wftv on wftv.id = ufta.show_field " +
"left join workflow_field_table_view as wftva on wftva.id = ufta.template_field " +
"left join workflow_field_table_view as wftvb on wftvb.id = ufta.attachment_field " +
"where workflow_type in " +
"(select id from workflow_base where activeVersionID in " +
"(select activeVersionID from workflow_base where id = ?) or id = ?) and attachment_type = ?";
rs.executeQuery(querySql, workflowId, workflowId,0);
if(rs.next()){
// id
int id = Util.getIntValue(rs.getString("id"));
// 显示值
int showValue = Util.getIntValue(rs.getString("show_value"));
// 隐藏值
int hiddenValue = Util.getIntValue(rs.getString("hidden_value"));
// 流程id
String workflowType = rs.getString("workflow_type");
// 模板字段
String templateField = rs.getString("template_field");
// 附件字段
String attachmentField = rs.getString("attachment_field");
// 是否用字段控制模板
String isTemplateShow = rs.getString("is_template_show");
// 模板建模表表名
String modelTableName = rs.getString("model_table_name");
// 控制模板显示与否的字段
String showField = rs.getString("show_field");
// 建模表福建模板字段
String modelField = rs.getString("model_field");
// 控制显示所在表
String showTableName = rs.getString("show_table_name");
// 模板字段所在表
String templateTableName = rs.getString("template_table_name");
// 附件字段所在表
String attachmentTableName = rs.getString("attachment_table_name");
// 附件字段id
String attachmentFieldId = rs.getString("attachment_field_id");
toolUtil.writeDebuggerLog("已经查询到数据!");
return ConfigEmpty.create()
.id(id)
.showValue(showValue)
.hiddenValue(hiddenValue)
.workflowType(workflowType)
.templateField(templateField)
.attachmentField(attachmentField)
.isTemplateShow(isTemplateShow)
.modelTableName(modelTableName)
.showField(showField)
.modelField(modelField)
.showTableName(showTableName)
.templateTableName(templateTableName)
.attachmentTableName(attachmentTableName)
.attachmentFieldId(attachmentFieldId)
.builder();
}
return null;
}
public static String[] getTemplateData(String tableName, String fieldName, String configId){
RecordSet rs = new RecordSet();
String queryBuilder = "select " + fieldName +
" from " +
tableName +
" where id = ?";
ToolUtil toolUtil = new ToolUtil();
toolUtil.writeDebuggerLog("接收到参数tableName{" + tableName + "},fieldName{" + fieldName + "}configId{" + configId);
toolUtil.writeDebuggerLog("sql:" + queryBuilder);
rs.executeQuery(queryBuilder,configId);
if(rs.next()){
String docIds = Util.null2String(rs.getString(1));
toolUtil.writeDebuggerLog("查询到数据:" + docIds);
return docIds.split(",");
}
return new String[0];
}
}

View File

@ -0,0 +1,121 @@
package com.api.aiyh_pcn.copy_attachment.dao;
import aiyh.utils.Util;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.zwl.common.ToolUtil;
import weaver.conn.RecordSet;
import weaver.docs.docs.DocManager;
import weaver.hrm.resource.ResourceComInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/26 0026 11:14
* copy dao
*/
public class DocTemplateDao {
ToolUtil toolUtil = new ToolUtil();
private int userId;
public int[] copyFile(int userId, String tableName, String fieldName, String configId) {
this.userId = userId;
String[] templateData = ConfigTableData.getTemplateData(tableName, fieldName, configId);
this.toolUtil.writeDebuggerLog("模板数据:" + Arrays.toString(templateData));
int[] array = Arrays.stream(templateData).mapToInt(Integer::parseInt).toArray();
return this.copyFile(array);
}
private int[] copyFile(int... ids) {
RecordSet rs = new RecordSet();
// 传入需要拷贝的附件的id
DocManager docManager = new DocManager();
int[] docIds = new int[ids.length];
try {
for (int i = 0; i < ids.length; i++) {
// 设置需要拷贝的附件的id
docManager.setId(ids[i]);
// 进行附件的拷贝
docManager.copyDocNew();
// 获取到新拷贝的附件的id
docIds[i] = docManager.getId();
// 对新文档进行权限重置
rs.executeProc("DocSecCategoryShare_SBySecCate", String.valueOf(docManager.getId()));
}
return docIds;
} catch (Exception e) {
this.toolUtil.writeErrorLog("复制错误" + e);
return null;
}
}
public boolean updateFileInfo(String workflowId, String fileFieldId, int... ids) {
RecordSet rs = new RecordSet();
// 通过流程查询到该流程对应的目录
String query = "select catelogType, (case when catelogType = 9 then " +
"(select docCategory from workflow_base where id = ?) else docCategory end )" +
" as docCategory from workflow_fileupload " +
"where workflowid = ? and fieldid = ?";
rs.executeQuery(query, workflowId, workflowId, fileFieldId);
String catelogType = "";
String docCategory = "";
if (rs.next()) {
catelogType = rs.getString("catelogType");
docCategory = rs.getString("docCategory");
}
this.toolUtil.writeDebuggerLog(catelogType + "," + docCategory);
if (!"1".equals(catelogType)) {
List<Object> list = new ArrayList<>();
for (int id : ids) {
list.add(id);
}
ResourceComInfo resourceComInfo = null;
try {
resourceComInfo = new ResourceComInfo();
} catch (Exception e) {
e.printStackTrace();
}
String departmentID = resourceComInfo.getDepartmentID(String.valueOf(this.userId));
// 附件目录不为自己选择,更新文件的目录信息和其他信息
Map<String, Object> updateMap = Util.createUtilHashMap().uPut("ownerid", this.userId)
.uPut("maincategory", 0)
.uPut("subcategory", 0)
.uPut("docstatus", 0)
.uPut("shareroleid", this.userId)
.uPut("doccreaterid", this.userId)
.uPut("doclastmoduserid", this.userId)
.uPut("docdepartmentid", departmentID)
.uPut("doclastmoddate", Util.getTime("yyyy-MM-dd"))
.uPut("doccreatedate", Util.getTime("yyyy-MM-dd"))
.uPut("doclastmodtime", Util.getTime("HH:mm:ss"))
.uPut("doccreatetime", Util.getTime("HH:mm:ss"))
.uPut("seccategory", docCategory.split(",")[docCategory.split(",").length - 1]);
Where whereIn = Util.createPrepWhereImpl().whereAnd("id").whereInList(list);
PrepSqlResultImpl updateResult = Util.createSqlBuilder().updateSql("docdetail", updateMap, whereIn);
this.toolUtil.writeDebuggerLog(updateResult.getSqlStr() + " : " + updateResult.getArgs());
return rs.executeUpdate(updateResult.getSqlStr(), updateResult.getArgs());
}
return false;
}
public boolean deleteFile(int... ids) throws Exception {
DocManager docManager = new DocManager();
for (int id : ids) {
try {
docManager.setId(id);
docManager.DeleteDocInfo();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
return true;
}
}

View File

@ -0,0 +1,255 @@
package com.api.aiyh_pcn.copy_attachment.model;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/26 0026 19:48
*/
public class ConfigEmpty {
/**
* id
*/
private int id;
/**
* id
*/
private String workflowType;
/**
*
*/
private String templateField;
/**
*
*/
private String attachmentField;
/**
*
*/
private String isTemplateShow;
/**
*
*/
private String showField;
/**
*
*/
private int showValue;
/**
*
*/
private int hiddenValue;
/**
*
*/
private String modelTableName;
/**
*
*/
private String modelField;
/**
*
*/
private String showTableName;
/**
*
*/
private String templateTableName;
/**
*
*/
private String attachmentTableName;
/**
* id
*/
private String attachmentFieldId;
public ConfigEmpty(Builder builder) {
this.id = builder.id;
this.workflowType = builder.workflowType;
this.templateField = builder.templateField;
this.attachmentField = builder.attachmentField;
this.isTemplateShow = builder.isTemplateShow;
this.showField = builder.showField;
this.showValue = builder.showValue;
this.hiddenValue = builder.hiddenValue;
this.modelTableName = builder.modelTableName;
this.modelField = builder.modelField;
this.showTableName = builder.showTableName;
this.templateTableName = builder.templateTableName;
this.attachmentTableName = builder.attachmentTableName;
this.attachmentFieldId = builder.attachmentFieldId;
}
@Override
public String toString() {
return "ConfigEmpty{" +
"id=" + id +
", workflowType='" + workflowType + '\'' +
", templetField='" + templateField + '\'' +
", attachmentField='" + attachmentField + '\'' +
", isTempletShow='" + isTemplateShow + '\'' +
", showField='" + showField + '\'' +
", showValue=" + showValue +
", hiddenValue=" + hiddenValue +
", modelTableName='" + modelTableName + '\'' +
", modelField='" + modelField + '\'' +
", showTableName='" + showTableName + '\'' +
", templateTableName='" + templateTableName + '\'' +
", attachmentTableName='" + attachmentTableName + '\'' +
", attachmentFieldId='" + attachmentFieldId + '\'' +
'}';
}
public String getAttachmentFieldId() {
return attachmentFieldId;
}
public int getId() {
return id;
}
public String getWorkflowType() {
return workflowType;
}
public String getTemplateField() {
return templateField;
}
public String getAttachmentField() {
return attachmentField;
}
public String getIsTemplateShow() {
return isTemplateShow;
}
public String getShowField() {
return showField;
}
public int getShowValue() {
return showValue;
}
public int getHiddenValue() {
return hiddenValue;
}
public String getModelTableName() {
return modelTableName;
}
public String getModelField() {
return modelField;
}
public String getShowTableName() {
return showTableName;
}
public String attachmentFieldId() {
return attachmentFieldId;
}
public String getTemplateTableName() {
return templateTableName;
}
public String getAttachmentTableName() {
return attachmentTableName;
}
public static Builder create(){
return new Builder();
}
public static class Builder{
private int id;
private String workflowType;
private String templateField;
private String attachmentField;
private String isTemplateShow;
private String showField;
private int showValue;
private int hiddenValue;
private String modelTableName;
private String modelField;
String showTableName;
String templateTableName;
String attachmentTableName;
String attachmentFieldId;
public ConfigEmpty builder(){
return new ConfigEmpty(this);
}
public Builder id(int id) {
this.id = id;
return this;
}
public Builder showTableName(String showTableName) {
this.showTableName = showTableName;
return this;
}
public Builder templateTableName(String templateTableName) {
this.templateTableName = templateTableName;
return this;
}
public Builder attachmentTableName(String attachmentTableName) {
this.attachmentTableName = attachmentTableName;
return this;
}
public Builder attachmentFieldId(String attachmentFieldId) {
this.attachmentFieldId = attachmentFieldId;
return this;
}
public Builder workflowType(String workflowType) {
this.workflowType = workflowType;
return this;
}
public Builder templateField(String templateField) {
this.templateField = templateField;
return this;
}
public Builder attachmentField(String attachmentField) {
this.attachmentField = attachmentField;
return this;
}
public Builder isTemplateShow(String isTemplateShow) {
this.isTemplateShow = isTemplateShow;
return this;
}
public Builder showField(String showField) {
this.showField = showField;
return this;
}
public Builder showValue(int showValue) {
this.showValue = showValue;
return this;
}
public Builder hiddenValue(int hiddenValue) {
this.hiddenValue = hiddenValue;
return this;
}
public Builder modelTableName(String modelTableName) {
this.modelTableName = modelTableName;
return this;
}
public Builder modelField(String modelField) {
this.modelField = modelField;
return this;
}
}
}

View File

@ -0,0 +1,97 @@
package com.api.aiyh_pcn.copy_attachment.service;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.workflow.constant.RequestAuthenticationConstant;
import com.engine.workflow.biz.requestForm.FileBiz;
import aiyh.utils.ApiResult;
import com.api.aiyh_pcn.copy_attachment.dao.DocTemplateDao;
import weaver.general.Util;
import weaver.hrm.User;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/27 0027 14:52
* copyservice
*/
public class CopyAttachmentService {
public static String copyFile(User user, Map<String, Object> params){
ToolUtil toolUtil = new ToolUtil();
// 建模表名称
String tableName = String.valueOf(params.get("tableName"));
// 建模字段名
String fieldName = String.valueOf(params.get("fieldName"));
// 附件字段id
String fileFieldId = String.valueOf(params.get("fileFieldId"));
// 配置id
String configId = String.valueOf(params.get("configId"));
// 流程id
String workflowId = String.valueOf(params.get("workflowId"));
DocTemplateDao docTemplateDao = new DocTemplateDao();
int[] docIds = null;
try{
docIds = docTemplateDao.copyFile(user.getUID(), tableName, fieldName, configId);
}catch(Exception e){
toolUtil.writeErrorLog("复制文件出错: " + e);
return null;
}
if(docIds == null){
return ApiResult.error("未查询到附件模板!");
}
try{
docTemplateDao.updateFileInfo(workflowId,fileFieldId,docIds);
}catch(Exception e){
toolUtil.writeErrorLog("复制文件更新权限和目录出错: " + e);
return null;
}
toolUtil.writeDebuggerLog("数据更新成功!" + Arrays.toString(docIds));
return ApiResult.success(docIds);
}
public static String deleteFile(String docIdStr) {
String[] docIds = docIdStr.split(",");
DocTemplateDao docTemplateDao = new DocTemplateDao();
int[] array = Arrays.stream(docIds).mapToInt(Integer::parseInt).toArray();
try {
docTemplateDao.deleteFile(array);
} catch (Exception e) {
e.printStackTrace();
return ApiResult.error("删除失败!");
}
return ApiResult.success(array,"删除成功!");
}
/**
*
* @param user user
* @param params
* @return
*/
public static String queryFilesData(User user, Map<String, Object> params){
String listType = Util.null2String(String.valueOf(params.get("listType")),"list");
int requestid = Util.getIntValue(Util.null2String(String.valueOf(params.get("requestid"))), -1);
int desrequestid = Util.getIntValue(Util.null2String(String.valueOf(params.get("desrequestid"))), -1);
int isprint = Util.getIntValue(Util.null2String(String.valueOf(params.get("isprint"))), 0);
int workflowid = Util.getIntValue(Util.null2String(String.valueOf(params.get("workflowid"))), 0);
String f_weaver_belongto_userid = Util.null2String(String.valueOf(params.get("f_weaver_belongto_userid")));
String f_weaver_belongto_usertype = Util.null2String(String.valueOf(params.get("f_weaver_belongto_usertype")));
String authStr = Util.null2String(String.valueOf(params.get(RequestAuthenticationConstant.AUTHORITY_STRING)));
String authSignatureStr = Util.null2String(String.valueOf(params.get(RequestAuthenticationConstant.AUTHORITY_SIGNATURESTRING)));
Map<String,Object> paramsMap = new HashMap<>();
paramsMap.put("user",user);
Map<String,Object> retobj;
try {
retobj = FileBiz.getFileDatas(Util.null2String(params.get("docIds")),listType,requestid,desrequestid,
isprint,f_weaver_belongto_userid,f_weaver_belongto_usertype,true,false,authStr,authSignatureStr,paramsMap);
} catch (Exception e) {
e.printStackTrace();
return ApiResult.error("查询附件信息失败:" + e);
}
return ApiResult.success(retobj);
}
}

View File

@ -0,0 +1,71 @@
package com.api.aiyh_pcn.copy_attachment.web;
import aiyh.utils.ApiResult;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_pcn.copy_attachment.service.CopyAttachmentService;
import com.api.aiyh_pcn.copy_attachment.dao.ConfigTableData;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/8/26 0026 10:16
* copy ttachment to workflow
*/
@Path("/copyAttachment")
public class CopyAttachment {
ToolUtil toolUtil = new ToolUtil();
@POST
@Path("/copy")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String copyAttachment(@Context HttpServletRequest request, @Context HttpServletResponse response,
@RequestBody Map<String, Object> params) {
this.toolUtil.writeDebuggerLog("文件拷贝,接收参数:" + params);
User user = HrmUserVarify.getUser(request, response);
return CopyAttachmentService.copyFile(user,params);
}
@Path("/deleteFile/{docIds}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String deleteFile(@Context HttpServletRequest request, @Context HttpServletResponse response,
@PathParam("docIds") String docIds) {
this.toolUtil.writeDebuggerLog("文件删除,接收参数:" + docIds);
return CopyAttachmentService.deleteFile(docIds);
}
@Path("/queryConfig/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryConfig(@PathParam("workflowId") String workflowId) {
this.toolUtil.writeDebuggerLog("获取配置参数,接收参数为: " + workflowId);
return ApiResult.success(ConfigTableData.getConfig(workflowId));
}
@Path("/queryFilesData")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String queryFilesData(@Context HttpServletRequest request, @Context HttpServletResponse response,
@RequestBody Map<String, Object> params){
this.toolUtil.writeDebuggerLog("查看文件信息,接收参数:" + params);
User user = HrmUserVarify.getUser(request, response);
return CopyAttachmentService.queryFilesData(user, params);
}
}

View File

@ -0,0 +1,176 @@
package com.api.aiyh_pcn.fadada.dao;
import aiyh.utils.Util;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO;
import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO;
import weaver.aiyh_pcn.fadada.entity.FileInfo;
import weaver.conn.RecordSet;
import weaver.workflow.workflow.WorkflowVersion;
import java.util.List;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/11/3 0003 14:56
*/
public class FaDDContractMapping {
private final RecordSet rs = new RecordSet();
private final ToolUtil toolUtil = new ToolUtil();
/**
*
*
* @param workflowId id
* @param type
* @return
*/
public FaDaDaConfigDTO queryConfig(String workflowId, int type) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String query = "select main.id,main.workflow_type,main.api_type, main.params_config, " +
"wf.fieldname field_control, wf1.fieldname contract_doc, " +
"(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " +
"where FIND_IN_SET(id,main.check_personal)) check_personal, " +
"(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem " +
"where FIND_IN_SET(id,main.check_enterprise)) check_enterprise, " +
"main.check_source_type,wdt.tablename check_source " +
"from uf_contract_config main " +
"left join workflow_field_table_view wf on wf.id = main.field_control " +
"left join workflow_field_table_view wf1 on wf1.id = main.contract_doc " +
"left join workflow_detail_table_view wdt on wdt.id = main.check_source and " +
"wdt.workflow_id = main.workflow_type " +
"where main.workflow_type in ( " + versionStringByWfid + ") and api_type = ?";
rs.executeQuery(query, type);
return Util.recordeSet2Entity(rs, FaDaDaConfigDTO.class, true);
}
/**
* workflowId
*
* @param versionStringByWfid workflowId
* @return
*/
public String getAllVersion(String versionStringByWfid) {
String query = "select distinct workflow_type from uf_contract_config where workflow_type in (" + versionStringByWfid + ")";
rs.executeQuery(query);
rs.next();
return rs.getString(1);
}
/**
*
*
* @param versionStringByWfid
* @param markOnly
* @return
*/
public String getNodes(String versionStringByWfid, String markOnly) {
String query = "select workflow_nodes from uf_node_config where workflow_type in (" + versionStringByWfid + ") and mark_only = ?";
rs.executeQuery(query, markOnly);
rs.next();
return rs.getString(1);
}
/**
*
*
* @param workflowId
* @return
*/
public String getMainTable(String workflowId) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String query = "select tablename from workflow_bill " +
" where id in (select formid from workflow_base " +
" where id in (" + versionStringByWfid + ") )";
rs.executeQuery(query);
rs.next();
String mainTable = rs.getString(1);
toolUtil.writeErrorLog("mainTable:" + mainTable);
return mainTable;
}
/**
*
*
* @param workflowId
* @param type
* @return
*/
public String getDetailTable(String workflowId, int type) {
FaDaDaConfigDTO faDaDaConfigDTO = this.queryConfig(workflowId, type);
String detailTable = faDaDaConfigDTO.getCheckSource();
toolUtil.writeErrorLog("detailTable:" + detailTable);
return detailTable;
}
/**
* id
*
* @param requestId id
* @param mainTableName
* @return
*/
public Map<String, Object> queryMainMap(String requestId, String mainTableName) {
String query = "select * from " + mainTableName + " where requestid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, requestId);
return Util.recordSet2Map(rs);
}
/**
*
*
* @param mainId id
* @param tableName
* @return
*/
public List<Map<String, Object>> queryDetailMaps(String mainId, String tableName) {
String query = "select * from " + tableName + " where mainid = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, mainId);
return Util.recordSet2MapList(rs);
}
/**
*
*
* @param workflowId
* @return
*/
/* public Map<String, Object> queryContractConfig(String workflowId) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
RecordSet rs = new RecordSet();
rs.executeQuery("select * from uf_contract_config where workflow_type in ( " + versionStringByWfid + " ) and api_type = ?", 2);
return Util.recordSet2Map(rs);
}*/
/**
* idid
* @param fileIds
* @return
*/
public List<FileInfo> queryImgFileIdByDocIds(String fileIds) {
String query = "select imagefileid,imagefilename from docimagefile where docid in ( " + fileIds + " )";
rs.executeQuery(query);
return Util.recordeSet2Array(rs, FileInfo.class);
}
public UfContractInfoDTO queryContractInfo(String contractNo) {
String query = "select * from uf_contract_info where contract_no = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query,contractNo);
return Util.recordeSet2Entity(rs,UfContractInfoDTO.class,true);
}
public UfContractInfoDTO queryContractInfoByRequestId(String requestId) {
String query = "select * from uf_contract_info where workflow_request_id = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query,requestId);
return Util.recordeSet2Entity(rs,UfContractInfoDTO.class,true);
}
}

View File

@ -0,0 +1,173 @@
package com.api.aiyh_pcn.fadada.dao;
import aiyh.utils.Util;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO;
import weaver.aiyh_pcn.fadada.entity.FileInfo;
import weaver.conn.RecordSet;
import weaver.workflow.workflow.WorkflowVersion;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/30 0030 11:18
*
*/
public class FaDDServiceMapping {
private final RecordSet rs = new RecordSet();
private final ToolUtil toolUtil = new ToolUtil();
// private final String MAIN_TABLE = "formtable_main_17";
// private final String DETAIL_TABLE = "formtable_main_17_dt1";
public FaDaDaConfigDTO queryConfig(String workflowId, int type) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String query = "select main.id,main.workflow_type,main.api_type, main.params_config, " +
"wf.fieldname field_control, " +
"(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_personal)) check_personal, " +
"(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_enterprise)) check_enterprise, " +
"main.check_source_type,wdt.tablename check_source " +
"from uf_contract_config main " +
"left join workflow_field_table_view wf on wf.id = main.field_control " +
"left join workflow_detail_table_view wdt on wdt.id = main.check_source and wdt.workflow_id = main.workflow_type " +
"where main.workflow_type in ( " + versionStringByWfid + ") and api_type = ?";
rs.executeQuery(query, type);
return Util.recordeSet2Entity(rs, FaDaDaConfigDTO.class, true);
}
public List<FileInfo> queryImgFileIdByDocIds(String fileIds) {
String query = "select imagefileid,imagefilename from docimagefile where docid in ( " + fileIds + " )";
rs.executeQuery(query);
return Util.recordeSet2Array(rs, FileInfo.class);
}
public List<Map<String, Object>> queryDetailInfo(String requestId,String workflowId,int type) {
String mainTable = this.getMainTable(workflowId);
toolUtil.writeErrorLog("进入查询数据库方法");
String query = "select id from " + mainTable + " where requestid = ?";
rs.executeQuery(query, requestId);
rs.next();
String mainId = rs.getString("id");
String detailTable = this.getDetailTable(workflowId, type);
query = "select * from " + detailTable + " where mainid = ? and ( contract_status in (1,6) or contract_status is null) ";
this.toolUtil.writeErrorLog(query);
RecordSet rs = new RecordSet();
rs.executeQuery(query, mainId);
List<Map<String, Object>> maps = null;
try {
maps = Util.recordSet2MapList(rs);
toolUtil.writeErrorLog("查询到状态:" + maps);
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog("工具类出现异常:" + e);
}
return maps == null ? new ArrayList<>() : maps;
}
public List<Map<String, Object>> queryDetailDownInfo(String requestId,String workflowId,int type) {
String mainTable = this.getMainTable(workflowId);
toolUtil.writeErrorLog("进入查询数据库方法");
String query = "select id from " + mainTable + " where requestid = ?";
rs.executeQuery(query, requestId);
rs.next();
String mainId = rs.getString("id");
String detailTable = this.getDetailTable(workflowId, type);
query = "select * from " + detailTable + " where mainid = ?";
this.toolUtil.writeErrorLog(query);
RecordSet rs = new RecordSet();
rs.executeQuery(query, mainId);
List<Map<String, Object>> maps = null;
try {
maps = Util.recordSet2MapList(rs);
toolUtil.writeErrorLog("查询到状态:" + maps);
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog("工具类出现异常:" + e);
}
return maps == null ? new ArrayList<>() : maps;
}
public List<Map<String, Object>> querySignedInfo(String requestId, String workflowId) {
String mainTable = this.getMainTable(workflowId);
String query = "select id from " + mainTable + " where requestid = ? and signed_oneself = 1";
rs.executeQuery(query, requestId);
return Util.recordSet2MapList(rs);
}
public void updateContractStatus(Map<String, Object> map,String workflowId,int type) {
String detailTable = this.getDetailTable(workflowId,type);
Map<String, Object> updateData = new HashMap<>();
updateData.put("contract_status", map.get("contract_status"));
Where where = Util.createPrepWhereImpl().whereAnd("id").whereEqual(map.get("id"));
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(detailTable, updateData, where);
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
}
public String getAllVersion(String versionStringByWfid) {
String query = "select distinct workflow_type from uf_contract_config where workflow_type in (" + versionStringByWfid + ")";
rs.executeQuery(query);
rs.next();
return rs.getString(1);
}
public String getMainTable(String workflowId){
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String query = "select tablename from workflow_bill " +
" where id in (select formid from workflow_base " +
" where id in (" + versionStringByWfid + ") )";
rs.executeQuery(query);
rs.next();
String mainTable = rs.getString(1);
toolUtil.writeErrorLog("mainTable:" + mainTable);
return mainTable;
}
public String getDetailTable(String workflowId, int type){
FaDaDaConfigDTO faDaDaConfigDTO = this.queryConfig(workflowId, type);
String detailTable = faDaDaConfigDTO.getCheckSource();
toolUtil.writeErrorLog("detailTable:" + detailTable);
return detailTable;
}
public String getNodes(String versionStringByWfid, String markOnly) {
String query = "select workflow_nodes from uf_node_config where workflow_type in (" + versionStringByWfid + ") and mark_only = ?";
rs.executeQuery(query,markOnly);
rs.next();
return rs.getString(1);
}
/* public FaDDConfigMainDTO getConfigParam(String workflowId) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
System.out.println(versionStringByWfid);
String query = "select main.id,main.workflow_type, wf.fieldname field_control, " +
"(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_personal)) check_personal, " +
"(select GROUP_CONCAT('',selectvalue,'') selectvalue from workflow_selectitem where FIND_IN_SET(id,main.check_enterprise)) check_enterprise, " +
"main.check_source_type,wdt.tablename check_source " +
"from uf_attestation_conf main " +
"left join workflow_field_table_view wf on wf.id = main.field_control " +
"left join workflow_detail_table_view wdt on wdt.id = main.check_source and wdt.workflow_id = main.workflow_type " +
"where main.workflow_type in ( " + versionStringByWfid + ")";
rs.executeQuery(query);
FaDDConfigMainDTO faDDConfigMainDTO = Util.recordeSet2Entity(rs, FaDDConfigMainDTO.class, true);
query = "select dt.id,dt.line_num,dt.param_name,dt.param_type,dt.object_child,dt.parent_line,dt.change_rule, " +
"dt.param_value,wf.fieldname workflow_field,wf.tablename tablename,dt.array_sql,dt.api_type " +
"from uf_attestation_conf_dt1 dt " +
"left join workflow_field_table_view wf on wf.id = dt.workflow_field " +
"where dt.mainid = ?";
rs.executeQuery(query, faDDConfigMainDTO.getId());
List<FaDDConfigDetailDTO> faDDConfigDetailDTOS = Util.recordeSet2Array(rs, FaDDConfigDetailDTO.class, true);
faDDConfigMainDTO.setList(faDDConfigDetailDTOS);
return faDDConfigMainDTO;
}*/
}

View File

@ -0,0 +1,93 @@
package com.api.aiyh_pcn.fadada.entity;
public class FaDaDaConfigDTO {
private int id;
private int workflowType;
private int apiType;
private String paramsConfig;
private String fieldControl;
private int checkSourceType;
private String checkSource;
private String contractDoc;
public void setId(int id){
this.id = id;
}
public void setWorkflowType(int workflowType){
this.workflowType = workflowType;
}
public void setApiType(int apiType){
this.apiType = apiType;
}
public void setParamsConfig(String paramsConfig){
this.paramsConfig = paramsConfig;
}
public void setFieldControl(String fieldControl){
this.fieldControl = fieldControl;
}
public void setCheckSourceType(int checkSourceType){
this.checkSourceType = checkSourceType;
}
public void setCheckSource(String checkSource){
this.checkSource = checkSource;
}
public int getId(){
return this.id;
}
public int getWorkflowType(){
return this.workflowType;
}
public int getApiType(){
return this.apiType;
}
public String getParamsConfig(){
return this.paramsConfig;
}
public String getFieldControl(){
return this.fieldControl;
}
public int getCheckSourceType(){
return this.checkSourceType;
}
public String getCheckSource(){
return this.checkSource;
}
public String getContractDoc() {
return contractDoc;
}
public void setContractDoc(String contractDoc) {
this.contractDoc = contractDoc;
}
@Override
public String toString() {
return "FaDaDaConfigDTO{" +
"id=" + id +
", workflowType=" + workflowType +
", apiType=" + apiType +
", paramsConfig='" + paramsConfig + '\'' +
", fieldControl='" + fieldControl + '\'' +
", checkSourceType=" + checkSourceType +
", checkSource='" + checkSource + '\'' +
", contractDoc='" + contractDoc + '\'' +
'}';
}
}

View File

@ -0,0 +1,29 @@
package com.api.aiyh_pcn.fadada.entity;
import java.util.List;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/12 0012 11:16
*
*/
public class TreeEntity<T> {
private List<T> children;
public List<T> getChildren() {
return children;
}
public void setChildren(List<T> children) {
this.children = children;
}
@Override
public String toString() {
return "TreeEntity{" +
"children=" + children +
'}';
}
}

View File

@ -0,0 +1,193 @@
package com.api.aiyh_pcn.fadada.entity;
public class UfContractInfoDTO {
private int id;
private int requestId;
private int workflowType;
private String contractNo;
private String fileNo;
private String fileName;
private int signedNum;
private int shouldSignedNum;
private int contractStatus;
private String contractViewUrl;
private String contractDownUrl;
private String workflowMainTable;
private int queueSigned;
private int singleContractFileNum;
private int singleSignedNum;
private String workflowRequestId;
private String workflowDetailTable;
private int mainId;
public void setId(int id){
this.id = id;
}
public void setRequestId(int requestId){
this.requestId = requestId;
}
public void setWorkflowType(int workflowType){
this.workflowType = workflowType;
}
public void setContractNo(String contractNo){
this.contractNo = contractNo;
}
public void setFileNo(String fileNo){
this.fileNo = fileNo;
}
public void setFileName(String fileName){
this.fileName = fileName;
}
public void setSignedNum(int signedNum){
this.signedNum = signedNum;
}
public void setShouldSignedNum(int shouldSignedNum){
this.shouldSignedNum = shouldSignedNum;
}
public void setContractStatus(int contractStatus){
this.contractStatus = contractStatus;
}
public void setContractViewUrl(String contractViewUrl){
this.contractViewUrl = contractViewUrl;
}
public void setContractDownUrl(String contractDownUrl){
this.contractDownUrl = contractDownUrl;
}
public void setWorkflowMainTable(String workflowMainTable){
this.workflowMainTable = workflowMainTable;
}
public void setQueueSigned(int queueSigned){
this.queueSigned = queueSigned;
}
public void setSingleContractFileNum(int singleContractFileNum){
this.singleContractFileNum = singleContractFileNum;
}
public void setSingleSignedNum(int singleSignedNum){
this.singleSignedNum = singleSignedNum;
}
public void setWorkflowRequestId(String workflowRequestId){
this.workflowRequestId = workflowRequestId;
}
public void setWorkflowDetailTable(String workflowDetailTable){
this.workflowDetailTable = workflowDetailTable;
}
public void setMainId(int mainId){
this.mainId = mainId;
}
public int getId(){
return this.id;
}
public int getRequestId(){
return this.requestId;
}
public int getWorkflowType(){
return this.workflowType;
}
public String getContractNo(){
return this.contractNo;
}
public String getFileNo(){
return this.fileNo;
}
public String getFileName(){
return this.fileName;
}
public int getSignedNum(){
return this.signedNum;
}
public int getShouldSignedNum(){
return this.shouldSignedNum;
}
public int getContractStatus(){
return this.contractStatus;
}
public String getContractViewUrl(){
return this.contractViewUrl;
}
public String getContractDownUrl(){
return this.contractDownUrl;
}
public String getWorkflowMainTable(){
return this.workflowMainTable;
}
public int getQueueSigned(){
return this.queueSigned;
}
public int getSingleContractFileNum(){
return this.singleContractFileNum;
}
public int getSingleSignedNum(){
return this.singleSignedNum;
}
public String getWorkflowRequestId(){
return this.workflowRequestId;
}
public String getWorkflowDetailTable(){
return this.workflowDetailTable;
}
public int getMainId(){
return this.mainId;
}
@Override
public String toString() {
return "UfContractInfoDTO{" +
"id='" + id + '\'' +
", requestId='" + requestId + '\'' +
", workflowType='" + workflowType + '\'' +
", contractNo='" + contractNo + '\'' +
", fileNo='" + fileNo + '\'' +
", fileName='" + fileName + '\'' +
", signedNum='" + signedNum + '\'' +
", shouldSignedNum='" + shouldSignedNum + '\'' +
", contractStatus='" + contractStatus + '\'' +
", contractViewUrl='" + contractViewUrl + '\'' +
", contractDownUrl='" + contractDownUrl + '\'' +
", workflowMainTable='" + workflowMainTable + '\'' +
", queueSigned='" + queueSigned + '\'' +
", singleContractFileNum='" + singleContractFileNum + '\'' +
", singleSignedNum='" + singleSignedNum + '\'' +
", workflowRequestId='" + workflowRequestId + '\'' +
", workflowDetailTable='" + workflowDetailTable + '\'' +
", mainId='" + mainId + '\'' +
'}';
}
}

View File

@ -0,0 +1,17 @@
package com.api.aiyh_pcn.fadada.service;
import com.api.aiyh_pcn.fadada.vo.TableFieldMappingVO;
import java.util.List;
import java.util.Map;
/**
* @author @author EBU7-dev1-ay
* @create 2021/9/30 0030 11:19
*
*/
public interface IFaDDService {
Map<String,Object> getConfigParam(String workflowId);
Map<String, Object> checkCertification(Map<String, Object> params);
}

View File

@ -0,0 +1,716 @@
package com.api.aiyh_pcn.fadada.service.impl;
import aiyh.utils.Util;
import aiyh.utils.entity.ApiConfigDetailDTO;
import aiyh.utils.entity.ApiConfigMainDTO;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.api.aiyh_pcn.fadada.dao.FaDDContractMapping;
import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO;
import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO;
import com.api.aiyh_pcn.fadada.util.FaDDRequestUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.axiom.util.base64.Base64Utils;
import org.apache.http.HttpEntity;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.xcommon.IOUtils;
import weaver.hrm.User;
import weaver.soa.workflow.FileProcessor;
import weaver.workflow.workflow.WorkflowVersion;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author EBU7-dev1-ayh
* @create 2021/11/3 0003 14:51
*/
public class FaDDContractService {
private final ToolUtil toolUtil = new ToolUtil();
private final String contractInfoTable = "uf_contract_info";
private final FaDDContractMapping faDDContractMapping = new FaDDContractMapping();
/**
* idid
*
* @param workflowId
* @param markOnly
* @return
*/
public Map<String, Object> getAllVersion(String workflowId, String markOnly) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String newWorkflowId = faDDContractMapping.getAllVersion(versionStringByWfid);
String allVersion = WorkflowVersion.getVersionStringByWfid(newWorkflowId);
if (allVersion == null) {
allVersion = "";
}
String[] split = allVersion.split(",");
Map<String, Object> data = new HashMap<>();
String[] nodes = this.getNodes(workflowId, markOnly);
data.put("workflowIds", split);
data.put("nodeIds", nodes);
return data;
}
/**
* id
*
* @param workflowId
* @param markOnly
* @return
*/
public String[] getNodes(String workflowId, String markOnly) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String nods = faDDContractMapping.getNodes(versionStringByWfid, markOnly);
if (nods == null) {
nods = "";
}
return nods.split(",");
}
/**
* SQL
*
* @param requestId
* @param workflowId
* @param mainTableName
* @param tableName
* @return
*/
public List<Map<String, Object>> getDataArr(String requestId, String workflowId, String mainTableName, String tableName) {
Map<String, Object> mainMap = faDDContractMapping.queryMainMap(requestId, mainTableName);
String mainId = Util.null2String(mainMap.get("id"));
List<Map<String, Object>> detailMaps = faDDContractMapping.queryDetailMaps(mainId, tableName);
return getDataArr(requestId, workflowId, tableName, mainMap, detailMaps);
}
public List<Map<String, Object>> getDataArr(String requestId, String workflowId, String mainTableName, String tableName, List<Map<String, Object>> detailMaps) {
Map<String, Object> mainMap = faDDContractMapping.queryMainMap(requestId, mainTableName);
String mainId = Util.null2String(mainMap.get("id"));
return getDataArr(requestId, workflowId, tableName, mainMap, detailMaps);
}
public List<Map<String, Object>> getDataArr(String requestId, String workflowId, String tableName,
Map<String, Object> mainMap, List<Map<String, Object>> detailMaps) {
List<Map<String, Object>> dataArr = new ArrayList<>();
String dt = tableName.substring(tableName.indexOf("_dt") + 3);
String main = "main.";
String detail = "detail_" + dt + ".";
for (Map<String, Object> detailMap : detailMaps) {
Map<String, Object> data = new HashMap<>();
for (Map.Entry<String, Object> entry : mainMap.entrySet()) {
data.put(main + entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : detailMap.entrySet()) {
data.put(detail + entry.getKey(), entry.getValue());
}
data.put("requestId", requestId);
data.put("workflowId", workflowId);
dataArr.add(data);
}
return dataArr;
}
/**
* objectList
*
* @param treeList
* @param dataArr
* @return
*/
public List<Map<String, Object>> objectAndListHandle(List<ApiConfigDetailDTO> treeList, List<Map<String, Object>> dataArr) {
List<Map<String, Object>> params = new ArrayList<>();
for (Map<String, Object> dataMap : dataArr) {
Map<String, Object> param = new HashMap<>();
for (ApiConfigDetailDTO apiConfigDetailDTO : treeList) {
Object value;
if (apiConfigDetailDTO.getParamType() == 3) {
Map<String, Object> map = new HashMap<>();
// object类型
for (ApiConfigDetailDTO child : apiConfigDetailDTO.getChildren()) {
if (child.getChildren() == null || child.getChildren().size() == 0) {
// handleChild(child.getChildren(), dataMap)
map.put(child.getParamName(), changeRuleHandle(child, dataMap));
} else {
map.put(child.getParamName(), handleChild(child.getChildren(), dataMap));
}
}
value = map;
} else if (apiConfigDetailDTO.getParamType() == 4) {
String sql = apiConfigDetailDTO.getArraySql();
String parsingSq = aiyh.utils.Util.parsingSq(sql, dataMap);
// list类型
if (parsingSq.contains("delete") || parsingSq.contains("update") ||
parsingSq.contains("exec") || parsingSq.contains("drop") ||
parsingSq.contains("truncate")) {
value = new ArrayList<>();
} else {
RecordSet rs = new RecordSet();
String replace = parsingSq.replace(" ", "select ")
.replaceAll(" ", " and ")
.replaceAll(" ", " or ")
.replaceAll(" ", " join ")
.replaceAll(" ", " in ");
rs.executeQuery(replace);
value = aiyh.utils.Util.recordeSet2Array(rs, String.class);
}
} else {
value = changeRuleHandle(apiConfigDetailDTO, dataMap);
}
param.put(apiConfigDetailDTO.getParamName(), value);
}
params.add(param);
}
return params;
}
/**
*
*
* @param children
* @param dataMap
* @return
*/
private Object handleChild(List<ApiConfigDetailDTO> children, Map<String, Object> dataMap) {
Map<String, Object> params = new HashMap<>();
for (ApiConfigDetailDTO child : children) {
Object value;
if (child.getChildren() != null) {
value = handleChild(child.getChildren(), dataMap);
} else {
value = changeRuleHandle(child, dataMap);
}
params.put(child.getParamName(), value);
}
return params;
}
/**
*
*
* @param apiConfigDetailDTO
* @param dataMap
* @return
*/
private Object changeRuleHandle(ApiConfigDetailDTO apiConfigDetailDTO, Map<String, Object> dataMap) {
Object value;
String tableName;
String table;
String sql;
String resultSql;
// 判断参数的转换规则
switch (apiConfigDetailDTO.getChangeRule()) {
case 0:
// 不转换
case 2:
// 流程字段值
table = apiConfigDetailDTO.getTablename();
if (!table.contains("_dt")) {
// 表示字段属于主表
tableName = "main";
} else {
// 字段属于明细表
String dt = table.substring(table.indexOf("_dt") + 3);
tableName = "detail_" + dt;
}
value = dataMap.get(tableName + "." + apiConfigDetailDTO.getWorkflowField());
break;
case 1:
// 固定值
value = apiConfigDetailDTO.getParamValue();
break;
case 3:
// 系统日期
value = aiyh.utils.Util.getTime("yyyy-MM-dd");
break;
case 4:
// 系统时间
value = aiyh.utils.Util.getTime("HH:mm:ss");
break;
case 5:
// 系统日期-时间
value = aiyh.utils.Util.getTime("yyyy-MM-dd HH:mm:ss");
break;
case 6:
// 自定义SQL
case 7:
// 流程字段转SQL
sql = apiConfigDetailDTO.getParamValue();
resultSql = aiyh.utils.Util.parsingSq(sql, dataMap);
if (resultSql.contains("delete ") || resultSql.contains("update ") ||
resultSql.contains("exec ") || resultSql.contains("drop ") ||
resultSql.contains("truncate ")) {
value = null;
} else {
RecordSet rs = new RecordSet();
String replace = resultSql.replace(" ", "select ")
.replaceAll(" ", " and ")
.replaceAll(" ", " or ")
.replaceAll(" ", " join ")
.replaceAll(" ", " in ");
rs.executeQuery(replace);
rs.next();
value = aiyh.utils.Util.null2String(rs.getString(1));
}
break;
case 8:
// TODO
// 流程名称
value = aiyh.utils.Util.getWorkflowNameById(String.valueOf(dataMap.get("workflowid")));
break;
case 9:
// TODO
// 请求标题
value = aiyh.utils.Util.getRequestTitleById(String.valueOf(dataMap.get("requestid")));
break;
case 10:
// 流程requestId
value = dataMap.get("requestid");
break;
default:
value = null;
break;
}
if (apiConfigDetailDTO.getParamType() == 1) {
// Integer
value = Integer.parseInt(String.valueOf(value));
} else if (apiConfigDetailDTO.getParamType() == 2) {
// Boolean
value = Boolean.parseBoolean(String.valueOf(value));
}
return value;
}
/**
*
*
* @param contractNo
*/
public void signedCallBack(String contractNo) {
// 查询合同信息表中的数据
UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfo(contractNo);
Map<String, Object> update = new HashMap<>();
if (ufContractInfoDTO.getQueueSigned() == 1) {
// 属于顺序签署合同,更新单份合同已签蜀几个文件
update.put("single_signed_num", ufContractInfoDTO.getSingleSignedNum() + 1);
// 如果单份合同签署数量等于合同文件数量,表示已经签署完成
if (ufContractInfoDTO.getSingleSignedNum() + 1 == ufContractInfoDTO.getSingleContractFileNum()) {
update.put("signed_num", ufContractInfoDTO.getSignedNum() + 1);
// 查询下一位合同方并发起签署
nextContractSigned(ufContractInfoDTO);
}
// 如果合同已签数量和应签数量相同,则状态为本方待签
if (ufContractInfoDTO.getSignedNum() + 1 == ufContractInfoDTO.getShouldSignedNum()) {
update.put("contract_status", 3);
}
} else {
// 全部合同一起发送的签署信息
// 直接合同已签署+1
update.put("signed_num", ufContractInfoDTO.getSignedNum() + 1);
// 如果已签文件数等于需要签署的合同数乘以合同文件数相等,则代表对方已经签署完毕
if (ufContractInfoDTO.getSignedNum() + 1 == ufContractInfoDTO.getShouldSignedNum() * ufContractInfoDTO.getSingleContractFileNum()) {
update.put("contract_status", 3);
}
}
// 更新状态
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql("uf_contract_info", update,
Util.createPrepWhereImpl().whereAnd("id").whereEqual(ufContractInfoDTO.getId()));
RecordSet rs = new RecordSet();
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
// 查询合同状态,更新明细表
/* Map<String,Object> data = new HashMap<>();
data.put("contractNo","6a265befb3944d93a7a8b32b8d5ca33d");
Map<String, Object> faResult = null;
try {
faResult = FaDDRequestUtils.queryDetailContractStatus(data);
String code = Util.null2String(faResult.get("code"));
if(!"200".equals(code)){
throw new RuntimeException("查询合同失败,失败原因:" + faResult);
}
Map<String,Object> resultData = (Map<String, Object>) faResult.get("data");
List<Map<String, Object>> contractSignerList = (List<Map<String, Object>>) resultData.get("contractSignerList");
for (Map<String, Object> signer : contractSignerList) {
if("-1".equals(signer.get("isSender"))){
continue;
}
String customerId = Util.null2String(signer.get("customerId"));
String signStatus = Util.null2String(signer.get("signStatus"));
if(!"1".equals(signStatus)){
continue;
}
// 更新数据库
update.clear();
update.put("signed_status",2);
// 查询明细表id
}
} catch (JsonProcessingException e) {
e.printStackTrace();
toolUtil.writeErrorLog("查询合同失败,失败原因:" + e);
}*/
}
/**
*
*
* @param ufContractInfoDTO
*/
private void nextContractSigned(UfContractInfoDTO ufContractInfoDTO) {
String query = "select * from " + ufContractInfoDTO.getWorkflowDetailTable() + " where mainid = ? and signed_status is null";
RecordSet rs = new RecordSet();
rs.executeQuery(query, ufContractInfoDTO.getMainId());
List<Map<String, Object>> detailMaps = Util.recordSet2MapList(rs);
// 获取配置表信息
FaDaDaConfigDTO faDaDaConfigDTO = faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 3);
// 查询接口配置树形结构
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig());
// 查询签署数据
List<Map<String, Object>> dataArr = getDataArr(ufContractInfoDTO.getWorkflowRequestId(),
String.valueOf(ufContractInfoDTO.getWorkflowType()), ufContractInfoDTO.getWorkflowMainTable(),
ufContractInfoDTO.getWorkflowDetailTable(), detailMaps);
// 处理数据
List<Map<String, Object>> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr);
if (maps == null) {
toolUtil.writeErrorLog("service签署合同错误错误原因maps为null!");
throw new RuntimeException("service签署合同错误错误原因maps为null");
}
if (maps.size() == 0) {
return;
}
Map<String, Object> updateData = new HashMap<>();
Map<String, Object> map = maps.get(0);
signedRequest(map, apiConfigMainDTO);
// 将合同签署信息更新到合同信息表中
updateData.put("single_signed_num", 0);
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(contractInfoTable, updateData,
Util.createPrepWhereImpl().whereAnd("workflow_request_id").whereEqual(ufContractInfoDTO.getWorkflowRequestId()));
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
updateData.clear();
// 更新明细表合同信息 TODO 明细表添加字段signed_status合同方签署状态
// 签署状态1 已发送待签署2 已签蜀
updateData.put("signed_status", 1);
sqlResult = Util.createSqlBuilder().updateSql(ufContractInfoDTO.getWorkflowDetailTable(), updateData,
Util.createPrepWhereImpl().whereAnd("id").whereEqual(String.valueOf(map.get("id"))));
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
}
/**
*
*
* @param map
* @param apiConfigMainDTO
*/
private void signedRequest(Map<String, Object> map, ApiConfigMainDTO apiConfigMainDTO) {
String contractNos = Util.null2String(map.get("contractNo"));
String[] split = contractNos.split(",");
// RecordSet rs = new RecordSet();
for (String s : split) {
map.put("contractNo", s);
ResponeVo responeVo = FaDDRequestUtils.signedContract(map, apiConfigMainDTO.getApiUrl());
Map<String, Object> response = null;
try {
response = responeVo.getEntityMap();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
if (!"200".equals(response.get("code"))) {
toolUtil.writeErrorLog("法大大接口签署合同失败!");
throw new RuntimeException("法大大接口签署合同失败!");
}
}
}
/**
*
*
* @param requestId
* @return
*/
public Map<String, Object> querySignedStatus(String requestId) {
// 查询合同状态
String query = "select * from " + contractInfoTable + " where workflow_request_id = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, requestId);
Map<String, Object> result = Util.recordSet2Map(rs);
this.toolUtil.writeErrorLog(result.toString());
boolean isAllSinged = false;
boolean isSingedOneself = false;
if (result == null) {
toolUtil.writeErrorLog("查询到状态为nullsql" + query + " ---> " + requestId);
return ParaMap.create().put("isAllSinged", false)
.put("isSingedOneself", false);
}
// 等待对方签署
/* if("2".equals(result.get("contract_status"))){
isAllSinged = false;
}*/
// 等待我方签署
if ("3".equals(Util.null2String(result.get("contract_status")))) {
isAllSinged = true;
}
// 签署完毕
if ("4".equals(Util.null2String(result.get("contract_status")))) {
isAllSinged = true;
isSingedOneself = true;
}
return ParaMap.create().put("isAllSinged", isAllSinged)
.put("isSingedOneself", isSingedOneself);
}
public void signedContractOwn(String requestId, User user) {
// 查询合同信息
UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfoByRequestId(requestId);
// 获取配置表信息
FaDaDaConfigDTO faDaDaConfigDTO = faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 4);
// 查询接口配置树形结构
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig());
// 查询签署数据
List<Map<String, Object>> dataArr = getDataArr(ufContractInfoDTO.getWorkflowRequestId(),
String.valueOf(ufContractInfoDTO.getWorkflowType()), ufContractInfoDTO.getWorkflowMainTable(),
ufContractInfoDTO.getWorkflowDetailTable());
// 处理数据
List<Map<String, Object>> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr);
if (maps == null) {
toolUtil.writeErrorLog("service签署合同错误错误原因maps为null!");
throw new RuntimeException("service签署合同错误错误原因maps为null");
}
if (maps.size() == 0) {
return;
}
Map<String, Object> data = maps.get(0);
String contractNos = String.valueOf(data.get("contractNo"));
String[] split = contractNos.split(",");
List<String> downloadUrlList = new ArrayList<>();
List<String> viewUrlList = new ArrayList<>();
for (String s : split) {
data.put("contractNo", s);
ResponeVo responeVo = FaDDRequestUtils.signedContract(data, apiConfigMainDTO.getApiUrl());
Map<String, Object> response = null;
try {
response = responeVo.getEntityMap();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
if (!"200".equals(response.get("code"))) {
this.toolUtil.writeErrorLog("签署参数:" + responeVo.getEntityString());
throw new RuntimeException("本方签署失败!法大大请求接口错误!");
}else{
Map<String,Object> result = (Map<String, Object>) response.get("data");
downloadUrlList.add(Util.null2String(result.get("downloadUrl")));
viewUrlList.add(Util.null2String(result.get("viewUrl")));
}
}
// 更新合同状态
RecordSet rs = new RecordSet();
Map<String, Object> update = new HashMap<>();
update.put("contract_status", 4);
update.put("contract_view_url", String.join(";",viewUrlList));
update.put("contract_down_url", String.join(";",downloadUrlList));
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(contractInfoTable, update,
Util.createPrepWhereImpl().whereAnd("workflow_request_id").whereEqual(requestId));
toolUtil.writeErrorLog(sqlResult.getSqlStr() + ",参数:" + sqlResult.getArgs());
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
// 获取流程中的合同字段的文档目录id
rs.executeQuery("select formid from workflow_base where id = ?",ufContractInfoDTO.getWorkflowType());
String formId = Util.recordeSet2Entity(rs, String.class);
String query = "select doccategory from workflow_fileupload where fieldid = (select id from workflow_billfield where fieldname = ? and billid = ?)";
rs.executeQuery(query,faDaDaConfigDTO.getContractDoc(),formId);
String docCategorys =Util.null2String(Util.recordeSet2Entity(rs, String.class));
if(StringUtils.isNullOrEmpty(docCategorys)){
query = "select doccategory from workflow_base where id = ?";
rs.executeQuery(query,ufContractInfoDTO.getWorkflowType());
rs.next();
docCategorys = Util.null2String(rs.getString(1));
}
if(StringUtils.isNullOrEmpty(docCategorys)){
docCategorys = ",,1";
}
// String[] docSplit = docCategorys.split(",");
// String category = docSplit[docSplit.length - 1];
// 下载合同到文件服务器中
String docIds = "";
try {
docIds = downloadContract2FileSystem(ufContractInfoDTO, docCategorys, user);
}catch (Exception e){
toolUtil.writeErrorLog("创建文档发生错误:" + e);
}
toolUtil.writeErrorLog("生成的文档的id" + docIds);
// 将id保存到流程字段中
sqlResult = Util.createSqlBuilder().updateSql(ufContractInfoDTO.getWorkflowMainTable(),
ParaMap.create().put(faDaDaConfigDTO.getContractDoc(), docIds),
Util.createPrepWhereImpl().whereAnd("id").whereEqual(ufContractInfoDTO.getMainId()));
toolUtil.writeErrorLog(sqlResult.getSqlStr() + ",参数:" + sqlResult.getArgs());
rs.executeUpdate(sqlResult.getSqlStr(),sqlResult.getArgs());
}
public String downloadContract2FileSystem(UfContractInfoDTO ufContractInfoDTO, String category, User user) {
/* ImageFileManager fileManager = new ImageFileManager();
int fileId = fileManager.saveImageFileByInputStream(downloadContract(ufContractInfoDTO.getContractNo(),
String.valueOf(ufContractInfoDTO.getWorkflowType())), ufContractInfoDTO.getFileName());*/
// 获取配置表信息
FaDaDaConfigDTO faDaDaConfigDTO = faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 5);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig());
String contractNos = Util.null2String(ufContractInfoDTO.getContractNo());
String[] split = contractNos.split(",");
List<String> docIds = new ArrayList<>();
for (String contractNo : split) {
// InputStream inputStream = downloadContract(s, String.valueOf(ufContractInfoDTO.getWorkflowType()));
Map<String, Object> data = new HashMap<>();
data.put("contractNo", contractNo);
AtomicReference<InputStream> content = new AtomicReference<>();
FaDDRequestUtils.downContract(data, response -> {
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("法大大请求接口错误!");
}
try {
content.set(entity.getContent());
} catch (IOException e) {
e.printStackTrace();
}
byte[] byteArray = null;
try {
byteArray = IOUtils.toByteArray(content.get());
} catch (IOException e) {
e.printStackTrace();
toolUtil.writeErrorLog("文件流处理错误将inputStream转换为byte数组出错" + e);
}
this.toolUtil.writeErrorLog(ufContractInfoDTO.toString());
String base64 = Base64Utils.encode(byteArray);
FileProcessor fileProcessor = new FileProcessor();
toolUtil.writeErrorLog("base64" + "base64:" + base64);
toolUtil.writeErrorLog("category" + category);
toolUtil.writeErrorLog("user" + JSON.toJSONString(user));
toolUtil.writeErrorLog("fileName" + ufContractInfoDTO.getFileName());
docIds.add(String.valueOf(fileProcessor.Process("base64:" + base64, category, user, ufContractInfoDTO.getFileName())));
}, apiConfigMainDTO.getApiUrl());
}
return String.join(",", docIds);
}
public InputStream downloadContract(String contractNo, String workflowId) {
// 获取配置表信息
FaDaDaConfigDTO faDaDaConfigDTO = faDDContractMapping.queryConfig(workflowId, 5);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig());
Map<String, Object> data = new HashMap<>();
data.put("contractNo", contractNo);
AtomicReference<InputStream> content = new AtomicReference<>();
FaDDRequestUtils.downContract(data, response -> {
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("法大大请求接口错误!");
}
try {
content.set(entity.getContent());
} catch (IOException e) {
e.printStackTrace();
}
}, apiConfigMainDTO.getApiUrl());
return content.get();
}
/**
*
* @param ufContractInfoDTO
* @return
*/
public StreamingOutput download4mFDD(UfContractInfoDTO ufContractInfoDTO){
// 获取配置表信息
FaDaDaConfigDTO faDaDaConfigDTO = faDDContractMapping.queryConfig(String.valueOf(ufContractInfoDTO.getWorkflowType()), 5);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig());
// 查询合同信息
// UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfoByRequestId(requestId);
String contractNos = Util.null2String(ufContractInfoDTO.getContractNo());
String fileNames = Util.null2String(ufContractInfoDTO.getFileName());
String[] contractNoArr = contractNos.split(",");
String[] fileNameArr = fileNames.split(",");
toolUtil.writeErrorLog("下载合同download4mFDD");
if(contractNoArr.length >= 2){
// 多个文件,需要下载压缩包
return outputStream -> {
ZipOutputStream zipOut = new ZipOutputStream(outputStream);
int catchLen = 10 * 1024;
for (int i = 0; i < contractNoArr.length; i++) {
// InputStream inputStream = downloadContract(contractNoArr[i], String.valueOf(ufContractInfoDTO.getWorkflowType()));
Map<String, Object> data = new HashMap<>();
data.put("contractNo", contractNoArr[i]);
AtomicReference<InputStream> content = new AtomicReference<>();
int finalI = i;
FaDDRequestUtils.downContract(data, response -> {
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("法大大请求接口错误!");
}
try {
content.set(entity.getContent());
zipOut.putNextEntry(new ZipEntry(fileNameArr[finalI]));
byte[] buffer = new byte[catchLen];
int len = 0;
while ((len = content.get().read(buffer)) != -1) {
zipOut.write(buffer, 0, len);
}
content.get().close();
zipOut.closeEntry();
} catch (IOException e) {
e.printStackTrace();
toolUtil.writeErrorLog("文件压缩处理出现问题!" + e);
}
}, apiConfigMainDTO.getApiUrl());
}
zipOut.flush();
zipOut.close();
outputStream.flush();
outputStream.close();
};
}
return outputStream->{
toolUtil.writeErrorLog("download4mFDD单文件下载");
// InputStream inputStream = downloadContract(contractNos,String.valueOf(ufContractInfoDTO.getWorkflowType()));
Map<String, Object> data = new HashMap<>();
data.put("contractNo", contractNos);
AtomicReference<InputStream> content = new AtomicReference<>();
FaDDRequestUtils.downContract(data, response -> {
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("法大大请求接口错误!");
}
try {
content.set(entity.getContent());
int catchLen = 10 * 1024;
byte[] buffer = new byte[catchLen];
int len = 0;
while ((len = content.get().read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
content.get().close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
toolUtil.writeErrorLog("单文件下载处理出现问题!" + e);
}
}, apiConfigMainDTO.getApiUrl());
};
}
}

View File

@ -0,0 +1,595 @@
package com.api.aiyh_pcn.fadada.service.impl;
import aiyh.utils.Util;
import aiyh.utils.entity.ApiConfigDetailDTO;
import aiyh.utils.entity.ApiConfigMainDTO;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping;
import com.api.aiyh_pcn.fadada.entity.FaDaDaConfigDTO;
import com.api.aiyh_pcn.fadada.service.IFaDDService;
import com.api.aiyh_pcn.fadada.util.FaDDRequestUtils;
import com.api.aiyh_pcn.fadada.vo.TableFieldMappingVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import weaver.conn.RecordSet;
import weaver.workflow.workflow.WorkflowVersion;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/30 0030 11:12
* service
*/
public class FaDDServiceImpl implements IFaDDService {
private final FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping();
private final ToolUtil toolUtil = new ToolUtil();
// private final String MAIN_TABLE = "formtable_main_17";
@Override
public Map<String, Object> getConfigParam(String workflowId) {
FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 0);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(faDaDaConfigDTO.getParamsConfig());
List<TableFieldMappingVO> tableFieldMappingVOS = new ArrayList<>();
List<ApiConfigDetailDTO> details = apiConfigMainDTO.getDetails();
for (ApiConfigDetailDTO detail : details) {
TableFieldMappingVO tableFieldMappingVO = new TableFieldMappingVO();
String tableName = "";
String fieldName = "";
int id = detail.getId();
String table = detail.getTablename();
if (!table.contains("_dt")) {
// 表示字段属于主表
tableName = "main";
} else {
// 字段属于明细表
String dt = table.substring(table.indexOf("_dt") + 3);
tableName = "detail_" + dt;
}
tableFieldMappingVO.setTableName(tableName);
tableFieldMappingVO.setId(id);
int changeRule = detail.getChangeRule();
if (changeRule == 0) {
// 不转换,需要获取到流程字段,前端获取流程字段对应的值
fieldName = detail.getWorkflowField();
tableFieldMappingVO.setField(fieldName);
tableFieldMappingVOS.add(tableFieldMappingVO);
} else if (changeRule == 2) {
// 流程字段值,与不转换一至
fieldName = detail.getWorkflowField();
tableFieldMappingVO.setField(fieldName);
tableFieldMappingVOS.add(tableFieldMappingVO);
}
if (changeRule == 7 || changeRule == 6) {
// 7 自定义SQL与流程转SQL一样
List<TableFieldMappingVO> tableFieldMappingVOList = new ArrayList<>();
// 6 流程字段转SQL需要获取SQL中的字段变量前端通过字段变量获取值
// 解析SQL
Map<String, List<String>> result = Util.parsingSq2Map(detail.getParamValue());
for (Map.Entry<String, List<String>> entry : result.entrySet()) {
for (String field : entry.getValue()) {
TableFieldMappingVO tf = new TableFieldMappingVO();
tf.setTableName(entry.getKey());
tf.setField(field);
tf.setId(id);
tableFieldMappingVOList.add(tf);
}
}
tableFieldMappingVOS.addAll(tableFieldMappingVOList);
}
if (detail.getParamType() == 4) {
// 数组类型的需要解析数组sql
List<TableFieldMappingVO> tableFieldMappingVOList = new ArrayList<>();
Map<String, List<String>> result = Util.parsingSq2Map(detail.getArraySql());
for (Map.Entry<String, List<String>> entry : result.entrySet()) {
for (String field : entry.getValue()) {
TableFieldMappingVO tf = new TableFieldMappingVO();
tf.setTableName(entry.getKey());
tf.setField(field);
tf.setId(id);
tableFieldMappingVOList.add(tf);
}
}
tableFieldMappingVOS.addAll(tableFieldMappingVOList);
}
}
List<TableFieldMappingVO> doDeWeight = Util.deWeight(tableFieldMappingVOS, e -> e.getTableName() + e.getField());
Map<String, Object> map = new HashMap<>();
map.put("tableFieldMappings", doDeWeight);
String checkSource = faDaDaConfigDTO.getCheckSource();
String sourceTable;
if (!checkSource.contains("_dt")) {
// 表示字段属于主表
sourceTable = "main";
map.put("isMain", true);
} else {
// 字段属于明细表
String dt = checkSource.substring(checkSource.indexOf("_dt") + 3);
sourceTable = "detail_" + dt;
map.put("isMain", false);
}
map.put("sourceTable", sourceTable);
return map;
}
@Override
public Map<String, Object> checkCertification(Map<String, Object> params) {
Map<String, Object> resultMap = new HashMap<>();
String workflowId = String.valueOf(params.get("workflowId"));
FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 0);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig());
List<Map<String, Object>> dataArr = (List<Map<String, Object>>) params.get("dataArr");
List<ApiConfigDetailDTO> details = apiConfigMainDTO.getDetails();
List<Map<String, Object>> datas = objectAndListHandle(details, dataArr);
List<Map<String, Object>> errorList = new ArrayList<>();
List<Map<String, Object>> nonsupportList = new ArrayList<>();
for (Map<String, Object> data : datas) {
System.out.println(JSONObject.toJSONString(data));
Map<String, Object> result = FaDDRequestUtils.checkCompanyInfo(data);
if (result == null) {
// 未查询到数据
errorList.add(data);
} else {
if ("1001005".equals(String.valueOf(result.get("code"))) || !"200".equals(String.valueOf(result.get("code")))) {
// 企业信息不存在或者未认证
nonsupportList.add(data);
}
}
}
if (errorList.size() == 0 && nonsupportList.size() == 0) {
// 所有的都通过
resultMap.put("allPass", true);
} else {
resultMap.put("allPass", false);
resultMap.put("errorList", errorList);
resultMap.put("nonsupportList", nonsupportList);
}
return resultMap;
}
private List<Map<String, Object>> objectAndListHandle(List<ApiConfigDetailDTO> treeList, List<Map<String, Object>> dataArr) {
List<Map<String, Object>> params = new ArrayList<>();
for (Map<String, Object> dataMap : dataArr) {
Map<String, Object> param = new HashMap<>();
for (ApiConfigDetailDTO apiConfigDetailDTO : treeList) {
Object value;
if (apiConfigDetailDTO.getParamType() == 3) {
Map<String, Object> map = new HashMap<>();
// object类型
for (ApiConfigDetailDTO child : apiConfigDetailDTO.getChildren()) {
if (child.getChildren() == null || child.getChildren().size() == 0) {
// handleChild(child.getChildren(), dataMap)
map.put(child.getParamName(), changeRuleHandle(child, dataMap));
} else {
map.put(child.getParamName(), handleChild(child.getChildren(), dataMap));
}
}
value = map;
} else if (apiConfigDetailDTO.getParamType() == 4) {
String sql = apiConfigDetailDTO.getArraySql();
String parsingSq = Util.parsingSq(sql, dataMap);
// list类型
if (parsingSq.contains("delete") || parsingSq.contains("update") ||
parsingSq.contains("exec") || parsingSq.contains("drop") ||
parsingSq.contains("truncate")) {
value = new ArrayList<>();
} else {
RecordSet rs = new RecordSet();
rs.executeQuery(parsingSq.replace("", "select"));
value = Util.recordeSet2Array(rs, String.class);
}
} else {
value = changeRuleHandle(apiConfigDetailDTO, dataMap);
}
param.put(apiConfigDetailDTO.getParamName(), value);
}
params.add(param);
}
return params;
}
private Object handleChild(List<ApiConfigDetailDTO> children, Map<String, Object> dataMap) {
Map<String, Object> params = new HashMap<>();
for (ApiConfigDetailDTO child : children) {
Object value;
if (child.getChildren() != null) {
value = handleChild(child.getChildren(), dataMap);
} else {
value = changeRuleHandle(child, dataMap);
}
params.put(child.getParamName(), value);
}
return params;
}
private Object changeRuleHandle(ApiConfigDetailDTO apiConfigDetailDTO, Map<String, Object> dataMap) {
Object value;
String tableName;
String table;
String sql;
String resultSql;
// 判断参数的转换规则
switch (apiConfigDetailDTO.getChangeRule()) {
case 0:
// 不转换
case 2:
// 流程字段值
table = apiConfigDetailDTO.getTablename();
if (!table.contains("_dt")) {
// 表示字段属于主表
tableName = "main";
} else {
// 字段属于明细表
String dt = table.substring(table.indexOf("_dt") + 3);
tableName = "detail_" + dt;
}
value = dataMap.get(tableName + "." + apiConfigDetailDTO.getWorkflowField());
break;
case 1:
// 固定值
value = apiConfigDetailDTO.getParamValue();
break;
case 3:
// 系统日期
value = Util.getTime("yyyy-MM-dd");
break;
case 4:
// 系统时间
value = Util.getTime("HH:mm:ss");
break;
case 5:
// 系统日期-时间
value = Util.getTime("yyyy-MM-dd HH:mm:ss");
break;
case 6:
// 自定义SQL
case 7:
// 流程字段转SQL
sql = apiConfigDetailDTO.getParamValue();
resultSql = Util.parsingSq(sql, dataMap);
toolUtil.writeErrorLog(dataMap.toString());
if (resultSql.contains("delete ") || resultSql.contains("update ") ||
resultSql.contains("exec ") || resultSql.contains("drop ") ||
resultSql.contains("truncate ")) {
value = null;
} else {
RecordSet rs = new RecordSet();
rs.executeQuery(resultSql.replace("", "select"));
rs.next();
value = Util.null2String(rs.getString(1));
toolUtil.writeErrorLog("转换值:" + value);
toolUtil.writeErrorLog("转换SQL" + resultSql.replace("", "select"));
}
break;
case 8:
// TODO
// 流程名称
value = Util.getWorkflowNameById(String.valueOf(dataMap.get("workflowid")));
break;
case 9:
// TODO
// 请求标题
value = Util.getRequestTitleById(String.valueOf(dataMap.get("requestid")));
break;
case 10:
// TODO
// 流程requestId
value = dataMap.get("requestid");
break;
default:
value = null;
break;
}
if (apiConfigDetailDTO.getParamType() == 1) {
// Integer
value = Integer.parseInt(String.valueOf(value));
} else if (apiConfigDetailDTO.getParamType() == 2) {
// Boolean
value = Boolean.parseBoolean(String.valueOf(value));
}
return value;
}
public void queryContractStatus(String workflowId, String requestId, int type) {
List<Map<String, Object>> maps = faDDServiceMapping.queryDetailInfo(requestId, workflowId, 2);
toolUtil.writeErrorLog("maps+:" + maps);
List<Map<String, Object>> notSignedContracts = new ArrayList<>();
// 查询是是否签署
for (Map<String, Object> map : maps) {
// 发送请求查询合同信息
Map<String, Object> data = new HashMap<>();
String contracts = String.valueOf(map.get("contract_no"));
if (contracts == null) {
contracts = "";
}
String[] split = contracts.split(",");
for (String s : split) {
toolUtil.writeErrorLog(s);
data.put("contractNo", s);
Map<String, Object> result = null;
// List<String> statusList = new ArrayList<>();
try {
Map<String, Object> response = FaDDRequestUtils.queryContractStatus(data);
if (!"200".equals(response.get("code"))) {
throw new RuntimeException("法大大请求接口错误!");
}
result = (Map<String, Object>) response.get("data");
this.toolUtil.writeErrorLog("催一催:" + result);
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
} catch (JsonProcessingException e) {
toolUtil.writeDebuggerLog("转换错误:" + e);
}
if ("1".equals(String.valueOf(result.get("status"))) || "6".equals(String.valueOf(result.get("status")))) {
// 发送请求催一下 TODO 签署合同
notSignedContracts.add(map);
} else {
// 合同状态发生改变,需要修改数据库中的状态信息 TODO 百分百会出问题
map.put("contract_status", result.get("status"));
// statusList.add()
faDDServiceMapping.updateContractStatus(map, workflowId, 3);
}
}
}
if (type == 0) {
signedContract(workflowId, requestId, notSignedContracts);
}
}
public void signedContract(String workflowId, String requestId, List<Map<String, Object>> detailMaps) {
String mainTable = faDDServiceMapping.getMainTable(workflowId);
RecordSet rs = new RecordSet();
String query = "select * from " + mainTable + " where requestid = ?";
rs.executeQuery(query, requestId);
Map<String, Object> mainMap;
mainMap = Util.recordSet2Map(rs);
String mainId = "";
if (mainMap != null) {
mainId = String.valueOf(mainMap.get("id"));
} else {
toolUtil.writeErrorLog("没有查询到相关的请求id的数据");
}
String detailTable1 = faDDServiceMapping.getDetailTable(workflowId, 3);
query = "select * from " + detailTable1 + " where mainid = ?";
rs.executeQuery(query, mainId);
/*List<Map<String,Object>> detailMaps;
detailMaps = Util.recordSet2MapList(rs);
if (detailMaps == null) {
toolUtil.writeErrorLog("查询明细失败maps为null");
return;
}*/
FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 3);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig());
List<Map<String, Object>> dataArr = new ArrayList<>();
String detailTable;
String dt = detailTable1.substring(detailTable1.indexOf("_dt") + 3);
detailTable = "detail_" + dt;
for (Map<String, Object> detailMap : detailMaps) {
Map<String, Object> dataMap = new HashMap<>();
for (Map.Entry<String, Object> entry : detailMap.entrySet()) {
dataMap.put(detailTable + "." + entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : mainMap.entrySet()) {
dataMap.put("main" + "." + entry.getKey(), entry.getValue());
}
dataArr.add(dataMap);
}
List<Map<String, Object>> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr);
for (Map<String, Object> map : maps) {
toolUtil.writeErrorLog(map.toString());
String contractNos = Util.null2String(map.get("contractNo"));
String[] split = contractNos.split(",");
for (String s : split) {
map.put("contractNo", s);
ResponeVo responeVo = FaDDRequestUtils.signedContract(map, apiConfigMainDTO.getApiUrl());
Map<String, Object> response = null;
try {
response = responeVo.getEntityMap();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
if (!"200".equals(response.get("code"))) {
throw new RuntimeException("法大大请求接口错误!");
}
}
}
}
public StreamingOutput contractDownload(String requestId, String workflowId) {
toolUtil.writeErrorLog("进入service方法");
List<Map<String, Object>> maps = null;
// 查询合同信息
try {
maps = faDDServiceMapping.queryDetailDownInfo(requestId, workflowId, 2);
} catch (Exception e) {
toolUtil.writeErrorLog(String.valueOf(faDDServiceMapping));
toolUtil.writeErrorLog("调用错误" + e);
}
toolUtil.writeErrorLog(String.valueOf(maps));
toolUtil.writeErrorLog(JSONObject.toJSONString(maps));
List<Map<String, Object>> finalMaps = maps;
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
RecordSet rs = new RecordSet();
rs.executeQuery("select * from uf_contract_config where workflow_type in ( " + versionStringByWfid + " ) and api_type = ?", 5);
rs.next();
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfig(rs.getString("params_config"));
return outputStream -> {
ZipOutputStream zipOut = new ZipOutputStream(outputStream);
toolUtil.writeErrorLog("进入方法!");
int catchLen = 10 * 1024;
String base = "";
for (Map<String, Object> map : finalMaps) {
base = base + map.get("gyshtfmczw") + "/";
// 获取合同id
String contractNoStr = String.valueOf(map.get("contract_no"));
String contractNameStr = String.valueOf(map.get("file_name"));
String[] contractNos = contractNoStr.split(",");
String[] contractNames = contractNameStr.split(",");
for (int i = 0; i < contractNos.length; i++) {
String contractNo = contractNos[i];
String contractName = contractNames[i];
Map<String, Object> data = new HashMap<>();
data.put("contractNo", contractNo);
// 下载合同
String finalBase = base;
FaDDRequestUtils.downContract(data, response -> {
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("法大大请求接口错误!");
}
InputStream content = null;
try {
content = entity.getContent();
Header contentHeader = response.getFirstHeader("Content-disposition");
String filename = contractName.substring(0, contractName.indexOf(".")) + ".pdf";
if (contentHeader != null) {
HeaderElement[] values = contentHeader.getElements();
NameValuePair param = values[0].getParameterByName("filename");
filename = param.getValue();
}
zipOut.putNextEntry(new ZipEntry(finalBase + filename));
byte[] buffer = new byte[catchLen];
int len = 0;
while ((len = content.read(buffer)) != -1) {
zipOut.write(buffer, 0, len);
}
zipOut.closeEntry();
} catch (IOException e) {
e.printStackTrace();
toolUtil.writeErrorLog("压缩错误!" + e + "\n");
}
},apiConfigMainDTO.getApiUrl());
}
}
zipOut.flush();
zipOut.close();
};
}
public boolean isAllSinged(String requestId, String workflowId) {
List<Map<String, Object>> maps = faDDServiceMapping.queryDetailInfo(requestId, workflowId, 2);
if (maps == null || maps.size() == 0) {
return true;
}
return false;
}
public boolean isSingedOneself(String requestId, String workflowId) {
List<Map<String, Object>> maps = faDDServiceMapping.querySignedInfo(requestId, workflowId);
if (maps == null || maps.size() == 0) {
return false;
}
return true;
}
public void signedContractOwn(String workflowId, String requestId) {
String mainTable = faDDServiceMapping.getMainTable(workflowId);
RecordSet rs = new RecordSet();
String query = "select * from " + mainTable + " where requestid = ?";
rs.executeQuery(query, requestId);
Map<String, Object> mainMap;
mainMap = Util.recordSet2Map(rs);
String mainId = "";
if (mainMap != null) {
mainId = String.valueOf(mainMap.get("id"));
} else {
toolUtil.writeErrorLog("没有查询到相关的请求id的数据");
}
String detailTable1 = faDDServiceMapping.getDetailTable(workflowId, 4);
query = "select * from " + detailTable1 + " where mainid = ?";
rs.executeQuery(query, mainId);
List<Map<String, Object>> detailMaps;
detailMaps = Util.recordSet2MapList(rs);
this.toolUtil.writeErrorLog("查询到的数据:" + detailMaps.toString());
if (detailMaps == null) {
toolUtil.writeErrorLog("查询明细失败maps为null");
return;
}
FaDaDaConfigDTO faDaDaConfigDTO = faDDServiceMapping.queryConfig(workflowId, 4);
ApiConfigMainDTO apiConfigMainDTO = Util.queryApiConfigTree(faDaDaConfigDTO.getParamsConfig());
List<Map<String, Object>> dataArr = new ArrayList<>();
String detailTable;
String dt = detailTable1.substring(detailTable1.indexOf("_dt") + 3);
detailTable = "detail_" + dt;
toolUtil.writeErrorLog("明细表:" + detailTable);
for (Map<String, Object> detailMap : detailMaps) {
Map<String, Object> dataMap = new HashMap<>();
for (Map.Entry<String, Object> entry : detailMap.entrySet()) {
dataMap.put(detailTable + "." + entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : mainMap.entrySet()) {
dataMap.put("main" + "." + entry.getKey(), entry.getValue());
}
dataArr.add(dataMap);
}
toolUtil.writeErrorLog("替换参数值:" + dataArr.toString());
List<Map<String, Object>> maps = objectAndListHandle(apiConfigMainDTO.getDetails(), dataArr);
for (Map<String, Object> map : maps) {
this.toolUtil.writeErrorLog("签署参数:" + map.toString());
String contractNos = Util.null2String(map.get("contractNo"));
String[] split = contractNos.split(",");
for (String s : split) {
map.put("contractNo", s);
ResponeVo responeVo = FaDDRequestUtils.signedContract(map,apiConfigMainDTO.getApiUrl());
Map<String, Object> response = null;
try {
response = responeVo.getEntityMap();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
if (!"200".equals(response.get("code"))) {
// throw new RuntimeException("法大大请求接口错误!");
this.toolUtil.writeErrorLog("签署参数:" + responeVo.getEntityString());
}
}
}
}
public Map<String, Object> getAllVersion(String workflowId, String markOnly) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String newWorkflowId = faDDServiceMapping.getAllVersion(versionStringByWfid);
String allVersion = WorkflowVersion.getVersionStringByWfid(newWorkflowId);
if (allVersion == null) {
allVersion = "";
}
String[] split = allVersion.split(",");
Map<String, Object> data = new HashMap<>();
String[] nodes = this.getNodes(workflowId, markOnly);
data.put("workflowIds", split);
data.put("nodeIds", nodes);
return data;
}
public String[] getNodes(String workflowId, String markOnly) {
String versionStringByWfid = WorkflowVersion.getVersionStringByWfid(workflowId);
String nods = faDDServiceMapping.getNodes(versionStringByWfid, markOnly);
if (nods == null) {
nods = "";
}
return nods.split(",");
}
}

View File

@ -0,0 +1,195 @@
package com.api.aiyh_pcn.fadada.util;
import aiyh.utils.Util;
import aiyh.utils.httpUtil.HttpArgsType;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.util.HttpUtils;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.codec.binary.Hex;
import org.apache.http.client.methods.CloseableHttpResponse;
import weaver.aiyh_pcn.fadada.entity.FileInfo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/13 0013 11:46
*
*/
public class FaDDRequestUtils {
private final static HttpUtils httpUtils = new HttpUtils();
private final static Map<String, String> header = httpUtils.getGlobalCache().header;
private final static FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping();
private final static ToolUtil TOOL_UTIL = new ToolUtil();
static {
header.put("appId", "100001");
header.put("signType", "SHA256");
header.put("apikey", "TulQxnZSRKeHoQfmeZzOUzGn6KpTDkDK");
header.put("Content-Type", HttpArgsType.APPLICATION_JSON);
}
// 查询企业认证状态
public static Map<String, Object> checkCompanyInfo(Map<String, Object> data) {
header.put("sign", builderSign(data));
try {
ResponeVo responeVo = httpUtils.apiPost("http://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/account/company/info",
data, null);
TOOL_UTIL.writeDebuggerLog("查询企业认真状态:" + JSONObject.toJSONString(data));
TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
// System.out.println(responeVo.getEntityString());
if (responeVo.getCode() != 200) {
return null;
}
return responeVo.getEntityMap();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// 创建合同
public static ResponeVo createContract(FileInfo fileInfo,String url) {
Map<String, Object> data = new HashMap<>();
data.put("contractExtension", fileInfo.getContractExtension());
data.put("contractTitle", fileInfo.getContractTitle());
data.put("uploadType", fileInfo.getUploadType());
data.put("customerNo", fileInfo.getCustomerNo());
header.put("sign", builderSign(data));
header.put("Content-Type", "multipart/form-data");
// System.out.println(JSONObject.toJSONString(data));
ResponeVo responeVo = null;
try {
responeVo = httpUtils.apiUploadFile(url,
fileInfo.getFile(), "file", fileInfo.getImagefilename(), data, null);
TOOL_UTIL.writeDebuggerLog("创建合同:" + JSONObject.toJSONString(data));
TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
} catch (IOException e) {
e.printStackTrace();
TOOL_UTIL.writeErrorLog(e.toString());
}
// System.out.println(JSONObject.toJSONString(responeVo));
return responeVo;
}
// 签署合同
public static ResponeVo signedContract(Map<String, Object> data, String url) {
header.put("sign", builderSign(data));
header.put("Content-Type", "application/json");
// System.out.println(JSONObject.toJSONString(data));
ResponeVo responeVo = null;
try {
// http://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/sign
responeVo = httpUtils.apiPost(url,
data, null);
TOOL_UTIL.writeDebuggerLog("签署合同:" + JSONObject.toJSONString(data));
TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
// System.out.println(JSONObject.toJSONString(responeVo));
} catch (IOException e) {
e.printStackTrace();
}
return responeVo;
}
public static void downContract(Map<String, Object> data, Consumer<CloseableHttpResponse> consumer,String url) {
header.put("sign", builderSign(data));
header.put("Content-Type", "application/json");
System.out.println(JSONObject.toJSONString(data));
try {
httpUtils.apiPost(url,
data, null, consumer);
TOOL_UTIL.writeDebuggerLog("下载合同文件:" + JSONObject.toJSONString(data));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, Object> queryContractStatus(Map<String, Object> data) throws JsonProcessingException {
header.put("sign", builderSign(data));
ResponeVo responeVo = null;
try {
responeVo = httpUtils.apiPost("https://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/sign/status/view",
data, null);
TOOL_UTIL.writeDebuggerLog("查询合同状态:" + JSONObject.toJSONString(data));
TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(JSONObject.toJSONString(responeVo));
return responeVo.getEntityMap();
}
public static Map<String, Object> queryDetailContractStatus(Map<String, Object> data) throws JsonProcessingException {
header.put("sign", builderSign(data));
ResponeVo responeVo = null;
try {
responeVo = httpUtils.apiPost("https://apigwaws-lite.porsche-cloudservice.com/env-101/econtract/econtract/contract/api/v1/contract/sign/detail/view",
data, null);
TOOL_UTIL.writeDebuggerLog("查询合同状态:" + JSONObject.toJSONString(data));
TOOL_UTIL.writeDebuggerLog(responeVo.getEntityString() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(JSONObject.toJSONString(responeVo));
return responeVo.getEntityMap();
}
private static String builderSign(Map<String, Object> data) {
header.put("timestamp", Util.getTime("yyyy-MM-dd HH:mm:ss"));
header.put("bizContent", builderBizContent(data));
String signStr = "appId=" + header.get("appId") +
"&bizContent=" + header.get("bizContent") +
"&signType=" + header.get("signType") +
"&timestamp=" + header.get("timestamp");
System.out.println(signStr);
String appKey = "L7P59oqA2An0XgJ1LeMN0fRu1";
String sha256 = string2SHA256(signStr) + appKey;
String sign = Base64.getEncoder().encodeToString(string2SHA256(sha256).getBytes(StandardCharsets.UTF_8));
// System.out.println(sign);
return sign;
}
public static String builderBizContent(Map<String, Object> data) {
String jsonString = JSONObject.toJSONString(data);
String encode = null;
try {
encode = URLEncoder.encode(jsonString, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return Base64.getEncoder().encodeToString(encode.getBytes(StandardCharsets.UTF_8));
}
private static String string2SHA256(String str) {
MessageDigest messageDigest;
String encdeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(str.getBytes(StandardCharsets.UTF_8));
encdeStr = Hex.encodeHexString(hash);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encdeStr.toUpperCase();
}
}

View File

@ -0,0 +1,47 @@
package com.api.aiyh_pcn.fadada.vo;
/**
* @author EBU7-dev1-ayh
* @create 2021/10/11 0011 15:11
*
*/
public class TableFieldMappingVO {
private String tableName;
private String field;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
@Override
public String toString() {
return "TableFieldMappingVO{" +
"tableName='" + tableName + '\'' +
", field='" + field + '\'' +
", id=" + id +
'}';
}
}

View File

@ -0,0 +1,175 @@
package com.api.aiyh_pcn.fadada.web;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.api.aiyh_pcn.fadada.dao.FaDDContractMapping;
import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO;
import com.api.aiyh_pcn.fadada.service.impl.FaDDContractService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.h2.util.StringUtils;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/11/3 0003 14:49
* fadada
*/
@Path("/v2/fadada")
public class FaDDContractController {
private final FaDDContractService faDDService = new FaDDContractService();
private final FaDDContractMapping faDDContractMapping = new FaDDContractMapping();
private final ToolUtil toolUtil = new ToolUtil();
/**
*
*
* @param workflowId id
* @return id
*/
@Path("/getAllVersion/{workflowId}/{markOnly}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getAllVersion(@PathParam("workflowId") String workflowId, @PathParam("markOnly") String markOnly) {
try {
Map<String, Object> allVersion = faDDService.getAllVersion(workflowId, markOnly);
return ApiResult.success(allVersion);
} catch (Exception e) {
toolUtil.writeErrorLog("错误:" + e.toString());
return ApiResult.error(e.toString());
}
}
/**
*
* @param params
* @return
*/
@Path("/callback/signed")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String signedCallBack(@RequestBody Map<String, Object> params) {
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "操作成功!");
String resultCode = String.valueOf(params.get("resultCode"));
if(!"1".equals(resultCode)){
// 签署失败
toolUtil.writeErrorLog("合同回调:签署失败,失败信息:" + JSON.toJSONString(params));
return JSON.toJSONString(result);
}
String contractNo = String.valueOf(params.get("docNo"));
faDDService.signedCallBack(contractNo);
return JSON.toJSONString(result);
}
/**
*
* @param requestId
* @param workflowId
* @return
*/
@Path("/isAllSigned/{workflowId}/{requestId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String querySignedStatus(@PathParam("requestId") String requestId, @PathParam("workflowId") String workflowId){
Map<String, Object> result = faDDService.querySignedStatus(requestId);
return ApiResult.success(result);
}
/**
*
*
* @param workflowId id
* @param requestId id
* @return
*/
@Path("/signedContract/own/{requestId}/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String signedContractOwn(@Context HttpServletRequest request, @Context HttpServletResponse response,
@PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId) {
// TODO 更换labelIndex
User user = HrmUserVarify.getUser(request, response);
try {
faDDService.signedContractOwn(requestId, user);
}catch (Exception e){
return ApiResult.error(Util.getHtmlLabelName(-87658,user.getLanguage(),"合同签署失败!"));
}
return ApiResult.success(Util.getHtmlLabelName(-87657,user.getLanguage(),"本方签署成功!"));
}
/**
*
*
* @param requestId id
* @return
*/
@Path("/signedContract/{requestId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String signedContract(@Context HttpServletRequest request, @Context HttpServletResponse response,
@PathParam("requestId") String requestId) {
return ApiResult.success("没有催一催接口还点!淦!等法大大调整,额。。。具体啥时候好我也不知道,反正不关我的事!");
}
/**
*
*
* @param requestId id
* @return
*/
@Path("/contract/download/{requestId}")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response contractDownload(@PathParam("requestId") String requestId) {
toolUtil.writeErrorLog("进入请求方法获取到请求id" + requestId);
try {
UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfoByRequestId(requestId);
StreamingOutput contractZipStream = faDDService.download4mFDD(ufContractInfoDTO);
String requestTitle = Util.null2String(Util.getRequestTitleById(String.valueOf(requestId)));
if(StringUtils.isNullOrEmpty(requestTitle)){
requestTitle = "contracts";
}
if(Util.null2String(ufContractInfoDTO.getContractNo()).split(",").length >= 2){
// 多文件
return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM)
.type("application/zip")
.header("Content-Disposition", "attachment;filename=" + requestTitle + ".zip").build();
}else{
// 单文件
return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM)
.type("application/pdf")
.header("Content-Disposition", "attachment;filename=" + requestTitle + ".pdf").build();
}
} catch (Exception e) {
toolUtil.writeErrorLog("文件流转换失败," + e);
return Response.ok(ApiResult.error("出现错误,错误原因: " + e), MediaType.TEXT_PLAIN).build();
}
}
}

View File

@ -0,0 +1,257 @@
package com.api.aiyh_pcn.fadada.web;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.api.aiyh_pcn.fadada.dao.FaDDServiceMapping;
import com.api.aiyh_pcn.fadada.service.impl.FaDDServiceImpl;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/28 0028 16:05
*
*/
@Path("/fadada")
public class FaDDController {
private final FaDDServiceImpl faDDService = new FaDDServiceImpl();
private final FaDDServiceMapping faDDServiceMapping = new FaDDServiceMapping();
private final ToolUtil toolUtil = new ToolUtil();
/**
*
*
* @param workflowId id
* @return
*/
@GET
@Path("/getConfig/{workflowId}")
public String getConfig(@PathParam("workflowId") String workflowId) {
try {
Map<String, Object> configParam = faDDService.getConfigParam(workflowId);
return ApiResult.success(configParam);
} catch (Exception e) {
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param params
* @return
*/
@Path("/signature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String checkCertification(@RequestBody Map<String, Object> params) {
try {
Map<String, Object> certificationResult = faDDService.checkCertification(params);
return ApiResult.success(certificationResult);
} catch (Exception e) {
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param workflowId id
* @param requestId id
* @return
*/
@Path("/signedContract/{languageGroupId}/{requestId}/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String signedContract(@Context HttpServletRequest request, @Context HttpServletResponse response,
@PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId,
@PathParam("languageGroupId") int languageGroupId) {
User user = HrmUserVarify.getUser(request, response);
try {
faDDService.queryContractStatus(workflowId, requestId,0);
Map<String, String> language = Util.queryLanguage(languageGroupId, user.getLanguage());
String info = language.get("rushInfo");
return ApiResult.success(info);
} catch (Exception e) {
toolUtil.writeErrorLog("错误:" + e);
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param workflowId id
* @param requestId id
* @return
*/
@Path("/signedContract/own/{languageGroupId}/{requestId}/{workflowId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String signedContractOwn(@Context HttpServletRequest request, @Context HttpServletResponse response,
@PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId,
@PathParam("languageGroupId") int languageGroupId) {
User user = HrmUserVarify.getUser(request, response);
try {
faDDService.signedContractOwn(workflowId, requestId);
String mainTable = faDDServiceMapping.getMainTable(workflowId);
// TODO 更新本方签署
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(mainTable, ParaMap.create()
.put("signed_oneself", 1), Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId));
RecordSet rs = new RecordSet();
rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
Map<String, String> language = Util.queryLanguage(languageGroupId, user.getLanguage());
String info = language.get("contractSignedInfo");
return ApiResult.success(info);
} catch (Exception e) {
toolUtil.writeErrorLog("错误:" + e.toString());
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param requestId id
* @return
*/
@Path("/contract/download/{workflowId}/{requestId}")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response contractDownload(@PathParam("requestId") String requestId, @PathParam("workflowId") String workflowId) {
toolUtil.writeErrorLog("进入请求方法获取到请求id" + requestId);
try {
StreamingOutput contractZipStream = faDDService.contractDownload(requestId, workflowId);
return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM)
.type("application/zip")
.header("Content-Disposition", "attachment;filename=contracts.zip").build();
} catch (Exception e) {
toolUtil.writeErrorLog("转换失败," + e.toString());
return Response.ok(ApiResult.error("出现错误,错误原因: " + e),MediaType.APPLICATION_JSON).build();
}
}
/**
*
*
* @param workflowId id
* @return id
*/
@Path("/getAllVersion/{workflowId}/{markOnly}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String getAllVersion(@PathParam("workflowId") String workflowId, @PathParam("markOnly") String markOnly) {
try {
Map<String, Object> allVersion = faDDService.getAllVersion(workflowId, markOnly);
return ApiResult.success(allVersion);
} catch (Exception e) {
toolUtil.writeErrorLog("错误:" + e.toString());
return ApiResult.error(e.toString());
}
}
/**
*
*
* @param requestId id
* @return
*/
@Path("/isAllSigned/{workflowId}/{requestId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String isAllSinged(@PathParam("requestId") String requestId, @PathParam("workflowId") String workflowId) {
try {
faDDService.queryContractStatus(workflowId,requestId,1);
boolean isAllSinged = faDDService.isAllSinged(requestId, workflowId);
boolean isSingedOneself = faDDService.isSingedOneself(requestId, workflowId);
Map<String, Object> result = ParaMap.create().put("isAllSinged", isAllSinged)
.put("isSingedOneself", isSingedOneself);
return ApiResult.success(result);
} catch (Exception e) {
toolUtil.writeErrorLog("错误:" + e);
return ApiResult.error(e.toString());
}
}
@Path("/getLanguage/{languageGroupId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getLanguage(@Context HttpServletRequest request, @Context HttpServletResponse response,
@PathParam("languageGroupId") int languageGroupId) {
User user = HrmUserVarify.getUser(request, response);
Map<String, String> map = Util.queryLanguage(languageGroupId, user.getLanguage());
return ApiResult.success(map);
}
@Path("/callback/signed")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String callBackSigned(@RequestBody Map<String, Object> params){
toolUtil.writeErrorLog("回调方法:" + JSONObject.toJSONString(params));
Map<String,Object> result = new HashMap<>();
String bizContent = String.valueOf(params.get("bizContent"));
if(StringUtils.isNullOrEmpty(bizContent)){
toolUtil.writeErrorLog("参数没获取到!");
result.put("code","200");
result.put("msg","操作失败!");
return JSONObject.toJSONString(result);
}
byte[] decode = Base64.getDecoder().decode(bizContent.getBytes(StandardCharsets.UTF_8));
String decodeStr = null;
try {
decodeStr = new String(decode,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String jsonStr = null;
try {
jsonStr = URLDecoder.decode(decodeStr, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONObject jsonObject = JSON.parseObject(jsonStr);
String resultCode = String.valueOf(jsonObject.getString("resultCode"));
String docNo = String.valueOf(jsonObject.getString("docNo"));
if(!"1".equals(resultCode)){
toolUtil.writeErrorLog("重复签署合同!" + docNo);
}
// Util.createSqlBuilder().updateSql()
this.toolUtil.writeErrorLog(jsonObject.toJSONString());
result.put("code","200");
result.put("msg","操作成功!");
return JSONObject.toJSONString(result);
}
}

View File

@ -0,0 +1,74 @@
package com.api.aiyh_quanshi.service.Impl;
import aiyh.utils.zwl.common.ToolUtil;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceBefore;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam;
import weaver.aiyh_quanshi.RequestApi;
import weaver.aiyh_quanshi.entity.QsResponse;
import weaver.conn.RecordSet;
import java.util.Map;
/**
*
*/
@WeaIocReplaceComponent("cancelMetingService")
public class CancelMetingServiceImpl {
ToolUtil toolUtil = new ToolUtil();
RequestApi requestApi = new RequestApi();
boolean flag = true;
/**
*
* @WeaReplaceBefore,valueapi
* orderapi
* WeaBeforeReplaceParam requestresponsemapapi
*/
@WeaReplaceBefore(value = "/api/meeting/base/cancelMeeting", order = 1, description = "会议接口前拦截")
public void before(WeaBeforeReplaceParam weaBeforeReplaceParam) {
// 获取会议id
Map paramMap = weaBeforeReplaceParam.getParamMap();
String id = String.valueOf(paramMap.get("meetingid"));
// 通过会议id获取全时会议id
String query = "select * from meeting where id = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, id);
rs.next();
String quanShiId = rs.getString("quan_shi_id");
String hrmId = rs.getString("contacter");
query = "select * from hrmresource where id = ?";
rs.executeQuery(query, hrmId);
rs.next();
String creatorEmail = rs.getString("email");
// 通过全时会议id对会议进行取消
QsResponse qsResponse = requestApi.cancelConference(quanShiId, creatorEmail);
if(!"0".equals(qsResponse.getStatus())){
// 取消失败
flag = false;
}
}
/**
*
* WeaReplaceAfter
* String
* WeaAfterReplaceParamdataString
* return
*/
@WeaReplaceAfter(value = "/api/meeting/base/cancelMeeting", order = 1)
public String after(WeaAfterReplaceParam weaAfterReplaceParam) {
//这个就是接口执行完的报文
String data = weaAfterReplaceParam.getData();
if(!flag){
// 取消会议失败
}else{
}
return data;
}
}

View File

@ -0,0 +1,72 @@
package com.api.aiyh_quanshi.service.Impl;
import aiyh.utils.zwl.common.ToolUtil;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceBefore;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam;
import weaver.aiyh_quanshi.RequestApi;
import weaver.aiyh_quanshi.entity.QsResponse;
import weaver.conn.RecordSet;
import java.util.Map;
/**
*
*/
@WeaIocReplaceComponent("deleteMetingService")
public class DeleteMetingServiceImpl {
ToolUtil toolUtil = new ToolUtil();
RequestApi requestApi = new RequestApi();
boolean flag = true;
/**
*
* @WeaReplaceBefore,valueapi
* orderapi
* WeaBeforeReplaceParam requestresponsemapapi
*/
@WeaReplaceBefore(value = "/api/meeting/monitor/delete", order = 1, description = "会议接口前拦截")
public void before(WeaBeforeReplaceParam weaBeforeReplaceParam) {
// 获取会议id
Map paramMap = weaBeforeReplaceParam.getParamMap();
String ids = String.valueOf(paramMap.get("meetingids"));
// 通过会议id获取全时会议id
String query = "select * from meeting where id in (" + ids + ") and cancel != 1 and meetingstatus not in (2,4)";
RecordSet rs = new RecordSet();
rs.executeQuery(query);
// 获取删除的会议的所有对应的全时id以及创建人
while (rs.next()) {
String quanShiId = rs.getString("quan_shi_id");
String hrmId = rs.getString("contacter");
query = "select * from hrmresource where id = ?";
rs.executeQuery(query, hrmId);
rs.next();
String creatorEmail = rs.getString("email");
QsResponse qsResponse = requestApi.cancelConference(quanShiId, creatorEmail);
// 通过全时会议id对会议进行取消
if (!"0".equals(qsResponse.getStatus())) {
// 取消失败
flag = false;
}
}
}
/**
*
* WeaReplaceAfter
* String
* WeaAfterReplaceParamdataString
* return
*/
@WeaReplaceAfter(value = "/api/meeting/monitor/delete", order = 1)
public String after(WeaAfterReplaceParam weaAfterReplaceParam) {
//这个就是接口执行完的报文
String data = weaAfterReplaceParam.getData();
if (!flag) {
// 取消会议失败
}
return data;
}
}

View File

@ -0,0 +1,186 @@
package com.api.aiyh_quanshi.service.Impl;
import aiyh.utils.httpUtil.staticUtil.HttpStaticUtils;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weaverboot.frame.ioc.anno.classAnno.WeaIocReplaceComponent;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceAfter;
import com.weaverboot.frame.ioc.anno.methodAnno.WeaReplaceBefore;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaAfterReplaceParam;
import com.weaverboot.frame.ioc.handler.replace.weaReplaceParam.impl.WeaBeforeReplaceParam;
import weaver.aiyh_quanshi.RequestApi;
import weaver.aiyh_quanshi.entity.QsConfParty;
import weaver.aiyh_quanshi.entity.QsResponse;
import weaver.conn.RecordSet;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
*/
@WeaIocReplaceComponent("newMetingService")
public class NewMetingServiceImpl {
ToolUtil toolUtil = new ToolUtil();
RequestApi requestApi = new RequestApi();
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
QsResponse meting = null;
private final Lock lock = new ReentrantLock();
/**
*
* @WeaReplaceBefore,valueapi
* orderapi
* WeaBeforeReplaceParam requestresponsemapapi
*/
@WeaReplaceBefore(value = "/api/meeting/base/newMeeting", order = 1, description = "会议接口前拦截")
public void before(WeaBeforeReplaceParam weaBeforeReplaceParam) {
try {
// 加锁
lock.lock();
RecordSet rs = new RecordSet();
String query;
// 同步会议到全时
// String path = Objects.requireNonNull(this.getClass().getResource("")).getPath();
// 获取请求参数
Map paramMap = weaBeforeReplaceParam.getParamMap();
// 获取会议标题
String title = String.valueOf(paramMap.get("name"));
// 会议内容
String desc_n = String.valueOf(paramMap.get("desc_n"));
// 获取会议创建人
String creator = String.valueOf(paramMap.get("contacter"));
// 获取会议创建人邮件
query = "select * from hrmresource where id = ?";
rs.executeQuery(query, creator);
rs.next();
String creatorEmail = rs.getString("email");
// 获取会议开始日期
String startDate = String.valueOf(paramMap.get("begindate"));
// 获取会议开始时间
String startTime = String.valueOf(paramMap.get("begintime"));
Date start = simpleFormat.parse(startDate + " " + startTime);
// 获取会议结束日期
String endDate = String.valueOf(paramMap.get("enddate"));
// 获取会议结束时间
String endTime = String.valueOf(paramMap.get("endtime"));
Date end = simpleFormat.parse(endDate + " " + endTime);
// 计算会议时长
int length = new Long((end.getTime() - start.getTime()) / (1000 * 60)).intValue();
// 获取会议参与人
String hrmStr = String.valueOf(paramMap.get("hrmmembers"));
// 处理会议参与人
List<QsConfParty> list = new ArrayList<>();
query = "select * from hrmresource where id in ( " + hrmStr + ")";
rs.executeQuery(query);
while (rs.next()) {
QsConfParty qsConfParty = new QsConfParty();
qsConfParty.setEmail(rs.getString("email"));
list.add(qsConfParty);
}
toolUtil.writeErrorLog(list.toString());
toolUtil.writeErrorLog(String.valueOf(length));
// 调取接口
meting = requestApi.createMeting(creatorEmail, title, length, startDate + " " + startTime + ":00 ", list);
toolUtil.writeErrorLog(meting.toString());
if (meting != null) {
// 请求失败
if (!"0".equals(meting.getStatus())) {
meting = null;
}
}
} catch (Exception e) {
toolUtil.writeErrorLog(e.toString());
} finally {
HttpStaticUtils.executorService.execute(() -> {
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
lock.unlock();
} catch (IllegalMonitorStateException e) {
// 锁已经被释放
}
}
});
}
// TODO 在after方法中更新会议id进入meting表中
}
/**
* apiCost: 688
* api_status: true
* meetingid: "8"
* retstatus: true
* status: true
*
* WeaReplaceAfter
* String
* WeaAfterReplaceParamdataString
* return
*/
@WeaReplaceAfter(value = "/api/meeting/base/newMeeting", order = 1)
public String after(WeaAfterReplaceParam weaAfterReplaceParam) {
String data = weaAfterReplaceParam.getData();
HttpServletRequest request = weaAfterReplaceParam.getRequest();
HttpServletResponse response = weaAfterReplaceParam.getResponse();
User user = HrmUserVarify.getUser(request, response);
Map<String, Object> jsonObject = new HashMap<>();
try {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(data, Map.class);
if (map == null) {
lock.unlock();
// 转换失败或数据为空
return data;
}
if (Boolean.parseBoolean(String.valueOf(map.get("status")))) {
// 添加成功
if (meting != null) {
// 更新全时会议id进入meting表中
String update = "update meeting set quan_shi_id = ? where id = ?";
RecordSet rs = new RecordSet();
Map<String, Object> resultMap;
resultMap = mapper.readValue(meting.getResult(), Map.class);
rs.executeUpdate(update, String.valueOf(resultMap.get("conferenceId")), String.valueOf(map.get("meetingid")));
toolUtil.writeErrorLog(resultMap.get("conferenceId") + " -:- " +
resultMap.get("pcode1") + " -:- " + resultMap.get("pcode2") + " -:- " + map.get("meetingid"));
} else {
// 添加失败
toolUtil.writeErrorLog("添加失败!");
jsonObject.put("api_status", false);
jsonObject.put("api_errormsg", "全时会议添加失败!");
lock.unlock();
toolUtil.writeErrorLog(jsonObject.toString());
return JSONObject.toJSONString(jsonObject);
}
}
return jsonObject.toString();
} catch (Exception e) {
toolUtil.writeErrorLog(e.toString());
jsonObject.put("api_status", false);
jsonObject.put("api_errormsg", e.toString());
return JSONObject.toJSONString(jsonObject);
} finally {
// 释放锁
lock.unlock();
toolUtil.writeErrorLog(data);
}
}
}

View File

@ -0,0 +1,800 @@
package com.api.doc.search.util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionType;
import com.engine.doc.util.CheckPermission;
import com.engine.doc.util.TimeZoneUtil;
import com.engine.hrm.biz.HrmClassifiedProtectionBiz;
import weaver.docs.docs.DocManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.setting.HrmUserSettingComInfo;
/**
* sqlwhere
*
* @author wangqs
*/
public class DocListUtil {
private String sqlWhere = " t1.id=t2.sourceid ";
private boolean needRight = true;
public DocListUtil(HttpServletRequest request, User user, DocTableType docTableType) {
this.packageCondition(request, user, docTableType);
}
public DocListUtil(
HttpServletRequest request, User user, DocTableType docTableType, boolean needRight) {
if (!needRight || user == null) { // user为null登录前门户元素more页面
sqlWhere = "";
this.needRight = false;
}
this.packageCondition(request, user, docTableType);
}
/** 封装查询条件 */
private void packageCondition(HttpServletRequest request, User user, DocTableType docTableType) {
String belongtoids = "";
if (needRight) {
HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo();
String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID() + "");
belongtoids = user.getBelongtoids();
if ("1".equals(belongtoshow) && "0".equals(user.getAccount_type()) && !"".equals(belongtoids))
belongtoids += "," + user.getUID();
else belongtoids = "";
}
Enumeration paramNames = request.getParameterNames();
String docstatus = "";
String customSql = "";
if (docTableType == DocTableType.DOC_COPYMOVE) {
sqlWhere = " t1.seccategory = " + request.getParameter("sourceId");
}
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
String paramValue = Util.null2String(request.getParameter(paramName));
boolean isCustom = true; // 是否是自定义字段
for (DocCondition condition : DocCondition.values()) {
if (paramValue.isEmpty()) continue;
if (condition.getConditionType() == ConditionType.DATE) {
if (paramName.equals(condition.getName() + ConditionUtil.DATE_SELECT)
&& !"6".equals(paramValue)) { // 只有6-时间范围,页面才传开始到结束时间,这里需要自己处理
sqlWhere += packDateType(condition.getName(), paramValue, condition);
} else if (paramName.equals(condition.getName() + ConditionUtil.DATE_FROM)) {
// if(paramValue.equals(request.getParameter(condition.getName() +
// ConditionUtil.DATE_TO))){ //开始日期==结束日期
// paramValue = TimeZoneUtil.getServerDate1(paramValue,"begin");
// sqlWhere += " and " + condition.getName() + "='" + paramValue + "'";
// }else{
String time_paramValue = TimeZoneUtil.getServerDate1(paramValue, "begin");
// if(!paramValue.equals(time_paramValue)){
// time_paramValue = paramValue;
// }
if ("doclastmoddate".equals(condition.getName())
|| "doccreatedate".equals(condition.getName())) {
String doclastmodtime = TimeZoneUtil.getServertime1(paramValue, "begin");
sqlWhere +=
TimeZoneUtil.handDateCondition(
"6", paramValue, "", condition.getName(), "", false);
} else {
sqlWhere +=
" and "
+ condition.getName()
+ ">='"
+ time_paramValue
+ "'"; // + " and " + condition.getName() + "=" + paramValue;
}
// }
} else if (paramName.equals(condition.getName() + ConditionUtil.DATE_TO)) {
// if(!paramValue.equals(request.getParameter(condition.getName() +
// ConditionUtil.DATE_FROM))){ //开始日期!=结束日期
// paramValue = TimeZoneUtil.getServerDate1(paramValue,"end");
String time_paramValue = TimeZoneUtil.getServerDate1(paramValue, "end");
// if(!paramValue.equals(time_paramValue)){
// time_paramValue = paramValue;
// }
if ("doclastmoddate".equals(condition.getName())
|| "doccreatedate".equals(condition.getName())) {
String doclastmodtime = TimeZoneUtil.getServertime1(paramValue, "end");
sqlWhere +=
TimeZoneUtil.handDateCondition(
"6", "", paramValue, condition.getName(), "", false);
// sqlWhere += " and (" + condition.getName() + "<='" + time_paramValue + "'"
// + " and " + "doclastmodtime<='"+ doclastmodtime +"')";
} else {
sqlWhere +=
" and "
+ condition.getName()
+ "<='"
+ time_paramValue
+ "'"; // + " and " + condition.getName() + "=" + paramValue;
}
// sqlWhere += " and " + condition.getName() + "<='" + time_paramValue + "'";
// }
}
continue;
}
if (condition.getConditionType() == ConditionType.SCOPE) {
if (paramName.equals(DocCondition.REPLAY_DOC_COUNT + ConditionUtil.INTERVAL_FROM)) {
String _val = Util.getIntValue(paramValue, 0) + "";
if (condition.getDbType() != DbType.INT) {
_val = "'" + _val.replace("'", "'") + "'";
}
sqlWhere += " and " + condition.getName() + " >= " + _val;
} else if (paramName.equals(DocCondition.REPLAY_DOC_COUNT + ConditionUtil.INTERVAL_TO)) {
String _val = Util.getIntValue(paramValue, 0) + "";
if (condition.getDbType() != DbType.INT) {
_val = "'" + _val.replace("'", "'") + "'";
}
sqlWhere += " and " + condition.getName() + " <= " + _val;
}
}
if (condition.getName().equals(paramName)) {
isCustom = false;
if (condition.getLogic() == LogicOperation.CUSTOM) {
if (paramName.equals(DocCondition.DOC_SUBJECT.getName())) { // 标题
sqlWhere += " and " + getDocSubjectSql(paramValue);
} else if (paramName.equals(DocCondition.KEYWORD.getName())) { // 关键字
sqlWhere += " and " + getKeyWordSql(paramValue);
} else if (paramName.equals(DocCondition.DEPARTMENT_ID.getName())) { // 创建部门
sqlWhere +=
" and exists(select 1 from HrmResource where departmentid="
+ paramValue
+ " and id=t1.doccreaterid)";
} else if (paramName.equals(DocCondition.CREATER_SUBCOMPANY_ID.getName())) { // 创建人分部
sqlWhere +=
" and exists(select 1 from HrmResource where subcompanyid1="
+ paramValue
+ " and id=t1.doccreaterid)";
} else if (paramName.equals(DocCondition.OWNER_DEPARTMENT_ID.getName())) { // 所有者部门
sqlWhere +=
" and exists(select 1 from HrmResource where departmentid="
+ paramValue
+ " and id=t1.ownerid)";
} else if (paramName.equals(DocCondition.OWNER_SUBCOMPANY_ID.getName())) { // 所有者分部
sqlWhere +=
" and exists(select 1 from HrmResource where subcompanyid1="
+ paramValue
+ " and id=t1.ownerid)";
} else if (paramName.equals(DocCondition.DATE2DURING.getName())) { // 修改期间
if (Util.getIntValue(paramValue, 0) > 36
|| Util.getIntValue(paramValue, 0) < 1) { // 表示全部
continue;
}
sqlWhere +=
" and t1.doclastmoddate>='"
+ getDate2During(Util.getIntValue(paramValue, 0))
+ "'";
} else if (paramName.equals(DocCondition.DOC_STATUS.getName())) { // 文档状态
docstatus = paramValue;
} else if (paramName.equals(DocCondition.TREE_DOC_FIELD_ID.getName())) { // 虚拟目录
paramValue = paramValue.startsWith(",") ? paramValue.substring(1) : paramValue;
paramValue =
paramValue.endsWith(",")
? paramValue.substring(0, paramValue.length() - 1)
: paramValue;
paramValue =
paramValue.indexOf(",") == -1
? (" = " + paramValue)
: (" in (" + paramValue + ")");
sqlWhere +=
" and exists(select 1 from DocDummyDetail where docid=t1.id and catelogid "
+ paramValue
+ ")";
}
} else if (condition.getLogic() == LogicOperation.EQ_OR_IN) {
paramValue = paramValue.startsWith(",") ? paramValue.substring(1) : paramValue;
paramValue =
paramValue.endsWith(",")
? paramValue.substring(0, paramValue.length() - 1)
: paramValue;
// 分为文档订阅部分的高级搜索条件拼接
if (paramValue.indexOf(",") == -1) {
if (condition.getDbType() == DbType.VARCHAR)
paramValue = "'" + paramValue.replace("'", "''") + "'";
paramValue = " = " + paramValue;
} else {
if (condition.getDbType() == DbType.VARCHAR)
paramValue = "'" + paramValue.replace("'", "''").replace(",", "','") + "'";
paramValue = " in (" + paramValue + ")";
}
if (condition == DocCondition.SUBSCRIPTION_APPROVE_DATE
|| condition == DocCondition.SUBSCRIPTION_DATE
|| condition == DocCondition.SUBSCRIPTION_STATE) {
sqlWhere += " and ds." + paramName + paramValue;
} else {
sqlWhere += " and t1." + paramName + paramValue;
}
} else if (condition.getLogic() != null) { // 分为文档订阅部分的高级搜索条件拼接
String _code = condition.getLogic().getCode();
if (_code == null) continue;
if (condition.getDbType() == DbType.VARCHAR) {
if (_code.indexOf("{#}") > -1) {
paramValue = paramValue.replace("'", "''");
} else {
paramValue = "'" + paramValue.replace("'", "''") + "'";
}
}
if (condition == DocCondition.SUBSCRIPTION_APPROVE_DATE
|| condition == DocCondition.SUBSCRIPTION_DATE
|| condition == DocCondition.SUBSCRIPTION_STATE) {
sqlWhere +=
" and ds."
+ paramName
+ (_code.indexOf("{#}") > -1
? _code.replace("{#}", paramValue)
: (_code + paramValue));
} else {
sqlWhere +=
" and t1."
+ paramName
+ (_code.indexOf("{#}") > -1
? _code.replace("{#}", paramValue)
: (_code + paramValue));
}
}
break;
}
}
// 处理自定义字段
// 如果开启了自定义查询,当前的条件是自定义字段中的值,则进行检查
if (isCustom
&& ConditionUtil.isCustomParamNameNew(paramName)
&& ConditionUtil.isCustomParamValue(paramName)) {
String id = ConditionUtil.getCustomIdNew(paramName);
int secid = Util.getIntValue(Util.null2String(request.getParameter("seccategory")));
if (docTableType == DocTableType.DOC_COPYMOVE) {
sqlWhere = " t1.seccategory = " + request.getParameter("sourceId");
}
String fieldValue = paramValue;
String fieldOpt =
Util.null2String(
request.getParameter(
ConditionUtil.CUSTOM_KEY_PREV + id + ConditionUtil.CUSTOM_KEY_OPT),
"-1");
String customSqlWhere = ConditionUtil.getCustomSql(id, secid, user, fieldValue, fieldOpt);
if (!customSqlWhere.isEmpty()) {
customSql += " and " + customSqlWhere;
}
}
}
String eqOrInBelongtoidsForSql =
needRight
? (belongtoids.isEmpty() ? (" = " + user.getUID()) : (" in (" + belongtoids + ")"))
: "";
// 处理特殊字段
docstatus = docstatus.startsWith(",") ? docstatus.substring(1) : docstatus;
docstatus =
docstatus.endsWith(",") ? docstatus.substring(0, docstatus.length() - 1) : docstatus;
if (docTableType == DocTableType.MY_DOC_TABLE) { // 我的文档
if (docstatus.isEmpty()) {
sqlWhere += " and t1.docstatus != 8 and t1.docstatus != 9 and t1.docstatus <=9";
} else {
sqlWhere +=
" and t1.docstatus "
+ (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
}
sqlWhere +=
" and (t1.doccreaterid "
+ eqOrInBelongtoidsForSql
+ " or t1.ownerid "
+ eqOrInBelongtoidsForSql
+ ")";
} else if (docTableType == DocTableType.DOC_BATCHSHARE) { // 批量共享
if (needRight) {
// sqlWhere += " and (t1.docstatus in(1,2,5) or (t1.docstatus=7 and (sharelevel>1 or
// (t1.doccreaterid="+user.getUID()+" or t1.ownerid="+user.getUID()+"))))";
sqlWhere +=
" and (t1.docstatus in(1,2,5) or (t1.docstatus=7 and (t1.doccreaterid="
+ user.getUID()
+ " or t1.ownerid="
+ user.getUID()
+ ")))";
} else {
sqlWhere += " and t1.docstatus in(1,2,5,7) ";
}
} else if (docTableType == DocTableType.DOC_COPYMOVE
|| docTableType == DocTableType.ENGINE_DOC_BATCHSHARE) { // 复制、移动 后台批量调整共享
if (docstatus.isEmpty()) {
sqlWhere += " and t1.docstatus in(1,2,5,7)";
} else {
docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
sqlWhere +=
" and t1.docstatus "
+ (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
}
} else if (docTableType == DocTableType.DOC_RECYCLE) { // 文档回收站
if (!docstatus.isEmpty()) {
docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
sqlWhere +=
" and t1.docstatus "
+ (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
}
} else if (docTableType == DocTableType.ENGINE_DOC_RECYCLE) { // 文档回收(后台)
if (!docstatus.isEmpty()) {
docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
sqlWhere +=
" and t1.docstatus "
+ (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
}
} else if (docTableType == DocTableType.DOC_SUBSCRIPTION_HISTORY) { // 文档订阅历史
if (docstatus.isEmpty()) {
// sqlWhere += " and t1.docstatus in(1,2,5) ";
if (needRight) {
// sqlWhere += " and (t1.docstatus in(1,2,5) or (t1.docstatus=7 and (sharelevel>1 or
// (t1.doccreaterid="+user.getUID()+" or t1.ownerid="+user.getUID()+"))))";
// ayh 默认可以查看全部文档,包括非正常状态的文档
/* sqlWhere +=
" and (t1.docstatus in(1,2,5) or (t1.docstatus=7 and (t1.doccreaterid="
+ user.getUID()
+ " or t1.ownerid="
+ user.getUID()
+ ")))";*/
sqlWhere +=
" and (t1.docstatus in(1,2,3,4,5,6,7,8,9) or (t1.docstatus=7 and (t1.doccreaterid="
+ user.getUID()
+ " or t1.ownerid="
+ user.getUID()
+ ")))";
} else {
// ayh 默认可以参看全部文档,包括处于非正常状态的文档
// sqlWhere += " and t1.docstatus in(1,2,5) ";
sqlWhere += " and t1.docstatus in(1,2,3,4,5,6,7,8,9) ";
}
} else {
docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
sqlWhere +=
" and t1.docstatus "
+ (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
}
if (docTableType == DocTableType.NEWEST_DOC
|| docTableType == DocTableType.NO_READ_DOC) { // 最新文档(未读文档)
sqlWhere +=
" and t1.doccreaterid "
+ (belongtoids.isEmpty()
? ("<> " + user.getUID())
: ("not in (" + belongtoids + ")"));
}
} else if (docTableType == DocTableType.ENGINE_DOC_PROP_SET) { // 文档弹出窗口设置
sqlWhere += " and t1.docstatus in(1,2,5) and t1.docextendname = 'html'";
} else {
if (docstatus.isEmpty()) {
// sqlWhere += " and t1.docstatus in(1,2,5) ";
if (needRight) {
// sqlWhere += " and (t1.docstatus in(1,2,5) or (t1.docstatus=7 and (sharelevel>1 or
// (t1.doccreaterid="+user.getUID()+" or t1.ownerid="+user.getUID()+"))))";
// ayh
// sqlWhere +=
// " and (t1.docstatus in(1,2,5) or (t1.docstatus=7 and (t1.doccreaterid="
// + user.getUID()
// + " or t1.ownerid="
// + user.getUID()
// + ")))";
sqlWhere +=
" and (t1.docstatus in(1,2,3,4,5,6,7,8,9) or (t1.docstatus=7 and (t1.doccreaterid="
+ user.getUID()
+ " or t1.ownerid="
+ user.getUID()
+ ")))";
} else {
// ayh
// sqlWhere += " and t1.docstatus in(1,2,5) ";
sqlWhere += " and t1.docstatus in(1,2,3,4,5,6,7,8,9) ";
}
} else {
docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
sqlWhere +=
" and t1.docstatus "
+ (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
}
if (docTableType == DocTableType.NEWEST_DOC
|| docTableType == DocTableType.NO_READ_DOC) { // 最新文档(未读文档)
sqlWhere +=
" and t1.doccreaterid "
+ (belongtoids.isEmpty()
? ("<> " + user.getUID())
: ("not in (" + belongtoids + ")"));
}
}
String isNew = Util.null2String(request.getParameter("isNew"));
if ("yes".equals(isNew)
|| docTableType == DocTableType.NEWEST_DOC
|| docTableType == DocTableType.NO_READ_DOC) {
sqlWhere +=
" and not exists(select 1 from docReadTag where t1.id=docid and userid "
+ eqOrInBelongtoidsForSql
+ " and usertype=1)";
}
if (!customSql.isEmpty()) {
sqlWhere +=
" and exists(select 1 from cus_fielddata tcm where scope='"
+ ConditionUtil.CUSTOM_SCOPE
+ "' and id=t1.id "
+ customSql
+ ")";
}
if (docTableType == DocTableType.DOC_BATCHSHARE && needRight) { // 批量共享(不需要权限的是后台批量共享)
// sqlWhere += " and sharelevel=3 and exists(select 1 from DocSecCategory where
// DocSecCategory.id=t1.secCategory and DocSecCategory.shareable='1')";
sqlWhere +=
" and exists(select 1 from DocSecCategory where DocSecCategory.id=t1.secCategory and DocSecCategory.shareable='1')";
}
// if(needRight){
if (docTableType == DocTableType.DOC_OUT_TABLE) { // 登录前门户more(只取内部)
boolean secretFlag = CheckPermission.isOpenSecret();
if (secretFlag) sqlWhere += " and t1.secretLevel=" + DocManager.DEFAILT_SECRET_LEVEL;
} else {
sqlWhere += DocListUtil.getSecretSql(user, " and t1.secretLevel");
}
// }
// 统一过滤字段
if (docTableType != DocTableType.DOC_SUBSCRIPTION_HISTORY
&& docTableType != DocTableType.DOC_SUBSCRIPTION_APPROVE
&& docTableType != DocTableType.DOC_SUBSCRIPTION_BACK
&& docTableType != DocTableType.DOC_RECYCLE) { // 非文档订阅过虑历史文件 、 非回收站
sqlWhere += " and (t1.ishistory is null or t1.ishistory = 0)";
}
if (docTableType == DocTableType.DOC_RECYCLE) { // 文档回收站
sqlWhere += " and t1.ishistory != 1 ";
sqlWhere += " and t1.docdeleteuserid=" + user.getUID();
} else if (docTableType == DocTableType.ENGINE_DOC_RECYCLE) { // 文档回收站(后台)
sqlWhere += " and t1.ishistory != 1 ";
} else {
sqlWhere += " and (t1.isreply is null or t1.isreply='' or t1.isreply='0')";
}
sqlWhere = sqlWhere.trim().startsWith("and") ? sqlWhere.substring(4) : sqlWhere;
// 初次进入列表,代入默认值条件
packDefaultValue(request, user, docTableType);
}
public static String getSecretSql(User user, String column) {
boolean secretFlag = CheckPermission.isOpenSecret();
if (secretFlag) {
HrmClassifiedProtectionBiz hcpb = new HrmClassifiedProtectionBiz();
String userSecretLevel = user == null ? "" : hcpb.getMaxResourceSecLevel(user);
return column + ">=" + Util.getIntValue(userSecretLevel, DocManager.DEFAILT_SECRET_LEVEL); //
}
return "";
}
public static Map<String, String> getCreateDate(HttpServletRequest request) {
String select =
request.getParameter(DocCondition.DOC_CREATEDATE_SELECT + ConditionUtil.DATE_SELECT);
String from =
request.getParameter(DocCondition.DOC_CREATEDATE_SELECT + ConditionUtil.DATE_FROM);
String to = request.getParameter(DocCondition.DOC_CREATEDATE_SELECT + ConditionUtil.DATE_TO);
Map<String, String> dateMap = new HashMap<String, String>();
if ("0".equals(select)) {
return dateMap;
}
dateMap = packDate(select, from, to);
from = dateMap.get("from");
to = dateMap.get("to");
if (from != null && !from.isEmpty()) {
from = new TimeZoneUtil().getServerDate(from + " 00:00:00");
}
if (to != null && !to.isEmpty()) {
to = new TimeZoneUtil().getServerDate(to + " 23:59:59");
}
dateMap.put(DocCondition.DOC_CREATEDATE_SELECT.getName() + ConditionUtil.DATE_FROM, from);
dateMap.put(DocCondition.DOC_CREATEDATE_SELECT.getName() + ConditionUtil.DATE_TO, to);
return dateMap;
}
/**
*
*
* @author wangqs
*/
public void packDefaultValue(HttpServletRequest request, User user, DocTableType docTableType) {
//
/***
* String during = request.getParameter(DocCondition.DATE2DURING.getName());
* if(during == null){
* List<SearchConditionOption> options = ConditionUtil.getDateSelectDuring(user.getLanguage());
* int date = 0;
* for(SearchConditionOption option : options){
* if(option.isSelected()){
* date = Util.getIntValue(option.getKey(),0);
* }
* }
* if(date >= 1 && date <= 36){
*
* sqlWhere += " and t1.doclastmoddate>='" + getDate2During(date) + "'";
* }
* }
*
***/
// 最新文档有tab页未读文档没有tab页
if (docTableType == DocTableType.NEWEST_DOC) { // 最新文档
try {
sqlWhere += this.packSearchTabDate(request.getParameter(ConditionUtil.TAB_REQ_NAME));
} catch (Exception e) {
e.printStackTrace();
}
} else if (docTableType == DocTableType.MY_DOC_TABLE
|| docTableType == DocTableType.SEARCH_DOC_TABLE
|| docTableType == DocTableType.CATEGORY_DOC_TABLE) { // 我的文档、查询文档、文档目录
try {
// 0-全部1-今天2-本周3-本月4-本季5-本年
int tab =
Util.getIntValue(
request.getParameter(ConditionUtil.TAB_REQ_NAME), ConditionUtil.TAB_DATE_DEFAULT);
String updateDate =
Util.null2String(
request.getParameter(
DocCondition.DOC_LAST_MODDATE.getName() + ConditionUtil.DATE_SELECT));
if (updateDate.isEmpty()) { // 没有修改日期,取默认时间
// sqlWhere += packDateType(DocCondition.DOC_LAST_MODDATE.getName(),tab + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
sqlWhere = sqlWhere.trim().startsWith("and") ? sqlWhere.substring(4) : sqlWhere;
}
/** 处理修改期间(最近n月)条件的查询 */
public static String getDate2During(int month) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -30 * month);
Date cDate = new Date(calendar.getTimeInMillis());
return new SimpleDateFormat("yyyy-MM-dd").format(cDate);
}
/** 处理特殊时间类型(今天、本周、本月....)条件查询 0-全部1-今天2-本周3-本月7-上个月4-本季5-本年8-上一年6-指定日期范围 */
public static String packDateType(String column, String value, DocCondition condition) {
Map<String, String> dateMap = packDate(value, "", "");
String sdate = Util.null2String(dateMap.get("from"));
String edate = Util.null2String(dateMap.get("to"));
if ("0".equals(value)) {
return "";
}
if (condition == DocCondition.SUBSCRIPTION_APPROVE_DATE
|| condition == DocCondition.SUBSCRIPTION_DATE
|| condition == DocCondition.SUBSCRIPTION_STATE) {
if (!sdate.isEmpty()) {
if ("8".equals(value)) {
return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "ds", false, true);
} else {
return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "ds", false, true);
}
// if(sdate.equals(edate)){
//// return TimeZoneUtil.handDateCondition(value,sdate,"",column,"ds",false,true);
// return " and ds." + column + "='" + sdate + "'";
// }else{
//// return TimeZoneUtil.handDateCondition(value,sdate,"",column,"ds",false,true);
// String test = " and ds." + column + ">='" + sdate + "' and ds." + column + "<='" +
// edate + "'";
// return test;
// }
}
} else {
if (!sdate.isEmpty()) {
if ("8".equals(value)) {
return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "t1", false, true);
} else {
return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "t1", false, true);
}
// if(sdate.equals(edate)){
// return " and t1." + column + "='" + sdate + "'";
// }else{
// String test = " and t1." + column + ">='" + sdate + "' and t1." + column + "<='" +
// edate + "'";
// return test;
// }
}
}
return "";
}
/**
* (....) 0-1-2-3-7-4-5-8-6-
*
* @author wangqs
* @params select-from-to-
*/
public static Map<String, String> packDate(String select, String from, String to) {
Map<String, String> dateMap = new HashMap<String, String>();
String sdate = "";
String edate = TimeUtil.getCurrentDateString();
switch (Util.getIntValue(select, 0)) {
case 1:
sdate = TimeUtil.getCurrentDateString();
break;
case 2:
sdate = TimeUtil.getFirstDayOfWeek();
break;
case 3:
sdate = TimeUtil.getFirstDayOfMonth();
break;
case 4:
sdate = TimeUtil.getFirstDayOfSeason();
break;
case 5:
sdate = TimeUtil.getFirstDayOfTheYear();
break;
case 6:
sdate = from;
edate = to;
case 7:
sdate = TimeUtil.getLastMonthBeginDay();
edate = TimeUtil.getLastMonthEndDay();
break;
case 8:
sdate = TimeUtil.getFirstDayOfLastYear();
edate = TimeUtil.getEndDayOfLastYear();
break;
default:
break;
}
// TimeZoneUtil timeZoneUtil = new TimeZoneUtil();
// //多时区转换
// sdate = timeZoneUtil.getServerDate(sdate,"begin");
// edate = timeZoneUtil.getServerDate(edate,"end");
dateMap.put("from", sdate);
dateMap.put("to", edate);
return dateMap;
}
/** 根据规则 处理有主题条件的查询 */
private String getDocSubjectSql(String docsubject) {
String tmpString = "";
docsubject = docsubject.replaceAll("'", "''").replaceAll("\"", "&quot;");
if ((docsubject.indexOf(" ") == -1 && docsubject.indexOf("+") == -1)
|| (docsubject.indexOf(" ") != -1 && docsubject.indexOf("+") != -1)) {
tmpString += " t1.docsubject like '%" + docsubject + "%'";
} else if (docsubject.indexOf(" ") != -1 && docsubject.indexOf("+") == -1) {
String orArray[] = Util.TokenizerString2(docsubject, " ");
if (orArray.length > 0) {
tmpString += " ( ";
}
for (int i = 0; i < orArray.length; i++) {
tmpString += " t1.docsubject like '%" + orArray[i] + "%'";
if (i + 1 < orArray.length) {
tmpString += " or ";
}
}
if (orArray.length > 0) {
tmpString += " ) ";
}
} else if (docsubject.indexOf(" ") == -1 && docsubject.indexOf("+") != -1) {
String andArray[] = Util.TokenizerString2(docsubject, "+");
for (int i = 0; i < andArray.length; i++) {
tmpString += " t1.docsubject like '%" + andArray[i] + "%'";
if (i + 1 < andArray.length) {
tmpString += " and ";
}
}
}
return tmpString;
}
/** 根据规则 处理有关键字条件的查询 */
private String getKeyWordSql(String keyword) {
String keywordSql = "";
keyword = keyword.trim().replaceAll("'", "''");
ArrayList keywordList = Util.TokenizerString(keyword, " ");
if (keywordList != null && keywordList.size() > 0) {
for (int i = 0; i < keywordList.size(); i++) {
String tempkeyword = (String) keywordList.get(i);
keywordSql +=
keywordSql.equals("")
? " t1.keyword like '%" + tempkeyword + "%' "
: " or t1.keyword like '%" + tempkeyword + "%' ";
}
if (!keywordSql.equals("")) {
keywordSql = " (" + keywordSql + ") ";
}
}
return keywordSql;
}
/**
* tab sql
*
* @author wangqs
*/
private String packSearchTabDate(String tabValue) throws Exception {
String sql = "";
switch (Util.getIntValue(tabValue, ConditionUtil.TAB_DEFAULT_VALUE)) {
case ConditionUtil.TAB_TODAY_VALUE:
sql = " and t1.doccreatedate='" + TimeUtil.getCurrentDateString() + "'";
break;
case ConditionUtil.TAB_WEEK_VALUE:
sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfWeek() + "'";
sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayOfWeek() + "'";
break;
case ConditionUtil.TAB_MONTH_VALUE:
sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfMonth() + "'";
sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayOfMonth() + "'";
break;
case ConditionUtil.TAB_SESSION_VALUE:
sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfSeason() + "'";
sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayDayOfSeason() + "'";
break;
case ConditionUtil.TAB_YEAR_VALUE:
sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfTheYear() + "'";
sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayOfYear() + "'";
break;
default:
break;
}
return sql;
}
public String getSqlWhere() {
// ayh
new BaseBean().writeLog("create sql string from docListUtil, sqlWhere is :" + this.sqlWhere);
return this.sqlWhere;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,544 @@
package com.customization.quanshimeting;
import aiyh.utils.Util;
import aiyh.utils.zwl.common.ToolUtil;
import com.engine.core.cfg.annotation.ServiceDynamicProxy;
import com.engine.core.cfg.annotation.ServiceMethodDynamicProxy;
import com.engine.core.impl.aop.AbstractServiceProxy;
import com.engine.meeting.service.MeetingBaseService;
import com.engine.meeting.service.impl.MeetingBaseServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import weaver.aiyh_quanshi.RequestApi;
import weaver.aiyh_quanshi.entity.QsConfParty;
import weaver.aiyh_quanshi.entity.QsResponse;
import weaver.conn.RecordSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author EBU7-dev1-ayh
* @create 2021/9/17 0017 16:18
*
*/
@ServiceDynamicProxy(target = MeetingBaseServiceImpl.class, desc = "对全时会议进行同步")
public class NewMeetingServiceProxy extends AbstractServiceProxy implements MeetingBaseService {
private final ToolUtil toolUtil = new ToolUtil();
private final RequestApi requestApi = new RequestApi();
private final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
@Override
@ServiceMethodDynamicProxy(desc = "创建会议,向全时会议中添加预约会议")
public Map<String, Object> newMeeting(Map<String, Object> map) {
toolUtil.writeErrorLog(map.toString());
try {
int quanShiType = Integer.parseInt(Util.null2String("".equals(toolUtil.getSystemParamValue("QUAN_SHI_TYPE")) ? null : toolUtil.getSystemParamValue("QUAN_SHI_TYPE"), "-1"));
int meetingType = Integer.parseInt(Util.null2String("".equals(String.valueOf(map.get("meetingtype"))) ? null : String.valueOf(map.get("meetingtype")), "0"));
if (quanShiType != meetingType) {
return (Map<String, Object>) executeMethod(map);
}
} catch (Exception e) {
toolUtil.writeErrorLog("转换失败,失败原因:" + e);
return (Map<String, Object>) executeMethod(map);
}
Map<String, Object> result = (Map<String, Object>) executeMethod(map);
// 获取会议标题
String title = String.valueOf(map.get("name"));
// 会议内容
String desc_n = String.valueOf(map.get("desc_n"));
// 获取会议创建人
String creator = String.valueOf(map.get("contacter"));
RecordSet rs = new RecordSet();
// 获取会议创建人邮件
String query = "select * from hrmresource where id = ?";
rs.executeQuery(query, creator);
rs.next();
String creatorEmail = rs.getString("email");
// 获取会议开始日期
String startDate = String.valueOf(map.get("begindate"));
// 获取会议开始时间
String startTime = String.valueOf(map.get("begintime"));
Date start;
try {
start = simpleFormat.parse(startDate + " " + startTime);
} catch (ParseException e) {
/* e.printStackTrace();
Map<String, Object> resultErr = new HashMap<>();
// 请求失败
resultErr.put("status", false);
resultErr.put("retstatus", true);
resultErr.put("error", "日期转换失败!");
resultErr.put("msg", "日期转换失败!");
resultErr.put("api_errormsg", "日期转换失败!");
return resultErr;*/
return result;
}
// 获取会议结束日期
String endDate = String.valueOf(map.get("enddate"));
// 获取会议结束时间
String endTime = String.valueOf(map.get("endtime"));
Date end;
try {
end = simpleFormat.parse(endDate + " " + endTime);
} catch (ParseException e) {
/* e.printStackTrace();
Map<String, Object> resultErr = new HashMap<>();
// 请求失败
resultErr.put("status", false);
resultErr.put("retstatus", true);
resultErr.put("error", "日期转换失败!");
resultErr.put("msg", "日期转换失败!");
resultErr.put("api_errormsg", "日期转换失败!");
return resultErr;*/
return result;
}
// 计算会议时长
int length = new Long((end.getTime() - start.getTime()) / (1000 * 60)).intValue();
// 获取会议参与人
String hrmStr = String.valueOf(map.get("hrmmembers"));
// 处理会议参与人
List<QsConfParty> list = new ArrayList<>();
List<String> emailList = new ArrayList<>();
query = "select * from hrmresource where id in ( " + hrmStr + ")";
rs.executeQuery(query);
while (rs.next()) {
QsConfParty qsConfParty = new QsConfParty();
qsConfParty.setEmail(rs.getString("email"));
emailList.add(rs.getString("email"));
list.add(qsConfParty);
if (emailList.size() == 199) {
QsResponse userIdsByEmails = requestApi.getInfoByEmail(emailList);
Map<String, Object> resultMap = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
resultMap = mapper.readValue(userIdsByEmails.getResult(), Map.class);
} catch (JsonProcessingException e) {
toolUtil.writeErrorLog(userIdsByEmails.toString());
toolUtil.writeErrorLog("请求结果转换失败,失败信息:" + e);
}
for (QsConfParty confParty : list) {
confParty.setUserId(Long.valueOf(String.valueOf(((Map<String, Object>) resultMap.get(confParty.getEmail())).get("userId"))));
}
emailList.clear();
}
}
QsResponse userIdsByEmails = requestApi.getInfoByEmail(emailList);
Map<String, Object> resultsMap = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
resultsMap = mapper.readValue(userIdsByEmails.getResult(), Map.class);
} catch (JsonProcessingException e) {
toolUtil.writeErrorLog(userIdsByEmails.toString());
toolUtil.writeErrorLog("请求结果转换失败,失败信息:" + e);
}
for (QsConfParty confParty : list) {
confParty.setUserId(Long.valueOf(String.valueOf(((Map<String, Object>) resultsMap.get(confParty.getEmail())).get("userId"))));
}
/* toolUtil.writeErrorLog(list.toString());
toolUtil.writeErrorLog(creatorEmail);
toolUtil.writeErrorLog(title);
toolUtil.writeErrorLog(String.valueOf(length));
toolUtil.writeErrorLog(startDate + " " + startTime + ":00 ");*/
QsResponse meeting = requestApi.createMeting(creatorEmail, title, length, startDate + " " + startTime + ":00", list);
if (meeting != null) {
if (!"0".equals(meeting.getStatus())) {
String update = "update meeting set quanshimeeting = ? where id = ?";
rs.executeUpdate(update, "全时会议添加失败!", String.valueOf(map.get("meetingid")));
toolUtil.writeErrorLog(meeting.toString());
/* Map<String, Object> result = new HashMap<>();
// 请求失败
result.put("status", false);
result.put("retstatus", false);
result.put("error", "全时会议添加失败");
result.put("msg", "全时会议添加失败!");
result.put("api_errormsg", "全时会议添加失败!");
return result;*/
return result;
} else {
// 请求成功
Map<String, Object> resultMap = new HashMap<>();
try {
resultMap = mapper.readValue(meeting.getResult(), Map.class);
} catch (JsonProcessingException e) {
toolUtil.writeErrorLog("请求结果转换失败,失败信息:" + e);
}
if (Boolean.parseBoolean(String.valueOf(result.get("status")))) {
// 添加成功
String update = "update meeting set quan_shi_id = ?, quanshimeeting = ? where id = ?";
String quanShjInfo = "会议密码:" + String.valueOf(resultMap.get("pcode2")) + "<br /><br />会议连接:" + String.valueOf(resultMap.get("attendeeJoinUrl"));
rs.executeUpdate(update, String.valueOf(resultMap.get("conferenceId")), quanShjInfo, String.valueOf(map.get("meetingid")));
return result;
} else {
QsResponse qsResponse = requestApi.cancelConference(String.valueOf(resultMap.get("conferenceId")), creatorEmail);
toolUtil.writeErrorLog(qsResponse.toString());
/* Map<String, Object> resultErr = new HashMap<>();
// 请求失败
resultErr.put("status", false);
resultErr.put("retstatus", false);
resultErr.put("error", "OA会议添加失败");
resultErr.put("msg", "OA会议添加失败");
resultErr.put("api_errormsg", "OA会议添加失败");
return resultErr;*/
return result;
}
}
} else {
/* Map<String, Object> resultErr = new HashMap<>();
// 请求失败
resultErr.put("status", false);
resultErr.put("retstatus", false);
resultErr.put("error", "全时会议添加失败");
resultErr.put("msg", "全时会议添加失败!");
resultErr.put("api_errormsg", "全时会议添加失败!");
return resultErr;*/
return result;
}
}
/*
Map<String, Object> result = (Map<String, Object>) executeMethod(map);
if (Boolean.parseBoolean(String.valueOf(result.get("status")))) {
// 会议添加成功,需要王全时会议中添加会议
String meetingId = String.valueOf(result.get("meetingid"));
// 通过会议id获取到会议相关的信息
String query = "select * from meeting where id = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, meetingId);
MeetingInfoDTO meetingInfoDTO = Util.recordeSet2Entity(rs, MeetingInfoDTO.class, true);
// 判断是否需要对会议进行全时会议添加
int quanShiType = Integer.parseInt(Util.null2String(toolUtil.getSystemParamValue("QUAN_SHI_TYPE"), "-1"));
if (meetingInfoDTO.getMeetingtype() != quanShiType) {
return result;
}
// 通过信息查询全时会议所需要的数据
// 获取创建人邮箱
query = "select email from hrmresource where id = ?";
rs.executeQuery(query, meetingInfoDTO.getCreater());
rs.next();
String creatorEmail = rs.getString("email");
// 获取参与人邮箱
List<QsConfParty> list = new ArrayList<>();
query = "select email from hrmresource where id in ( " + meetingInfoDTO.getHrmmembers() + ")";
rs.executeQuery(query);
while (rs.next()) {
QsConfParty qsConfParty = new QsConfParty();
qsConfParty.setEmail(rs.getString("email"));
list.add(qsConfParty);
}
// 获取开始i时间和结束时间以及计算会议时长
int length = 0;
String startDate = "";
String startTime = "";
try {
// 获取会议开始日期
startDate = String.valueOf(meetingInfoDTO.getBegindate());
// 获取会议开始时间
startTime = String.valueOf(meetingInfoDTO.getBegintime());
Date start = simpleFormat.parse(startDate + " " + startTime);
// 获取会议结束日期
String endDate = String.valueOf(meetingInfoDTO.getEnddate());
// 获取会议结束时间
String endTime = String.valueOf(meetingInfoDTO.getEndtime());
Date end = simpleFormat.parse(endDate + " " + endTime);
// 计算会议时长
length = new Long((end.getTime() - start.getTime()) / (1000 * 60)).intValue();
} catch (Exception e) {
toolUtil.writeErrorLog("日期传换失败,失败信息:" + e);
}
// 调取接口
QsResponse meting = requestApi.createMeting(creatorEmail, meetingInfoDTO.getName(), length, startDate + " " + startTime + ":00 ", list);
if (!"0".equals(meting.getStatus())) {
toolUtil.writeErrorLog("全时会议添加失败!失败结果" + meting);
// 需要删除OA会议
// 添加全时会议失败
result.put("status", false);
result.put("retstatus", false);
result.put("error", "全时会议添加失败");
result.put("msg", "全时会议添加失败!");
result.put("api_errormsg", "abab全时会议添加失败");
result.remove("apiCost");
result.remove("meetingid");
} else {
// 添加全时会议成功
String update = "update meeting set quan_shi_id = ? where id = ?";
Map<String, Object> resultMap = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
try {
resultMap = mapper.readValue(meting.getResult(), Map.class);
} catch (JsonProcessingException e) {
toolUtil.writeErrorLog("请求结果转换失败,失败信息:" + e);
}
rs.executeUpdate(update, String.valueOf(resultMap.get("conferenceId")), String.valueOf(map.get("meetingid")));
}
}
// throw new RuntimeException("全时会议添加失败!");
return result;*/
@Override
@ServiceMethodDynamicProxy(desc = "删除会议时, 需要判断是否需要对全时会议的会议进行取消预约")
public Map<String, Object> deleteMeeting(Map<String, Object> map) {
Map<String, Object> result = (Map<String, Object>) executeMethod(map);
// 获取请求参数中的会议id
String meetingIds = String.valueOf(map.get("meetingids"));
// 查询要删除的会议中是否存再全时会议预约的,如果有需要对全时会议进行取消
String query = "select * from meeting where id in (" + meetingIds + ") and cancel != 1 and quan_shi_id is not null and quan_shi_cancel is null";
RecordSet rs = new RecordSet();
rs.executeQuery(query);
RecordSet rs_1 = new RecordSet();
while (rs.next()) {
// 取消会议
String quanShiId = rs.getString("quan_shi_id");
String hrmId = rs.getString("contacter");
query = "select * from hrmresource where id = ?";
rs_1.executeQuery(query, hrmId);
rs_1.next();
String creatorEmail = rs_1.getString("email");
QsResponse qsResponse = requestApi.cancelConference(quanShiId, creatorEmail);
if (!"0".equals(qsResponse.getStatus())) {
// 取消失败
toolUtil.writeErrorLog("全时会议取消失败!失败结果" + qsResponse);
/*Map<String, Object> resultErr = new HashMap<>();
resultErr.put("status", false);
resultErr.put("retstatus", false);
resultErr.put("ret", false);
resultErr.put("error", "全时会议取消失败!");
resultErr.put("msg", "全时会议取消失败!");
resultErr.put("api_errormsg", "全时会议取消失败!");
return resultErr;*/
return result;
} else {
String update = "update meeting set quan_shi_cancel = ? where id = ?";
rs_1.executeUpdate(update, "1", rs.getString("id"));
}
}
// 取消成功需要删除OA中会议
// Map<String, Object> result = (Map<String, Object>) executeMethod(map);
return result;
}
@Override
public Map<String, Object> editMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> overMeeting(Map<String, Object> map) {
return null;
}
@Override
@ServiceMethodDynamicProxy(desc = "取消会议时,需要对全时会议的会议也进行同步取消")
public Map<String, Object> cancelMeeting(Map<String, Object> map) {
String meetingId = String.valueOf(map.get("meetingid"));
// 通过会议id获取到会议相关的信息
String query = "select * from meeting where id = ?";
RecordSet rs = new RecordSet();
rs.executeQuery(query, meetingId);
rs.next();
String quanShiId = rs.getString("quan_shi_id");
Map<String, Object> result = (Map<String, Object>) executeMethod(map);
int quanShiType = Integer.parseInt(Util.null2String(toolUtil.getSystemParamValue("QUAN_SHI_TYPE"), "-1"));
if (rs.getInt("meetingtype") != quanShiType) {
return result;
}
RecordSet rs_1 = new RecordSet();
// 取消会议
String hrmId = rs.getString("contacter");
query = "select * from hrmresource where id = ?";
rs_1.executeQuery(query, hrmId);
rs_1.next();
String creatorEmail = rs_1.getString("email");
QsResponse qsResponse = requestApi.cancelConference(quanShiId, creatorEmail);
if (!"0".equals(qsResponse.getStatus())) {
// 取消失败
toolUtil.writeErrorLog("全时会议取消失败!失败结果" + qsResponse);
/*Map<String, Object> resultErr = new HashMap<>();
resultErr.put("status", false);
resultErr.put("retstatus", false);
resultErr.put("ret", false);
resultErr.put("error", "全时会议取消失败!");
resultErr.put("msg", "全时会议取消失败!");
resultErr.put("api_errormsg", "全时会议取消失败!");
return resultErr;*/
return result;
} else {
String update = "update meeting set quan_shi_cancel = ? where id = ?";
rs_1.executeUpdate(update, "1", rs.getString("id"));
}
return result;
}
@Override
public Map<String, Object> chkMember(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkRoom(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkservice(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkRoomAttribute(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkWPMember(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> updateCkIsck(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> customMeetingChk(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> changeMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> submitMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> afterMeetingNormal(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> afterMeetingChange(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getUnReadCount(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> doSubmit(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> selRejectNode(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> doReject(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getUserDefInfo(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getNowMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getMoreMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getMeetingCornerMark(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getRequestParams(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> exportExcel(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkRight(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> customChangeHrm(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getMeetingTabElement(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> chkRepeatMeeting(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> afterMeetingDelete(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> meetingToGovern(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> meetingDecisionToGovern(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getMeetingInfluenceInfo(String s) {
return null;
}
@Override
public Map<String, Object> getMeetingSysWorkRecordList(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getDefalutByLevel(Map<String, Object> map) {
return null;
}
@Override
public Map<String, Object> getMeetingBaseInfo(Map<String, Object> map) {
return null;
}
}

View File

@ -0,0 +1,113 @@
package com.customization.quanshimeting.entity;
public class MeetingInfoDTO {
private int id;
private String name;
private int meetingtype;
private String begindate;
private String begintime;
private String endtime;
private String enddate;
private String descN;
private int creater;
private String hrmmembers;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setMeetingtype(int meetingtype){
this.meetingtype = meetingtype;
}
public void setBegindate(String begindate){
this.begindate = begindate;
}
public void setBegintime(String begintime){
this.begintime = begintime;
}
public void setEndtime(String endtime){
this.endtime = endtime;
}
public void setEnddate(String enddate){
this.enddate = enddate;
}
public void setDescN(String descN){
this.descN = descN;
}
public void setCreater(int creater){
this.creater = creater;
}
public void setHrmmembers(String hrmmembers){
this.hrmmembers = hrmmembers;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
public int getMeetingtype(){
return this.meetingtype;
}
public String getBegindate(){
return this.begindate;
}
public String getBegintime(){
return this.begintime;
}
public String getEndtime(){
return this.endtime;
}
public String getEnddate(){
return this.enddate;
}
public String getDescN(){
return this.descN;
}
public int getCreater(){
return this.creater;
}
public String getHrmmembers(){
return this.hrmmembers;
}
@Override
public String toString() {
return "MeetingInfoDTO{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", meetingtype='" + meetingtype + '\'' +
", begindate='" + begindate + '\'' +
", begintime='" + begintime + '\'' +
", endtime='" + endtime + '\'' +
", enddate='" + enddate + '\'' +
", descN='" + descN + '\'' +
", creater='" + creater + '\'' +
", hrmmembers='" + hrmmembers + '\'' +
'}';
}
}

BIN
customization/.DS_Store vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,54 @@
package customization.action.demo;
import customization.commons.Console;
import customization.commons.CustomAction;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
/**
*
* SAP
* +SAP MM050_SC_1230_FI_DocCreate_eg
* ********************************************
* SAP
* __nodeid (before)/(after)/(export)/()end
*
*
*/
public class MM050_SC_1230_FI_DocCreate_eg extends CustomAction implements Action {
@Override
public String execute(RequestInfo request) {
//封装流程表单的值
super.getWorkflowDataValue(request);
writeLog("execute action MM050_SC_1230_FI_DocCreate_eg");//打印日志
RequestManager rm = request.getRequestManager();
String requestid = request.getRequestid();
try {
String srcString = Util.null2String(rm.getSrc());
writeLog("srcString:"+srcString);
//当提交时执行
if (srcString.equals("submit")) {
//在这里编写业务逻辑代码调用往SAP系统写入值如果需要阻止流程继续流转参考下方catch里面信息处理。
Console.log( "mainFieldValuesMap"+mainMap);
Console.log( "detailFieldValuesMap"+detailMap);
System.out.println("selectvalue:"+super.getSeletItemValue("cgsqlxjms",rm.getFormid(), Util.null2String(mainMap.get("cgsqlxjms"))));
}
}catch (Exception e){
//异常报错是填写异常信息,阻止流程继续流转
request.getRequestManager().setMessageid("90001");
request.getRequestManager().setMessagecontent("-"+rm.getRequestid()+" 系统异常终止流程提交!");
}
return Action.SUCCESS;
}
}

Some files were not shown because too many files have changed in this diff Show More