util jar文件更新

main
youHong.ai 2022-11-22 14:44:37 +08:00
parent 20cfe4a37e
commit bef608d57f
21 changed files with 1884 additions and 1030 deletions

View File

@ -1,6 +1,5 @@
package aiyh.utils; package aiyh.utils;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;

View File

@ -39,8 +39,11 @@ public class GenerateFileUtil {
* @param tClass Action * @param tClass Action
* @param <T> Action * @param <T> Action
*/ */
public static <T extends Action> void createActionDocument(Class<T> tClass) { @SafeVarargs
createDocument(tClass, 1); public static <T extends Action> void createActionDocument(Class<T>... tClass) {
for (Class<T> aClass : tClass) {
createDocument(aClass, 1);
}
} }
@ -50,8 +53,11 @@ public class GenerateFileUtil {
* @param tClass * @param tClass
* @param <T> Action * @param <T> Action
*/ */
public static <T extends BaseCronJob> void createCronJobDocument(Class<T> tClass) { @SafeVarargs
createDocument(tClass, 2); public static <T extends BaseCronJob> void createCronJobDocument(Class<T>... tClass) {
for (Class<T> aClass : tClass) {
createDocument(aClass, 2);
}
} }
/** /**

View File

@ -19,8 +19,8 @@ public class ThreadPoolConfig {
synchronized (ThreadPoolConfig.class) { synchronized (ThreadPoolConfig.class) {
if (threadPool == null) { if (threadPool == null) {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-aiyh-%d").build(); ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-aiyh-%d").build();
threadPool = new ThreadPoolExecutor(10, threadPool = new ThreadPoolExecutor(25,
20, 50,
60L, 60L,
TimeUnit.SECONDS, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100), new ArrayBlockingQueue<>(100),

View File

@ -94,10 +94,13 @@ public class Util extends weaver.general.Util {
private static final UtilService utilService = new UtilService(); private static final UtilService utilService = new UtilService();
private static final RecordsetUtil recordsetUtil = new RecordsetUtil(); private static final RecordsetUtil recordsetUtil = new RecordsetUtil();
private static final UtilMapper mapper = recordsetUtil.getMapper(UtilMapper.class); 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(); static ToolUtil toolUtil = new ToolUtil();
private static RecordSet rs; private static RecordSet rs;
private static volatile Logger log = null; private static volatile Logger log = null;
private static final Map<String, Logger> otherLog = new HashMap<>(8);
static { static {
try { try {
rs = new RecordSet(); rs = new RecordSet();
@ -732,7 +735,7 @@ public class Util extends weaver.general.Util {
underlineBefore = true; underlineBefore = true;
} else if (underlineBefore) { } else if (underlineBefore) {
// 如果为true代表上次的字符是"_",当前字符需要转成大写 // 如果为true代表上次的字符是"_",当前字符需要转成大写
buffer.append(charArray[i] -= 32); buffer.append(Character.toUpperCase(charArray[i]));
underlineBefore = false; underlineBefore = false;
} else { } else {
// 不是"_"后的字符就直接追加 // 不是"_"后的字符就直接追加
@ -2079,10 +2082,25 @@ public class Util extends weaver.general.Util {
appender.setAppend(true); appender.setAppend(true);
appender.activateOptions(); appender.activateOptions();
log.addAppender(appender); 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) { if (!enableDebug) {
log.setLevel(Level.INFO); log.setLevel(Level.INFO);
} }
*/
} }
} }
} }
@ -2091,9 +2109,18 @@ public class Util extends weaver.general.Util {
public static Logger getLogger(String name) { public static Logger getLogger(String name) {
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(); DailyRollingFileAppender appender = new DailyRollingFileAppender();
Logger cusLog = Logger.getLogger(name); Logger cusLog = Logger.getLogger("cus_" + name);
appender.setName(name); appender.setName("cus_" + name);
appender.setEncoding("UTF-8"); appender.setEncoding("UTF-8");
appender.setDatePattern("'_'yyyyMMdd'.log'"); appender.setDatePattern("'_'yyyyMMdd'.log'");
appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log"); appender.setFile(weaver.general.GCONST.getLogPath() + "cus" + File.separator + name + File.separator + "cus.log");
@ -2102,18 +2129,31 @@ public class Util extends weaver.general.Util {
appender.setAppend(true); appender.setAppend(true);
appender.activateOptions(); appender.activateOptions();
cusLog.addAppender(appender); cusLog.addAppender(appender);
if (mapper != null) { /*
boolean enableDebug = false;
try { try {
Boolean enableDebug = mapper.selectLogLevel(); // Boolean enableDebug = mapper.selectLogLevel();
if (!enableDebug) { RecordSet rs = new RecordSet();
cusLog.setLevel(Level.INFO); 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) { } catch (Exception ignore) {
} }
if (!enableDebug) {
cusLog.setLevel(Level.INFO);
} }
*/
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 * @return
*/ */
public static String getCusConfigValue(String onlyMark) { 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);
}
/**
* <h2></h2>
*
* @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 * @param defaultStr
* @return * @return
*/ */
public static String getCusConfigValue(String onlyMark, String defaultStr) { public static String getCusConfigDefaultValue(String onlyMark, String defaultStr) {
String cusConfigValue = getCusConfigValue(onlyMark); String cusConfigValue = getCusConfigValue(onlyMark);
return cusConfigValue == null ? defaultStr : cusConfigValue; return cusConfigValue == null ? defaultStr : cusConfigValue;
} }
@ -2617,9 +2699,25 @@ public class Util extends weaver.general.Util {
* @param remark * @param remark
*/ */
public static void submitWorkflowThread(Integer requestId, Integer userId, String remark) { public static void submitWorkflowThread(Integer requestId, Integer userId, String remark) {
submitWorkflowThread(requestId, userId, remark, 60);
}
/**
* <h2>action</h2>
*
* @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(() -> { new Thread(() -> {
try { try {
Thread.sleep(1000 * 60); Thread.sleep(1000 * finalSeconds);
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
Util.getLogger().error("线程休眠失败", e); Util.getLogger().error("线程休眠失败", e);
@ -2748,8 +2846,8 @@ public class Util extends weaver.general.Util {
ImageFileManager imageFileManager = new ImageFileManager(); ImageFileManager imageFileManager = new ImageFileManager();
int imgFileId; int imgFileId;
try { try {
ImageFileManager.class.getMethod("saveImageFileByInputStream", InputStream.class, String.class); Method saveImageFileByInputStream = ImageFileManager.class.getMethod("saveImageFileByInputStream", InputStream.class, String.class);
imgFileId = imageFileManager.saveImageFileByInputStream(content, fileName); imgFileId = (int) saveImageFileByInputStream.invoke(imageFileManager, content, fileName);
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
imageFileManager.setImagFileName(fileName); imageFileManager.setImagFileName(fileName);
try { try {
@ -2887,7 +2985,7 @@ public class Util extends weaver.general.Util {
} }
if (printParam.size() > 0) { 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))); JSONObject.toJSONString(printParam, SerializerFeature.PrettyFormat, SerializerFeature.WriteDateUseDateFormat)));
} }
return true; return true;
@ -3141,27 +3239,45 @@ public class Util extends weaver.general.Util {
boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class); boolean hasDefaultValue = declaredField.isAnnotationPresent(ActionDefaultTestValue.class);
RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class); RequiredMark requiredMark = declaredField.getAnnotation(RequiredMark.class);
ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class); ActionDefaultTestValue defaultTestValue = declaredField.getAnnotation(ActionDefaultTestValue.class);
boolean hasOptional = declaredField.isAnnotationPresent(ActionOptionalParam.class);
// 如果存在默认值,并且是必填参数
if (hasDefaultValue && hasRequiredMark) { if (hasDefaultValue && hasRequiredMark) {
if (value == null) { // 如果参数map中没有则赋值为默认值
if (null == value) {
// 获取默认值赋值
String defaultValue = defaultTestValue.value(); String defaultValue = defaultTestValue.value();
if (defaultValue == null) { if (defaultValue == null) {
throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value()));
} }
value = defaultValue; value = defaultValue;
} }
// 如果没有默认值,并且是必填参数
} else if (!hasDefaultValue && hasRequiredMark) { } else if (!hasDefaultValue && hasRequiredMark) {
if (value == null) { // 如果没有从param中获取到则抛出异常
if (Util.isNullOrEmpty(value)) {
throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value())); throw new CustomerException(String.format("必填参数[%s]未填写:%s", name, requiredMark.value()));
} }
// 如果有默认值,并且没有从params中获得,则赋值
} else if (hasDefaultValue) { } else if (hasDefaultValue) {
if (null == value) {
value = defaultTestValue.value(); value = defaultTestValue.value();
}
} else if (hasOptional) {
// 如果存在可选值
ActionOptionalParam optionalParam = declaredField.getAnnotation(ActionOptionalParam.class);
String defaultValue = optionalParam.value();
// 可选值没有在param中存在
if (null == value) {
value = defaultValue;
}
} else { } else {
if (!params.containsKey(name)) {
// 都不符合必填和默认值的参数判断params中是否存在如果不存在则直接跳过
if (null == value) {
continue; continue;
} }
value = params.get(name); value = params.get(name);
} }
Method method = cronJobClass.getMethod(setMethodName, String.class); Method method = cronJobClass.getMethod(setMethodName, String.class);
method.invoke(action, value); method.invoke(action, value);
} }
@ -3171,7 +3287,7 @@ public class Util extends weaver.general.Util {
throw new CustomerException("计划任务执行异常!异常信息:\n" + Util.getErrString(e)); 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) { } else if (hasDefaultValue) {
value = defaultTestValue.value(); value = defaultTestValue.value();
} else { }
if (!params.containsKey(name)) { if (!params.containsKey(name) && Util.isNullOrEmpty(value)) {
continue; continue;
} }
if (params.containsKey(name)) {
value = params.get(name); value = params.get(name);
} }
Method method = actionClass.getMethod(setMethodName, String.class); Method method = actionClass.getMethod(setMethodName, String.class);
method.invoke(action, value); method.invoke(action, value);
} }
@ -3242,7 +3358,7 @@ public class Util extends weaver.general.Util {
if (Action.FAILURE_AND_CONTINUE.equals(execute)) { if (Action.FAILURE_AND_CONTINUE.equals(execute)) {
throw new CustomerException("action执行失败失败原因\n" + requestInfo.getRequestManager().getMessagecontent()); 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) { public static String getSetMethodName(String fieldName) {
@ -3345,7 +3461,10 @@ public class Util extends weaver.general.Util {
key:hah key:hah
value:haode*/ value:haode*/
// 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类将参数传递给这个类 // 最终通过反射调用weaver.aiyh_jitu.pushdata.service.GetAssignProcessorProcessorImpl类将参数传递给这个类
String pattern = "&?(?<key>([#.\\w\\u4E00-\\u9FA5]+))=(?<value>((#(\\{|sql\\{))?([()\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?))&?"; // String pattern = "&?(?<key>([#.\\w\\u4E00-\\u9FA5]+))=(?<value>((#(\\{|sql\\{))?([()\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?))&?";
String pattern = "&?(?<key>([#.\\w\\u4E00-\\u9FA5]+))=" +
"(?<value>((`([():/\\-&$#={ }.\\w\\u4E00-\\u9FA5?]*)`)|" +
"((#(\\{|sql\\{))?([():/\\-$#={ }.\\w\\u4E00-\\u9FA5?]+)?}?)))&?";
Pattern compile = Pattern.compile(pattern); Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(paramStr); Matcher matcher = compile.matcher(paramStr);
Map<String, String> pathParamMap = new HashMap<>(8); Map<String, String> pathParamMap = new HashMap<>(8);

View File

@ -13,20 +13,19 @@ import weaver.workflow.workflow.WorkflowBillComInfo;
import weaver.workflow.workflow.WorkflowComInfo; import weaver.workflow.workflow.WorkflowComInfo;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* <h1>action</h1> * <h1>action</h1>
* @author EBU7-dev-1 aiyh
* *
* @author EBU7-dev-1 aiyh
*/ */
public abstract class CusBaseAction implements Action { public abstract class CusBaseAction implements Action {
/** /**
* *
*/ */
@ -94,7 +93,7 @@ public abstract class CusBaseAction implements Action{
return Action.FAILURE_AND_CONTINUE; return Action.FAILURE_AND_CONTINUE;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); 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))); e.getMessage(), Util.getErrString(e)));
Util.actionFail(requestManager, e.getMessage()); Util.actionFail(requestManager, e.getMessage());
return Action.FAILURE_AND_CONTINUE; return Action.FAILURE_AND_CONTINUE;
@ -104,9 +103,11 @@ public abstract class CusBaseAction implements Action{
/** /**
* <h2></h2> * <h2></h2>
*
* @param actionHandleMethod map * @param actionHandleMethod map
*/ */
public void registerHandler(Map<String,CusBaseActionHandleFunction> actionHandleMethod){}; public void registerHandler(Map<String, CusBaseActionHandleFunction> actionHandleMethod) {
}
/** /**
@ -127,7 +128,6 @@ public abstract class CusBaseAction implements Action{
User user, RequestManager requestManager); User user, RequestManager requestManager);
/** /**
* <h2>action 退</h2> * <h2>action 退</h2>
* <p> * <p>
@ -142,7 +142,8 @@ public abstract class CusBaseAction implements Action{
* @param requestManager * @param requestManager
*/ */
public void doReject(String requestId, String billTable, int workflowId, public void doReject(String requestId, String billTable, int workflowId,
User user, RequestManager requestManager){}; User user, RequestManager requestManager) {
}
/** /**
* <h2>action </h2> * <h2>action </h2>
@ -158,7 +159,8 @@ public abstract class CusBaseAction implements Action{
* @param requestManager * @param requestManager
*/ */
public void doWithdraw(String requestId, String billTable, int workflowId, 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 * @param requestManager
*/ */
public void doDrawBack(String requestId, String billTable, int workflowId, 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(); Property[] propertyArr = requestInfo.getMainTableInfo().getProperty();
if (null == propertyArr) { if (null == propertyArr) {
return null; return Collections.emptyMap();
} }
Map<String, String> mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 0.75)); Map<String, String> mainTable = new HashMap<>((int) Math.ceil(propertyArr.length * 0.75));
for (Property property : propertyArr) { for (Property property : propertyArr) {
@ -252,13 +255,21 @@ 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 REJECT = "reject";
/** 撤回 */ /**
*
*/
public static final String WITHDRAW = "withdraw"; public static final String WITHDRAW = "withdraw";
/** 强制收回 */ /**
*
*/
public static final String DRAW_BACK = "drawBack"; public static final String DRAW_BACK = "drawBack";
/** 提交 */ /**
*
*/
public static final String SUBMIT = "submit"; public static final String SUBMIT = "submit";
} }

View File

@ -0,0 +1,20 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* <p>create: 2022-08-09 17:40</p>
*
* @author aiyh EBU7-dev-1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface BatchDelete {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -0,0 +1,20 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* <p>create: 2022-08-09 17:40</p>
*
* @author aiyh EBU7-dev-1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface BatchInsert {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -0,0 +1,18 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* <p>create: 2022-08-10 10:53</p>
*
* @author aiyh EBU7-dev-1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface BatchSqlArgs {
}

View File

@ -0,0 +1,20 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* <p>create: 2022-08-09 17:40</p>
*
* @author aiyh EBU7-dev-1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface BatchUpdate {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -16,5 +16,6 @@ public class DocImageInfo {
private String imageFileName; private String imageFileName;
private Integer id; private Integer id;
private Integer detailId; private Integer detailId;
private Integer fileSize;
} }

View File

@ -56,6 +56,10 @@ public class CustomerPdfRenderListener implements RenderListener {
for (char c : text.toCharArray()) { for (char c : text.toCharArray()) {
char keywordChar = keywordChars[n]; char keywordChar = keywordChars[n];
if (n > 0 && keywordChar != c) {
n = 0;
keywordChar = keywordChars[n];
}
if (keywordChar == c) { if (keywordChar == c) {
if (n == 0) { if (n == 0) {
this.startX = boundingRectange.x; this.startX = boundingRectange.x;

View File

@ -0,0 +1,35 @@
package aiyh.utils.httpUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.InputStream;
/**
* <h1></h1>
*
* <p>create: 2022-11-21 11:54</p>
*
* @author youHong.ai
*/
@Setter
@Getter
@ToString
public class MultipartFile {
/**
*
*/
String fileName;
/**
* key
*/
String fileKey;
/**
*
*/
InputStream stream;
Long fileSize;
}

View File

@ -1,10 +1,21 @@
package aiyh.utils.httpUtil.httpAsync; 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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient; 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; import java.util.function.Consumer;
/** /**
@ -17,24 +28,66 @@ import java.util.function.Consumer;
public class HttpAsyncThreadCallBack implements Runnable { public class HttpAsyncThreadCallBack implements Runnable {
private final CloseableHttpClient httpClient; private final CloseableHttpClient httpClient;
private final HttpUriRequest request; private final HttpUriRequest request;
private final Consumer<CloseableHttpResponse> consumer; private final Consumer<ResponeVo> consumer;
private String defaultEncoding = "UTF-8";
private static final Logger log = Util.getLogger("http_util");
public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer){ private HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<ResponeVo> consumer) {
this.httpClient = httpClient; this.httpClient = httpClient;
this.request = request; this.request = request;
this.consumer = consumer; this.consumer = consumer;
} }
public HttpAsyncThreadCallBack(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<ResponeVo> consumer, String defaultEncoding) {
this.httpClient = httpClient;
this.request = request;
this.consumer = consumer;
this.defaultEncoding = defaultEncoding;
}
@Override @Override
public void run() { public void run() {
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
response = httpClient.execute(request); response = httpClient.execute(request);
consumer.accept(response); 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) { } 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); consumer.accept(null);
} }
ExtendedIOUtils.closeQuietly(httpClient); ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response); ExtendedIOUtils.closeQuietly(response);
} }
public void setHttpUtilParamInfo(HttpUtilParamInfo httpUtilParamInfo) {
this.httpUtilParamInfo = httpUtilParamInfo;
}
} }

View File

@ -46,6 +46,7 @@ public class HttpStaticUtils {
// 线程池 // 线程池
public static final ThreadPoolExecutor executorService; public static final ThreadPoolExecutor executorService;
static { static {
// private final ExecutorService executorService = Executors.newFixedThreadPool(3); // private final ExecutorService executorService = Executors.newFixedThreadPool(3);
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
@ -82,6 +83,7 @@ public class HttpStaticUtils {
/** /**
* get * get
*
* @param url * @param url
* @return * @return
* @throws IOException io * @throws IOException io
@ -101,6 +103,7 @@ public class HttpStaticUtils {
/** /**
* delete * delete
*
* @param url * @param url
* @return * @return
* @throws IOException io * @throws IOException io
@ -119,6 +122,7 @@ public class HttpStaticUtils {
/** /**
* get * get
*
* @param url * @param url
* @param headers * @param headers
* @return * @return
@ -138,6 +142,7 @@ public class HttpStaticUtils {
/** /**
* delete * delete
*
* @param url * @param url
* @param headers * @param headers
* @return * @return
@ -181,6 +186,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param url * @param url
* @param params * @param params
* @param headers * @param headers
@ -203,6 +209,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param url * @param url
* @param params * @param params
* @param headers * @param headers
@ -223,6 +230,7 @@ public class HttpStaticUtils {
/** /**
* post * post
*
* @param url * @param url
* @param params * @param params
* @return * @return
@ -247,6 +255,7 @@ public class HttpStaticUtils {
/** /**
* post * post
*
* @param url * @param url
* @param params * @param params
* @param headers * @param headers
@ -345,7 +354,6 @@ public class HttpStaticUtils {
/** /**
*
* @param url * @param url
* @param params * @param params
* @param headers * @param headers
@ -361,7 +369,6 @@ public class HttpStaticUtils {
} }
/** /**
*
* @param url * @param url
* @param params * @param params
* @param headers * @param headers
@ -378,6 +385,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param httpClient httpclient * @param httpClient httpclient
* @param request * @param request
* @param consumer * @param consumer
@ -400,6 +408,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param httpClient httpclient * @param httpClient httpclient
* @param request * @param request
* @return * @return
@ -559,7 +568,7 @@ public class HttpStaticUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public static void asyncApiGet(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public static void asyncApiGet(String url, Map<String, String> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params); Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -580,7 +589,7 @@ public class HttpStaticUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public static void asyncApiDelete(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public static void asyncApiDelete(String url, Map<String, String> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params); Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -632,7 +641,7 @@ public class HttpStaticUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public static void asyncApiPost(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public static void asyncApiPost(String url, Map<String, String> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null);
Map<String, String> paramsMap = paramsHandle(params); Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -647,7 +656,7 @@ public class HttpStaticUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public static void asyncApiPut(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public static void asyncApiPut(String url, Map<String, String> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, null);
Map<String, String> paramsMap = paramsHandle(params); Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -658,6 +667,7 @@ public class HttpStaticUtils {
/** /**
* post * post
*
* @param url * @param url
* @param headerMap * @param headerMap
* @param paramsMap * @param paramsMap
@ -738,6 +748,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param headers * @param headers
* @return * @return
*/ */
@ -756,6 +767,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param params * @param params
* @return * @return
*/ */
@ -774,6 +786,7 @@ public class HttpStaticUtils {
/** /**
* urlget * urlget
*
* @param url * @param url
* @param params * @param params
* @return url * @return url
@ -802,6 +815,7 @@ public class HttpStaticUtils {
/** /**
* *
*
* @param params * @param params
* @return * @return
*/ */

View File

@ -1,10 +1,7 @@
package aiyh.utils.httpUtil.util; package aiyh.utils.httpUtil.util;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.httpUtil.ExtendedIOUtils; import aiyh.utils.httpUtil.*;
import aiyh.utils.httpUtil.HttpArgsType;
import aiyh.utils.httpUtil.HttpManager;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread; import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack; import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack;
import aiyh.utils.zwl.common.ToolUtil; import aiyh.utils.zwl.common.ToolUtil;
@ -48,19 +45,19 @@ import java.util.function.Function;
public class HttpUtils { public class HttpUtils {
// 默认编码 public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY";
private String DEFAULT_ENCODING = "UTF-8"; public static final ThreadLocal<HttpUtilParamInfo> 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 ToolUtil toolUtil = new ToolUtil();
private final GlobalCache globalCache = new GlobalCache(); private final GlobalCache globalCache = new GlobalCache();
// 线程池 // 线程池
private final ThreadPoolExecutor executorService; private final ThreadPoolExecutor executorService;
public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY"; // 默认编码
private String DEFAULT_ENCODING = "UTF-8";
public static final ThreadLocal<HttpUtilParamInfo> HTTP_UTIL_PARAM_INFO_THREAD_LOCAL = new ThreadLocal<>(); /**
* basic
private static final Logger log = Util.getLogger("http_util"); */
private CredentialsProvider credentialsProvider = null;
{ {
// private final ExecutorService executorService = Executors.newFixedThreadPool(3); // private final ExecutorService executorService = Executors.newFixedThreadPool(3);
@ -77,15 +74,64 @@ public class HttpUtils {
} }
/**
* basic
*/
private CredentialsProvider credentialsProvider = null;
public HttpUtils(CredentialsProvider credentialsProvider) { public HttpUtils(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider; this.credentialsProvider = credentialsProvider;
} }
public HttpUtils(String DEFAULT_ENCODING) {
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
public static String urlHandle(String url, Map<String, Object> params) {
if (params == null || params.size() <= 0) {
return url;
}
String serializeParams = serializeParams(params);
String getUrl;
if (!url.contains("?")) {
if (url.endsWith("/")) {
getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams;
} else {
getUrl = url + "?" + serializeParams;
}
} else {
if (url.endsWith("?")) {
getUrl = url + serializeParams;
} else {
getUrl = url + "&" + serializeParams;
}
}
return getUrl;
}
private static String serializeParams(Map<String, Object> params) {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.append("&");
builder.append(entry.getKey());
builder.append("=");
builder.append(entry.getValue());
}
return removeSeparator(builder);
}
return "";
}
private 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) { public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider; this.credentialsProvider = credentialsProvider;
} }
@ -98,10 +144,6 @@ public class HttpUtils {
this.DEFAULT_ENCODING = DEFAULT_ENCODING; this.DEFAULT_ENCODING = DEFAULT_ENCODING;
} }
public HttpUtils(String DEFAULT_ENCODING) {
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
public HttpPost getHttpPost(String url) { public HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url); HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom() RequestConfig requestConfig = RequestConfig.custom()
@ -153,7 +195,6 @@ public class HttpUtils {
return baseRequest(httpConnection, httpGet); return baseRequest(httpConnection, httpGet);
} }
/** /**
* delete * delete
* *
@ -349,7 +390,6 @@ public class HttpUtils {
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
public ResponeVo apiPut(String url, Map<String, Object> params) throws IOException { public ResponeVo apiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
@ -358,7 +398,6 @@ public class HttpUtils {
return baseRequest(httpConnection, httpPut); return baseRequest(httpConnection, httpPut);
} }
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
@ -374,7 +413,6 @@ public class HttpUtils {
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
public ResponeVo apiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public ResponeVo apiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
@ -383,24 +421,111 @@ public class HttpUtils {
return baseRequest(httpConnection, httpPut); return baseRequest(httpConnection, httpPut);
} }
/**
* <h2></h2>
*
* @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, public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> 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); return baseRequest(httpConnection, httpPost);
} }
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return
* @throws IOException Io
*/
public ResponeVo apiUploadFiles(String url, List<MultipartFile> multipartFileList, Map<String, Object> params,
Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return
* @throws IOException Io
*/
public ResponeVo apiPutUploadFiles(String url, List<MultipartFile> multipartFileList, Map<String, Object> params,
Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap);
return baseRequest(httpConnection, httpPut);
}
/**
* <h2></h2>
*
* @param url
* @param inputStream
* @param fileKey key
* @param fileName
* @param params
* @param headers
* @return
* @throws IOException IO
*/
public Future<ResponeVo> apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName, public Future<ResponeVo> apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> 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)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
} }
/**
* <h2></h2>
*
* @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, public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
@ -410,17 +535,34 @@ public class HttpUtils {
return baseRequest(httpConnection, httpPost); return baseRequest(httpConnection, httpPost);
} }
/**
* <h2>ImageFileId</h2>
*
* @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, public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException { Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id); 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); return baseRequest(httpConnection, httpPost);
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -467,7 +609,6 @@ public class HttpUtils {
callBackRequest(httpConnection, httpPut, consumer); callBackRequest(httpConnection, httpPut, consumer);
} }
private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException { private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
try { try {
@ -483,7 +624,6 @@ public class HttpUtils {
} }
} }
private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException { private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
ResponeVo apply = null; ResponeVo apply = null;
@ -546,7 +686,6 @@ public class HttpUtils {
return apply; return apply;
} }
public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException { public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
ResponeVo responeVo = new ResponeVo(); ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
@ -593,7 +732,6 @@ public class HttpUtils {
return responeVo; return responeVo;
} }
/** /**
* get * get
* *
@ -613,7 +751,6 @@ public class HttpUtils {
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
} }
/** /**
* delete * delete
* *
@ -698,7 +835,7 @@ public class HttpUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public void asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public void asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -707,7 +844,14 @@ public class HttpUtils {
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue()); 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 * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public void asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public void asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap); String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
@ -726,7 +870,14 @@ public class HttpUtils {
for (Map.Entry<String, String> entry : headerMap.entrySet()) { for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue()); 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<ResponeVo> asyncApiPost(String url, Map<String, Object> params) throws IOException { public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params) throws IOException {
@ -745,7 +896,6 @@ public class HttpUtils {
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
} }
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException { public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
@ -762,7 +912,6 @@ public class HttpUtils {
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
} }
/** /**
* @param url * @param url
* @param params * @param params
@ -770,15 +919,21 @@ public class HttpUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public void asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public void asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); 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 url
* @param params * @param params
@ -786,12 +941,19 @@ public class HttpUtils {
* @param consumer * @param consumer
* @throws IOException io * @throws IOException io
*/ */
public void asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException { public void asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider); CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params); Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers); Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); 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<String, String> headerMap, Object paramsMap) throws UnsupportedEncodingException { private HttpPost handleHttpPostObject(String url, Map<String, String> headerMap, Object paramsMap) throws UnsupportedEncodingException {
@ -844,20 +1006,40 @@ public class HttpUtils {
return httpPost; return httpPost;
} }
private HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException { private HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
return handleHttpPostObject(url, headerMap, paramsMap); return handleHttpPostObject(url, headerMap, paramsMap);
} }
/**
public HttpPost uploadFileByInputStream(String url, InputStream inputStream, String fileKey, String fileName, * <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return httpPost
*/
private HttpPost uploadFileByInputStream(String url, List<MultipartFile> multipartFileList,
Map<String, Object> params, Map<String, String> headers) { Map<String, Object> params, Map<String, String> headers) {
log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + log.info(Util.logStr("start request : url is [{}]" +
"", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); "", 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(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8); builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 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); ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
for (Map.Entry<String, Object> param : params.entrySet()) { for (Map.Entry<String, Object> param : params.entrySet()) {
StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType);
@ -876,10 +1058,65 @@ public class HttpUtils {
return httpPost; return httpPost;
} }
public HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName,
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return httpPost
*/
private HttpPut uploadFileByInputStreamPut(String url, List<MultipartFile> multipartFileList,
Map<String, Object> params, Map<String, String> 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<String, Object> 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<String, String> 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<String, Object> params, Map<String, String> headers) { Map<String, Object> params, Map<String, String> headers) {
log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + 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)); "", 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(); MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName); builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName);
@ -900,7 +1137,6 @@ public class HttpUtils {
return httpPost; return httpPost;
} }
private HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException { private HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap); httpUtilParamInfo.setParams(paramsMap);
@ -936,7 +1172,6 @@ public class HttpUtils {
return httpPut; return httpPut;
} }
private String inputStreamToString(InputStream is) { private String inputStreamToString(InputStream is) {
String line = ""; String line = "";
StringBuilder total = new StringBuilder(); StringBuilder total = new StringBuilder();
@ -976,54 +1211,4 @@ public class HttpUtils {
} }
return map; return map;
} }
public String urlHandle(String url, Map<String, Object> params) {
if (params == null || params.size() <= 0) {
return url;
}
String serializeParams = serializeParams(params);
String getUrl;
if (!url.contains("?")) {
if (url.endsWith("/")) {
getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams;
} else {
getUrl = url + "?" + serializeParams;
}
} else {
if (url.endsWith("?")) {
getUrl = url + serializeParams;
} else {
getUrl = url + "&" + serializeParams;
}
}
return getUrl;
}
private String serializeParams(Map<String, Object> params) {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.append("&");
builder.append(entry.getKey());
builder.append("=");
builder.append(entry.getValue());
}
return removeSeparator(builder);
}
return "";
}
private String removeSeparator(StringBuilder sqlBuilder) {
String str = sqlBuilder.toString().trim();
String removeSeparator = "&";
if (str.endsWith(removeSeparator)) {
// 如果以分&号结尾,则去除&号
str = str.substring(0, str.length() - 1);
}
if (str.trim().startsWith(removeSeparator)) {
// 如果以&开头,则去除&
str = str.substring(1);
}
return str;
}
} }

