diff --git a/src/main/java/aiyh/utils/ApiResult.java b/src/main/java/aiyh/utils/ApiResult.java index d7afe63..74e6e88 100644 --- a/src/main/java/aiyh/utils/ApiResult.java +++ b/src/main/java/aiyh/utils/ApiResult.java @@ -1,6 +1,5 @@ package aiyh.utils; -import aiyh.utils.zwl.common.ToolUtil; import com.alibaba.fastjson.JSON; @@ -12,55 +11,55 @@ import com.alibaba.fastjson.JSON; public class ApiResult { - private final int code; - private final String msg; - private final Object data; + 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 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 successNoData() { + return ApiResult.success(null, 200, "请求成功!"); + } - public static String success(Object data){ - return ApiResult.success(data, 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, 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 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() { + return ApiResult.error(0, "服务器异常!"); + } - public static String error(String msg){ - return ApiResult.error(0, msg); - } + 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 static String error(int code, String msg) { + return JSON.toJSONString(new ApiResult(code, msg, null)); + } - public int getCode() { - return code; - } + public int getCode() { + return code; + } - public String getMsg() { - return msg; - } + public String getMsg() { + return msg; + } - public Object getData() { - return data; - } + public Object getData() { + return data; + } } diff --git a/src/main/java/aiyh/utils/GenerateFileUtil.java b/src/main/java/aiyh/utils/GenerateFileUtil.java index 6694140..54b3cda 100644 --- a/src/main/java/aiyh/utils/GenerateFileUtil.java +++ b/src/main/java/aiyh/utils/GenerateFileUtil.java @@ -39,8 +39,11 @@ public class GenerateFileUtil { * @param tClass Action类 * @param Action接口 */ - public static void createActionDocument(Class tClass) { - createDocument(tClass, 1); + @SafeVarargs + public static void createActionDocument(Class... tClass) { + for (Class aClass : tClass) { + createDocument(aClass, 1); + } } @@ -50,8 +53,11 @@ public class GenerateFileUtil { * @param tClass 定时任务类 * @param Action接口 */ - public static void createCronJobDocument(Class tClass) { - createDocument(tClass, 2); + @SafeVarargs + public static void createCronJobDocument(Class... tClass) { + for (Class aClass : tClass) { + createDocument(aClass, 2); + } } /** @@ -137,17 +143,17 @@ public class GenerateFileUtil { if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } - //创建文件输出流 + // 创建文件输出流 FileOutputStream outStream = new FileOutputStream(saveFile); - //因为模板整合的时候,需要提供一个Writer,所以创建一个Writer + // 因为模板整合的时候,需要提供一个Writer,所以创建一个Writer OutputStreamWriter writer = new OutputStreamWriter(outStream); - //创建一个缓冲流 + // 创建一个缓冲流 BufferedWriter bufferWriter = new BufferedWriter(writer); VelocityContext ctx = new VelocityContext(vmParam); - //5 合并模板和数据并输出 + // 5 合并模板和数据并输出 template.merge(ctx, bufferWriter); - //强制刷新 + // 强制刷新 bufferWriter.flush(); outStream.close(); bufferWriter.close(); @@ -198,7 +204,7 @@ public class GenerateFileUtil { if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } - if(saveFile.exists()){ + if (saveFile.exists()) { throw new CustomerException("文件:" + fileName + " is exists;"); } FileOutputStream outStream = new FileOutputStream(saveFile); diff --git a/src/main/java/aiyh/utils/ThreadPoolConfig.java b/src/main/java/aiyh/utils/ThreadPoolConfig.java index 75e87fb..1975126 100644 --- a/src/main/java/aiyh/utils/ThreadPoolConfig.java +++ b/src/main/java/aiyh/utils/ThreadPoolConfig.java @@ -15,12 +15,12 @@ public class ThreadPoolConfig { private static volatile ExecutorService threadPool; public static ExecutorService createThreadPoolInstance() { - if(threadPool == null){ - synchronized (ThreadPoolConfig.class){ - if(threadPool == null){ + if (threadPool == null) { + synchronized (ThreadPoolConfig.class) { + if (threadPool == null) { ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-aiyh-%d").build(); - threadPool = new ThreadPoolExecutor(10, - 20, + threadPool = new ThreadPoolExecutor(25, + 50, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index a9423c7..b5f3ed9 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -83,7 +83,7 @@ public class Util extends weaver.general.Util { public static final ModeRightInfo MODE_RIGHT_INFO = new ModeRightInfo(); public static final ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance(); public static final char SBC_SPACE = 12288; // 全角空格 12288 - public static final char DBC_SPACE = 32; //半角空格 32 + public static final char DBC_SPACE = 32; // 半角空格 32 // ASCII character 33-126 <-> unicode 65281-65374 public static final char ASCII_START = 33; public static final char ASCII_END = 126; @@ -94,10 +94,13 @@ public class Util extends weaver.general.Util { private static final UtilService utilService = new UtilService(); private static final RecordsetUtil recordsetUtil = new RecordsetUtil(); private static final UtilMapper mapper = recordsetUtil.getMapper(UtilMapper.class); + public static final String UF_CUS_DEV_CONFIG = "uf_cus_dev_config"; static ToolUtil toolUtil = new ToolUtil(); private static RecordSet rs; private static volatile Logger log = null; + private static final Map otherLog = new HashMap<>(8); + static { try { rs = new RecordSet(); @@ -732,7 +735,7 @@ public class Util extends weaver.general.Util { underlineBefore = true; } else if (underlineBefore) { // 如果为true,代表上次的字符是"_",当前字符需要转成大写 - buffer.append(charArray[i] -= 32); + buffer.append(Character.toUpperCase(charArray[i])); underlineBefore = false; } else { // 不是"_"后的字符就直接追加 @@ -755,7 +758,7 @@ public class Util extends weaver.general.Util { // 将驼峰字符串转换成数组 char[] charArray = camelCaseStr.toCharArray(); StringBuilder buffer = new StringBuilder(); - //处理字符串 + // 处理字符串 for (int i = 0, l = charArray.length; i < l; i++) { if (charArray[i] >= 65 && charArray[i] <= 90) { if (i == 0) { @@ -1563,10 +1566,10 @@ public class Util extends weaver.general.Util { try { File file = new File(AZipOutputStream.filePath); if (!file.exists()) { - //先得到文件的上级目录,并创建上级目录,在创建文件 + // 先得到文件的上级目录,并创建上级目录,在创建文件 file.getParentFile().mkdirs(); try { - //创建文件 + // 创建文件 file.createNewFile(); } catch (IOException ex) { ex.printStackTrace(); @@ -2079,10 +2082,25 @@ public class Util extends weaver.general.Util { appender.setAppend(true); appender.activateOptions(); log.addAppender(appender); - Boolean enableDebug = mapper.selectLogLevel(); + log.setLevel(Level.INFO); + /* + boolean enableDebug = false; + try { + // Boolean enableDebug = mapper.selectLogLevel(); + RecordSet rs = new RecordSet(); + rs.executeQuery("select param_value from uf_cus_dev_config where only_mark = 'enableDebugLog'"); + if (rs.next()) { + String value = rs.getString("param_value"); + enableDebug = Boolean.parseBoolean(value); + + } + } catch (Exception ignore) { + + } if (!enableDebug) { log.setLevel(Level.INFO); } + */ } } } @@ -2091,28 +2109,50 @@ public class Util extends weaver.general.Util { public static Logger getLogger(String name) { - DailyRollingFileAppender appender = new DailyRollingFileAppender(); - Logger cusLog = Logger.getLogger(name); - appender.setName(name); - appender.setEncoding("UTF-8"); - appender.setDatePattern("'_'yyyyMMdd'.log'"); - appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log"); - appender.setThreshold(Priority.DEBUG); - appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); - appender.setAppend(true); - appender.activateOptions(); - cusLog.addAppender(appender); - if (mapper != null) { - try { - Boolean enableDebug = mapper.selectLogLevel(); + + if (otherLog.containsKey(name)) { + return otherLog.get(name); + } + if (!otherLog.containsKey(name)) { + synchronized (Util.otherLog) { + if (otherLog.containsKey(name)) { + return otherLog.get(name); + } + DailyRollingFileAppender appender = new DailyRollingFileAppender(); + Logger cusLog = Logger.getLogger("cus_" + name); + appender.setName("cus_" + name); + appender.setEncoding("UTF-8"); + appender.setDatePattern("'_'yyyyMMdd'.log'"); + appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log"); + appender.setThreshold(Priority.DEBUG); + appender.setLayout(new PatternLayout("[%-5p] [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%r] [Thread:%t][%F.%M:%L] ==> : %m %x %n")); + appender.setAppend(true); + appender.activateOptions(); + cusLog.addAppender(appender); + /* + boolean enableDebug = false; + try { + // Boolean enableDebug = mapper.selectLogLevel(); + RecordSet rs = new RecordSet(); + rs.executeQuery("select param_value from uf_cus_dev_config where only_mark = 'enableDebugLog'"); + if (rs.next()) { + String value = rs.getString("param_value"); + enableDebug = Boolean.parseBoolean(value); + + } + } catch (Exception ignore) { + + } if (!enableDebug) { cusLog.setLevel(Level.INFO); } - } catch (Exception ignore) { - + */ + cusLog.setLevel(Level.INFO); + otherLog.put(name, cusLog); + return cusLog; } } - return cusLog; + return null; } /** @@ -2122,7 +2162,49 @@ public class Util extends weaver.general.Util { * @return 参数值 */ public static String getCusConfigValue(String onlyMark) { - return mapper.selectCusConfigParam(onlyMark); + return mapper.selectCusConfigParam(onlyMark, UF_CUS_DEV_CONFIG); + } + + /** + * 查询自定义配置参数值 + * + * @param onlyMark 唯一标识 + * @return 参数值 + */ + public static String getCusConfigValue(String onlyMark, String configTable) { + return mapper.selectCusConfigParam(onlyMark, configTable); + } + + /** + *

更新或插入自定义配置参数

+ * + * @param onlyMark 唯一标识 + * @param value 参数值 + * @param desc 描述信息 + * @return 是否插入成功 + */ + public static boolean insertOrUpdateConfigValue(String onlyMark, String value, String desc) { + String selectValue = getCusConfigValue(onlyMark); + if (Util.isNullOrEmpty(selectValue)) { + String modeId = getModeIdByTableName(UF_CUS_DEV_CONFIG); + int dataId = getModeDataId(UF_CUS_DEV_CONFIG, Integer.parseInt(modeId), 1); + boolean success = mapper.updateConfigValueById(onlyMark, value, desc, String.valueOf(dataId), UF_CUS_DEV_CONFIG); + rebuildModeDataShare(1, Integer.valueOf(modeId), dataId); + return success; + } + return mapper.updateConfigValueByOnlyMark(onlyMark, value, desc, UF_CUS_DEV_CONFIG); + } + + public static boolean insertOrUpdateConfigValue(String onlyMark, String value, String desc, String configTable) { + String selectValue = mapper.selectCusConfigParam(onlyMark, configTable); + if (Util.isNullOrEmpty(selectValue)) { + String modeId = getModeIdByTableName(UF_CUS_DEV_CONFIG); + int dataId = getModeDataId(UF_CUS_DEV_CONFIG, Integer.parseInt(modeId), 1); + boolean success = mapper.updateConfigValueById(onlyMark, value, desc, String.valueOf(dataId), configTable); + rebuildModeDataShare(1, Integer.valueOf(modeId), dataId); + return success; + } + return mapper.updateConfigValueByOnlyMark(onlyMark, value, desc, configTable); } /** @@ -2132,7 +2214,7 @@ public class Util extends weaver.general.Util { * @param defaultStr 默认值 * @return 参数值 */ - public static String getCusConfigValue(String onlyMark, String defaultStr) { + public static String getCusConfigDefaultValue(String onlyMark, String defaultStr) { String cusConfigValue = getCusConfigValue(onlyMark); return cusConfigValue == null ? defaultStr : cusConfigValue; } @@ -2617,9 +2699,25 @@ public class Util extends weaver.general.Util { * @param remark 签字意见 */ public static void submitWorkflowThread(Integer requestId, Integer userId, String remark) { + submitWorkflowThread(requestId, userId, remark, 60); + } + + /** + *

异步提交流程,一般作用于action在节点前

+ * + * @param requestId 流程ID + * @param userId 用户id + * @param remark 签字意见 + * @param seconds 延时多少秒提交 + */ + public static void submitWorkflowThread(Integer requestId, Integer userId, String remark, int seconds) { + if (seconds <= 0) { + seconds = 1; + } + int finalSeconds = seconds; new Thread(() -> { try { - Thread.sleep(1000 * 60); + Thread.sleep(1000 * finalSeconds); } catch (InterruptedException e) { e.printStackTrace(); Util.getLogger().error("线程休眠失败", e); @@ -2748,8 +2846,8 @@ public class Util extends weaver.general.Util { ImageFileManager imageFileManager = new ImageFileManager(); int imgFileId; try { - ImageFileManager.class.getMethod("saveImageFileByInputStream", InputStream.class, String.class); - imgFileId = imageFileManager.saveImageFileByInputStream(content, fileName); + Method saveImageFileByInputStream = ImageFileManager.class.getMethod("saveImageFileByInputStream", InputStream.class, String.class); + imgFileId = (int) saveImageFileByInputStream.invoke(imageFileManager, content, fileName); } catch (NoSuchMethodException e) { imageFileManager.setImagFileName(fileName); try { @@ -2887,7 +2985,7 @@ public class Util extends weaver.general.Util { } if (printParam.size() > 0) { - log.info(Util.logStr("Acton[{}]参数:\n{}", obj.getClass().toString(), + getLogger().info(Util.logStr("Acton[{}]参数:\n{}", obj.getClass().toString(), JSONObject.toJSONString(printParam, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat))); } return true; @@ -3141,27 +3239,45 @@ public class Util extends weaver.general.Util { boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); + boolean hasOptional = declaredField.isAnnotationPresent(ActionOptionalParam.class); + // 如果存在默认值,并且是必填参数 if (hasDefaultValue && hasRequiredMark) { - if (value == null) { + // 如果参数map中没有则赋值为默认值 + if (null == value) { + // 获取默认值赋值 String defaultValue = defaultTestValue.value(); if (defaultValue == null) { throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); } value = defaultValue; } + // 如果没有默认值,并且是必填参数 } else if (!hasDefaultValue && hasRequiredMark) { - if (value == null) { + // 如果没有从param中获取到,则抛出异常 + if (Util.isNullOrEmpty(value)) { throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); } + // 如果有默认值,并且没有从params中获得,则赋值 } else if (hasDefaultValue) { - value = defaultTestValue.value(); + if (null == value) { + value = defaultTestValue.value(); + } + } else if (hasOptional) { + // 如果存在可选值 + ActionOptionalParam optionalParam = declaredField.getAnnotation(ActionOptionalParam.class); + String defaultValue = optionalParam.value(); + // 可选值没有在param中存在 + if (null == value) { + value = defaultValue; + } } else { - if (!params.containsKey(name)) { + + // 都不符合必填和默认值的参数,判断params中是否存在,如果不存在则直接跳过 + if (null == value) { continue; } value = params.get(name); } - Method method = cronJobClass.getMethod(setMethodName, String.class); method.invoke(action, value); } @@ -3171,7 +3287,7 @@ public class Util extends weaver.general.Util { throw new CustomerException("计划任务执行异常!异常信息:\n" + Util.getErrString(e)); } - log.info(Util.logStr("\n\t计划任务 [{}] execute success!\n", cronJobClass.getName())); + getLogger().info(Util.logStr("\n\t计划任务 [{}] execute success!\n", cronJobClass.getName())); } @@ -3218,13 +3334,13 @@ public class Util extends weaver.general.Util { } } else if (hasDefaultValue) { value = defaultTestValue.value(); - } else { - if (!params.containsKey(name)) { - continue; - } + } + if (!params.containsKey(name) && Util.isNullOrEmpty(value)) { + continue; + } + if (params.containsKey(name)) { value = params.get(name); } - Method method = actionClass.getMethod(setMethodName, String.class); method.invoke(action, value); } @@ -3242,7 +3358,7 @@ public class Util extends weaver.general.Util { if (Action.FAILURE_AND_CONTINUE.equals(execute)) { throw new CustomerException("action执行失败,失败原因:\n" + requestInfo.getRequestManager().getMessagecontent()); } - log.info(Util.logStr("\n\n\tAction [{}] execute success!\n", actionClass.getName())); + getLogger().info(Util.logStr("\n\n\tAction [{}] execute success!\n", actionClass.getName())); } public static String getSetMethodName(String fieldName) { @@ -3345,7 +3461,10 @@ public class Util extends weaver.general.Util { key:hah value:haode*/ // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类,将参数传递给这个类, - String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=(?((#(\\{|sql\\{))?([()\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?))&?"; + // String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=(?((#(\\{|sql\\{))?([()\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?))&?"; + String pattern = "&?(?([#.\\w\\u4E00-\\u9FA5]+))=" + + "(?((`([():/\\-&$#={ }.\\w\\u4E00-\\u9FA5?]*)`)|" + + "((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?"; Pattern compile = Pattern.compile(pattern); Matcher matcher = compile.matcher(paramStr); Map pathParamMap = new HashMap<>(8); diff --git a/src/main/java/aiyh/utils/action/CusBaseAction.java b/src/main/java/aiyh/utils/action/CusBaseAction.java index a152949..6dc2c26 100644 --- a/src/main/java/aiyh/utils/action/CusBaseAction.java +++ b/src/main/java/aiyh/utils/action/CusBaseAction.java @@ -13,18 +13,17 @@ import weaver.workflow.workflow.WorkflowBillComInfo; import weaver.workflow.workflow.WorkflowComInfo; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** *

基础的action,实现一些基础的参数

- * @author EBU7-dev-1 aiyh * + * @author EBU7-dev-1 aiyh */ -public abstract class CusBaseAction implements Action{ - - +public abstract class CusBaseAction implements Action { /** @@ -38,21 +37,21 @@ public abstract class CusBaseAction implements Action{ protected RequestInfo requestInfo; - private final Map actionHandleMethod = new HashMap<>(); + private final Map actionHandleMethod = new HashMap<>(); /** *

初始化流程默认的处理方法

*/ - private void initHandleMethod(){ + private void initHandleMethod() { // 提交 - actionHandleMethod.put(ActionRunType.SUBMIT,this::doSubmit); + actionHandleMethod.put(ActionRunType.SUBMIT, this::doSubmit); // 退回 - actionHandleMethod.put(ActionRunType.REJECT,this::doReject); + actionHandleMethod.put(ActionRunType.REJECT, this::doReject); // 撤回 - actionHandleMethod.put(ActionRunType.WITHDRAW,this::doWithdraw); + actionHandleMethod.put(ActionRunType.WITHDRAW, this::doWithdraw); // 强制收回 - actionHandleMethod.put(ActionRunType.DRAW_BACK,this::doDrawBack); + actionHandleMethod.put(ActionRunType.DRAW_BACK, this::doDrawBack); } @@ -84,17 +83,17 @@ public abstract class CusBaseAction implements Action{ // 获取流程对应的处理方法 CusBaseActionHandleFunction cusBaseActionHandleFunction = actionHandleMethod.get(src); // 默认没有直接成功不做拦截 - if(null == cusBaseActionHandleFunction){ + if (null == cusBaseActionHandleFunction) { return Action.SUCCESS; } - cusBaseActionHandleFunction.handle(requestId,billTable,workflowId,user,requestManager); + cusBaseActionHandleFunction.handle(requestId, billTable, workflowId, user, requestManager); } catch (CustomerException e) { e.printStackTrace(); Util.actionFail(requestManager, e.getMessage()); return Action.FAILURE_AND_CONTINUE; } catch (Exception e) { e.printStackTrace(); - log.info(Util.logStr("execute action fail, exception message is [{}], error stack trace msg is: \n{}" , + log.error(Util.logStr("execute action fail, exception message is [{}], error stack trace msg is: \n{}", e.getMessage(), Util.getErrString(e))); Util.actionFail(requestManager, e.getMessage()); return Action.FAILURE_AND_CONTINUE; @@ -104,9 +103,11 @@ public abstract class CusBaseAction implements Action{ /** *

流程其他流转类型处理方法注册

+ * * @param actionHandleMethod 处理方法对应map */ - public void registerHandler(Map actionHandleMethod){}; + public void registerHandler(Map actionHandleMethod) { + } /** @@ -124,8 +125,7 @@ public abstract class CusBaseAction implements Action{ */ public abstract void doSubmit(String requestId, String billTable, int workflowId, - User user, RequestManager requestManager); - + User user, RequestManager requestManager); /** @@ -142,7 +142,8 @@ public abstract class CusBaseAction implements Action{ * @param requestManager 请求管理对象 */ public void doReject(String requestId, String billTable, int workflowId, - User user, RequestManager requestManager){}; + User user, RequestManager requestManager) { + } /** *

action 撤回、撤回流程流程业务处理方法

@@ -158,7 +159,8 @@ public abstract class CusBaseAction implements Action{ * @param requestManager 请求管理对象 */ public void doWithdraw(String requestId, String billTable, int workflowId, - User user, RequestManager requestManager){}; + User user, RequestManager requestManager) { + } /** @@ -175,7 +177,8 @@ public abstract class CusBaseAction implements Action{ * @param requestManager 请求管理对象 */ public void doDrawBack(String requestId, String billTable, int workflowId, - User user, RequestManager requestManager){}; + User user, RequestManager requestManager) { + } /** @@ -187,7 +190,7 @@ public abstract class CusBaseAction implements Action{ // 获取主表数据 Property[] propertyArr = requestInfo.getMainTableInfo().getProperty(); if (null == propertyArr) { - return null; + return Collections.emptyMap(); } Map mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 0.75)); for (Property property : propertyArr) { @@ -251,14 +254,22 @@ public abstract class CusBaseAction implements Action{ } - public static final class ActionRunType{ - /** 退回 */ + public static final class ActionRunType { + /** + * 退回 + */ public static final String REJECT = "reject"; - /** 撤回 */ + /** + * 撤回 + */ public static final String WITHDRAW = "withdraw"; - /** 强制收回 */ + /** + * 强制收回 + */ public static final String DRAW_BACK = "drawBack"; - /** 提交 */ + /** + * 提交 + */ public static final String SUBMIT = "submit"; } diff --git a/src/main/java/aiyh/utils/annotation/recordset/BatchDelete.java b/src/main/java/aiyh/utils/annotation/recordset/BatchDelete.java new file mode 100644 index 0000000..520cc48 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/BatchDelete.java @@ -0,0 +1,20 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

批量插入

+ * + *

create: 2022-08-09 17:40

+ * + * @author aiyh EBU7-dev-1 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface BatchDelete { + String value() default ""; + + // sql是否是在参数中 + boolean custom() default false; +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/BatchInsert.java b/src/main/java/aiyh/utils/annotation/recordset/BatchInsert.java new file mode 100644 index 0000000..1378c71 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/BatchInsert.java @@ -0,0 +1,20 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

批量插入

+ * + *

create: 2022-08-09 17:40

+ * + * @author aiyh EBU7-dev-1 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface BatchInsert { + String value() default ""; + + // sql是否是在参数中 + boolean custom() default false; +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/BatchSqlArgs.java b/src/main/java/aiyh/utils/annotation/recordset/BatchSqlArgs.java new file mode 100644 index 0000000..41e7d00 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/BatchSqlArgs.java @@ -0,0 +1,18 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

批量参数标识

+ * + *

create: 2022-08-10 10:53

+ * + * @author aiyh EBU7-dev-1 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.PARAMETER) +@Documented +public @interface BatchSqlArgs { + +} diff --git a/src/main/java/aiyh/utils/annotation/recordset/BatchUpdate.java b/src/main/java/aiyh/utils/annotation/recordset/BatchUpdate.java new file mode 100644 index 0000000..e2dc2f4 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/BatchUpdate.java @@ -0,0 +1,20 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

批量插入

+ * + *

create: 2022-08-09 17:40

+ * + * @author aiyh EBU7-dev-1 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface BatchUpdate { + String value() default ""; + + // sql是否是在参数中 + boolean custom() default false; +} diff --git a/src/main/java/aiyh/utils/entity/DocImageInfo.java b/src/main/java/aiyh/utils/entity/DocImageInfo.java index 006bb8b..9834f9f 100644 --- a/src/main/java/aiyh/utils/entity/DocImageInfo.java +++ b/src/main/java/aiyh/utils/entity/DocImageInfo.java @@ -16,5 +16,6 @@ public class DocImageInfo { private String imageFileName; private Integer id; private Integer detailId; + private Integer fileSize; } diff --git a/src/main/java/aiyh/utils/fileUtil/pdf/CustomerPdfRenderListener.java b/src/main/java/aiyh/utils/fileUtil/pdf/CustomerPdfRenderListener.java index 192bf2a..414ff9f 100644 --- a/src/main/java/aiyh/utils/fileUtil/pdf/CustomerPdfRenderListener.java +++ b/src/main/java/aiyh/utils/fileUtil/pdf/CustomerPdfRenderListener.java @@ -45,30 +45,34 @@ public class CustomerPdfRenderListener implements RenderListener { @Override public void renderText(TextRenderInfo textRenderInfo) { String text = textRenderInfo.getText(); - if(text == null){ + if (text == null) { return; } Rectangle2D.Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange(); - if(text.equals(keyWord)){ + if (text.equals(keyWord)) { createKeywordPotion(boundingRectange); return; } for (char c : text.toCharArray()) { char keywordChar = keywordChars[n]; - if(keywordChar == c){ - if(n == 0){ + if (n > 0 && keywordChar != c) { + n = 0; + keywordChar = keywordChars[n]; + } + if (keywordChar == c) { + if (n == 0) { this.startX = boundingRectange.x; this.startY = boundingRectange.y; this.startPage = page; } - if(n == keywordChars.length - 1){ + if (n == keywordChars.length - 1) { createKeywordPotion(boundingRectange); n = 0; return; } - n ++; - }else { + n++; + } else { n = 0; } } @@ -125,7 +129,7 @@ public class CustomerPdfRenderListener implements RenderListener { public void setKeyWord(String keyWord) { this.keyWord = keyWord; - if(StringUtils.isNullOrEmpty(keyWord)){ + if (StringUtils.isNullOrEmpty(keyWord)) { throw new CustomerException("keyWord is null"); } this.keywordChars = keyWord.toCharArray(); diff --git a/src/main/java/aiyh/utils/httpUtil/MultipartFile.java b/src/main/java/aiyh/utils/httpUtil/MultipartFile.java new file mode 100644 index 0000000..bb2ed73 --- /dev/null +++ b/src/main/java/aiyh/utils/httpUtil/MultipartFile.java @@ -0,0 +1,35 @@ +package aiyh.utils.httpUtil; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +import java.io.InputStream; + +/** + *

文件上传类

+ * + *

create: 2022-11-21 11:54

+ * + * @author youHong.ai + */ + +@Setter +@Getter +@ToString +public class MultipartFile { + /** + * 文件名 + */ + String fileName; + /** + * 上传文件的key + */ + String fileKey; + /** + * 文件流信息 + */ + InputStream stream; + + Long fileSize; +} diff --git a/src/main/java/aiyh/utils/httpUtil/httpAsync/HttpAsyncThreadCallBack.java b/src/main/java/aiyh/utils/httpUtil/httpAsync/HttpAsyncThreadCallBack.java index aa6ebee..4bcf525 100644 --- a/src/main/java/aiyh/utils/httpUtil/httpAsync/HttpAsyncThreadCallBack.java +++ b/src/main/java/aiyh/utils/httpUtil/httpAsync/HttpAsyncThreadCallBack.java @@ -1,10 +1,21 @@ package aiyh.utils.httpUtil.httpAsync; +import aiyh.utils.Util; +import aiyh.utils.httpUtil.ExtendedIOUtils; +import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.util.HttpUtilParamInfo; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +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 aiyh.utils.httpUtil.ExtendedIOUtils; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; +import java.util.Date; +import java.util.Locale; import java.util.function.Consumer; /** @@ -14,27 +25,69 @@ import java.util.function.Consumer; */ -public class HttpAsyncThreadCallBack implements Runnable{ - private final CloseableHttpClient httpClient; - private final HttpUriRequest request; - private final Consumer consumer; +public class HttpAsyncThreadCallBack implements Runnable { + private final CloseableHttpClient httpClient; + private final HttpUriRequest request; + private final Consumer consumer; + private String defaultEncoding = "UTF-8"; + private static final Logger log = Util.getLogger("http_util"); - public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer){ - this.httpClient = httpClient; - this.request = request; - this.consumer = consumer; - } + private HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - @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); - } + public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer) { + this.httpClient = httpClient; + this.request = request; + this.consumer = consumer; + } + + public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer, String defaultEncoding) { + this.httpClient = httpClient; + this.request = request; + this.consumer = consumer; + this.defaultEncoding = defaultEncoding; + } + + @Override + public void run() { + CloseableHttpResponse response = null; + try { + + response = httpClient.execute(request); + HttpEntity entity = response.getEntity(); + Header[] allHeaders = response.getAllHeaders(); + ResponeVo responeVo = new ResponeVo(); + Locale locale = response.getLocale(); + responeVo.setLocale(locale); + responeVo.setAllHeaders(allHeaders); + responeVo.setEntityString(EntityUtils.toString(entity, defaultEncoding)); + responeVo.setCode(response.getStatusLine().getStatusCode()); + httpUtilParamInfo.setResponse(responeVo); + httpUtilParamInfo.setResponseDate(new Date()); + try { + log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), + JSONObject.toJSONString(httpUtilParamInfo, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + } catch (Exception ignore) { + } + consumer.accept(responeVo); + } catch (Exception e) { + log.error(" http调用失败:" + Util.getErrString(e)); + try { + httpUtilParamInfo.setResponseDate(new Date()); + log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), + JSONObject.toJSONString(httpUtilParamInfo, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + } catch (Exception ignore) { + } + consumer.accept(null); + } + ExtendedIOUtils.closeQuietly(httpClient); + ExtendedIOUtils.closeQuietly(response); + } + + public void setHttpUtilParamInfo(HttpUtilParamInfo httpUtilParamInfo) { + this.httpUtilParamInfo = httpUtilParamInfo; + } } diff --git a/src/main/java/aiyh/utils/httpUtil/staticUtil/HttpStaticUtils.java b/src/main/java/aiyh/utils/httpUtil/staticUtil/HttpStaticUtils.java index 8c46eed..8688af4 100644 --- a/src/main/java/aiyh/utils/httpUtil/staticUtil/HttpStaticUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/staticUtil/HttpStaticUtils.java @@ -39,797 +39,811 @@ import java.util.function.Consumer; public class HttpStaticUtils { - // 默认编码 - public static String DEFAULT_ENCODING = "UTF-8"; + // 默认编码 + public static String DEFAULT_ENCODING = "UTF-8"; - private static final ToolUtil toolUtil = new ToolUtil(); + 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 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 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; - } + 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,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return baseRequest(httpConnection, httpGet); - } + /** + * get请求 + * + * @param url 请求地址 + * @return 请求结果 + * @throws IOException io异常 + */ + public static ResponeVo apiGet(String url) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry 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,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return baseRequest(httpConnection, httpDelete); - } + /** + * delete请求 + * + * @param url 请求地址 + * @return 请求结果 + * @throws IOException io异常 + */ + public static ResponeVo apiDelete(String url) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry 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 headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return baseRequest(httpConnection, httpGet); - } + /** + * get请求 + * + * @param url 请求地址 + * @param headers 请求头 + * @return 响应结果封装 + * @throws IOException io异常 + */ + public static ResponeVo apiGet(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry 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 headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return baseRequest(httpConnection, httpDelete); - } + /** + * delete请求 + * + * @param url 请求地址 + * @param headers 请求头 + * @return 请求结果 + * @throws IOException io异常 + */ + public static ResponeVo apiDelete(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + return baseRequest(httpConnection, httpDelete); + } - public static ResponeVo apiGet(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return baseRequest(httpConnection, httpGet); - } + public static ResponeVo apiGet(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return baseRequest(httpConnection, httpGet); + } - public static ResponeVo apiDelete(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return baseRequest(httpConnection, httpDelete); - } + public static ResponeVo apiDelete(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry 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 params, Map headers, Consumer consumer) throws IOException { + /** + * 回调方法 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public static void apiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - System.out.println(getUrl); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - callBackRequest(httpConnection, httpGet, consumer); - } + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + System.out.println(getUrl); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry 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 params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - callBackRequest(httpConnection, httpDelete, consumer); - } + /** + * 回调方法 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public static void apiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry 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 params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPost); - } + /** + * post请求 + * + * @param url 请求地址 + * @param params 请求参数 + * @return 请求结果 + * @throws IOException io异常 + */ + public static ResponeVo apiPost(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return baseRequest(httpConnection, httpPost); + } - public static ResponeVo apiPut(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPut); - } + public static ResponeVo apiPut(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPost); - } + /** + * post请求 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头 + * @return 请求结果 + * @throws IOException io异常 + */ + public static ResponeVo apiPost(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return baseRequest(httpConnection, httpPost); + } - public static ResponeVo apiPut(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPut); - } + public static ResponeVo apiPut(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } + public static ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } + public static ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - InputStream inputStream = ImageFileManager.getInputStreamById(id); - HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } + public static ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers){ - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - builder.addBinaryBody(fileKey,inputStream, ContentType.MULTIPART_FORM_DATA,fileName); - for (Map.Entry param : params.entrySet()){ - StringBody stringBody = new StringBody(param.getValue(),ContentType.MULTIPART_FORM_DATA); - builder.addPart(param.getKey(),stringBody); - } - HttpPost httpPost = new HttpPost(url.trim()); + public static HttpPost uploadFileByInputStream(String url, InputStream inputStream, String fileKey, String fileName, + Map params, Map headers) { + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.addBinaryBody(fileKey, inputStream, ContentType.MULTIPART_FORM_DATA, fileName); + for (Map.Entry 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 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; - } + for (Map.Entry 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 params, Map headers){ - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - builder.addBinaryBody(fileKey,file, ContentType.MULTIPART_FORM_DATA,fileName); - for (Map.Entry param : params.entrySet()){ - StringBody stringBody = new StringBody(param.getValue(),ContentType.MULTIPART_FORM_DATA); - builder.addPart(param.getKey(),stringBody); - } - HttpPost httpPost = new HttpPost(url.trim()); + public static HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, + Map params, Map headers) { + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName); + for (Map.Entry 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 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; - } + for (Map.Entry 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 params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map 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 apiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - callBackRequest(httpConnection, httpPut, consumer); - } + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public static void apiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 consumer) throws IOException { - CloseableHttpResponse response = null; - try { - response = httpClient.execute(request); - consumer.accept(response); - } catch (Exception e) { - toolUtil.writeErrorLog(" http调用失败:" + e); - throw e; - } + /** + * 回调请求方法 + * + * @param httpClient httpclient对象 + * @param request 请求对象 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + private static void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer 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); - } + 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; - } + /** + * 请求封装 + * + * @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; - } + ExtendedIOUtils.closeQuietly(httpClient); + ExtendedIOUtils.closeQuietly(response); + return responeVo; + } - /** - * 异步get请求 - * - * @param url 请求地址 - * @return 请求结果 Future类 - * @throws IOException io异常 - */ - public static Future asyncApiGet(String url) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); - } + /** + * 异步get请求 + * + * @param url 请求地址 + * @return 请求结果 Future类 + * @throws IOException io异常 + */ + public static Future asyncApiGet(String url) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headers.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); + } - public static Future asyncApiUploadFile(String url,InputStream inputStream, String fileKey,String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } + public static Future asyncApiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = uploadFileByInputStream(url, inputStream, fileKey, fileName, paramsMap, headerMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } - public static Future asyncApiUploadFile(String url,File file, String fileKey,String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } + public static Future asyncApiUploadFile(String url, File file, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } - public static Future asyncApiUploadFileById(String url,int id, String fileKey,String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map 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)); - } + public static Future asyncApiUploadFileById(String url, int id, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 asyncApiDelete(String url) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); - } + /** + * 异步delete请求 + * + * @param url 请求地址 + * @return 请求结果Future类 + * @throws IOException io异常 + */ + public static Future asyncApiDelete(String url) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry 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 asyncApiGet(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); - } + /** + * 异步get请求 + * + * @param url 请求地址 + * @param headers 请求头 + * @return 请求结果 + * @throws IOException io异常 + */ + public static Future asyncApiGet(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); + } - public static Future asyncApiDelete(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); - } + public static Future asyncApiDelete(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); + } - public static Future asyncApiGet(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); - } + public static Future asyncApiGet(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); + } - public static Future asyncApiDelete(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); - } + public static Future asyncApiDelete(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry 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 params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry 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 asyncApiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry 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 params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer)); - } + /** + * 回调方法 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public static void asyncApiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer)); + } - public static Future asyncApiPost(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } + public static Future asyncApiPost(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } - public static Future asyncApiPut(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); - } + public static Future asyncApiPut(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); + } - public static Future asyncApiPost(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } + public static Future asyncApiPost(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } - public static Future asyncApiPut(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); - } + public static Future asyncApiPut(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map 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 asyncApiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url,null); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer)); - } + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public static void asyncApiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); + Map paramsMap = paramsHandle(params); + Map 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 headerMap, Map paramsMap) throws UnsupportedEncodingException { - String contentType = ""; - HttpPost httpPost = new HttpPost(url.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpPost.setHeader(entry.getKey(), entry.getValue()); - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - contentType = entry.getValue(); - } - } - if (Strings.isNullOrEmpty(contentType)) { - List nvps = new ArrayList<>(); - for (Map.Entry 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 nvps = new ArrayList<>(); - for (Map.Entry 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; - } + /** + * 处理post请求参数等,根据请求头设置参数类型 + * + * @param url 请求地址 + * @param headerMap 请求头 + * @param paramsMap 请求参数 + * @return 请求结果 + * @throws UnsupportedEncodingException 编码转换异常 + */ + private static HttpPost handleHttpPost(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { + String contentType = ""; + HttpPost httpPost = new HttpPost(url.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpPost.setHeader(entry.getKey(), entry.getValue()); + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + contentType = entry.getValue(); + } + } + if (Strings.isNullOrEmpty(contentType)) { + List nvps = new ArrayList<>(); + for (Map.Entry 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 nvps = new ArrayList<>(); + for (Map.Entry 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 headerMap, Map paramsMap) throws UnsupportedEncodingException { - String contentType = ""; - HttpPut httpPut = new HttpPut(url.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpPut.setHeader(entry.getKey(), entry.getValue()); - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - contentType = entry.getValue(); - } - } - if (Strings.isNullOrEmpty(contentType)) { - List nvps = new ArrayList<>(); - for (Map.Entry 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 nvps = new ArrayList<>(); - for (Map.Entry 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 HttpPut handleHttpPut(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { + String contentType = ""; + HttpPut httpPut = new HttpPut(url.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpPut.setHeader(entry.getKey(), entry.getValue()); + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + contentType = entry.getValue(); + } + } + if (Strings.isNullOrEmpty(contentType)) { + List nvps = new ArrayList<>(); + for (Map.Entry 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 nvps = new ArrayList<>(); + for (Map.Entry 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(); - } + 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 headersHandle(Map headers) { - Map 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 headers 请求头 + * @return 处理后的请求头 + */ + public static Map headersHandle(Map headers) { + Map 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 paramsHandle(Map params) { - Map 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; - } + /** + * 请求参数处理。添加全局请求参数 + * + * @param params 请求参数 + * @return 处理后的请求参数 + */ + public static Map paramsHandle(Map params) { + Map 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; + } - /** - * url地址处理,get请求地址序列化 - * @param url 请求地址 - * @param params 请求参数 - * @return 处理后的url - */ - public static String urlHandle(String url, Map 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; - } + /** + * url地址处理,get请求地址序列化 + * + * @param url 请求地址 + * @param params 请求参数 + * @return 处理后的url + */ + public static String urlHandle(String url, Map 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 params) { - if (params != null && params.size() > 0) { - StringBuilder builder = new StringBuilder(); - for (Map.Entry entry : params.entrySet()) { - builder.append("&"); - builder.append(entry.getKey()); - builder.append("="); - builder.append(entry.getValue()); - } - return removeSeparator(builder); - } - return ""; - } + /** + * 请求参数序列化 + * + * @param params 请求参数 + * @return 处理后的参数 + */ + private static String serializeParams(Map params) { + if (params != null && params.size() > 0) { + StringBuilder builder = new StringBuilder(); + for (Map.Entry 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)) { + 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(0, str.length() - 1); + } + if (str.trim().startsWith(removeSeparator)) { // 如果以&开头,则去除& - str = str.substring(1); - } - return str; - } + str = str.substring(1); + } + return str; + } } diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index cdbd189..7fe3370 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -1,10 +1,7 @@ package aiyh.utils.httpUtil.util; import aiyh.utils.Util; -import aiyh.utils.httpUtil.ExtendedIOUtils; -import aiyh.utils.httpUtil.HttpArgsType; -import aiyh.utils.httpUtil.HttpManager; -import aiyh.utils.httpUtil.ResponeVo; +import aiyh.utils.httpUtil.*; import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread; import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack; import aiyh.utils.zwl.common.ToolUtil; @@ -48,19 +45,19 @@ import java.util.function.Function; public class HttpUtils { - // 默认编码 - private String DEFAULT_ENCODING = "UTF-8"; - + public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY"; + public static final ThreadLocal HTTP_UTIL_PARAM_INFO_THREAD_LOCAL = new ThreadLocal<>(); + private static final Logger log = Util.getLogger("http_util"); private final ToolUtil toolUtil = new ToolUtil(); - private final GlobalCache globalCache = new GlobalCache(); // 线程池 private final ThreadPoolExecutor executorService; - public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY"; - - public static final ThreadLocal HTTP_UTIL_PARAM_INFO_THREAD_LOCAL = new ThreadLocal<>(); - - private static final Logger log = Util.getLogger("http_util"); + // 默认编码 + private String DEFAULT_ENCODING = "UTF-8"; + /** + * basic 认证 + */ + private CredentialsProvider credentialsProvider = null; { // private final ExecutorService executorService = Executors.newFixedThreadPool(3); @@ -77,15 +74,64 @@ public class HttpUtils { } - /** - * basic 认证 - */ - private CredentialsProvider credentialsProvider = null; - public HttpUtils(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } + public HttpUtils(String DEFAULT_ENCODING) { + this.DEFAULT_ENCODING = DEFAULT_ENCODING; + } + + public static String urlHandle(String url, Map 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 static String serializeParams(Map params) { + if (params != null && params.size() > 0) { + StringBuilder builder = new StringBuilder(); + for (Map.Entry 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; + } + public void setCredentialsProvider(CredentialsProvider credentialsProvider) { this.credentialsProvider = credentialsProvider; } @@ -98,10 +144,6 @@ public class HttpUtils { 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() @@ -153,7 +195,6 @@ public class HttpUtils { return baseRequest(httpConnection, httpGet); } - /** * delete请求 * @@ -349,7 +390,6 @@ public class HttpUtils { return baseRequest(httpConnection, httpPost); } - public ResponeVo apiPut(String url, Map params) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); @@ -358,7 +398,6 @@ public class HttpUtils { return baseRequest(httpConnection, httpPut); } - public ResponeVo apiPost(String url, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); @@ -374,7 +413,6 @@ public class HttpUtils { return baseRequest(httpConnection, httpPost); } - public ResponeVo apiPut(String url, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); @@ -383,24 +421,111 @@ public class HttpUtils { return baseRequest(httpConnection, httpPut); } + /** + *

上传单文件

+ * + * @param url 上传地址 + * @param inputStream 文件流 + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应实体 + * @throws IOException IO异常 + */ + public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url, inputStream, fileKey, fileName, paramsMap, headerMap); + MultipartFile multipartFile = new MultipartFile(); + multipartFile.setFileName(fileName); + multipartFile.setFileKey(fileKey); + multipartFile.setStream(inputStream); + multipartFile.setFileSize(inputStream.available() / 1024L); + HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); return baseRequest(httpConnection, httpPost); } + + /** + *

上传多附件

+ * + * @param url 上传地址 + * @param multipartFileList 附件信息 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应数 + * @throws IOException Io异常 + */ + public ResponeVo apiUploadFiles(String url, List multipartFileList, Map params, + Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap); + return baseRequest(httpConnection, httpPost); + } + + + /** + *

上传多附件

+ * + * @param url 上传地址 + * @param multipartFileList 附件信息 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应数 + * @throws IOException Io异常 + */ + public ResponeVo apiPutUploadFiles(String url, List multipartFileList, Map params, + Map headers) throws IOException { + CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap); + return baseRequest(httpConnection, httpPut); + } + + /** + *

异步上传文集爱你

+ * + * @param url 上传地址 + * @param inputStream 文件流 + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 其他参数 + * @param headers 请求头 + * @return 异步响应信息 + * @throws IOException IO异常 + */ public Future apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url, inputStream, fileKey, fileName, paramsMap, headerMap); + MultipartFile multipartFile = new MultipartFile(); + multipartFile.setFileName(fileName); + multipartFile.setFileKey(fileKey); + multipartFile.setStream(inputStream); + multipartFile.setFileSize(inputStream.available() / 1024L); + HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); } + /** + *

上传文件

+ * + * @param url 上传路径 + * @param file 文件对象 + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应参数 + * @throws IOException IO异常 + */ public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); @@ -410,17 +535,34 @@ public class HttpUtils { return baseRequest(httpConnection, httpPost); } + /** + *

通过ImageFileId上传文件

+ * + * @param url 请求地址 + * @param id 附件ID + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 文件参数 + * @param headers 请求头信息 + * @return 响应信息 + * @throws IOException IO异常 + */ + public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); InputStream inputStream = ImageFileManager.getInputStreamById(id); - HttpPost httpPost = uploadFileByInputStream(url, inputStream, fileKey, fileName, paramsMap, headerMap); + MultipartFile multipartFile = new MultipartFile(); + multipartFile.setFileName(fileName); + multipartFile.setFileKey(fileKey); + multipartFile.setStream(inputStream); + multipartFile.setFileSize(inputStream.available() / 1024L); + HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); return baseRequest(httpConnection, httpPost); } - /** * @param url 请求地址 * @param params 请求参数 @@ -467,7 +609,6 @@ public class HttpUtils { callBackRequest(httpConnection, httpPut, consumer); } - private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer) throws IOException { CloseableHttpResponse response = null; try { @@ -483,7 +624,6 @@ public class HttpUtils { } } - private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function consumer) throws IOException { CloseableHttpResponse response = null; ResponeVo apply = null; @@ -546,7 +686,6 @@ public class HttpUtils { return apply; } - public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException { ResponeVo responeVo = new ResponeVo(); CloseableHttpResponse response = null; @@ -593,7 +732,6 @@ public class HttpUtils { return responeVo; } - /** * get请求 * @@ -613,7 +751,6 @@ public class HttpUtils { return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); } - /** * delete请求 * @@ -698,7 +835,7 @@ public class HttpUtils { * @param consumer 回调函数 * @throws IOException io异常 */ - public void asyncApiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { + public void asyncApiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); @@ -707,7 +844,14 @@ public class HttpUtils { for (Map.Entry entry : headerMap.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } - executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer)); + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); } /** @@ -717,7 +861,7 @@ public class HttpUtils { * @param consumer 回调方法 * @throws IOException io异常 */ - public void asyncApiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { + public void asyncApiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { Map paramsMap = paramsHandle(params); String getUrl = urlHandle(url, paramsMap); Map headerMap = headersHandle(headers); @@ -726,7 +870,14 @@ public class HttpUtils { for (Map.Entry entry : headerMap.entrySet()) { httpDelete.setHeader(entry.getKey(), entry.getValue()); } - executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer)); + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); } public Future asyncApiPost(String url, Map params) throws IOException { @@ -745,7 +896,6 @@ public class HttpUtils { return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); } - public Future asyncApiPost(String url, Map params, Map headers) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); @@ -762,7 +912,6 @@ public class HttpUtils { return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); } - /** * @param url 请求地址 * @param params 请求参数 @@ -770,15 +919,21 @@ public class HttpUtils { * @param consumer 回调方法 * @throws IOException io异常 */ - public void asyncApiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { + public void asyncApiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer)); + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); } - /** * @param url 请求地址 * @param params 请求参数 @@ -786,12 +941,19 @@ public class HttpUtils { * @param consumer 回调方法 * @throws IOException io异常 */ - public void asyncApiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { + public void asyncApiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); Map paramsMap = paramsHandle(params); Map headerMap = headersHandle(headers); HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer)); + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); } private HttpPost handleHttpPostObject(String url, Map headerMap, Object paramsMap) throws UnsupportedEncodingException { @@ -844,20 +1006,40 @@ public class HttpUtils { return httpPost; } - private HttpPost handleHttpPost(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { return handleHttpPostObject(url, headerMap, paramsMap); } - - public HttpPost uploadFileByInputStream(String url, InputStream inputStream, String fileKey, String fileName, - Map params, Map headers) { - log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + - "", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); + /** + *

上传文件

+ * + * @param url 上床地址 + * @param multipartFileList 文件信息 + * @param params 其他参数 + * @param headers 请求头信息 + * @return 返回httpPost + */ + private HttpPost uploadFileByInputStream(String url, List multipartFileList, + Map params, Map headers) { + log.info(Util.logStr("start request : url is [{}]" + + "", url)); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setSendDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(StandardCharsets.UTF_8); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - builder.addBinaryBody(fileKey, inputStream, ContentType.MULTIPART_FORM_DATA, fileName); + Long totalSize = 0L; + for (MultipartFile multipartFile : multipartFileList) { + log.info(Util.logStr("add file, file info: fileName => [{}], fileKey => [{}], fileSize => [{}]kb", + multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize())); + totalSize += multipartFile.getFileSize(); + builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName()); + } + log.info("total file size: [" + totalSize + "]"); ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8); for (Map.Entry param : params.entrySet()) { StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); @@ -876,10 +1058,65 @@ public class HttpUtils { return httpPost; } - public HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, - Map params, Map headers) { + + /** + *

上传文件

+ * + * @param url 上床地址 + * @param multipartFileList 文件信息 + * @param params 其他参数 + * @param headers 请求头信息 + * @return 返回httpPost + */ + private HttpPut uploadFileByInputStreamPut(String url, List multipartFileList, + Map params, Map headers) { + log.info(Util.logStr("start request : url is [{}]" + + "", url)); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setSendDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setCharset(StandardCharsets.UTF_8); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + Long totalSize = 0L; + for (MultipartFile multipartFile : multipartFileList) { + log.info(Util.logStr("add file, file info: fileName => [{}], fileKey => [{}], fileSize => [{}]kb", + multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize())); + totalSize += multipartFile.getFileSize(); + builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName()); + } + log.info("total file size: [" + totalSize + "]"); + ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8); + for (Map.Entry param : params.entrySet()) { + StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); + builder.addPart(param.getKey(), stringBody); + } + HttpPut httpPut = new HttpPut(url.trim()); + + for (Map.Entry entry : headers.entrySet()) { + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + continue; + } + httpPut.setHeader(entry.getKey(), entry.getValue()); + } + HttpEntity entity = builder.build(); + httpPut.setEntity(entity); + return httpPut; + } + + private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, + Map params, Map headers) { log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + "", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setSendDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName); @@ -900,7 +1137,6 @@ public class HttpUtils { return httpPost; } - private HttpPut handleHttpPut(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); httpUtilParamInfo.setParams(paramsMap); @@ -936,7 +1172,6 @@ public class HttpUtils { return httpPut; } - private String inputStreamToString(InputStream is) { String line = ""; StringBuilder total = new StringBuilder(); @@ -976,54 +1211,4 @@ public class HttpUtils { } return map; } - - public String urlHandle(String url, Map 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 params) { - if (params != null && params.size() > 0) { - StringBuilder builder = new StringBuilder(); - for (Map.Entry 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; - } } diff --git a/src/main/java/aiyh/utils/mapper/UtilMapper.java b/src/main/java/aiyh/utils/mapper/UtilMapper.java index 4cd4b60..6cfc53d 100644 --- a/src/main/java/aiyh/utils/mapper/UtilMapper.java +++ b/src/main/java/aiyh/utils/mapper/UtilMapper.java @@ -1,9 +1,6 @@ package aiyh.utils.mapper; -import aiyh.utils.annotation.recordset.Delete; -import aiyh.utils.annotation.recordset.ParamMapper; -import aiyh.utils.annotation.recordset.Select; -import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.*; import aiyh.utils.entity.DocImageInfo; import aiyh.utils.entity.SelectValueEntity; import aiyh.utils.entity.WorkflowNodeConfig; @@ -23,23 +20,27 @@ public interface UtilMapper { /** * 查询日志级别是否开启Debug模式 + * * @return 是否开启Debug模式 */ - @Select("select param_value from uf_cus_dev_config where only_mark = 'enableDebugLog'") - public Boolean selectLogLevel(); + @Select("select param_value from $t{configTableName} where only_mark = 'enableDebugLog'") + public Boolean selectLogLevel(@ParamMapper("configTableName") String configTableName); /** * 根据唯一标识查询参数值 + * * @param onlyMark 唯一标识 * @return 参数值 */ - @Select("select param_value from uf_cus_dev_config where only_mark = #{onlyMark} and enable_param = 1") - public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark); + @Select("select param_value from $t{cusConfigTableName} where only_mark = #{onlyMark} and enable_param = 1") + public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark, + @ParamMapper("configTableName") String cusConfigTableName); /** * 查询文件名 + * * @param imageFileId 查询文件名 * @return 文件名 */ @@ -48,6 +49,7 @@ public interface UtilMapper { /** * 查询流程主表 + * * @param workflowId 流程id * @return 流程表名 */ @@ -60,12 +62,13 @@ public interface UtilMapper { @Select("select id,workflow_type,mark_only,workflow_nodes,enable_nodes from uf_node_config where enable_nodes = 1 and workflow_type in ($t{allVersion}) and mark_only = #{markOnly}") - WorkflowNodeConfig selectNodeConfig(@ParamMapper("allVersion")String allVersion,@ParamMapper("markOnly") String markOnly); + WorkflowNodeConfig selectNodeConfig(@ParamMapper("allVersion") String allVersion, @ParamMapper("markOnly") String markOnly); /** * 查询下拉框值 + * * @param tableName 表明 - * @param fileName 字段名 + * @param fileName 字段名 * @return 下拉框 */ @Select("select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, ws.selectname,ws.selectvalue " + @@ -81,17 +84,51 @@ public interface UtilMapper { /** * 查询文件信息 + * * @param imageFileId 查询文件名 * @return 文件名 */ @Select("select * from imagefile where imagefileid = #{imageFileId}") - Map selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId); + Map selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId); /** * 删除文件信息 + * * @param imageFileId 文件ID * @return 是否删除成功 */ @Delete("delete from imagefile where imagefileid = #{imageFileId}") boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId); + + /** + *

插入自定义配置数据

+ * + * @param onlyMark 唯一标识 + * @param value 参数值 + * @param desc 描述 + * @return 是否插入成功 + */ + @Update("update $t{configTableName} set only_mark = #{onlyMark},param_value = #{paramValue}, \n" + + "param_desc = #{paramDesc} where id = #{id}") + boolean updateConfigValueById(@ParamMapper("onlyMark") String onlyMark, + @ParamMapper("paramValue") String value, + @ParamMapper("paramDesc") String desc, + @ParamMapper("id") String id, + @ParamMapper("configTableName") String configTableName); + + /** + *

修改自定义配置数据

+ * + * @param onlyMark 唯一标识 + * @param value 值 + * @param desc 描述 + * @return 是否更新成功 + */ + @Update("update $t{configTableName} set param_value = #{paramValue}, \n" + + "param_desc = #{paramDesc} where only_mark = #{onlyMark}") + boolean updateConfigValueByOnlyMark(@ParamMapper("onlyMark") String onlyMark, + @ParamMapper("paramValue") String value, + @ParamMapper("paramDesc") String desc, + @ParamMapper("configTableName") String configTableName); + } diff --git a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java index 7bf3e58..b465644 100644 --- a/src/main/java/aiyh/utils/recordset/RecordsetUtil.java +++ b/src/main/java/aiyh/utils/recordset/RecordsetUtil.java @@ -4,8 +4,8 @@ import aiyh.utils.Util; import aiyh.utils.annotation.recordset.*; import aiyh.utils.excention.BindingException; import aiyh.utils.excention.CustomerException; +import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; -import org.apache.log4j.Logger; import weaver.conn.RecordSet; import java.lang.reflect.InvocationHandler; @@ -20,7 +20,6 @@ import java.lang.reflect.Proxy; public class RecordsetUtil implements InvocationHandler { - private static final Logger logger = Util.getLogger("sql_util_log"); private final RecordSet recordSet = new RecordSet(); public T getMapper(Class tClass) { @@ -46,7 +45,10 @@ public class RecordsetUtil implements InvocationHandler { String sql = select.value(); boolean custom = select.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - logger.info("解析sql===>" + handler.toString()); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { + throw new CustomerException("The sql statement does not match, the @Select annotation can only execute the select statement, please check whether the sql statement matches!"); + } + Util.getLogger("sql_log").info("解析sql===>" + handler); if (handler.getArgs().isEmpty()) { rs.executeQuery(handler.getSqlStr()); } else { @@ -61,7 +63,10 @@ public class RecordsetUtil implements InvocationHandler { String sql = update.value(); boolean custom = update.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - logger.info(handler.toString()); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only execute the update statement, please check whether the sql statement matches!"); + } + Util.getLogger("sql_log").info(handler.toString()); Class returnType = method.getReturnType(); boolean b; if (handler.getArgs().isEmpty()) { @@ -89,7 +94,10 @@ public class RecordsetUtil implements InvocationHandler { String sql = insert.value(); boolean custom = insert.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - logger.info(handler.toString()); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only execute the insert statement, please check whether the sql statement matches!"); + } + Util.getLogger("sql_log").info(handler.toString()); Class returnType = method.getReturnType(); boolean b; if (handler.getArgs().isEmpty()) { @@ -110,7 +118,10 @@ public class RecordsetUtil implements InvocationHandler { String sql = delete.value(); boolean custom = delete.custom(); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); - logger.info(handler.toString()); + if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only execute the delete statement, please check whether the sql statement matches!"); + } + Util.getLogger("sql_log").info(handler.toString()); Class returnType = method.getReturnType(); boolean b; if (handler.getArgs().isEmpty()) { @@ -125,7 +136,76 @@ public class RecordsetUtil implements InvocationHandler { return b; } } - throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete"); + boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); + if (hasBatchInsert) { + BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); + String sql = batchInsert.value(); + Class returnType = method.getReturnType(); + boolean custom = batchInsert.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger("sql_log").info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { + throw new CustomerException("The sql statement does not match, the @Insert annotation can only execute the insert statement, please check whether the sql statement matches!"); + } + boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); + if (hasBatchUpdate) { + BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); + String sql = batchUpdate.value(); + Class returnType = method.getReturnType(); + boolean custom = batchUpdate.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger("sql_log").info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { + throw new CustomerException("The sql statement does not match, the @Update annotation can only execute the update statement, please check whether the sql statement matches!"); + } + boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); + if (hasBatchDelete) { + BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); + String sql = batchDelete.value(); + Class returnType = method.getReturnType(); + boolean custom = batchDelete.custom(); + BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); + Util.getLogger("sql_log").info(batchSqlResult.toString()); + if (batchSqlResult.getBatchList().isEmpty()) { + throw new CustomerException("execute batch sql error , batch sql args is empty!"); + } + if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { + throw new CustomerException("The sql statement does not match, the @Delete annotation can only execute the delete statement, please check whether the sql statement matches!"); + } + boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList()); + if (returnType.equals(void.class)) { + return null; + } + if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { + return b; + } + + } + throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); } } diff --git a/src/main/java/aiyh/utils/recordset/ResultMapper.java b/src/main/java/aiyh/utils/recordset/ResultMapper.java index e02111f..7b7a5df 100644 --- a/src/main/java/aiyh/utils/recordset/ResultMapper.java +++ b/src/main/java/aiyh/utils/recordset/ResultMapper.java @@ -2,6 +2,7 @@ package aiyh.utils.recordset; import aiyh.utils.Util; import aiyh.utils.annotation.recordset.CaseConversion; +import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.TypeNonsupportException; import com.google.common.base.Strings; import weaver.conn.RecordSet; @@ -68,7 +69,24 @@ public class ResultMapper { rawType = HashMap.class; } while (rs.next()) { - Object o = rawType.newInstance(); + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } Object object = getObject(rs, o, method); ((Collection) t).add(object); } @@ -85,7 +103,25 @@ public class ResultMapper { if (rawType.equals(Map.class)) { rawType = HashMap.class; } - Object o = rawType.newInstance(); +// Object o = rawType.newInstance(); + Object o = null; + try { + Constructor constructor = rawType.getConstructor(); + o = constructor.newInstance(); + } catch (NoSuchMethodException | InvocationTargetException ignored) { + if (Number.class.isAssignableFrom(rawType)) { + Constructor constructor; + try { + constructor = rawType.getConstructor(String.class); + o = constructor.newInstance("-1"); + } catch (NoSuchMethodException | InvocationTargetException e) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); + } + } + } + if (o == null) { + throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); + } if (o instanceof Map || o instanceof Collection) { throw new TypeNonsupportException("An unsupported return type!"); } @@ -198,7 +234,7 @@ public class ResultMapper { Object value = null; String fieldName = propertyDescriptor.getName(); - if(Strings.isNullOrEmpty(fieldName)){ + if (Strings.isNullOrEmpty(fieldName)) { fieldName = propertyDescriptor.getDisplayName(); } // Util.getLogger().info("获取类字段:" + fieldName); diff --git a/src/main/java/aiyh/utils/recordset/SqlHandler.java b/src/main/java/aiyh/utils/recordset/SqlHandler.java index 6d8dd27..09607b9 100644 --- a/src/main/java/aiyh/utils/recordset/SqlHandler.java +++ b/src/main/java/aiyh/utils/recordset/SqlHandler.java @@ -1,10 +1,12 @@ package aiyh.utils.recordset; +import aiyh.utils.annotation.recordset.BatchSqlArgs; import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.SqlString; import aiyh.utils.excention.BindingException; import aiyh.utils.excention.MethodNotFindException; import aiyh.utils.excention.ParseSqlException; +import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import org.apache.commons.lang3.StringUtils; @@ -25,6 +27,14 @@ public class SqlHandler { List sqlArgs = new ArrayList<>(); + List batchSqlArgs = new ArrayList<>(); + + + List batchSqlArgsList = new ArrayList(); + + + private Object batchObj = null; + public PrepSqlResultImpl handler(String sql, boolean custom, Method method, Object[] args) { String findSql = findSql(sql, custom, method, args); Map methodArgNameMap = buildMethodArgNameMap(method, args); @@ -35,7 +45,7 @@ public class SqlHandler { } if (methodArgNameMap.size() == 1) { Optional first = methodArgNameMap.values().stream().findFirst(); - parse = parse(findSql, first.get()); + parse = parse(findSql, first.orElse(null)); } else { parse = parse(findSql, methodArgNameMap); } @@ -43,16 +53,39 @@ public class SqlHandler { return new PrepSqlResultImpl(parse, sqlArgs); } - private int findArg(Method method) { - Parameter[] parameters = method.getParameters(); - for (int i = 0; i < parameters.length; i++) { - Parameter parameter = parameters[i]; - SqlString annotation = parameter.getAnnotation(SqlString.class); - if (annotation == null) { - return i; + private String parseBatch(String findSql, Object o) { + String parse = ""; + if (!batchSqlArgsList.isEmpty()) { + for (Object o1 : batchSqlArgsList) { + Map map = new HashMap<>(8); + map.put("item", o1); + map.putAll((Map) o); + parse = parse(findSql, map); + List tempArgs = new ArrayList<>(); + tempArgs.addAll(sqlArgs); + batchSqlArgs.add(tempArgs); + sqlArgs.clear(); } } - throw new BindingException("Wrong parameter annotation, cannot have two SQL string annotations!"); + if ("".equals(parse)) { + parse = findSql; + } + return parse; + } + + public BatchSqlResultImpl handlerBatch(String sql, boolean custom, Method method, Object[] args) { + String findSql = findSql(sql, custom, method, args); + Map methodArgNameMap = buildMethodArgNameMap(method, args); +// 处理基本类型以及包装类 + String parse; + if (methodArgNameMap.size() == 0) { + Object o = batchSqlArgsList.get(0); + if (o instanceof List) { + return new BatchSqlResultImpl(findSql, batchSqlArgs); + } + } + parse = parseBatch(findSql, methodArgNameMap); + return new BatchSqlResultImpl(parse, batchSqlArgs); } @@ -105,6 +138,15 @@ public class SqlHandler { params.put(paramAnnotation.value(), arg); continue; } + BatchSqlArgs batchSqlArgs = parameter.getAnnotation(BatchSqlArgs.class); + if (batchSqlArgs != null) { + try { + this.batchSqlArgsList = (List) arg; + } catch (Exception e) { + throw new BindingException("can not parse batchSqlArgs for " + parameter.getName() + ", param index is " + i); + } + continue; + } params.put(name, arg); } } catch (NullPointerException e) { @@ -206,6 +248,9 @@ public class SqlHandler { throw new ParseSqlException("Failed to find {" + key + "} related field after parsing exception!"); } Object o = ((Map) arg).get(key); + if (null == o) { + return ""; + } if (o instanceof Character || o instanceof String) { // 处理字符类型 if (isEscape) { @@ -214,7 +259,24 @@ public class SqlHandler { return "'" + o + "'"; } } -// return valueHandler(o,key,isEscape); + if (o instanceof Collection) { + return valueHandler(o, key, isEscape); + } + if (o.getClass().isArray()) { + return valueHandler(o, key, isEscape); + } + if (o instanceof Number) { +// 处理数字类型 + return valueHandler(o, key, isEscape); + } + if (o instanceof Boolean) { +// 处理布尔类型 + return valueHandler(o, key, isEscape); + } + if (o instanceof Character || o instanceof String) { +// 处理字符类型 + return valueHandler(o, key, isEscape); + } return o; } String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1); diff --git a/src/main/java/aiyh/utils/sqlUtil/sqlResult/impl/BatchSqlResultImpl.java b/src/main/java/aiyh/utils/sqlUtil/sqlResult/impl/BatchSqlResultImpl.java index 8c034a7..c6c5cc9 100644 --- a/src/main/java/aiyh/utils/sqlUtil/sqlResult/impl/BatchSqlResultImpl.java +++ b/src/main/java/aiyh/utils/sqlUtil/sqlResult/impl/BatchSqlResultImpl.java @@ -10,19 +10,27 @@ import java.util.List; public class BatchSqlResultImpl implements aiyh.utils.sqlUtil.sqlResult.SqlResult { - private final String sqlStr; - private final List batchList; + private final String sqlStr; + private final List batchList; - public BatchSqlResultImpl(String sqlStr, List batchList) { - this.sqlStr = sqlStr; - this.batchList = batchList; - } + public BatchSqlResultImpl(String sqlStr, List batchList) { + this.sqlStr = sqlStr; + this.batchList = batchList; + } - public String getSqlStr() { - return sqlStr; - } + public String getSqlStr() { + return sqlStr; + } - public List getBatchList() { - return batchList; - } + public List getBatchList() { + return batchList; + } + + @Override + public String toString() { + return "BatchSqlResultImpl{" + + "sqlStr='" + sqlStr + '\'' + + ", batchList=" + batchList + + '}'; + } } diff --git a/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/SftpConnectUtil.java b/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/SftpConnectUtil.java index 998f3bf..1e47e08 100644 --- a/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/SftpConnectUtil.java +++ b/src/main/java/weaver/youhong/ai/pcn/hrorganization/sftp/SftpConnectUtil.java @@ -1,5 +1,13 @@ package weaver.youhong.ai.pcn.hrorganization.sftp; +import aiyh.utils.excention.CustomerException; +import com.jcraft.jsch.*; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Properties; + /** *

sftp连接工具类

* @@ -8,8 +16,126 @@ package weaver.youhong.ai.pcn.hrorganization.sftp; * @author youHong.ai */ -public class SftpConnectUtil { +@Getter +@NoArgsConstructor +public class SftpConnectUtil extends ChannelSftp { + + /** + * sftp对象 + */ + private ChannelSftp sftp; + /** + * 会话对象 + */ + private Session session; + /** + * 用户名 + */ + private String userName; + + /** + * 密码 + */ + private String password; + + /** + * 密钥地址 + */ + private String prvKeyFilePath; + + /** + * 是否成功 + */ + private boolean success; + + /** + * sftp地址 + */ + private String sftpIp; + + /** + * 端口 + */ + private Integer port; + + /** + * 超时事件 + */ + private Integer sftpTimeOut; + public SftpConnectUtil(String userName, String prvKeyFilePath,String password, String sftpIp, + Integer port, Integer sftpTimeOut) { + this.userName = userName; + this.prvKeyFilePath = prvKeyFilePath; + this.sftpIp = sftpIp; + this.port = port; + this.password = password; + this.sftpTimeOut = sftpTimeOut; + this.login(); + } + + /** + *

登陆sftp

+ * + * @author youHong.ai + */ + + private void login() { + + JSch jSch = new JSch(); + try { + if (prvKeyFilePath != null && !"".equals(prvKeyFilePath)) { + if (password != null && !"".equals(password)) { + jSch.addIdentity(prvKeyFilePath, password); + } else { + jSch.addIdentity(prvKeyFilePath); + } + } else { + throw new RuntimeException("从sftp下载需要的ppk文件未找到"); + } + if (port > 0) { + this.session = jSch.getSession(userName, sftpIp, port); + } else { + this.session = jSch.getSession(userName, sftpIp); + } + Properties config = new Properties(); + config.put("StrictHostKeyChecking", "no"); + this.session.setConfig(config); + this.session.setTimeout(sftpTimeOut); + this.session.connect(); + Channel channel = this.session.openChannel("sftp"); + channel.connect(); + this.sftp = (ChannelSftp) channel; + this.success = true; + } catch (JSchException e) { + throw new CustomerException("SFTP链接失败!", e); + } + } + + /** + * 关闭连接 server + * + * @author youHong.ai + */ + private void logout() { + if (sftp != null) { + if (sftp.isConnected()) { + sftp.disconnect(); + } + } + if (session != null) { + if (session.isConnected()) { + session.disconnect(); + } + } + } + + /** + *

关闭链接释放资源

+ */ + public void close(){ + this.login(); + } }