View File

@ -1,9 +1,6 @@
package aiyh.utils.mapper; package aiyh.utils.mapper;
import aiyh.utils.annotation.recordset.Delete; import aiyh.utils.annotation.recordset.*;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.entity.DocImageInfo; import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.entity.SelectValueEntity; import aiyh.utils.entity.SelectValueEntity;
import aiyh.utils.entity.WorkflowNodeConfig; import aiyh.utils.entity.WorkflowNodeConfig;
@ -23,23 +20,27 @@ public interface UtilMapper {
/** /**
* Debug * Debug
*
* @return Debug * @return Debug
*/ */
@Select("select param_value from uf_cus_dev_config where only_mark = 'enableDebugLog'") @Select("select param_value from $t{configTableName} where only_mark = 'enableDebugLog'")
public Boolean selectLogLevel(); public Boolean selectLogLevel(@ParamMapper("configTableName") String configTableName);
/** /**
* *
*
* @param onlyMark * @param onlyMark
* @return * @return
*/ */
@Select("select param_value from uf_cus_dev_config where only_mark = #{onlyMark} and enable_param = 1") @Select("select param_value from $t{cusConfigTableName} where only_mark = #{onlyMark} and enable_param = 1")
public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark); public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark,
@ParamMapper("configTableName") String cusConfigTableName);
/** /**
* *
*
* @param imageFileId * @param imageFileId
* @return * @return
*/ */
@ -48,6 +49,7 @@ public interface UtilMapper {
/** /**
* *
*
* @param workflowId id * @param workflowId id
* @return * @return
*/ */
@ -64,6 +66,7 @@ public interface UtilMapper {
/** /**
* *
*
* @param tableName * @param tableName
* @param fileName * @param fileName
* @return * @return
@ -81,6 +84,7 @@ public interface UtilMapper {
/** /**
* *
*
* @param imageFileId * @param imageFileId
* @return * @return
*/ */
@ -89,9 +93,42 @@ public interface UtilMapper {
/** /**
* *
*
* @param imageFileId ID * @param imageFileId ID
* @return * @return
*/ */
@Delete("delete from imagefile where imagefileid = #{imageFileId}") @Delete("delete from imagefile where imagefileid = #{imageFileId}")
boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId); boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId);
/**
* <h2></h2>
*
* @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);
/**
* <h2></h2>
*
* @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);
} }

View File

@ -4,8 +4,8 @@ import aiyh.utils.Util;
import aiyh.utils.annotation.recordset.*; import aiyh.utils.annotation.recordset.*;
import aiyh.utils.excention.BindingException; import aiyh.utils.excention.BindingException;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet; import weaver.conn.RecordSet;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
@ -20,7 +20,6 @@ import java.lang.reflect.Proxy;
public class RecordsetUtil implements InvocationHandler { public class RecordsetUtil implements InvocationHandler {
private static final Logger logger = Util.getLogger("sql_util_log");
private final RecordSet recordSet = new RecordSet(); private final RecordSet recordSet = new RecordSet();
public <T> T getMapper(Class<T> tClass) { public <T> T getMapper(Class<T> tClass) {
@ -46,7 +45,10 @@ public class RecordsetUtil implements InvocationHandler {
String sql = select.value(); String sql = select.value();
boolean custom = select.custom(); boolean custom = select.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); 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()) { if (handler.getArgs().isEmpty()) {
rs.executeQuery(handler.getSqlStr()); rs.executeQuery(handler.getSqlStr());
} else { } else {
@ -61,7 +63,10 @@ public class RecordsetUtil implements InvocationHandler {
String sql = update.value(); String sql = update.value();
boolean custom = update.custom(); boolean custom = update.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); 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(); Class<?> returnType = method.getReturnType();
boolean b; boolean b;
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
@ -89,7 +94,10 @@ public class RecordsetUtil implements InvocationHandler {
String sql = insert.value(); String sql = insert.value();
boolean custom = insert.custom(); boolean custom = insert.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); 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(); Class<?> returnType = method.getReturnType();
boolean b; boolean b;
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
@ -110,7 +118,10 @@ public class RecordsetUtil implements InvocationHandler {
String sql = delete.value(); String sql = delete.value();
boolean custom = delete.custom(); boolean custom = delete.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); 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(); Class<?> returnType = method.getReturnType();
boolean b; boolean b;
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
@ -125,7 +136,76 @@ public class RecordsetUtil implements InvocationHandler {
return b; 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");
} }
} }

View File

@ -2,6 +2,7 @@ package aiyh.utils.recordset;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.annotation.recordset.CaseConversion; import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.excention.TypeNonsupportException; import aiyh.utils.excention.TypeNonsupportException;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import weaver.conn.RecordSet; import weaver.conn.RecordSet;
@ -68,7 +69,24 @@ public class ResultMapper {
rawType = HashMap.class; rawType = HashMap.class;
} }
while (rs.next()) { 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); Object object = getObject(rs, o, method);
((Collection<? super Object>) t).add(object); ((Collection<? super Object>) t).add(object);
} }
@ -85,7 +103,25 @@ public class ResultMapper {
if (rawType.equals(Map.class)) { if (rawType.equals(Map.class)) {
rawType = HashMap.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) { if (o instanceof Map || o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!"); throw new TypeNonsupportException("An unsupported return type!");
} }

View File

@ -1,10 +1,12 @@
package aiyh.utils.recordset; package aiyh.utils.recordset;
import aiyh.utils.annotation.recordset.BatchSqlArgs;
import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.SqlString; import aiyh.utils.annotation.recordset.SqlString;
import aiyh.utils.excention.BindingException; import aiyh.utils.excention.BindingException;
import aiyh.utils.excention.MethodNotFindException; import aiyh.utils.excention.MethodNotFindException;
import aiyh.utils.excention.ParseSqlException; import aiyh.utils.excention.ParseSqlException;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -25,6 +27,14 @@ public class SqlHandler {
List<Object> sqlArgs = new ArrayList<>(); List<Object> sqlArgs = new ArrayList<>();
List<List> batchSqlArgs = new ArrayList<>();
List<Object> batchSqlArgsList = new ArrayList();
private Object batchObj = null;
public PrepSqlResultImpl handler(String sql, boolean custom, Method method, Object[] args) { public PrepSqlResultImpl handler(String sql, boolean custom, Method method, Object[] args) {
String findSql = findSql(sql, custom, method, args); String findSql = findSql(sql, custom, method, args);
Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args); Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args);
@ -35,7 +45,7 @@ public class SqlHandler {
} }
if (methodArgNameMap.size() == 1) { if (methodArgNameMap.size() == 1) {
Optional<Object> first = methodArgNameMap.values().stream().findFirst(); Optional<Object> first = methodArgNameMap.values().stream().findFirst();
parse = parse(findSql, first.get()); parse = parse(findSql, first.orElse(null));
} else { } else {
parse = parse(findSql, methodArgNameMap); parse = parse(findSql, methodArgNameMap);
} }
@ -43,16 +53,39 @@ public class SqlHandler {
return new PrepSqlResultImpl(parse, sqlArgs); return new PrepSqlResultImpl(parse, sqlArgs);
} }
private int findArg(Method method) { private String parseBatch(String findSql, Object o) {
Parameter[] parameters = method.getParameters(); String parse = "";
for (int i = 0; i < parameters.length; i++) { if (!batchSqlArgsList.isEmpty()) {
Parameter parameter = parameters[i]; for (Object o1 : batchSqlArgsList) {
SqlString annotation = parameter.getAnnotation(SqlString.class); Map<String, Object> map = new HashMap<>(8);
if (annotation == null) { map.put("item", o1);
return i; map.putAll((Map<String, Object>) o);
parse = parse(findSql, map);
List<Object> 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<String, Object> 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); params.put(paramAnnotation.value(), arg);
continue; continue;
} }
BatchSqlArgs batchSqlArgs = parameter.getAnnotation(BatchSqlArgs.class);
if (batchSqlArgs != null) {
try {
this.batchSqlArgsList = (List<Object>) arg;
} catch (Exception e) {
throw new BindingException("can not parse batchSqlArgs for " + parameter.getName() + ", param index is " + i);
}
continue;
}
params.put(name, arg); params.put(name, arg);
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
@ -206,6 +248,9 @@ public class SqlHandler {
throw new ParseSqlException("Failed to find {" + key + "} related field after parsing exception!"); throw new ParseSqlException("Failed to find {" + key + "} related field after parsing exception!");
} }
Object o = ((Map<?, ?>) arg).get(key); Object o = ((Map<?, ?>) arg).get(key);
if (null == o) {
return "";
}
if (o instanceof Character || o instanceof String) { if (o instanceof Character || o instanceof String) {
// 处理字符类型 // 处理字符类型
if (isEscape) { if (isEscape) {
@ -214,7 +259,24 @@ public class SqlHandler {
return "'" + o + "'"; 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; return o;
} }
String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1); String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);

View File

@ -25,4 +25,12 @@ public class BatchSqlResultImpl implements aiyh.utils.sqlUtil.sqlResult.SqlResul
public List<List> getBatchList() { public List<List> getBatchList() {
return batchList; return batchList;
} }
@Override
public String toString() {
return "BatchSqlResultImpl{" +
"sqlStr='" + sqlStr + '\'' +
", batchList=" + batchList +
'}';
}
} }

View File

@ -1,5 +1,13 @@
package weaver.youhong.ai.pcn.hrorganization.sftp; 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;
/** /**
* <h1>sftp</h1> * <h1>sftp</h1>
* *
@ -8,8 +16,126 @@ package weaver.youhong.ai.pcn.hrorganization.sftp;
* @author youHong.ai * @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();
}
/**
* <h2>sftp</h2>
*
* @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();
}
}
}
/**
* <h2></h2>
*/
public void close(){
this.login();
}
} }