Compare commits

...

14 Commits
main ... dev

124 changed files with 9003 additions and 7511 deletions

4
.gitignore vendored
View File

@ -18,6 +18,7 @@ log
.idea/
#.gitignore
!.gitignore
*.iml
# Project files, i.e. `.project`, `.actionScriptProperties` and `.flexProperties`
# should NOT be excluded as they contain compiler settings and other important
# information for Eclipse / Flash Builder.
@ -37,6 +38,9 @@ DirectoryV2.xml
/lib/classbeanLib/web-inf-class-lib.jar
/lib/weaverLib/
*.groovy
*.log
src/main/resources/WEB-INF/sqllog/
java.io.tempdir/

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
</content>
</component>
</module>

View File

@ -1,174 +1,174 @@
package aiyh.utils;
import aiyh.utils.entity.LabelHtmlIndex;
import aiyh.utils.service.UtilService;
import aiyh.utils.zwl.common.ToolUtil;
import weaver.systeminfo.SystemEnv;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author EBU7-dev1-ayh
* create 2021/12/13 0013 10:29
*
*/
public class LabelHtmlUtils {
private final UtilService utilService = new UtilService();
private Map<String, Object> htmlLabel = null;
private ToolUtil toolUtil = new ToolUtil();
public LabelHtmlUtils(String prefix) {
if (!this.init(prefix)) {
toolUtil.writeErrorLog("配置文件异常,请检查配置文件结构是否符合要求!");
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
}
public LabelHtmlUtils() {
}
/**
*
*
* @param prefix
* @return
*/
public synchronized boolean init(String prefix) {
if (this.htmlLabel != null) {
return true;
}
try {
this.htmlLabel = Util.readProperties2Map("htmlLabelIndex", prefix);
return this.htmlLabel != null;
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog(e.toString());
return false;
}
}
/**
* id
*
* @param id id
* @param languageId id
* @param defaultStr
* @return
*/
public String getHtmlLabelName(int id, int languageId, String defaultStr) {
String htmlLabelName = SystemEnv.getHtmlLabelName(id, languageId);
return htmlLabelName == null ? defaultStr : htmlLabelName;
}
/**
* id
*
* @param id id
* @param languageId id
* @return
*/
public String getHtmlLabelName(int id, int languageId) {
return SystemEnv.getHtmlLabelName(id, languageId);
}
/**
* id
*
* @param languageId id
* @param languageStr
* @return
*/
public String getHtmlLabelNameByStr(int languageId, String languageStr) {
String pattern = "(`~`" + languageId + " )(?<label>(\\w*|\\W*|[\\u4e00-\\u9fa5]*))(`~`)";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(languageStr);
if (matcher.find()) {
return matcher.group("label");
}
return languageStr;
}
/**
*
*
* @param key
*/
public Map<String, Object> getHtmlLabelMap(String key) {
if (this.htmlLabel == null) {
throw new RuntimeException("请初始化以读取配置信息调用方法init(String prefix)");
}
Map<String, Object> map;
try {
map = (Map<String, Object>) this.htmlLabel.get(key);
} catch (Exception e) {
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
return map;
}
/**
*
*
* @param key
* @return Map
*/
public Map<String, String> getHtmlLabel(String key) {
if (this.htmlLabel == null) {
throw new RuntimeException("请初始化以读取配置信息调用方法init(String prefix)");
}
Map<String, String> map;
try {
map = (Map<String, String>) this.htmlLabel.get(key);
} catch (Exception e) {
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
return map;
}
/**
*
*
* @param key
* @return
*/
public LabelHtmlIndex getLabelHtmlIndex(String key) {
if (this.htmlLabel == null) {
throw new RuntimeException("请初始化以读取配置信息调用方法init(String prefix)");
}
Map<String, Object> map;
LabelHtmlIndex labelHtmlIndex;
try {
map = (Map<String, Object>) this.htmlLabel.get(key);
labelHtmlIndex = Util.mapToObject(map, LabelHtmlIndex.class);
} catch (Exception e) {
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
return labelHtmlIndex;
}
/**
*
*
* @param map
* @return
*/
public LabelHtmlIndex getLabelHtmlIndex(Map<String, Object> map, String key) {
LabelHtmlIndex labelHtmlIndex;
Map<String, Object> resultMap;
try {
resultMap = (Map<String, Object>) map.get(key);
labelHtmlIndex = Util.mapToObject(resultMap, LabelHtmlIndex.class);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("map转换异常");
}
return labelHtmlIndex;
}
}
package aiyh.utils;
import aiyh.utils.entity.LabelHtmlIndex;
import aiyh.utils.service.UtilService;
import aiyh.utils.zwl.common.ToolUtil;
import weaver.systeminfo.SystemEnv;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author EBU7-dev1-ayh
* create 2021/12/13 0013 10:29
*
*/
public class LabelHtmlUtils {
private final UtilService utilService = new UtilService();
private Map<String, Object> htmlLabel = null;
private ToolUtil toolUtil = new ToolUtil();
public LabelHtmlUtils(String prefix) {
if (!this.init(prefix)) {
toolUtil.writeErrorLog("配置文件异常,请检查配置文件结构是否符合要求!");
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
}
public LabelHtmlUtils() {
}
/**
*
*
* @param prefix
* @return
*/
public synchronized boolean init(String prefix) {
if (this.htmlLabel != null) {
return true;
}
try {
this.htmlLabel = Util.readProperties2Map("htmlLabelIndex", prefix);
return this.htmlLabel != null;
} catch (Exception e) {
e.printStackTrace();
toolUtil.writeErrorLog(e.toString());
return false;
}
}
/**
* id
*
* @param id id
* @param languageId id
* @param defaultStr
* @return
*/
public String getHtmlLabelName(int id, int languageId, String defaultStr) {
String htmlLabelName = SystemEnv.getHtmlLabelName(id, languageId);
return htmlLabelName == null ? defaultStr : htmlLabelName;
}
/**
* id
*
* @param id id
* @param languageId id
* @return
*/
public String getHtmlLabelName(int id, int languageId) {
return SystemEnv.getHtmlLabelName(id, languageId);
}
/**
* id
*
* @param languageId id
* @param languageStr
* @return
*/
public String getHtmlLabelNameByStr(int languageId, String languageStr) {
String pattern = "(`~`" + languageId + " )(?<label>(\\w*|\\W*|[\\u4e00-\\u9fa5]*))(`~`)";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(languageStr);
if (matcher.find()) {
return matcher.group("label");
}
return languageStr;
}
/**
*
*
* @param key
*/
public Map<String, Object> getHtmlLabelMap(String key) {
if (this.htmlLabel == null) {
throw new RuntimeException("请初始化以读取配置信息调用方法init(String prefix)");
}
Map<String, Object> map;
try {
map = (Map<String, Object>) this.htmlLabel.get(key);
} catch (Exception e) {
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
return map;
}
/**
*
*
* @param key
* @return Map
*/
public Map<String, String> getHtmlLabel(String key) {
if (this.htmlLabel == null) {
throw new RuntimeException("请初始化以读取配置信息调用方法init(String prefix)");
}
Map<String, String> map;
try {
map = (Map<String, String>) this.htmlLabel.get(key);
} catch (Exception e) {
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
return map;
}
/**
*
*
* @param key
* @return
*/
public LabelHtmlIndex getLabelHtmlIndex(String key) {
if (this.htmlLabel == null) {
throw new RuntimeException("请初始化以读取配置信息调用方法init(String prefix)");
}
Map<String, Object> map;
LabelHtmlIndex labelHtmlIndex;
try {
map = (Map<String, Object>) this.htmlLabel.get(key);
labelHtmlIndex = Util.mapToObject(map, LabelHtmlIndex.class);
} catch (Exception e) {
throw new RuntimeException("配置文件异常,请检查配置文件结构是否符合要求!");
}
return labelHtmlIndex;
}
/**
*
*
* @param map
* @return
*/
public LabelHtmlIndex getLabelHtmlIndex(Map<String, Object> map, String key) {
LabelHtmlIndex labelHtmlIndex;
Map<String, Object> resultMap;
try {
resultMap = (Map<String, Object>) map.get(key);
labelHtmlIndex = Util.mapToObject(resultMap, LabelHtmlIndex.class);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("map转换异常");
}
return labelHtmlIndex;
}
}

View File

@ -1,40 +1,40 @@
package aiyh.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionManager;
import java.io.File;
import java.io.Reader;
/**
* @author EBU7-dev1-ayh
* create 2021/12/14 0014 15:57
*/
public class MybatisUtil {
private static SqlSessionManager sqlSessionManager = null;
private synchronized static void init(String config){
try {
Reader resourceAsReader = Resources.getResourceAsReader("WEB-INF" + File.separator +config);
sqlSessionManager = SqlSessionManager.newInstance(resourceAsReader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionManager getSessionManager(String config){
if(sqlSessionManager == null){
synchronized (MybatisUtil.class) {
if (sqlSessionManager == null) {
init(config);
}
}
}
return sqlSessionManager;
}
public static <T> T getMapper(Class<T> tClass){
return sqlSessionManager.getMapper(tClass);
}
}
package aiyh.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionManager;
import java.io.File;
import java.io.Reader;
/**
* @author EBU7-dev1-ayh
* create 2021/12/14 0014 15:57
*/
public class MybatisUtil {
private static SqlSessionManager sqlSessionManager = null;
private synchronized static void init(String config){
try {
Reader resourceAsReader = Resources.getResourceAsReader("WEB-INF" + File.separator +config);
sqlSessionManager = SqlSessionManager.newInstance(resourceAsReader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSessionManager getSessionManager(String config){
if(sqlSessionManager == null){
synchronized (MybatisUtil.class) {
if (sqlSessionManager == null) {
init(config);
}
}
}
return sqlSessionManager;
}
public static <T> T getMapper(Class<T> tClass){
return sqlSessionManager.getMapper(tClass);
}
}

View File

@ -3287,7 +3287,7 @@ public class Util extends weaver.general.Util {
throw new CustomerException("计划任务执行异常!异常信息:\n" + Util.getErrString(e));
}
getLogger().info(Util.logStr("\n\t计划任务 [{}] execute success!\n", cronJobClass.getName()));
getLogger().info(Util.logStr("\n\t计划任务 [{}] getDataId success!\n", cronJobClass.getName()));
}
@ -3358,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());
}
getLogger().info(Util.logStr("\n\n\tAction [{}] execute success!\n", actionClass.getName()));
getLogger().info(Util.logStr("\n\n\tAction [{}] getDataId success!\n", actionClass.getName()));
}
public static String getSetMethodName(String fieldName) {

View File

@ -30,7 +30,7 @@ public abstract class CusBaseAction implements Action {
/**
* requestInfo
*/
protected RequestInfo requestInfo;
protected RequestInfo globalRequestInfo;
/**
* <h2></h2>
@ -49,7 +49,7 @@ public abstract class CusBaseAction implements Action {
@Override
public final String execute(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
this.globalRequestInfo = requestInfo;
RequestManager requestManager = requestInfo.getRequestManager();
String billTable = requestManager.getBillTableName();
String requestId = requestInfo.getRequestid();
@ -105,14 +105,12 @@ public abstract class CusBaseAction implements Action {
*/
public boolean exceptionCallback(Exception e, RequestManager requestManager) {
e.printStackTrace();
log.error(Util.logStr("execute action fail, exception message is [{}], error stack trace msg is: \n{}",
log.error(Util.logStr("getDataId action fail, exception message is [{}], error stack trace msg is: \n{}",
e.getMessage(), Util.getErrString(e)));
Util.actionFail(requestManager, e.getMessage());
return true;
}
;
/**
* <h2></h2>
@ -199,9 +197,26 @@ public abstract class CusBaseAction implements Action {
*
* @return
*/
@Deprecated
protected Map<String, String> getMainTableValue() {
// 获取主表数据
Property[] propertyArr = globalRequestInfo.getMainTableInfo().getProperty();
return getStringMap(propertyArr);
}
/**
* <h2></h2>
*
* @return
*/
protected Map<String, String> getMainTableValue(RequestInfo requestInfo) {
// 获取主表数据
Property[] propertyArr = requestInfo.getMainTableInfo().getProperty();
return getStringMap(propertyArr);
}
@NotNull
private Map<String, String> getStringMap(Property[] propertyArr) {
if (null == propertyArr) {
return Collections.emptyMap();
}
@ -220,8 +235,25 @@ public abstract class CusBaseAction implements Action {
*
* @return
*/
@Deprecated
protected Map<String, List<Map<String, String>>> getDetailTableValue() {
DetailTable[] detailTableArr = globalRequestInfo.getDetailTableInfo().getDetailTable();
return getListMap(detailTableArr);
}
/**
* <h2></h2>
*
* @return
*/
protected Map<String, List<Map<String, String>>> getDetailTableValue(RequestInfo requestInfo) {
DetailTable[] detailTableArr = requestInfo.getDetailTableInfo().getDetailTable();
return getListMap(detailTableArr);
}
@NotNull
private Map<String, List<Map<String, String>>> getListMap(DetailTable[] detailTableArr) {
Map<String, List<Map<String, String>>> detailDataList = new HashMap<>((int) Math.ceil(detailTableArr.length * 1.4));
for (DetailTable detailTable : detailTableArr) {
List<Map<String, String>> detailData = getDetailValue(detailTable);
@ -237,10 +269,21 @@ public abstract class CusBaseAction implements Action {
* @param detailNo
* @return
*/
@Deprecated
protected List<Map<String, String>> getDetailTableValueByDetailNo(int detailNo) {
DetailTable detailTable = globalRequestInfo.getDetailTableInfo().getDetailTable(detailNo);
return getDetailValue(detailTable);
}
/**
* <h2></h2>
*
* @param detailNo
* @return
*/
protected List<Map<String, String>> getDetailTableValueByDetailNo(int detailNo, RequestInfo requestInfo) {
DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(detailNo);
List<Map<String, String>> detailData = getDetailValue(detailTable);
return detailData;
return getDetailValue(detailTable);
}
/**

View File

@ -1,15 +1,15 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/21 0021 15:25
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CaseConversion {
boolean value() default true;
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/21 0021 15:25
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface CaseConversion {
boolean value() default true;
}

View File

@ -1,17 +1,17 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Delete {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Delete {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -1,17 +1,17 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Insert {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Insert {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -1,15 +1,15 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:20
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface ParamMapper {
String value();
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:20
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface ParamMapper {
String value();
}

View File

@ -1,17 +1,17 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Select {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Select {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -1,15 +1,15 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:01
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface SqlMapper {
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:01
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface SqlMapper {
}

View File

@ -1,13 +1,13 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:31
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface SqlString {
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:31
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface SqlString {
}

View File

@ -1,17 +1,17 @@
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Update {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}
package aiyh.utils.annotation.recordset;
import java.lang.annotation.*;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/19 0019 15:08
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Update {
String value() default "";
// sql是否是在参数中
boolean custom() default false;
}

View File

@ -1,18 +1,18 @@
package aiyh.utils.apirequest.core.factory;
/**
* <p></p>
* <p>create 2022/1/26 0026 12:03</p>
*
* @author EBU7-dev1-ayh
*/
public interface AbstractFactory {
/**
*
* @param type
* @return
*/
<T> T createParamHandlerFactory(Class<T> type);
}
package aiyh.utils.apirequest.core.factory;
/**
* <p></p>
* <p>create 2022/1/26 0026 12:03</p>
*
* @author EBU7-dev1-ayh
*/
public interface AbstractFactory {
/**
*
* @param type
* @return
*/
<T> T createParamHandlerFactory(Class<T> type);
}

View File

@ -1,21 +1,21 @@
package aiyh.utils.apirequest.core.factory;
/**
* <p></p>
* <p>create 2022/1/26 0026 12:55</p>
*
* @author EBU7-dev1-ayh
*/
public class AbstractFactoryImpl implements AbstractFactory {
@Override
public <T> T createParamHandlerFactory(Class<T> type) {
if(ApiAsyncFactory.class.equals(type)){
return (T) new ApiAsyncFactory();
}
return null;
}
}
package aiyh.utils.apirequest.core.factory;
/**
* <p></p>
* <p>create 2022/1/26 0026 12:55</p>
*
* @author EBU7-dev1-ayh
*/
public class AbstractFactoryImpl implements AbstractFactory {
@Override
public <T> T createParamHandlerFactory(Class<T> type) {
if(ApiAsyncFactory.class.equals(type)){
return (T) new ApiAsyncFactory();
}
return null;
}
}

View File

@ -1,19 +1,19 @@
package aiyh.utils.apirequest.core.factory;
/**
* <p></p>
* <p>create 2022/1/24 0024 10:59</p>
*
* @author EBU7-dev1-ayh
*/
public interface TypeHandlerFactory<R,V> {
/**
*
* @param factoryEnum
* @return
*/
public R createParamHandler(V factoryEnum);
}
package aiyh.utils.apirequest.core.factory;
/**
* <p></p>
* <p>create 2022/1/24 0024 10:59</p>
*
* @author EBU7-dev1-ayh
*/
public interface TypeHandlerFactory<R,V> {
/**
*
* @param factoryEnum
* @return
*/
public R createParamHandler(V factoryEnum);
}

View File

@ -1,32 +1,32 @@
package aiyh.utils.apirequest.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import weaver.hrm.User;
/**
* <p>api</p>
* <p>create 2022/1/28 0028 9:16</p>
*
* @author EBU7-dev1-ayh
*/
@Setter
@Getter
@ToString
public class ApiBaseInfo {
/**
* requestId
*/
private String requestId;
/**
* id
*/
private String workflowId;
/**
*
*/
private User user;
}
package aiyh.utils.apirequest.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import weaver.hrm.User;
/**
* <p>api</p>
* <p>create 2022/1/28 0028 9:16</p>
*
* @author EBU7-dev1-ayh
*/
@Setter
@Getter
@ToString
public class ApiBaseInfo {
/**
* requestId
*/
private String requestId;
/**
* id
*/
private String workflowId;
/**
*
*/
private User user;
}

View File

@ -1,85 +1,85 @@
package aiyh.utils.apirequest.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/27 0027 16:07</p>
*
* @author EBU7-dev1-ayh
*/
@Getter
@Setter
@ToString
public class ApiRequestData {
/**
* id
*/
private Integer id;
/**
* api
*/
private String apiUrl;
/**
* api
*/
private String testApiUrl;
/**
*
*/
private Integer requestType;
/**
* api
*/
private Integer apiType;
/**
*
*/
private Integer dataSource;
/**
* api
*/
private String apiDesc;
/**
*
*/
private String workflowType;
/**
*
*/
private String modelTableName;
/**
*
*/
private Integer paramRequestType;
/**
*
*/
private String requestDetailTableName;
/**
*
*/
private String onlyMark;
/**
*
*/
private List<ApiRequestParamData> paramDetailList;
/**
*
*/
private List<ApiRequestHeardData> heardDetailList;
/**
* api
*/
private ApiBaseInfo apiBaseInfo;
}
package aiyh.utils.apirequest.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/27 0027 16:07</p>
*
* @author EBU7-dev1-ayh
*/
@Getter
@Setter
@ToString
public class ApiRequestData {
/**
* id
*/
private Integer id;
/**
* api
*/
private String apiUrl;
/**
* api
*/
private String testApiUrl;
/**
*
*/
private Integer requestType;
/**
* api
*/
private Integer apiType;
/**
*
*/
private Integer dataSource;
/**
* api
*/
private String apiDesc;
/**
*
*/
private String workflowType;
/**
*
*/
private String modelTableName;
/**
*
*/
private Integer paramRequestType;
/**
*
*/
private String requestDetailTableName;
/**
*
*/
private String onlyMark;
/**
*
*/
private List<ApiRequestParamData> paramDetailList;
/**
*
*/
private List<ApiRequestHeardData> heardDetailList;
/**
* api
*/
private ApiBaseInfo apiBaseInfo;
}

View File

@ -1,14 +1,14 @@
package aiyh.utils.apirequest.entity;
import aiyh.utils.apirequest.pojo.ApiRequestHeardDetail;
/**
* <p>api </p>
* <p>create 2022/2/8 0008 11:15</p>
*
* @author EBU7-dev1-ayh
*/
public class ApiRequestHeardData extends ApiRequestHeardDetail {
}
package aiyh.utils.apirequest.entity;
import aiyh.utils.apirequest.pojo.ApiRequestHeardDetail;
/**
* <p>api </p>
* <p>create 2022/2/8 0008 11:15</p>
*
* @author EBU7-dev1-ayh
*/
public class ApiRequestHeardData extends ApiRequestHeardDetail {
}

View File

@ -1,21 +1,21 @@
package aiyh.utils.apirequest.entity;
import aiyh.utils.apirequest.pojo.ApiRequestParamDetail;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* <p>Api </p>
* <p>create 2022/1/28 0028 12:09</p>
*
* @author EBU7-dev1-ayh
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ApiRequestParamData extends ApiRequestParamDetail {
private List<ApiRequestParamData> childList;
private List<ParamInfo> paramInfoList;
}
package aiyh.utils.apirequest.entity;
import aiyh.utils.apirequest.pojo.ApiRequestParamDetail;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* <p>Api </p>
* <p>create 2022/1/28 0028 12:09</p>
*
* @author EBU7-dev1-ayh
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ApiRequestParamData extends ApiRequestParamDetail {
private List<ApiRequestParamData> childList;
private List<ParamInfo> paramInfoList;
}

View File

@ -1,24 +1,24 @@
package aiyh.utils.apirequest.entity;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 21:09</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class HeardInfo {
/**
*
*/
private String heardName;
/**
*
*/
private String heardValue;
}
package aiyh.utils.apirequest.entity;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 21:09</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class HeardInfo {
/**
*
*/
private String heardName;
/**
*
*/
private String heardValue;
}

View File

@ -1,69 +1,69 @@
package aiyh.utils.apirequest.entity;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 21:08</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ParamConfigInfo {
/**
* id
*/
private Integer id;
/**
* api
*/
private String apiUrl;
/**
* api
*/
private String testApiUrl;
/**
*
*/
private Integer requestType;
/**
*
*/
private Integer dataSource;
/**
* api
*/
private String apiDesc;
/**
*
*/
private String workflowType;
/**
*
*/
private String modelTableName;
/**
*
*/
private Integer paramRequestType;
/**
*
*/
private String requestDetailTableName;
/**
*
*/
private List<ParamInfo> paramInfoList;
/**
*
*/
private List<HeardInfo> heardInfoList;
}
package aiyh.utils.apirequest.entity;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 21:08</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ParamConfigInfo {
/**
* id
*/
private Integer id;
/**
* api
*/
private String apiUrl;
/**
* api
*/
private String testApiUrl;
/**
*
*/
private Integer requestType;
/**
*
*/
private Integer dataSource;
/**
* api
*/
private String apiDesc;
/**
*
*/
private String workflowType;
/**
*
*/
private String modelTableName;
/**
*
*/
private Integer paramRequestType;
/**
*
*/
private String requestDetailTableName;
/**
*
*/
private List<ParamInfo> paramInfoList;
/**
*
*/
private List<HeardInfo> heardInfoList;
}

View File

@ -1,36 +1,36 @@
package aiyh.utils.apirequest.entity;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 21:04</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ParamInfo {
/**
*
*/
private Integer lineNum;
/**
*
*/
private String paramName;
/**
*
*/
private Object paramValue;
/**
*
*/
private Integer parentLine;
/**
*
*/
private List<ParamInfo> childList;
}
package aiyh.utils.apirequest.entity;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 21:04</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ParamInfo {
/**
*
*/
private Integer lineNum;
/**
*
*/
private String paramName;
/**
*
*/
private Object paramValue;
/**
*
*/
private Integer parentLine;
/**
*
*/
private List<ParamInfo> childList;
}

View File

@ -1,26 +1,26 @@
package aiyh.utils.apirequest.entity;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/23 0023 20:33</p>
*
* @author EBU7-dev1-ayh
*/
public class ParseAfterData {
/**
*
*/
private boolean autoRequest;
/**
*
*/
private Map<String,Object> requestData;
/**
*
*/
private Map<String,Object> requestHeard;
}
package aiyh.utils.apirequest.entity;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/23 0023 20:33</p>
*
* @author EBU7-dev1-ayh
*/
public class ParseAfterData {
/**
*
*/
private boolean autoRequest;
/**
*
*/
private Map<String,Object> requestData;
/**
*
*/
private Map<String,Object> requestHeard;
}

View File

@ -1,48 +1,48 @@
package aiyh.utils.apirequest.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/26 0026 10:43</p>
*
* @author EBU7-dev1-ayh
*/
public enum DataSourceRuleEnum {
/**
*
*/
WORKFLOW_DATA(0),
/**
*
*/
MODEL_DATA(1);
private static final Map<Integer, DataSourceRuleEnum> LOOKUP;
static {
LOOKUP = new HashMap<>();
for (DataSourceRuleEnum enumType : EnumSet.allOf(DataSourceRuleEnum.class)) {
LOOKUP.put(enumType.getValue(), enumType);
}
}
private final int value;
DataSourceRuleEnum(int value) {
this.value = value;
}
public static DataSourceRuleEnum get(int value) {
return LOOKUP.get(value);
}
public int getValue() {
return this.value;
}
}
package aiyh.utils.apirequest.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/26 0026 10:43</p>
*
* @author EBU7-dev1-ayh
*/
public enum DataSourceRuleEnum {
/**
*
*/
WORKFLOW_DATA(0),
/**
*
*/
MODEL_DATA(1);
private static final Map<Integer, DataSourceRuleEnum> LOOKUP;
static {
LOOKUP = new HashMap<>();
for (DataSourceRuleEnum enumType : EnumSet.allOf(DataSourceRuleEnum.class)) {
LOOKUP.put(enumType.getValue(), enumType);
}
}
private final int value;
DataSourceRuleEnum(int value) {
this.value = value;
}
public static DataSourceRuleEnum get(int value) {
return LOOKUP.get(value);
}
public int getValue() {
return this.value;
}
}

View File

@ -1,67 +1,67 @@
package aiyh.utils.apirequest.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/25 0025 10:36</p>
*
* @author EBU7-dev1-ayh
*/
public enum ParamTypeEnum {
/**
* string
*/
STRING_TYPE(0),
/**
* long
*/
LONG_TYPE(1),
/**
* boolean
*/
BOOLEAN_TYPE(2),
/**
* object
*/
OBJECT_TYPE(3),
/**
* list
*/
LIST_TYPE(4),
/**
* double
*/
DOUBLE_TYPE(5);
private static final Map<Integer, ParamTypeEnum> LOOKUP;
static {
LOOKUP = new HashMap<>();
for (ParamTypeEnum enumType : EnumSet.allOf(ParamTypeEnum.class)) {
LOOKUP.put(enumType.getValue(), enumType);
}
}
private final int value;
ParamTypeEnum(int value) {
this.value = value;
}
public static ParamTypeEnum get(int value) {
return LOOKUP.get(value);
}
public int getValue() {
return this.value;
}
}
package aiyh.utils.apirequest.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/25 0025 10:36</p>
*
* @author EBU7-dev1-ayh
*/
public enum ParamTypeEnum {
/**
* string
*/
STRING_TYPE(0),
/**
* long
*/
LONG_TYPE(1),
/**
* boolean
*/
BOOLEAN_TYPE(2),
/**
* object
*/
OBJECT_TYPE(3),
/**
* list
*/
LIST_TYPE(4),
/**
* double
*/
DOUBLE_TYPE(5);
private static final Map<Integer, ParamTypeEnum> LOOKUP;
static {
LOOKUP = new HashMap<>();
for (ParamTypeEnum enumType : EnumSet.allOf(ParamTypeEnum.class)) {
LOOKUP.put(enumType.getValue(), enumType);
}
}
private final int value;
ParamTypeEnum(int value) {
this.value = value;
}
public static ParamTypeEnum get(int value) {
return LOOKUP.get(value);
}
public int getValue() {
return this.value;
}
}

View File

@ -1,83 +1,83 @@
package aiyh.utils.apirequest.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/25 0025 10:16</p>
*
* @author EBU7-dev1-ayh
*/
public enum ParamValueRuleEnum {
/**
*
*/
NULL_VALUE(0),
/**
*
*/
FIXED_VALUE(1),
/**
*
*/
SYSTEM_FIELD(2),
/**
* SQL
*/
CUSTOMER_SQL(3),
/**
*
*/
CURRENT_TIME(4),
/**
* id
*/
REQUEST_ID(5),
/**
* id
*/
WORKFLOW_ID(6),
/**
*
*/
RANDOM_VALUE(7),
/**
*
*/
ATTACHMENT_FILE(8),
/**
*
*/
TIME_STAMP(9),
/**
* SQL
*/
SQL_FIELD(10);
private static final Map<Integer, ParamValueRuleEnum> LOOKUP;
static {
LOOKUP = new HashMap<>();
for (ParamValueRuleEnum enumType : EnumSet.allOf(ParamValueRuleEnum.class)) {
LOOKUP.put(enumType.getValue(), enumType);
}
}
private final int value;
ParamValueRuleEnum(int value) {
this.value = value;
}
public static ParamValueRuleEnum get(int value) {
return LOOKUP.get(value);
}
public int getValue() {
return this.value;
}
}
package aiyh.utils.apirequest.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/25 0025 10:16</p>
*
* @author EBU7-dev1-ayh
*/
public enum ParamValueRuleEnum {
/**
*
*/
NULL_VALUE(0),
/**
*
*/
FIXED_VALUE(1),
/**
*
*/
SYSTEM_FIELD(2),
/**
* SQL
*/
CUSTOMER_SQL(3),
/**
*
*/
CURRENT_TIME(4),
/**
* id
*/
REQUEST_ID(5),
/**
* id
*/
WORKFLOW_ID(6),
/**
*
*/
RANDOM_VALUE(7),
/**
*
*/
ATTACHMENT_FILE(8),
/**
*
*/
TIME_STAMP(9),
/**
* SQL
*/
SQL_FIELD(10);
private static final Map<Integer, ParamValueRuleEnum> LOOKUP;
static {
LOOKUP = new HashMap<>();
for (ParamValueRuleEnum enumType : EnumSet.allOf(ParamValueRuleEnum.class)) {
LOOKUP.put(enumType.getValue(), enumType);
}
}
private final int value;
ParamValueRuleEnum(int value) {
this.value = value;
}
public static ParamValueRuleEnum get(int value) {
return LOOKUP.get(value);
}
public int getValue() {
return this.value;
}
}

View File

@ -1,51 +1,51 @@
package aiyh.utils.apirequest.interceptor;
import aiyh.utils.apirequest.entity.ParamConfigInfo;
import aiyh.utils.apirequest.entity.ParseAfterData;
import aiyh.utils.apirequest.pojo.ApiRequestMain;
import aiyh.utils.httpUtil.ResponeVo;
/**
* <p>api </p>
* <p>create 2022/1/22 0022 20:19</p>
*
* @author EBU7-dev1-ayh
*/
public interface ApiRequestInterceptor {
/**
* '
* @param apiRequestMain
* @return
*/
public ApiRequestMain parseBefore(ApiRequestMain apiRequestMain);
/**
*
* @param paramConfigInfo
* @return
*/
public ParamConfigInfo parseAfter(ParamConfigInfo paramConfigInfo);
/**
*
* @param paramConfigTreeInfo
* @return
*/
public ParamConfigInfo parseTreeAfter(ParamConfigInfo paramConfigTreeInfo);
/**
*
* @param parseAfterData
* @return
*/
public ParseAfterData requestBefore(ParseAfterData parseAfterData);
/**
*
* @param isSuccess
* @param responeVo
*/
public void requestAfter(ResponeVo responeVo,boolean isSuccess);
}
package aiyh.utils.apirequest.interceptor;
import aiyh.utils.apirequest.entity.ParamConfigInfo;
import aiyh.utils.apirequest.entity.ParseAfterData;
import aiyh.utils.apirequest.pojo.ApiRequestMain;
import aiyh.utils.httpUtil.ResponeVo;
/**
* <p>api </p>
* <p>create 2022/1/22 0022 20:19</p>
*
* @author EBU7-dev1-ayh
*/
public interface ApiRequestInterceptor {
/**
* '
* @param apiRequestMain
* @return
*/
public ApiRequestMain parseBefore(ApiRequestMain apiRequestMain);
/**
*
* @param paramConfigInfo
* @return
*/
public ParamConfigInfo parseAfter(ParamConfigInfo paramConfigInfo);
/**
*
* @param paramConfigTreeInfo
* @return
*/
public ParamConfigInfo parseTreeAfter(ParamConfigInfo paramConfigTreeInfo);
/**
*
* @param parseAfterData
* @return
*/
public ParseAfterData requestBefore(ParseAfterData parseAfterData);
/**
*
* @param isSuccess
* @param responeVo
*/
public void requestAfter(ResponeVo responeVo,boolean isSuccess);
}

View File

@ -1,53 +1,53 @@
package aiyh.utils.apirequest.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.apirequest.pojo.ApiRequestHeardDetail;
import aiyh.utils.apirequest.pojo.ApiRequestMain;
import aiyh.utils.apirequest.pojo.ApiRequestParamDetail;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 17:52</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface ApiRequestMapper {
/**
*
* @param onlyMark
* @return
*/
@Select("")
public ApiRequestMain selectApiConfigByOnlyMark(@ParamMapper("onlyMark") String onlyMark);
/**
*
* @param id id
* @return
*/
@Select("")
public ApiRequestMain selectApiConfigById(@ParamMapper("id") int id);
/**
* id
* @param mainId id
* @return
*/
@Select("")
public List<ApiRequestParamDetail> selectApiParamListByMainId(@ParamMapper("mainId") int mainId);
/**
* id
* @param mainId id
* @return
*/
@Select("")
public List<ApiRequestHeardDetail> selectApiHeardListByMainId(@ParamMapper("mainId") int mainId);
}
package aiyh.utils.apirequest.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.apirequest.pojo.ApiRequestHeardDetail;
import aiyh.utils.apirequest.pojo.ApiRequestMain;
import aiyh.utils.apirequest.pojo.ApiRequestParamDetail;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 17:52</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface ApiRequestMapper {
/**
*
* @param onlyMark
* @return
*/
@Select("")
public ApiRequestMain selectApiConfigByOnlyMark(@ParamMapper("onlyMark") String onlyMark);
/**
*
* @param id id
* @return
*/
@Select("")
public ApiRequestMain selectApiConfigById(@ParamMapper("id") int id);
/**
* id
* @param mainId id
* @return
*/
@Select("")
public List<ApiRequestParamDetail> selectApiParamListByMainId(@ParamMapper("mainId") int mainId);
/**
* id
* @param mainId id
* @return
*/
@Select("")
public List<ApiRequestHeardDetail> selectApiHeardListByMainId(@ParamMapper("mainId") int mainId);
}

View File

@ -1,40 +1,40 @@
package aiyh.utils.apirequest.mapper;
import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import java.util.List;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/26 0026 14:10</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface DataSourceMapper {
/**
* id
* @param versionIds id
* @return
*/
@Select("select distinct tablename from workflow_base wb " +
"left join workflow_bill wbi on wbi.id = wb.formid " +
"where wb.id in (${versionIds})")
public String selectWorkflowTableById(@ParamMapper("versionIds") String[] versionIds);
@Select("select * from $t{workflowTable} where requestid = #{requestid}")
@CaseConversion(false)
Map<String,Object> selectMainData(@ParamMapper("workflowTable") String workflowTable,
@ParamMapper("requestId") String requestId);
@Select("select * from $t{detailTable} where mainid = #{mainId}")
@CaseConversion(false)
List<Map<String, Object>> selectDetailData(@ParamMapper("detailTable") String requestDetailTableName,
@ParamMapper("mainId") String mainId);
}
package aiyh.utils.apirequest.mapper;
import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import java.util.List;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/26 0026 14:10</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface DataSourceMapper {
/**
* id
* @param versionIds id
* @return
*/
@Select("select distinct tablename from workflow_base wb " +
"left join workflow_bill wbi on wbi.id = wb.formid " +
"where wb.id in (${versionIds})")
public String selectWorkflowTableById(@ParamMapper("versionIds") String[] versionIds);
@Select("select * from $t{workflowTable} where requestid = #{requestid}")
@CaseConversion(false)
Map<String,Object> selectMainData(@ParamMapper("workflowTable") String workflowTable,
@ParamMapper("requestId") String requestId);
@Select("select * from $t{detailTable} where mainid = #{mainId}")
@CaseConversion(false)
List<Map<String, Object>> selectDetailData(@ParamMapper("detailTable") String requestDetailTableName,
@ParamMapper("mainId") String mainId);
}

View File

@ -1,77 +1,77 @@
package aiyh.utils.apirequest.mapper;
import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.SqlString;
import java.util.List;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/26 0026 16:32</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface ParamValueParseMapper {
/**
* SQL
*
* @param sql SQL
* @param map
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public String selectCustomerSql(@SqlString String sql, Map<String, Object> map);
/**
* SQL
*
* @param sqlStr SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public Map<String, Object> selectMapByCustomerSql(@SqlString String sqlStr, Map<String, Object> dataMap);
/**
* SQL
*
* @param sql SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public List<Map<String, Object>> selectListByCustomerSql(@SqlString String sql, Map<String, Object> dataMap);
/**
*
*
* @param sql SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public List<String> selectStringListByCustomerSql(@SqlString String sql, Map<String, Object> dataMap);
/**
*
*
* @param sql SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public List<Integer> selectIntegerListByCustomerSql(@SqlString String sql, Map<String, Object> dataMap);
}
package aiyh.utils.apirequest.mapper;
import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.SqlString;
import java.util.List;
import java.util.Map;
/**
* <p></p>
* <p>create 2022/1/26 0026 16:32</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface ParamValueParseMapper {
/**
* SQL
*
* @param sql SQL
* @param map
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public String selectCustomerSql(@SqlString String sql, Map<String, Object> map);
/**
* SQL
*
* @param sqlStr SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public Map<String, Object> selectMapByCustomerSql(@SqlString String sqlStr, Map<String, Object> dataMap);
/**
* SQL
*
* @param sql SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public List<Map<String, Object>> selectListByCustomerSql(@SqlString String sql, Map<String, Object> dataMap);
/**
*
*
* @param sql SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public List<String> selectStringListByCustomerSql(@SqlString String sql, Map<String, Object> dataMap);
/**
*
*
* @param sql SQL
* @param dataMap
* @return
*/
@Select(custom = true)
@CaseConversion(false)
public List<Integer> selectIntegerListByCustomerSql(@SqlString String sql, Map<String, Object> dataMap);
}

View File

@ -1,31 +1,31 @@
package aiyh.utils.apirequest.pojo;
import lombok.Data;
/**
* <p>api</p>
* <p>create 2022/1/23 0023 18:10</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ApiRequestHeardDetail {
private Integer mainId;
/**
*
*/
private String heardName;
/**
*
*/
private Integer valueRule;
/**
*
*/
private String customerValue;
/**
*
*/
private Integer enableParam;
}
package aiyh.utils.apirequest.pojo;
import lombok.Data;
/**
* <p>api</p>
* <p>create 2022/1/23 0023 18:10</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ApiRequestHeardDetail {
private Integer mainId;
/**
*
*/
private String heardName;
/**
*
*/
private Integer valueRule;
/**
*
*/
private String customerValue;
/**
*
*/
private Integer enableParam;
}

View File

@ -1,76 +1,76 @@
package aiyh.utils.apirequest.pojo;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 17:55</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ApiRequestMain {
/**
* id
*/
private Integer id;
/**
* api
*/
private String apiUrl;
/**
* api
*/
private String testApiUrl;
/**
*
*/
private Integer requestType;
/**
* api
*/
private Integer apiType;
/**
*
*/
private Integer dataSource;
/**
* api
*/
private String apiDesc;
/**
*
*/
private String workflowType;
/**
*
*/
private String modelTableName;
/**
*
*/
private Integer paramRequestType;
/**
*
*/
private String requestDetailTableName;
/**
*
*/
private String onlyMark;
/**
*
*/
private List<ApiRequestParamDetail> paramDetailList;
/**
*
*/
private List<ApiRequestHeardDetail> heardDetailList;
}
package aiyh.utils.apirequest.pojo;
import lombok.Data;
import java.util.List;
/**
* <p></p>
* <p>create 2022/1/23 0023 17:55</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ApiRequestMain {
/**
* id
*/
private Integer id;
/**
* api
*/
private String apiUrl;
/**
* api
*/
private String testApiUrl;
/**
*
*/
private Integer requestType;
/**
* api
*/
private Integer apiType;
/**
*
*/
private Integer dataSource;
/**
* api
*/
private String apiDesc;
/**
*
*/
private String workflowType;
/**
*
*/
private String modelTableName;
/**
*
*/
private Integer paramRequestType;
/**
*
*/
private String requestDetailTableName;
/**
*
*/
private String onlyMark;
/**
*
*/
private List<ApiRequestParamDetail> paramDetailList;
/**
*
*/
private List<ApiRequestHeardDetail> heardDetailList;
}

View File

@ -1,65 +1,65 @@
package aiyh.utils.apirequest.pojo;
import lombok.Data;
/**
* <p></p>
* <p>create 2022/1/23 0023 18:04</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ApiRequestParamDetail {
/**
* id
*/
private Integer mainId;
/**
*
*/
private Integer lineNum;
/**
*
*/
private String paramName;
/**
*
*/
private Integer paramType;
/**
*
*/
private Integer dataSource;
/**
*
*/
private String detailTableName;
/**
*
*/
private Integer parentLine;
/**
*
*/
private Integer valueRule;
/**
*
*/
private String systemFieldName;
/**
*
*/
private String customerValue;
/**
*
*/
private Integer enableParam;
/**
*
*/
private String fieldTableName;
}
package aiyh.utils.apirequest.pojo;
import lombok.Data;
/**
* <p></p>
* <p>create 2022/1/23 0023 18:04</p>
*
* @author EBU7-dev1-ayh
*/
@Data
public class ApiRequestParamDetail {
/**
* id
*/
private Integer mainId;
/**
*
*/
private Integer lineNum;
/**
*
*/
private String paramName;
/**
*
*/
private Integer paramType;
/**
*
*/
private Integer dataSource;
/**
*
*/
private String detailTableName;
/**
*
*/
private Integer parentLine;
/**
*
*/
private Integer valueRule;
/**
*
*/
private String systemFieldName;
/**
*
*/
private String customerValue;
/**
*
*/
private Integer enableParam;
/**
*
*/
private String fieldTableName;
}

View File

@ -1,39 +1,39 @@
package aiyh.utils.entity;
/**
* @author EBU7-dev1-ayh
* create 2021/12/13 0013 11:19
*/
public class LabelHtmlIndex {
private Integer labelIndex;
private String defaultStr;
public LabelHtmlIndex() {
}
public LabelHtmlIndex(Integer labelIndex, String defaultStr) {
this.labelIndex = labelIndex;
this.defaultStr = defaultStr;
}
public Integer getLabelIndex() {
return labelIndex;
}
public String getDefaultStr() {
return defaultStr;
}
@Override
public String toString() {
return "LabelHtmlIndex{" +
"labelIndex='" + labelIndex + '\'' +
", defaultStr='" + defaultStr + '\'' +
'}';
}
}
package aiyh.utils.entity;
/**
* @author EBU7-dev1-ayh
* create 2021/12/13 0013 11:19
*/
public class LabelHtmlIndex {
private Integer labelIndex;
private String defaultStr;
public LabelHtmlIndex() {
}
public LabelHtmlIndex(Integer labelIndex, String defaultStr) {
this.labelIndex = labelIndex;
this.defaultStr = defaultStr;
}
public Integer getLabelIndex() {
return labelIndex;
}
public String getDefaultStr() {
return defaultStr;
}
@Override
public String toString() {
return "LabelHtmlIndex{" +
"labelIndex='" + labelIndex + '\'' +
", defaultStr='" + defaultStr + '\'' +
'}';
}
}

View File

@ -1,13 +1,13 @@
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 14:51
*/
public class BindingException extends RuntimeException{
public BindingException(String msg){
super(msg);
}
}
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 14:51
*/
public class BindingException extends RuntimeException{
public BindingException(String msg){
super(msg);
}
}

View File

@ -1,13 +1,13 @@
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 19:33
*/
public class MethodNotFindException extends RuntimeException{
public MethodNotFindException(String msg){
super(msg);
}
}
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 19:33
*/
public class MethodNotFindException extends RuntimeException{
public MethodNotFindException(String msg){
super(msg);
}
}

View File

@ -1,13 +1,13 @@
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 10:33
*/
public class ParseSqlException extends RuntimeException{
public ParseSqlException(String message) {
super(message);
}
}
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 10:33
*/
public class ParseSqlException extends RuntimeException{
public ParseSqlException(String message) {
super(message);
}
}

View File

@ -1,13 +1,13 @@
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 19:24
*/
public class TypeNonsupportException extends RuntimeException{
public TypeNonsupportException(String msg){
super(msg);
}
}
package aiyh.utils.excention;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 19:24
*/
public class TypeNonsupportException extends RuntimeException{
public TypeNonsupportException(String msg){
super(msg);
}
}

View File

@ -70,7 +70,7 @@ public abstract class Try<T> {
* .recover((t) -&gt; 1)
* returns Integer(1)
*
* @param f function to execute on successful result.
* @param f function to getDataId on successful result.
* @return new composed Try
*/

View File

@ -1,18 +1,18 @@
package aiyh.utils.function;
/**
* <p>function</p>
* <p>create 2022/1/22 0022 18:26</p>
*
* @author EBU7-dev1-ayh
*/
@FunctionalInterface
public interface ListToTreeSetChildFunction<T> {
/**
*
* @param parent
* @param child
*/
void setChildItem(T parent, T child);
}
package aiyh.utils.function;
/**
* <p>function</p>
* <p>create 2022/1/22 0022 18:26</p>
*
* @author EBU7-dev1-ayh
*/
@FunctionalInterface
public interface ListToTreeSetChildFunction<T> {
/**
*
* @param parent
* @param child
*/
void setChildItem(T parent, T child);
}

View File

@ -1,39 +1,39 @@
package aiyh.utils.httpUtil;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
/**
* IOIOUtilscloseQuietly
*
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
*/
public class ExtendedIOUtils {
public static void flush(Flushable... resources) throws IOException {
int length = resources.length;
for (int i = 0; i < length; ++i) {
Flushable resource = resources[i];
if (resource != null) {
resource.flush();
}
}
}
public static void closeQuietly(Closeable... resources) {
int length = resources.length;
for (int i = 0; i < length; ++i) {
Closeable resource = resources[i];
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
//ignore exception
}
}
}
}
}
package aiyh.utils.httpUtil;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
/**
* IOIOUtilscloseQuietly
*
* @author EBU7-dev1-ayh
* @since 2021/08/30 17:56
*/
public class ExtendedIOUtils {
public static void flush(Flushable... resources) throws IOException {
int length = resources.length;
for (int i = 0; i < length; ++i) {
Flushable resource = resources[i];
if (resource != null) {
resource.flush();
}
}
}
public static void closeQuietly(Closeable... resources) {
int length = resources.length;
for (int i = 0; i < length; ++i) {
Closeable resource = resources[i];
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
//ignore exception
}
}
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -1,134 +1,134 @@
package aiyh.utils.mapper;
import aiyh.utils.annotation.recordset.*;
import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.entity.SelectValueEntity;
import aiyh.utils.entity.WorkflowNodeConfig;
import java.util.List;
import java.util.Map;
/**
* <p>SQL</p>
* <p>create 2022/1/27 0027 12:01</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface UtilMapper {
/**
* Debug
*
* @return Debug
*/
@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 $t{configTableName} where only_mark = #{onlyMark} and enable_param = 1")
public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark,
@ParamMapper("configTableName") String cusConfigTableName);
/**
*
*
* @param imageFileId
* @return
*/
@Select("select imagefilename from imagefile where imagefileid = #{imageFileId}")
String selectFileNameByImageFileId(@ParamMapper("imageFileId") int imageFileId);
/**
*
*
* @param workflowId id
* @return
*/
@Select("select bill.tablename from workflow_bill bill join workflow_base base on base.formid = bill.id where base.id = #{workflowId}")
String selectWorkfowMainTable(@ParamMapper("workflowId") String workflowId);
@Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid = #{docId}")
DocImageInfo selectDocImageInfo(@ParamMapper("docId") String docId);
@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);
/**
*
*
* @param tableName
* @param fileName
* @return
*/
@Select("select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, ws.selectname,ws.selectvalue " +
"from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " +
"left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName}")
List<SelectValueEntity> selectSelectFieldValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName);
@Select("select ws.selectname " +
"from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " +
"left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName} and selectvalue = #{value}")
String selectSelectFieldValueByValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName,
@ParamMapper("value") String value);
/**
*
*
* @param imageFileId
* @return
*/
@Select("select * from imagefile where imagefileid = #{imageFileId}")
Map<String, Object> selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId);
/**
*
*
* @param imageFileId ID
* @return
*/
@Delete("delete from imagefile where imagefileid = #{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);
}
package aiyh.utils.mapper;
import aiyh.utils.annotation.recordset.*;
import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.entity.SelectValueEntity;
import aiyh.utils.entity.WorkflowNodeConfig;
import java.util.List;
import java.util.Map;
/**
* <p>SQL</p>
* <p>create 2022/1/27 0027 12:01</p>
*
* @author EBU7-dev1-ayh
*/
@SqlMapper
public interface UtilMapper {
/**
* Debug
*
* @return Debug
*/
@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 $t{configTableName} where only_mark = #{onlyMark} and enable_param = 1")
public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark,
@ParamMapper("configTableName") String cusConfigTableName);
/**
*
*
* @param imageFileId
* @return
*/
@Select("select imagefilename from imagefile where imagefileid = #{imageFileId}")
String selectFileNameByImageFileId(@ParamMapper("imageFileId") int imageFileId);
/**
*
*
* @param workflowId id
* @return
*/
@Select("select bill.tablename from workflow_bill bill join workflow_base base on base.formid = bill.id where base.id = #{workflowId}")
String selectWorkfowMainTable(@ParamMapper("workflowId") String workflowId);
@Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid = #{docId}")
DocImageInfo selectDocImageInfo(@ParamMapper("docId") String docId);
@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);
/**
*
*
* @param tableName
* @param fileName
* @return
*/
@Select("select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, ws.selectname,ws.selectvalue " +
"from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " +
"left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName}")
List<SelectValueEntity> selectSelectFieldValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName);
@Select("select ws.selectname " +
"from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " +
"left join workflow_selectitem ws on ws.fieldid = wbf.id where wb.tablename = #{tableName} and fieldname = #{fileName} and selectvalue = #{value}")
String selectSelectFieldValueByValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName,
@ParamMapper("value") String value);
/**
*
*
* @param imageFileId
* @return
*/
@Select("select * from imagefile where imagefileid = #{imageFileId}")
Map<String, Object> selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId);
/**
*
*
* @param imageFileId ID
* @return
*/
@Delete("delete from imagefile where imagefileid = #{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

@ -1,68 +1,68 @@
package aiyh.utils.recordset;
import aiyh.utils.annotation.BooleanConverter;
import aiyh.utils.annotation.BooleanConverterEnum;
import aiyh.utils.excention.CustomerException;
import com.google.common.base.Strings;
import org.jetbrains.annotations.NotNull;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:34
*/
public class BooleanTypeHandler implements TypeHandler{
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
return getBoolean(declaredField, rs.getString(fieldName));
}
@Override
public Object getValue(RecordSet rs, int index,Field declaredField) {
return getBoolean(declaredField, rs.getString(index));
}
@NotNull
private Object getBoolean(Field declaredField, String fieldValue) {
try {
BooleanConverter annotation = declaredField.getAnnotation(BooleanConverter.class);
BooleanConverterEnum value = annotation.value();
String trueStr = annotation.trueStr();
String falseStr = annotation.falseStr();
String trueInteger = annotation.trueInteger();
String falseInteger = annotation.falseInteger();
boolean defaultValue = annotation.defaultValue();
String booleanVal = null;
try {
booleanVal = fieldValue;
} catch (Exception ignored) {
}
boolean hasValueTrue = annotation.hasValueTrue();
if (value == BooleanConverterEnum.STRING) {
if (booleanVal == null || booleanVal.equals(falseStr)) {
return false;
} else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueStr)) {
return true;
} else {
return defaultValue;
}
} else if (value == BooleanConverterEnum.INTEGER) {
if (booleanVal == null || booleanVal.equals(falseInteger)) {
return false;
} else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueInteger)) {
return true;
} else {
return defaultValue;
}
}else {
return defaultValue;
}
} catch (Exception e) {
throw new CustomerException("不支持的类型转换!");
}
}
}
package aiyh.utils.recordset;
import aiyh.utils.annotation.BooleanConverter;
import aiyh.utils.annotation.BooleanConverterEnum;
import aiyh.utils.excention.CustomerException;
import com.google.common.base.Strings;
import org.jetbrains.annotations.NotNull;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:34
*/
public class BooleanTypeHandler implements TypeHandler{
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
return getBoolean(declaredField, rs.getString(fieldName));
}
@Override
public Object getValue(RecordSet rs, int index,Field declaredField) {
return getBoolean(declaredField, rs.getString(index));
}
@NotNull
private Object getBoolean(Field declaredField, String fieldValue) {
try {
BooleanConverter annotation = declaredField.getAnnotation(BooleanConverter.class);
BooleanConverterEnum value = annotation.value();
String trueStr = annotation.trueStr();
String falseStr = annotation.falseStr();
String trueInteger = annotation.trueInteger();
String falseInteger = annotation.falseInteger();
boolean defaultValue = annotation.defaultValue();
String booleanVal = null;
try {
booleanVal = fieldValue;
} catch (Exception ignored) {
}
boolean hasValueTrue = annotation.hasValueTrue();
if (value == BooleanConverterEnum.STRING) {
if (booleanVal == null || booleanVal.equals(falseStr)) {
return false;
} else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueStr)) {
return true;
} else {
return defaultValue;
}
} else if (value == BooleanConverterEnum.INTEGER) {
if (booleanVal == null || booleanVal.equals(falseInteger)) {
return false;
} else if ((hasValueTrue && !Strings.isNullOrEmpty(booleanVal)) || booleanVal.equals(trueInteger)) {
return true;
} else {
return defaultValue;
}
}else {
return defaultValue;
}
} catch (Exception e) {
throw new CustomerException("不支持的类型转换!");
}
}
}

View File

@ -1,56 +1,56 @@
package aiyh.utils.recordset;
import aiyh.utils.annotation.DateFormatAn;
import aiyh.utils.excention.TypeNonsupportException;
import com.ibm.icu.text.SimpleDateFormat;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Date;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:35
*/
public class DataTypeHandler implements TypeHandler {
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
if (declaredField == null) {
throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
}
DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
Date date = null;
if (annotation != null) {
String value = annotation.value();
try {
date = new SimpleDateFormat(value).parse(rs.getString(fieldName));
} catch (ParseException e) {
e.printStackTrace();
throw new TypeNonsupportException("Failed to convert [" + rs.getString(fieldName) + "] to a Date object as [" + value + "]!!");
}
}
return date;
}
@Override
public Object getValue(RecordSet rs, int index, Field declaredField) {
if (declaredField == null) {
throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
}
DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
Date date = null;
if (annotation != null) {
String value = annotation.value();
try {
date = new SimpleDateFormat(value).parse(rs.getString(index));
} catch (ParseException e) {
e.printStackTrace();
throw new TypeNonsupportException("Failed to convert [" + rs.getString(index) + "] to a Date object as [" + value + "]!!");
}
}
return date;
}
}
package aiyh.utils.recordset;
import aiyh.utils.annotation.DateFormatAn;
import aiyh.utils.excention.TypeNonsupportException;
import com.ibm.icu.text.SimpleDateFormat;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Date;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:35
*/
public class DataTypeHandler implements TypeHandler {
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
if (declaredField == null) {
throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
}
DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
Date date = null;
if (annotation != null) {
String value = annotation.value();
try {
date = new SimpleDateFormat(value).parse(rs.getString(fieldName));
} catch (ParseException e) {
e.printStackTrace();
throw new TypeNonsupportException("Failed to convert [" + rs.getString(fieldName) + "] to a Date object as [" + value + "]!!");
}
}
return date;
}
@Override
public Object getValue(RecordSet rs, int index, Field declaredField) {
if (declaredField == null) {
throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
}
DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
Date date = null;
if (annotation != null) {
String value = annotation.value();
try {
date = new SimpleDateFormat(value).parse(rs.getString(index));
} catch (ParseException e) {
e.printStackTrace();
throw new TypeNonsupportException("Failed to convert [" + rs.getString(index) + "] to a Date object as [" + value + "]!!");
}
}
return date;
}
}

View File

@ -1,32 +1,32 @@
package aiyh.utils.recordset;
import aiyh.utils.Util;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:10
*/
public class IntegerTypeHandler implements TypeHandler{
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(fieldName),"-1");
if(string.contains(".")){
string = string.substring(0,string.indexOf("."));
}
return Integer.parseInt(string);
}
@Override
public Object getValue(RecordSet rs, int index,Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(index),"-1");
if(string.contains(".")){
string = string.substring(0,string.indexOf("."));
}
return Integer.parseInt(string);
}
}
package aiyh.utils.recordset;
import aiyh.utils.Util;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:10
*/
public class IntegerTypeHandler implements TypeHandler{
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(fieldName),"-1");
if(string.contains(".")){
string = string.substring(0,string.indexOf("."));
}
return Integer.parseInt(string);
}
@Override
public Object getValue(RecordSet rs, int index,Field declaredField) {
String string = Util.null2DefaultStr(rs.getString(index),"-1");
if(string.contains(".")){
string = string.substring(0,string.indexOf("."));
}
return Integer.parseInt(string);
}
}

View File

@ -1,211 +1,211 @@
package aiyh.utils.recordset;
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 weaver.conn.RecordSet;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 14:39
*/
public class RecordsetUtil implements InvocationHandler {
private final RecordSet recordSet = new RecordSet();
public <T> T getMapper(Class<T> tClass) {
if (tClass == null) {
throw new BindingException("class is null!");
}
if (tClass.getAnnotation(SqlMapper.class) == null) {
throw new BindingException("can not find SqlMapper annotation!");
}
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
SqlHandler sqlHandler = new SqlHandler();
ResultMapper resultMapper = new ResultMapper();
Select select = method.getAnnotation(Select.class);
if (select != null) {
// 查询
RecordSet rs = new RecordSet();
String sql = select.value();
boolean custom = select.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
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 {
rs.executeQuery(handler.getSqlStr(), handler.getArgs());
}
return resultMapper.mapperResult(rs, method, method.getReturnType());
}
Update update = method.getAnnotation(Update.class);
if (update != null) {
// 查询
String sql = update.value();
boolean custom = update.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
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()) {
b = recordSet.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(int.class) || returnType.equals(Integer.class)) {
if (b) {
return 1;
} else {
return 0;
}
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
Insert insert = method.getAnnotation(Insert.class);
if (insert != null) {
// 查询
String sql = insert.value();
boolean custom = insert.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
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()) {
b = recordSet.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
Delete delete = method.getAnnotation(Delete.class);
if (delete != null) {
// 查询
String sql = delete.value();
boolean custom = delete.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
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()) {
b = recordSet.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
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");
}
}
package aiyh.utils.recordset;
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 weaver.conn.RecordSet;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 14:39
*/
public class RecordsetUtil implements InvocationHandler {
private final RecordSet recordSet = new RecordSet();
public <T> T getMapper(Class<T> tClass) {
if (tClass == null) {
throw new BindingException("class is null!");
}
if (tClass.getAnnotation(SqlMapper.class) == null) {
throw new BindingException("can not find SqlMapper annotation!");
}
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
SqlHandler sqlHandler = new SqlHandler();
ResultMapper resultMapper = new ResultMapper();
Select select = method.getAnnotation(Select.class);
if (select != null) {
// 查询
RecordSet rs = new RecordSet();
String sql = select.value();
boolean custom = select.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) {
throw new CustomerException("The sql statement does not match, the @Select annotation can only getDataId 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 {
rs.executeQuery(handler.getSqlStr(), handler.getArgs());
}
return resultMapper.mapperResult(rs, method, method.getReturnType());
}
Update update = method.getAnnotation(Update.class);
if (update != null) {
// 查询
String sql = update.value();
boolean custom = update.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) {
throw new CustomerException("The sql statement does not match, the @Update annotation can only getDataId 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()) {
b = recordSet.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(int.class) || returnType.equals(Integer.class)) {
if (b) {
return 1;
} else {
return 0;
}
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
Insert insert = method.getAnnotation(Insert.class);
if (insert != null) {
// 查询
String sql = insert.value();
boolean custom = insert.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) {
throw new CustomerException("The sql statement does not match, the @Insert annotation can only getDataId 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()) {
b = recordSet.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
Delete delete = method.getAnnotation(Delete.class);
if (delete != null) {
// 查询
String sql = delete.value();
boolean custom = delete.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) {
throw new CustomerException("The sql statement does not match, the @Delete annotation can only getDataId 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()) {
b = recordSet.executeUpdate(handler.getSqlStr());
} else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
}
if (returnType.equals(void.class)) {
return null;
}
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b;
}
}
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("getDataId 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 getDataId 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("getDataId 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 getDataId 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("getDataId 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 getDataId 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

@ -1,278 +1,278 @@
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;
import weaver.conn.RecordSetTrans;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.*;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 11:03
*/
public class ResultMapper {
private static Map<Class<?>, TypeHandler> typeHandler = new HashMap<>();
static {
IntegerTypeHandler integerTypeHandler = new IntegerTypeHandler();
typeHandler.put(String.class, new StringTypeHandler());
typeHandler.put(Integer.class, integerTypeHandler);
typeHandler.put(int.class, integerTypeHandler);
typeHandler.put(byte.class, integerTypeHandler);
typeHandler.put(short.class, integerTypeHandler);
typeHandler.put(long.class, integerTypeHandler);
typeHandler.put(Long.class, integerTypeHandler);
typeHandler.put(Boolean.class, new BooleanTypeHandler());
typeHandler.put(boolean.class, new BooleanTypeHandler());
typeHandler.put(Date.class, new DataTypeHandler());
typeHandler.put(Float.class, new FloatTypeHandler());
typeHandler.put(float.class, new FloatTypeHandler());
}
public <T> T mapperResult(RecordSet rs, Method method, Class<T> tClass) {
if (tClass.equals(void.class)) {
return null;
}
if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) {
return (T) rs;
}
try {
if (tClass.equals(List.class)) {
tClass = (Class<T>) ArrayList.class;
}
if (tClass.equals(Map.class)) {
tClass = (Class<T>) HashMap.class;
}
if (ResultMapper.typeHandler.containsKey(tClass)) {
rs.next();
return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null);
}
T t = tClass.newInstance();
if (t instanceof Collection) {
// 集合求出泛型
//获取返回值的类型
Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(Map.class)) {
rawType = HashMap.class;
}
while (rs.next()) {
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<? super Object>) t).add(object);
}
return t;
}
if (t instanceof Map) {
// map
Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(List.class)) {
rawType = (Class<T>) ArrayList.class;
}
if (rawType.equals(Map.class)) {
rawType = HashMap.class;
}
// 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!");
}
if (rs.next()) {
return (T) getObject(rs, t, method);
}
return null;
}
if (t.getClass().isArray()) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (rs.next()) {
return (T) getObject(rs, t, method);
}
return null;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Object getObject(RecordSet rs, Object o, Method method) {
CaseConversion annotation = method.getAnnotation(CaseConversion.class);
boolean enable = annotation == null ? true : annotation.value();
String[] columnName = rs.getColumnName();
String[] columnTypeName = rs.getColumnTypeName();
int[] columnTypes = rs.getColumnType();
if (columnTypeName == null) {
columnTypeName = new String[columnTypes.length];
for (int i = 0; i < columnTypes.length; i++) {
int type = columnTypes[i];
switch (type) {
case -1:
columnTypeName[i] = "TEXT";
break;
case 4:
columnTypeName[i] = "INT";
break;
case 12:
columnTypeName[i] = "VARCHAR";
break;
default:
columnTypeName[i] = "VARCHAR";
}
}
}
try {
if (o instanceof Map) {
for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[i];
if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getInt(i + 1));
continue;
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getFloat(i + 1));
continue;
}
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getString(i + 1));
continue;
}
return o;
}
if (o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (o instanceof Number) {
for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[i];
if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) {
return rs.getInt(i + 1);
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
return rs.getFloat(i + 1);
}
}
return o;
}
if (o instanceof String) {
for (int i = 0; i < columnName.length; i++) {
return rs.getString(i + 1);
}
return o;
}
if (o instanceof Boolean) {
for (int i = 0; i < columnName.length; i++) {
return rs.getBoolean(i + 1);
}
return o;
}
// Util.getLogger().info("获取对象:" + o.toString());
BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object value = null;
String fieldName = propertyDescriptor.getName();
if (Strings.isNullOrEmpty(fieldName)) {
fieldName = propertyDescriptor.getDisplayName();
}
// Util.getLogger().info("获取类字段:" + fieldName);
// Util.getLogger().info("获取类字段1" + propertyDescriptor.getDisplayName());
// Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName));
Field declaredField = o.getClass().getDeclaredField(fieldName);
if (enable) {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField);
} else {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField);
}
propertyDescriptor.getWriteMethod().invoke(o, value);
}
} catch (Exception e) {
e.printStackTrace();
Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e));
}
return o;
}
public Class<?> getRawType(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
return (Class) rawType;
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
} else if (type instanceof TypeVariable) {
return Object.class;
} else if (type instanceof WildcardType) {
return getRawType(((WildcardType) type).getUpperBounds()[0]);
} else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className);
}
}
}
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;
import weaver.conn.RecordSetTrans;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.*;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 11:03
*/
public class ResultMapper {
private static Map<Class<?>, TypeHandler> typeHandler = new HashMap<>();
static {
IntegerTypeHandler integerTypeHandler = new IntegerTypeHandler();
typeHandler.put(String.class, new StringTypeHandler());
typeHandler.put(Integer.class, integerTypeHandler);
typeHandler.put(int.class, integerTypeHandler);
typeHandler.put(byte.class, integerTypeHandler);
typeHandler.put(short.class, integerTypeHandler);
typeHandler.put(long.class, integerTypeHandler);
typeHandler.put(Long.class, integerTypeHandler);
typeHandler.put(Boolean.class, new BooleanTypeHandler());
typeHandler.put(boolean.class, new BooleanTypeHandler());
typeHandler.put(Date.class, new DataTypeHandler());
typeHandler.put(Float.class, new FloatTypeHandler());
typeHandler.put(float.class, new FloatTypeHandler());
}
public <T> T mapperResult(RecordSet rs, Method method, Class<T> tClass) {
if (tClass.equals(void.class)) {
return null;
}
if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) {
return (T) rs;
}
try {
if (tClass.equals(List.class)) {
tClass = (Class<T>) ArrayList.class;
}
if (tClass.equals(Map.class)) {
tClass = (Class<T>) HashMap.class;
}
if (ResultMapper.typeHandler.containsKey(tClass)) {
rs.next();
return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null);
}
T t = tClass.newInstance();
if (t instanceof Collection) {
// 集合求出泛型
//获取返回值的类型
Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(Map.class)) {
rawType = HashMap.class;
}
while (rs.next()) {
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<? super Object>) t).add(object);
}
return t;
}
if (t instanceof Map) {
// map
Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(List.class)) {
rawType = (Class<T>) ArrayList.class;
}
if (rawType.equals(Map.class)) {
rawType = HashMap.class;
}
// 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!");
}
if (rs.next()) {
return (T) getObject(rs, t, method);
}
return null;
}
if (t.getClass().isArray()) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (rs.next()) {
return (T) getObject(rs, t, method);
}
return null;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public Object getObject(RecordSet rs, Object o, Method method) {
CaseConversion annotation = method.getAnnotation(CaseConversion.class);
boolean enable = annotation == null ? true : annotation.value();
String[] columnName = rs.getColumnName();
String[] columnTypeName = rs.getColumnTypeName();
int[] columnTypes = rs.getColumnType();
if (columnTypeName == null) {
columnTypeName = new String[columnTypes.length];
for (int i = 0; i < columnTypes.length; i++) {
int type = columnTypes[i];
switch (type) {
case -1:
columnTypeName[i] = "TEXT";
break;
case 4:
columnTypeName[i] = "INT";
break;
case 12:
columnTypeName[i] = "VARCHAR";
break;
default:
columnTypeName[i] = "VARCHAR";
}
}
}
try {
if (o instanceof Map) {
for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[i];
if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getInt(i + 1));
continue;
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getFloat(i + 1));
continue;
}
if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1));
continue;
}
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getString(i + 1));
continue;
}
return o;
}
if (o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!");
}
if (o instanceof Number) {
for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[i];
if ("int".equalsIgnoreCase(columnType) || "long".equalsIgnoreCase(columnType) || "number".equalsIgnoreCase(columnType) || "MEDIUMINT".equalsIgnoreCase(columnType) || "TINYINT".equalsIgnoreCase(columnType) || "SMALLINT".equalsIgnoreCase(columnType) || "BIGINT".equalsIgnoreCase(columnType) || "INTEGER".equalsIgnoreCase(columnType)) {
return rs.getInt(i + 1);
}
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
return rs.getFloat(i + 1);
}
}
return o;
}
if (o instanceof String) {
for (int i = 0; i < columnName.length; i++) {
return rs.getString(i + 1);
}
return o;
}
if (o instanceof Boolean) {
for (int i = 0; i < columnName.length; i++) {
return rs.getBoolean(i + 1);
}
return o;
}
// Util.getLogger().info("获取对象:" + o.toString());
BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Class<?> propertyType = propertyDescriptor.getPropertyType();
Object value = null;
String fieldName = propertyDescriptor.getName();
if (Strings.isNullOrEmpty(fieldName)) {
fieldName = propertyDescriptor.getDisplayName();
}
// Util.getLogger().info("获取类字段:" + fieldName);
// Util.getLogger().info("获取类字段1" + propertyDescriptor.getDisplayName());
// Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName));
Field declaredField = o.getClass().getDeclaredField(fieldName);
if (enable) {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField);
} else {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField);
}
propertyDescriptor.getWriteMethod().invoke(o, value);
}
} catch (Exception e) {
e.printStackTrace();
Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e));
}
return o;
}
public Class<?> getRawType(Type type) {
if (type instanceof Class) {
return (Class) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType();
return (Class) rawType;
} else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
} else if (type instanceof TypeVariable) {
return Object.class;
} else if (type instanceof WildcardType) {
return getRawType(((WildcardType) type).getUpperBounds()[0]);
} else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className);
}
}
}

View File

@ -1,305 +1,305 @@
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;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 15:28
*/
public class SqlHandler {
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) {
String findSql = findSql(sql, custom, method, args);
Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args);
// 处理基本类型以及包装类
String parse;
if (methodArgNameMap.size() == 0) {
return new PrepSqlResultImpl(findSql, sqlArgs);
}
if (methodArgNameMap.size() == 1) {
Optional<Object> first = methodArgNameMap.values().stream().findFirst();
parse = parse(findSql, first.orElse(null));
} else {
parse = parse(findSql, methodArgNameMap);
}
return new PrepSqlResultImpl(parse, sqlArgs);
}
private String parseBatch(String findSql, Object o) {
String parse = "";
if (!batchSqlArgsList.isEmpty()) {
for (Object o1 : batchSqlArgsList) {
Map<String, Object> map = new HashMap<>(8);
map.put("item", o1);
map.putAll((Map<String, Object>) o);
parse = parse(findSql, map);
List<Object> tempArgs = new ArrayList<>();
tempArgs.addAll(sqlArgs);
batchSqlArgs.add(tempArgs);
sqlArgs.clear();
}
}
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);
}
private String findSql(String sql, boolean custom, Method method, Object[] args) {
String parsing = sql;
if (custom) {
// 自定义
Parameter[] parameters = method.getParameters();
try {
if (parameters.length == 0) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!");
}
} catch (NullPointerException e) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!");
}
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
Object arg = args[i];
Class<?> type = parameter.getType();
SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class);
if (sqlAnnotation != null && type.equals(String.class)) {
try {
parsing = arg.toString();
} catch (NullPointerException e) {
throw new BindingException("sql String param is null!");
}
break;
}
}
}
return parsing;
}
private Map<String, Object> buildMethodArgNameMap(Method method, Object[] args) {
Parameter[] parameters = method.getParameters();
Map<String, Object> params = new HashMap<>();
// 参数处理
try {
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
Object arg = args[i];
String name = parameter.getName();
Class<?> type = parameter.getType();
SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class);
ParamMapper paramAnnotation = parameter.getAnnotation(ParamMapper.class);
if (sqlAnnotation != null && type.equals(String.class)) {
continue;
}
if (paramAnnotation != null) {
params.put(paramAnnotation.value(), arg);
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);
}
} catch (NullPointerException e) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!");
}
return params;
}
private String parse(String sql, Object arg) {
String parseSql = sql;
String pattern = "\\$t\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(parseSql);
while (matcher.find()) {
String regx = matcher.group("regx");
String field = matcher.group("field");
String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, true);
parseSql = parseSql.replaceFirst(pattern, value.toString());
}
pattern = "\\$\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
compile = Pattern.compile(pattern);
matcher = compile.matcher(parseSql);
while (matcher.find()) {
String regx = matcher.group("regx");
String field = matcher.group("field");
String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, false);
parseSql = parseSql.replaceFirst(pattern, value.toString());
}
// pattern = "#\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
pattern = "#\\{\\s*(?<regx>(?<field>\\w+)\\.*(?<other>\\w+)*)\\s*}";
compile = Pattern.compile(pattern);
matcher = compile.matcher(parseSql);
while (matcher.find()) {
String regx = matcher.group("regx");
String field = matcher.group("field");
String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, true);
parseSql = parseSql.replaceFirst(pattern, "?");
sqlArgs.add(value);
}
return parseSql;
}
private Object getValueByRegx(String regx, String field, String other, Object arg, boolean isEscape) {
if (!regx.contains(".")) {
return valueHandler(arg, field, isEscape);
}
String pattern = "(?<field>\\w+)\\.*(?<other>(\\S+)*)";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(other);
Object o = valueHandler(arg, field, isEscape);
if (matcher.find()) {
String innerField = matcher.group("field");
String innerOther = matcher.group("other");
return getValueByRegx(other, innerField, innerOther, o, isEscape);
}
// return getValueByRegx(other,)
throw new BindingException("Unable to find value " + other);
}
private Object valueHandler(Object arg, String key, boolean isEscape) {
if (arg == null) {
return null;
// throw new CustomerException(String.format("sql参数{%s} 为null请检查",key));
}
if (arg instanceof Number) {
// 处理数字类型
return arg;
}
if (arg instanceof Boolean) {
// 处理布尔类型
return arg;
}
if (arg instanceof Character || arg instanceof String) {
// 处理字符类型
if (isEscape) {
return arg;
} else {
return "'" + arg + "'";
}
}
if (arg.getClass().isArray()) {
// throw new TypeNonsupportException("A value is expected, but a set is received");
return StringUtils.join((Object[]) arg, ",");
}
// 判断参数类型
if (arg instanceof Collection) {
// list
// throw new TypeNonsupportException("A value is expected, but a set is received");
return StringUtils.join((Collection<?>) arg, ",");
}
if (arg instanceof Map) {
// map
if (!((Map<?, ?>) arg).containsKey(key)) {
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) {
return o;
} else {
return "'" + o + "'";
}
}
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);
// 当做javaBean处理
try {
Method method = arg.getClass().getMethod(methodName);
Object invoke = method.invoke(arg);
if (invoke instanceof Character || invoke instanceof String) {
// 处理字符类型
if (isEscape) {
return invoke;
} else {
return "'" + invoke + "'";
}
}
return invoke;
} catch (NoSuchMethodException e) {
// e.printStackTrace();
throw new MethodNotFindException(methodName + " is not find!");
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e.toString());
}
}
}
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;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author EBU7-dev1-ayh
* create 2021/12/19 0019 15:28
*/
public class SqlHandler {
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) {
String findSql = findSql(sql, custom, method, args);
Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args);
// 处理基本类型以及包装类
String parse;
if (methodArgNameMap.size() == 0) {
return new PrepSqlResultImpl(findSql, sqlArgs);
}
if (methodArgNameMap.size() == 1) {
Optional<Object> first = methodArgNameMap.values().stream().findFirst();
parse = parse(findSql, first.orElse(null));
} else {
parse = parse(findSql, methodArgNameMap);
}
return new PrepSqlResultImpl(parse, sqlArgs);
}
private String parseBatch(String findSql, Object o) {
String parse = "";
if (!batchSqlArgsList.isEmpty()) {
for (Object o1 : batchSqlArgsList) {
Map<String, Object> map = new HashMap<>(8);
map.put("item", o1);
map.putAll((Map<String, Object>) o);
parse = parse(findSql, map);
List<Object> tempArgs = new ArrayList<>();
tempArgs.addAll(sqlArgs);
batchSqlArgs.add(tempArgs);
sqlArgs.clear();
}
}
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);
}
private String findSql(String sql, boolean custom, Method method, Object[] args) {
String parsing = sql;
if (custom) {
// 自定义
Parameter[] parameters = method.getParameters();
try {
if (parameters.length == 0) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!");
}
} catch (NullPointerException e) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!");
}
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
Object arg = args[i];
Class<?> type = parameter.getType();
SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class);
if (sqlAnnotation != null && type.equals(String.class)) {
try {
parsing = arg.toString();
} catch (NullPointerException e) {
throw new BindingException("sql String param is null!");
}
break;
}
}
}
return parsing;
}
private Map<String, Object> buildMethodArgNameMap(Method method, Object[] args) {
Parameter[] parameters = method.getParameters();
Map<String, Object> params = new HashMap<>();
// 参数处理
try {
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
Object arg = args[i];
String name = parameter.getName();
Class<?> type = parameter.getType();
SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class);
ParamMapper paramAnnotation = parameter.getAnnotation(ParamMapper.class);
if (sqlAnnotation != null && type.equals(String.class)) {
continue;
}
if (paramAnnotation != null) {
params.put(paramAnnotation.value(), arg);
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);
}
} catch (NullPointerException e) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!");
}
return params;
}
private String parse(String sql, Object arg) {
String parseSql = sql;
String pattern = "\\$t\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(parseSql);
while (matcher.find()) {
String regx = matcher.group("regx");
String field = matcher.group("field");
String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, true);
parseSql = parseSql.replaceFirst(pattern, value.toString());
}
pattern = "\\$\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
compile = Pattern.compile(pattern);
matcher = compile.matcher(parseSql);
while (matcher.find()) {
String regx = matcher.group("regx");
String field = matcher.group("field");
String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, false);
parseSql = parseSql.replaceFirst(pattern, value.toString());
}
// pattern = "#\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
pattern = "#\\{\\s*(?<regx>(?<field>\\w+)\\.*(?<other>\\w+)*)\\s*}";
compile = Pattern.compile(pattern);
matcher = compile.matcher(parseSql);
while (matcher.find()) {
String regx = matcher.group("regx");
String field = matcher.group("field");
String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, true);
parseSql = parseSql.replaceFirst(pattern, "?");
sqlArgs.add(value);
}
return parseSql;
}
private Object getValueByRegx(String regx, String field, String other, Object arg, boolean isEscape) {
if (!regx.contains(".")) {
return valueHandler(arg, field, isEscape);
}
String pattern = "(?<field>\\w+)\\.*(?<other>(\\S+)*)";
Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(other);
Object o = valueHandler(arg, field, isEscape);
if (matcher.find()) {
String innerField = matcher.group("field");
String innerOther = matcher.group("other");
return getValueByRegx(other, innerField, innerOther, o, isEscape);
}
// return getValueByRegx(other,)
throw new BindingException("Unable to find value " + other);
}
private Object valueHandler(Object arg, String key, boolean isEscape) {
if (arg == null) {
return null;
// throw new CustomerException(String.format("sql参数{%s} 为null请检查",key));
}
if (arg instanceof Number) {
// 处理数字类型
return arg;
}
if (arg instanceof Boolean) {
// 处理布尔类型
return arg;
}
if (arg instanceof Character || arg instanceof String) {
// 处理字符类型
if (isEscape) {
return arg;
} else {
return "'" + arg + "'";
}
}
if (arg.getClass().isArray()) {
// throw new TypeNonsupportException("A value is expected, but a set is received");
return StringUtils.join((Object[]) arg, ",");
}
// 判断参数类型
if (arg instanceof Collection) {
// list
// throw new TypeNonsupportException("A value is expected, but a set is received");
return StringUtils.join((Collection<?>) arg, ",");
}
if (arg instanceof Map) {
// map
if (!((Map<?, ?>) arg).containsKey(key)) {
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) {
return o;
} else {
return "'" + o + "'";
}
}
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);
// 当做javaBean处理
try {
Method method = arg.getClass().getMethod(methodName);
Object invoke = method.invoke(arg);
if (invoke instanceof Character || invoke instanceof String) {
// 处理字符类型
if (isEscape) {
return invoke;
} else {
return "'" + invoke + "'";
}
}
return invoke;
} catch (NoSuchMethodException e) {
// e.printStackTrace();
throw new MethodNotFindException(methodName + " is not find!");
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e.toString());
}
}
}

View File

@ -1,23 +1,23 @@
package aiyh.utils.recordset;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:06
*/
public class StringTypeHandler implements TypeHandler{
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
return rs.getString(fieldName);
}
@Override
public Object getValue(RecordSet rs, int index,Field declaredField) {
return rs.getString(index);
}
}
package aiyh.utils.recordset;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author EBU7-dev1-ayh
* create 2021/12/21 0021 13:06
*/
public class StringTypeHandler implements TypeHandler{
@Override
public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
return rs.getString(fieldName);
}
@Override
public Object getValue(RecordSet rs, int index,Field declaredField) {
return rs.getString(index);
}
}

View File

@ -1,15 +1,15 @@
package aiyh.utils.recordset;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/21 0021 13:05
*/
public interface TypeHandler {
Object getValue(RecordSet rs, String fieldName, Field declaredField);
Object getValue(RecordSet rs,int index,Field declaredField);
}
package aiyh.utils.recordset;
import weaver.conn.RecordSet;
import java.lang.reflect.Field;
/**
* @author @author EBU7-dev1-ay
* create 2021/12/21 0021 13:05
*/
public interface TypeHandler {
Object getValue(RecordSet rs, String fieldName, Field declaredField);
Object getValue(RecordSet rs,int index,Field declaredField);
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,52 @@
package com.api.xuanran.wang.saic_travel.model_create_workflow.controller;
import aiyh.utils.ApiResult;
import aiyh.utils.Util;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.xuanran.wang.common.util.CommonUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* <h1>id</h1>
* @Author xuanran.wang
* @Date 2022/12/5 11:53
*/
@Path("/wxr/saicTravel/")
public class CusCreateWorkFlowController {
private final Logger logger = Util.getLogger();
@Path("cusCreateWorkFlow")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String getOrgChartTree(@Context HttpServletRequest request, @Context HttpServletResponse response) {
User logInUser = HrmUserVarify.getUser(request, response);
if(logInUser == null){
return ApiResult.error(403,"请先登录!");
}
String choiceData = request.getParameter("choiceData");
int modelId = Util.getIntValue(request.getParameter("modelId"), -1);
List<String> dataList = Arrays.stream(choiceData.split(",")).collect(Collectors.toList());
List<String> requestIds = CommonUtil.doCreateWorkFlow(modelId, dataList);
List<String> errorData = new ArrayList<>();
for (int i = 0; i < requestIds.size(); i++) {
if (Util.getIntValue(requestIds.get(i), -1) < 0) {
errorData.add(dataList.get(i));
}
}
logger.error(Util.logStr("执行创建流程失败集合: {}",JSONObject.toJSONString(errorData)));
return ApiResult.success(errorData);
}
}

View File

@ -44,7 +44,7 @@ public interface OrgChartMapper {
" inner join hrmjobtitles job on hrm.JOBTITLE = job.id " +
" inner join cus_fielddata cus on cus.ID = hrm.ID " +
" and cus.SCOPE = 'HrmCustomFieldByInfoType' " +
" and cus.SCOPEID = -1 " +
" and cus.SCOPEID = 1 " +
" inner join hrmdepartment dept on dept.id = hrm.DEPARTMENTID " +
"where hrm.status in (0, 1)")
List<HrmResource> selectAll(@ParamMapper("typeOfEmploymentFiled") String typeOfEmploymentField,

View File

@ -1,6 +1,7 @@
package com.api.youhong.ai.pcn.organization.orgchart.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import cn.hutool.core.lang.Assert;
import com.api.youhong.ai.pcn.organization.orgchart.dto.HrmResourceDto;
import com.api.youhong.ai.pcn.organization.orgchart.mapper.OrgChartMapper;
@ -45,28 +46,17 @@ public class OrgChartService {
String lastNameEnField = Util.getCusConfigValue("lastNameEnField");
Assert.notBlank(lastNameEnField, "config [lastNameEnField] is null or blank!");
List<HrmResource> hrmResourceList = mapper.selectAll(typeOfEmploymentField, lastNameEnField);
if (Objects.isNull(hrmResourceList) || hrmResourceList.isEmpty()) {
throw new CustomerException("查询不到相关人员!");
}
//List<HrmResourceDto> hrmResourceDtoList = new ArrayList();
AtomicReference<HrmResourceDto> currentUser = new AtomicReference<>();
/* ******************* 将pojo转换为Dto对象对节点属性默认值赋值找出当前用户并设置显示 ******************* */
List<HrmResourceDto> hrmResourceDtoList = hrmResourceList.stream()
.map(struct::hrmResourceToDto)
.peek(item -> Builder.startSet(item)
.with(HrmResourceDto::setShow, 0)
.with(HrmResourceDto::setShowBrother, 0)
.with(HrmResourceDto::setShowChildren, 0)
.endSet())
.collect(Collectors.toList());
hrmResourceDtoList.stream()
.filter(item -> item.getId() == userId)
.forEach(item -> {
Builder.startSet(item)
.with(HrmResourceDto::setShow, 1)
.with(HrmResourceDto::setShowBrother, 1)
.with(HrmResourceDto::setShowChildren, 1)
.with(HrmResourceDto::setCurrent, true)
.endSet();
currentUser.set(item);
});
List<HrmResourceDto> hrmResourceDtoList = hrmResourceList.stream().map(struct::hrmResourceToDto).peek(item -> Builder.startSet(item).with(HrmResourceDto::setShow, 0).with(HrmResourceDto::setShowBrother, 0).with(HrmResourceDto::setShowChildren, 0).endSet()).collect(Collectors.toList());
hrmResourceDtoList.stream().filter(item -> item.getId() == userId).forEach(item -> {
Builder.startSet(item).with(HrmResourceDto::setShow, 1).with(HrmResourceDto::setShowBrother, 1).with(HrmResourceDto::setShowChildren, 1).with(HrmResourceDto::setCurrent, true).endSet();
currentUser.set(item);
});
Assert.notNull(currentUser, "not find current login user info!");
/* ******************* 查找当前登陆人员的所有上级 ******************* */
String currentUserManagerStr = currentUser.get().getManagerStr();
@ -74,16 +64,9 @@ public class OrgChartService {
currentUserManagerStr = "";
}
currentUserManagerStr = Util.removeSeparator(currentUserManagerStr, ",");
List<Integer> currentUserManagerList = Arrays.stream(currentUserManagerStr.split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
List<Integer> currentUserManagerList = Arrays.stream(currentUserManagerStr.split(",")).map(Integer::parseInt).collect(Collectors.toList());
/* ******************* 对当前用户的所有直接上级设置标识 ******************* */
hrmResourceDtoList.stream()
.filter(item -> currentUserManagerList.contains(item.getId()))
.forEach(item -> Builder.startSet(item)
.with(HrmResourceDto::setShowChildren, 1)
.with(HrmResourceDto::setCurrentParent, true)
.endSet());
hrmResourceDtoList.stream().filter(item -> currentUserManagerList.contains(item.getId())).forEach(item -> Builder.startSet(item).with(HrmResourceDto::setShowChildren, 1).with(HrmResourceDto::setCurrentParent, true).endSet());
/* ******************* 查询当前用户的是否全部展示或显示小红点的配置信息 ******************* */
ShowPointOrAll showPointOrAll = mapper.selectShowPointOrAll(userId);
@ -92,34 +75,21 @@ public class OrgChartService {
/* ******************* 转换dto为Vo并且设置根节点标识 ******************* */
orgChartNodeVoList = hrmResourceDtoList.stream()
.map(struct::hrmResourceDtoToVo)
.peek(item -> item.setType(-1))
.collect(Collectors.toList());
} else {
/* ******************* 转换dto为Vo并且设置根节点标识 ******************* */
orgChartNodeVoList = hrmResourceDtoList.stream()
.map(struct::hrmResourceDtoToVo)
.peek(item -> {
if (showPointOrAll.isShowAll()) {
Builder.startSet(item)
.with(OrgChartNodeVo::setShow, 1)
.with(OrgChartNodeVo::setShowBrother, 1)
.with(OrgChartNodeVo::setShowChildren, 1)
.endSet();
}
if (!showPointOrAll.isShowType()) {
item.setType(-1);
}
})
.collect(Collectors.toList());
orgChartNodeVoList = hrmResourceDtoList.stream().map(struct::hrmResourceDtoToVo).peek(item -> {
if (showPointOrAll.isShowAll()) {
Builder.startSet(item).with(OrgChartNodeVo::setShow, 1).with(OrgChartNodeVo::setShowBrother, 1).with(OrgChartNodeVo::setShowChildren, 1).endSet();
}
if (!showPointOrAll.isShowType()) {
item.setType(-1);
}
}).collect(Collectors.toList());
}
return Util.listToTree(orgChartNodeVoList, OrgChartNodeVo::getId,
OrgChartNodeVo::getManagerId, OrgChartNodeVo::getChildren,
OrgChartNodeVo::setChildren,
parentId -> parentId == null || parentId <= 0)
.stream()
.peek(item -> item.setIsRoot(true))
.peek(item -> recursionChildrenNums(item, 0))
.collect(Collectors.toList());
return Util.listToTree(orgChartNodeVoList, OrgChartNodeVo::getId, OrgChartNodeVo::getManagerId, OrgChartNodeVo::getChildren, OrgChartNodeVo::setChildren, parentId -> parentId == null || parentId <= 0).stream().peek(item -> item.setIsRoot(true)).peek(item -> recursionChildrenNums(item, 0)).collect(Collectors.toList());
}

View File

@ -1,163 +1,163 @@
package weaver.xiao.commons.config.dao;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.xiao.commons.config.entity.DocImageFile;
import weaver.xiao.commons.config.entity.FieldMessage;
import weaver.xiao.commons.config.entity.MappingDetail;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.enumtype.DataSourceEnum;
import weaver.xiao.commons.exception.ValueDealException;
import weaver.xiao.commons.utils.SqlUtil;
import weaver.zwl.common.ToolUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author XiaoBokang
* @create 2021/12/29 9:46
*/
public class ConfigMappingCMD {
private final ToolUtil toolUtil = new ToolUtil();
private final String configTableName = "uf_request_config";
private final SqlUtil sqlUtil = new SqlUtil();
public RequestMappingConfig selectByUniqueCode(String uniqueCode) {
toolUtil.writeDebuggerLog("=======================查询配置列表=======================");
RequestMappingConfig requestMappingConfig = new RequestMappingConfig();
RecordSet recordSet = new RecordSet();
String querySql = "select id,workflow,requestUrl,dataSource,uniqueCode, relationWorkFlow,cusWhereSql from " + configTableName + " where uniqueCode = ?";
toolUtil.writeDebuggerLog("执行查询的sql query mainRequestMappingConfig list sql new>>>>" + querySql + " uniqueCode >>" + uniqueCode);
recordSet.executeQuery(querySql, uniqueCode);
if (recordSet.next()) {
int mainId = Util.getIntValue(recordSet.getString("id"));
requestMappingConfig = sqlUtil.recordSetToEntityByEntity(recordSet, RequestMappingConfig.class);
this.setDetailMapping(mainId, requestMappingConfig);
}
return requestMappingConfig;
}
private void setDetailMapping(int mainId, RequestMappingConfig requestMappingConfig) {
// 查询明细1的信息
RecordSet detail1RecordSet = new RecordSet();
String dataSource = requestMappingConfig.getDataSource();
if (Objects.isNull(dataSource) || "".equals(dataSource)) {
dataSource = "0";
}
DataSourceEnum anEnum = DataSourceEnum.getEnum(dataSource);
String queryDetail1Sql = "";
switch (anEnum) {
case CUS_TABLE:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext," +
" from " + configTableName + "_dt1 config ";
break;
case WORKFLOW:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,valueContext,relationWorkFlowField, " +
" fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " +
" from " + configTableName + "_dt1 config " +
" left join workflow_field_table_view fv " +
" on config.workflowField = fv.id or config.relationWorkFlowField = fv.id" +
" where mainid = ? ";
break;
case MODEL:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext, " +
" fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " +
" from " + configTableName + "_dt1 config " +
" left join workflow_field_table_view fv on config.modelField = fv.id " +
" where mainid = ? ";
break;
default:
throw new ValueDealException("不支持的数据来源");
}
toolUtil.writeDebuggerLog("执行查询的明细1sql query detail1Sql >>>>" + queryDetail1Sql + " mainId:" + mainId);
detail1RecordSet.executeQuery(queryDetail1Sql, mainId);
List<MappingDetail> mappingDetails = new ArrayList<>();
while (detail1RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, MappingDetail.class);
String getValueType = mappingDetail.getGetValueType();
// 设置流程字段相关信息
// if("0".equals(getValueType) || "4".equals(getValueType)){
FieldMessage fieldMessage = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, FieldMessage.class);
mappingDetail.setFieldMassage(fieldMessage);
// }
mappingDetails.add(mappingDetail);
}
// 查询明细2的信息
RecordSet detail2RecordSet = new RecordSet();
String queryDetail2Sql = "select paramName,belongTo,childType,dataSource,detailId,cusWhereSql from uf_request_config_dt2 where mainid = ?";
toolUtil.writeDebuggerLog("执行查询的明细sql query detail2Sql >>>>" + queryDetail2Sql + " mainId:" + mainId);
detail2RecordSet.executeQuery(queryDetail2Sql, mainId);
while (detail2RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail2RecordSet, MappingDetail.class);
mappingDetail.setParamType("6");// 设置参数类型为List
mappingDetails.add(mappingDetail);
}
// 查询明细3的信息
RecordSet detail3RecordSet = new RecordSet();
String queryDetail3Sql = "select paramName,belongTo from uf_request_config_dt3 where mainid = ?";
toolUtil.writeDebuggerLog("执行查询的明细sql query detail3Sql >>>>" + queryDetail3Sql + " mainId:" + mainId);
detail3RecordSet.executeQuery(queryDetail3Sql, mainId);
while (detail3RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail3RecordSet, MappingDetail.class);
mappingDetail.setParamType("5");// 设置参数类型为Object
mappingDetails.add(mappingDetail);
}
requestMappingConfig.setConfigDetail(mappingDetails);
// //查询明细4的信息
// RecordSet detail4RecordSet = new RecordSet();
// List<ResponseMapping> responseMappingList = new ArrayList<>();
// String queryDetail4Sql = "select responseFieldName,workflowField,mainOrDetail,detailTableId,workflowFieldName from uf_request_config_dt4 where mainid = ?";
// toolUtil.writeDebuggerLog("执行查询的明细sql query detail4Sql >>>>"+queryDetail4Sql+" mainId:"+mainId);
// detail4RecordSet.executeQuery(queryDetail4Sql,mainId);
// while (detail4RecordSet.next()){
// ResponseMapping responseMapping = sqlUtil.recordSetToEntityByEntity(detail4RecordSet, ResponseMapping.class);
// responseMappingList.add(responseMapping);
// }
// requestMappingConfig.setResponseMappingList(responseMappingList);
requestMappingConfig.setConfigDetail(mappingDetails);
}
/**
* <h2></h2>
*
* @param docIds id
* @return
* @author YouHong.ai
*/
public List<DocImageFile> selectDocImageFileList(String docIds) {
String sql = "select docfile.IMAGEFILEID,docfile.IMAGEFILENAME,docfile.DOCID,docfile.ID, " +
" imf.FILESIZE " +
"from docimagefile docfile " +
"left join imagefile imf on imf.IMAGEFILEID = docfile.IMAGEFILEID " +
"where docid in (" + docIds + ")";
RecordSet rs = new RecordSet();
rs.executeQuery(sql);
List<DocImageFile> docImageFileList = new ArrayList<>();
while (rs.next()) {
String IMAGEFILEID = rs.getString("IMAGEFILEID");
String IMAGEFILENAME = rs.getString("IMAGEFILENAME");
String DOCID = rs.getString("DOCID");
String ID = rs.getString("ID");
String fileSize = rs.getString("FILESIZE");
DocImageFile docImageFile = new DocImageFile();
docImageFile.setImageFileId(Util.getIntValue(IMAGEFILEID));
docImageFile.setImageFileName(IMAGEFILENAME);
docImageFile.setDocId(Util.getIntValue(DOCID));
docImageFile.setId(Util.getIntValue(ID));
docImageFile.setFileSize(Util.getIntValue(fileSize) / 1024L);
docImageFileList.add(docImageFile);
}
if (docImageFileList.isEmpty()) {
throw new NullPointerException("附件字段不存在值!请检查数据表或配置表数据类型是否正确!");
}
return docImageFileList;
}
}
package weaver.xiao.commons.config.dao;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.xiao.commons.config.entity.DocImageFile;
import weaver.xiao.commons.config.entity.FieldMessage;
import weaver.xiao.commons.config.entity.MappingDetail;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.enumtype.DataSourceEnum;
import weaver.xiao.commons.exception.ValueDealException;
import weaver.xiao.commons.utils.SqlUtil;
import weaver.zwl.common.ToolUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author XiaoBokang
* @create 2021/12/29 9:46
*/
public class ConfigMappingCMD {
private final ToolUtil toolUtil = new ToolUtil();
private final String configTableName = "uf_request_config";
private final SqlUtil sqlUtil = new SqlUtil();
public RequestMappingConfig selectByUniqueCode(String uniqueCode) {
toolUtil.writeDebuggerLog("=======================查询配置列表=======================");
RequestMappingConfig requestMappingConfig = new RequestMappingConfig();
RecordSet recordSet = new RecordSet();
String querySql = "select id,workflow,requestUrl,dataSource,uniqueCode, relationWorkFlow,cusWhereSql from " + configTableName + " where uniqueCode = ?";
toolUtil.writeDebuggerLog("执行查询的sql query mainRequestMappingConfig list sql new>>>>" + querySql + " uniqueCode >>" + uniqueCode);
recordSet.executeQuery(querySql, uniqueCode);
if (recordSet.next()) {
int mainId = Util.getIntValue(recordSet.getString("id"));
requestMappingConfig = sqlUtil.recordSetToEntityByEntity(recordSet, RequestMappingConfig.class);
this.setDetailMapping(mainId, requestMappingConfig);
}
return requestMappingConfig;
}
private void setDetailMapping(int mainId, RequestMappingConfig requestMappingConfig) {
// 查询明细1的信息
RecordSet detail1RecordSet = new RecordSet();
String dataSource = requestMappingConfig.getDataSource();
if (Objects.isNull(dataSource) || "".equals(dataSource)) {
dataSource = "0";
}
DataSourceEnum anEnum = DataSourceEnum.getEnum(dataSource);
String queryDetail1Sql = "";
switch (anEnum) {
case CUS_TABLE:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext," +
" from " + configTableName + "_dt1 config ";
break;
case WORKFLOW:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,valueContext,relationWorkFlowField, " +
" fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " +
" from " + configTableName + "_dt1 config " +
" left join workflow_field_table_view fv " +
" on config.workflowField = fv.id or config.relationWorkFlowField = fv.id" +
" where mainid = ? ";
break;
case MODEL:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext, " +
" fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " +
" from " + configTableName + "_dt1 config " +
" left join workflow_field_table_view fv on config.modelField = fv.id " +
" where mainid = ? ";
break;
default:
throw new ValueDealException("不支持的数据来源");
}
toolUtil.writeDebuggerLog("执行查询的明细1sql query detail1Sql >>>>" + queryDetail1Sql + " mainId:" + mainId);
detail1RecordSet.executeQuery(queryDetail1Sql, mainId);
List<MappingDetail> mappingDetails = new ArrayList<>();
while (detail1RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, MappingDetail.class);
String getValueType = mappingDetail.getGetValueType();
// 设置流程字段相关信息
// if("0".equals(getValueType) || "4".equals(getValueType)){
FieldMessage fieldMessage = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, FieldMessage.class);
mappingDetail.setFieldMassage(fieldMessage);
// }
mappingDetails.add(mappingDetail);
}
// 查询明细2的信息
RecordSet detail2RecordSet = new RecordSet();
String queryDetail2Sql = "select paramName,belongTo,childType,dataSource,detailId,cusWhereSql from uf_request_config_dt2 where mainid = ?";
toolUtil.writeDebuggerLog("执行查询的明细sql query detail2Sql >>>>" + queryDetail2Sql + " mainId:" + mainId);
detail2RecordSet.executeQuery(queryDetail2Sql, mainId);
while (detail2RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail2RecordSet, MappingDetail.class);
mappingDetail.setParamType("6");// 设置参数类型为List
mappingDetails.add(mappingDetail);
}
// 查询明细3的信息
RecordSet detail3RecordSet = new RecordSet();
String queryDetail3Sql = "select paramName,belongTo from uf_request_config_dt3 where mainid = ?";
toolUtil.writeDebuggerLog("执行查询的明细sql query detail3Sql >>>>" + queryDetail3Sql + " mainId:" + mainId);
detail3RecordSet.executeQuery(queryDetail3Sql, mainId);
while (detail3RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail3RecordSet, MappingDetail.class);
mappingDetail.setParamType("5");// 设置参数类型为Object
mappingDetails.add(mappingDetail);
}
requestMappingConfig.setConfigDetail(mappingDetails);
// //查询明细4的信息
// RecordSet detail4RecordSet = new RecordSet();
// List<ResponseMapping> responseMappingList = new ArrayList<>();
// String queryDetail4Sql = "select responseFieldName,workflowField,mainOrDetail,detailTableId,workflowFieldName from uf_request_config_dt4 where mainid = ?";
// toolUtil.writeDebuggerLog("执行查询的明细sql query detail4Sql >>>>"+queryDetail4Sql+" mainId:"+mainId);
// detail4RecordSet.executeQuery(queryDetail4Sql,mainId);
// while (detail4RecordSet.next()){
// ResponseMapping responseMapping = sqlUtil.recordSetToEntityByEntity(detail4RecordSet, ResponseMapping.class);
// responseMappingList.add(responseMapping);
// }
// requestMappingConfig.setResponseMappingList(responseMappingList);
requestMappingConfig.setConfigDetail(mappingDetails);
}
/**
* <h2></h2>
*
* @param docIds id
* @return
* @author YouHong.ai
*/
public List<DocImageFile> selectDocImageFileList(String docIds) {
String sql = "select docfile.IMAGEFILEID,docfile.IMAGEFILENAME,docfile.DOCID,docfile.ID, " +
" imf.FILESIZE " +
"from docimagefile docfile " +
"left join imagefile imf on imf.IMAGEFILEID = docfile.IMAGEFILEID " +
"where docid in (" + docIds + ")";
RecordSet rs = new RecordSet();
rs.executeQuery(sql);
List<DocImageFile> docImageFileList = new ArrayList<>();
while (rs.next()) {
String IMAGEFILEID = rs.getString("IMAGEFILEID");
String IMAGEFILENAME = rs.getString("IMAGEFILENAME");
String DOCID = rs.getString("DOCID");
String ID = rs.getString("ID");
String fileSize = rs.getString("FILESIZE");
DocImageFile docImageFile = new DocImageFile();
docImageFile.setImageFileId(Util.getIntValue(IMAGEFILEID));
docImageFile.setImageFileName(IMAGEFILENAME);
docImageFile.setDocId(Util.getIntValue(DOCID));
docImageFile.setId(Util.getIntValue(ID));
docImageFile.setFileSize(Util.getIntValue(fileSize) / 1024L);
docImageFileList.add(docImageFile);
}
if (docImageFileList.isEmpty()) {
throw new NullPointerException("附件字段不存在值!请检查数据表或配置表数据类型是否正确!");
}
return docImageFileList;
}
}

View File

@ -1,26 +1,26 @@
package weaver.xiao.commons.config.entity;
import lombok.Data;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
/**
* @author XiaoBokang
* @create 2021/12/31 10:15
*/
@Data
public class FieldMessage {
@SqlFieldMapping("fieldId")
private String fieldId;
@SqlFieldMapping("fieldName")
private String fieldName;
@SqlFieldMapping("indexDesc")
private String indexDesc;
@SqlFieldMapping("tableName")
private String tableName;
}
package weaver.xiao.commons.config.entity;
import lombok.Data;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
/**
* @author XiaoBokang
* @create 2021/12/31 10:15
*/
@Data
public class FieldMessage {
@SqlFieldMapping("fieldId")
private String fieldId;
@SqlFieldMapping("fieldName")
private String fieldName;
@SqlFieldMapping("indexDesc")
private String indexDesc;
@SqlFieldMapping("tableName")
private String tableName;
}

View File

@ -1,53 +1,53 @@
package weaver.xiao.commons.config.entity;
import lombok.Data;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
import java.util.List;
/**
* @author XiaoBokang
* @create 2021/12/28 17:45
*/
@Data
public class MappingDetail {
@SqlFieldMapping("paramName")
private String paramName;
@SqlFieldMapping("paramType")
private String paramType;
@SqlFieldMapping("getValueType")
private String getValueType;
@SqlFieldMapping("childType")
private String childType;
@SqlFieldMapping("dataSource")
private String dataSource;
@SqlFieldMapping("detailId")
private String detailId;
@SqlFieldMapping("belongTo")
private String belongTo;
@SqlFieldMapping("workflowField")
private String workflowField;
@SqlFieldMapping("valueContext")
private String valueContext;
@SqlFieldMapping("relationWorkFlowField")
private String relationWorkFlowField;
@SqlFieldMapping("cusWhereSql")
private String cusWhereSql;
private List<MappingDetail> childList;
private FieldMessage fieldMassage;
}
package weaver.xiao.commons.config.entity;
import lombok.Data;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
import java.util.List;
/**
* @author XiaoBokang
* @create 2021/12/28 17:45
*/
@Data
public class MappingDetail {
@SqlFieldMapping("paramName")
private String paramName;
@SqlFieldMapping("paramType")
private String paramType;
@SqlFieldMapping("getValueType")
private String getValueType;
@SqlFieldMapping("childType")
private String childType;
@SqlFieldMapping("dataSource")
private String dataSource;
@SqlFieldMapping("detailId")
private String detailId;
@SqlFieldMapping("belongTo")
private String belongTo;
@SqlFieldMapping("workflowField")
private String workflowField;
@SqlFieldMapping("valueContext")
private String valueContext;
@SqlFieldMapping("relationWorkFlowField")
private String relationWorkFlowField;
@SqlFieldMapping("cusWhereSql")
private String cusWhereSql;
private List<MappingDetail> childList;
private FieldMessage fieldMassage;
}

View File

@ -34,4 +34,14 @@ public class MultipartFile {
*
*/
Long fileSize;
/**
* id
*/
private Integer imageFileId;
/**
* docId
*/
private Integer docId;
}

View File

@ -1,48 +1,48 @@
package weaver.xiao.commons.config.entity;
import lombok.Data;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
import java.util.List;
/**
* @author XiaoBokang
* @create 2021/12/28 17:43
*/
@Data
public class RequestMappingConfig {
@SqlFieldMapping("workflow")
private String workflow;
@SqlFieldMapping("requestUrl")
private String requestUrl;
@SqlFieldMapping("uniqueCode")
private String uniqueCode;
@SqlFieldMapping("dataSource")
private String dataSource;
@SqlFieldMapping("modelId")
private String modelId;
@SqlFieldMapping("tableName")
private String tableName;
@SqlFieldMapping("urlDesc")
private String urlDesc;
@SqlFieldMapping("relationWorkFlow")
private String relationWorkFlow;
@SqlFieldMapping("cusWhereSql")
private String cusWhereSql;
private List<MappingDetail> configDetail;
private List<ResponseMapping> responseMappingList;
}
package weaver.xiao.commons.config.entity;
import lombok.Data;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
import java.util.List;
/**
* @author XiaoBokang
* @create 2021/12/28 17:43
*/
@Data
public class RequestMappingConfig {
@SqlFieldMapping("workflow")
private String workflow;
@SqlFieldMapping("requestUrl")
private String requestUrl;
@SqlFieldMapping("uniqueCode")
private String uniqueCode;
@SqlFieldMapping("dataSource")
private String dataSource;
@SqlFieldMapping("modelId")
private String modelId;
@SqlFieldMapping("tableName")
private String tableName;
@SqlFieldMapping("urlDesc")
private String urlDesc;
@SqlFieldMapping("relationWorkFlow")
private String relationWorkFlow;
@SqlFieldMapping("cusWhereSql")
private String cusWhereSql;
private List<MappingDetail> configDetail;
private List<ResponseMapping> responseMappingList;
}

View File

@ -1,17 +1,17 @@
package weaver.xiao.commons.config.entity;
import lombok.Data;
/**
* @author XiaoBokang
* @create 2022/4/12 22:28
*/
@Data
public class ResponseMapping {
private String responseFieldName;
private String workflowField;
private String mainOrDetail;
private String detailTableId;
private String workflowFieldName;
}
package weaver.xiao.commons.config.entity;
import lombok.Data;
/**
* @author XiaoBokang
* @create 2022/4/12 22:28
*/
@Data
public class ResponseMapping {
private String responseFieldName;
private String workflowField;
private String mainOrDetail;
private String detailTableId;
private String workflowFieldName;
}

View File

@ -1,35 +1,35 @@
package weaver.xiao.commons.config.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2022/6/14 12:26
*/
public enum DataSourceEnum {
WORKFLOW("0"),
MODEL("1"),
CUS_TABLE("2");
private static final Map<String, DataSourceEnum> LOOK_UP = new HashMap<>(8);
static {
for (DataSourceEnum dataSource : EnumSet.allOf(DataSourceEnum.class)){
LOOK_UP.put(dataSource.value,dataSource);
}
}
public final String value;
DataSourceEnum(String value){
this.value = value;
}
public static DataSourceEnum getEnum(String value){
return LOOK_UP.get(value);
}
}
package weaver.xiao.commons.config.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2022/6/14 12:26
*/
public enum DataSourceEnum {
WORKFLOW("0"),
MODEL("1"),
CUS_TABLE("2");
private static final Map<String, DataSourceEnum> LOOK_UP = new HashMap<>(8);
static {
for (DataSourceEnum dataSource : EnumSet.allOf(DataSourceEnum.class)){
LOOK_UP.put(dataSource.value,dataSource);
}
}
public final String value;
DataSourceEnum(String value){
this.value = value;
}
public static DataSourceEnum getEnum(String value){
return LOOK_UP.get(value);
}
}

View File

@ -1,44 +1,44 @@
package weaver.xiao.commons.config.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2022/6/14 13:13
*/
public enum GetValueTypeEnum {
WORKFLOW_FIELD("0"),
DEFAULT_VALUE("1"),
CURRENT_TIME("3"),
CUS_SQL("4"),
REQUEST_ID("5"),
MAIN_DATA_ID("6"),
RANDOM("7"),
ATTACHMENT("8"),
CUS_INTERFACE("9"),
CUS_FIELD("10");
private static final Map<String, GetValueTypeEnum> LOOK_UP = new HashMap<>(8);
static {
for (GetValueTypeEnum getValueTypeEnum : EnumSet.allOf(GetValueTypeEnum.class)) {
LOOK_UP.put(getValueTypeEnum.value, getValueTypeEnum);
}
}
public final String value;
GetValueTypeEnum(String value) {
this.value = value;
}
public static GetValueTypeEnum getEnum(String value) {
return LOOK_UP.get(value);
}
}
package weaver.xiao.commons.config.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2022/6/14 13:13
*/
public enum GetValueTypeEnum {
WORKFLOW_FIELD("0"),
DEFAULT_VALUE("1"),
CURRENT_TIME("3"),
CUS_SQL("4"),
REQUEST_ID("5"),
MAIN_DATA_ID("6"),
RANDOM("7"),
ATTACHMENT("8"),
CUS_INTERFACE("9"),
CUS_FIELD("10");
private static final Map<String, GetValueTypeEnum> LOOK_UP = new HashMap<>(8);
static {
for (GetValueTypeEnum getValueTypeEnum : EnumSet.allOf(GetValueTypeEnum.class)) {
LOOK_UP.put(getValueTypeEnum.value, getValueTypeEnum);
}
}
public final String value;
GetValueTypeEnum(String value) {
this.value = value;
}
public static GetValueTypeEnum getEnum(String value) {
return LOOK_UP.get(value);
}
}

View File

@ -1,43 +1,49 @@
package weaver.xiao.commons.config.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2022/6/14 12:56
*/
public enum ParamTypeEnum {
STRING("0"),
INT("1"),
DOUBLE("2"),
DATE("3"),
DATE_TIME("4"),
OBJECT("5"),
LIST("6"),
CUS_DATE_STR("7"),
TIME_STAMP("8"),
DATE_VAL("9"),
Boolean("10");
private static final Map<String, ParamTypeEnum> LOOK_UP = new HashMap<>(8);
static {
for (ParamTypeEnum paramTypeEnum : EnumSet.allOf(ParamTypeEnum.class)){
LOOK_UP.put(paramTypeEnum.value,paramTypeEnum);
}
}
public final String value;
ParamTypeEnum(String value){
this.value = value;
}
public static ParamTypeEnum getEnum(String value){
return LOOK_UP.get(value);
}
}
package weaver.xiao.commons.config.enumtype;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* <h1></h1>
* @author XiaoBokang
* @create 2022/6/14 12:56
* <h1> : </h1>
* <p>
* v2.0 xuanran.wang 2022-12-06
* Object
* </p>
*/
public enum ParamTypeEnum {
STRING("0"),
INT("1"),
DOUBLE("2"),
DATE("3"),
DATE_TIME("4"),
OBJECT("5"),
LIST("6"),
CUS_DATE_STR("7"),
TIME_STAMP("8"),
DATE_VAL("9"),
Boolean("10"),
Object("11");
private static final Map<String, ParamTypeEnum> LOOK_UP = new HashMap<>(8);
static {
for (ParamTypeEnum paramTypeEnum : EnumSet.allOf(ParamTypeEnum.class)){
LOOK_UP.put(paramTypeEnum.value,paramTypeEnum);
}
}
public final String value;
ParamTypeEnum(String value){
this.value = value;
}
public static ParamTypeEnum getEnum(String value){
return LOOK_UP.get(value);
}
}

View File

@ -1,21 +1,21 @@
package weaver.xiao.commons.exception;
/**
* @author XiaoBokang
* @create 2022/1/12 11:06
*/
public class RequestException extends RuntimeException{
public RequestException(String message){
super(message);
}
public RequestException(String message, Throwable cause) {
super(message, cause);
}
@Override
public synchronized Throwable fillInStackTrace() {
return super.fillInStackTrace();
}
}
package weaver.xiao.commons.exception;
/**
* @author XiaoBokang
* @create 2022/1/12 11:06
*/
public class RequestException extends RuntimeException{
public RequestException(String message){
super(message);
}
public RequestException(String message, Throwable cause) {
super(message, cause);
}
@Override
public synchronized Throwable fillInStackTrace() {
return super.fillInStackTrace();
}
}

View File

@ -1,22 +1,22 @@
package weaver.xiao.commons.exception;
/**
* @author XiaoBokang
* @create 2022/1/4 9:50
*/
public class ValueDealException extends RuntimeException{
public ValueDealException(String message){
super(message);
}
public ValueDealException(String message, Throwable cause) {
super(message, cause);
}
@Override
public synchronized Throwable fillInStackTrace() {
return super.fillInStackTrace();
}
}
package weaver.xiao.commons.exception;
/**
* @author XiaoBokang
* @create 2022/1/4 9:50
*/
public class ValueDealException extends RuntimeException{
public ValueDealException(String message){
super(message);
}
public ValueDealException(String message, Throwable cause) {
super(message, cause);
}
@Override
public synchronized Throwable fillInStackTrace() {
return super.fillInStackTrace();
}
}

View File

@ -1,70 +1,70 @@
package weaver.xiao.commons.utils;
import com.alibaba.fastjson.JSONObject;
/**
* @author XiaoBokang
* @create 2021/9/9 19:33
*/
public class JsonResult {
private Integer code;
private String message;
private Object Data;
public JsonResult(Integer code, String message, Object data) {
this.code = code;
this.message = message;
Data = data;
}
public static String success(String message){
return JSONObject.toJSONString(new JsonResult(200,message,null));
}
public static String success(){
return JSONObject.toJSONString(new JsonResult(200,"success",null));
}
public static String successData(String message,Object data){
return JSONObject.toJSONString(new JsonResult(200,message,data));
}
public static String successData(Object data){
return JSONObject.toJSONString(new JsonResult(200,"success",data));
}
public static String error(int code,String message){
return JSONObject.toJSONString(new JsonResult(code,message,null));
}
public static String error(String message){
return JSONObject.toJSONString(new JsonResult(500,message,null));
}
public static String error(){
return JSONObject.toJSONString(new JsonResult(500,"fail",null));
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return Data;
}
public void setData(Object data) {
Data = data;
}
}
package weaver.xiao.commons.utils;
import com.alibaba.fastjson.JSONObject;
/**
* @author XiaoBokang
* @create 2021/9/9 19:33
*/
public class JsonResult {
private Integer code;
private String message;
private Object Data;
public JsonResult(Integer code, String message, Object data) {
this.code = code;
this.message = message;
Data = data;
}
public static String success(String message){
return JSONObject.toJSONString(new JsonResult(200,message,null));
}
public static String success(){
return JSONObject.toJSONString(new JsonResult(200,"success",null));
}
public static String successData(String message,Object data){
return JSONObject.toJSONString(new JsonResult(200,message,data));
}
public static String successData(Object data){
return JSONObject.toJSONString(new JsonResult(200,"success",data));
}
public static String error(int code,String message){
return JSONObject.toJSONString(new JsonResult(code,message,null));
}
public static String error(String message){
return JSONObject.toJSONString(new JsonResult(500,message,null));
}
public static String error(){
return JSONObject.toJSONString(new JsonResult(500,"fail",null));
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return Data;
}
public void setData(Object data) {
Data = data;
}
}

View File

@ -1,73 +1,73 @@
package weaver.xiao.commons.utils;
import org.apache.log4j.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* @author XiaoBokang
* @create 2022/3/3 14:16
*/
public class LogUtil {
private static volatile Logger log = null;
public static Logger getLogger(){
return LogUtil.getLogger(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "util_cus" + File.separator + "cus.log");
}
/**
*
* @return
*/
public static Logger getLogger(String file) {
if (log == null) {
synchronized (LogUtil.class) {
if (log == null) {
DailyRollingFileAppender appender = new DailyRollingFileAppender();
log = Logger.getLogger("xbk_cus");
appender.setName("xbk_cus");
appender.setEncoding("UTF-8");
appender.setDatePattern("'_'yyyyMMdd'.log'");
appender.setFile(file);
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();
log.addAppender(appender);
boolean enableDebug = true;
if (!enableDebug) {
log.setLevel(Level.INFO);
}
}
}
}
return log;
}
public static Logger getSqlLogger(){
return LogUtil.getLogger(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "sql" + File.separator + "cussql.log");
}
/**
*
* @param throwable
* @return
*/
public static String getExceptionStr(Throwable throwable){
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter,true));
String s = stringWriter.getBuffer().toString();
try{
stringWriter.close();
}catch (Exception ignored){
ignored.printStackTrace();
}
return s;
}
}
package weaver.xiao.commons.utils;
import org.apache.log4j.*;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* @author XiaoBokang
* @create 2022/3/3 14:16
*/
public class LogUtil {
private static volatile Logger log = null;
public static Logger getLogger(){
return LogUtil.getLogger(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "util_cus" + File.separator + "cus.log");
}
/**
*
* @return
*/
public static Logger getLogger(String file) {
if (log == null) {
synchronized (LogUtil.class) {
if (log == null) {
DailyRollingFileAppender appender = new DailyRollingFileAppender();
log = Logger.getLogger("xbk_cus");
appender.setName("xbk_cus");
appender.setEncoding("UTF-8");
appender.setDatePattern("'_'yyyyMMdd'.log'");
appender.setFile(file);
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();
log.addAppender(appender);
boolean enableDebug = true;
if (!enableDebug) {
log.setLevel(Level.INFO);
}
}
}
}
return log;
}
public static Logger getSqlLogger(){
return LogUtil.getLogger(weaver.general.GCONST.getLogPath() + "cus" + File.separator + "sql" + File.separator + "cussql.log");
}
/**
*
* @param throwable
* @return
*/
public static String getExceptionStr(Throwable throwable){
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter,true));
String s = stringWriter.getBuffer().toString();
try{
stringWriter.close();
}catch (Exception ignored){
ignored.printStackTrace();
}
return s;
}
}

View File

@ -1,26 +1,26 @@
package weaver.xiao.commons.utils;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2021/8/20 14:01
*/
public class PreMap extends HashMap<String,Object> implements Map<String,Object> {
public PreMap(){
super();
}
public static PreMap create(){
return new PreMap();
}
@Override
public PreMap put(String key, Object value){
super.put(key,value);
return this;
}
}
package weaver.xiao.commons.utils;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2021/8/20 14:01
*/
public class PreMap extends HashMap<String,Object> implements Map<String,Object> {
public PreMap(){
super();
}
public static PreMap create(){
return new PreMap();
}
@Override
public PreMap put(String key, Object value){
super.put(key,value);
return this;
}
}

View File

@ -1,57 +1,57 @@
package weaver.xiao.commons.utils;
import weaver.common.util.string.StringUtil;
import weaver.general.GCONST;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @author XiaoBokang
* @create 2022/3/10 11:13
*/
public class PropUtil {
/**
* map
* @param fileName prop/.properties
* @return map
*/
public static Map<String, Object> getProperties2Map(String fileName) {
String propertyPath = GCONST.getPropertyPath();
if (StringUtil.isNullOrEmpty(fileName)) {
return null;
}
if (fileName.contains(".properties")) {
fileName = fileName.replace(".properties", "");
}
String path = propertyPath + File.separator + fileName + ".properties";
Properties prop = new Properties();
Map<String, Object> map = new HashMap<>();
InputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(path));
prop.load(inputStream);
Enumeration<?> enumeration = prop.propertyNames();
while (enumeration.hasMoreElements()) {
String key = String.valueOf(enumeration.nextElement());
map.put(key, prop.getProperty(key));
}
} catch (IOException e) {
throw new RuntimeException("找不到文件:" + path);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
}
package weaver.xiao.commons.utils;
import weaver.common.util.string.StringUtil;
import weaver.general.GCONST;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @author XiaoBokang
* @create 2022/3/10 11:13
*/
public class PropUtil {
/**
* map
* @param fileName prop/.properties
* @return map
*/
public static Map<String, Object> getProperties2Map(String fileName) {
String propertyPath = GCONST.getPropertyPath();
if (StringUtil.isNullOrEmpty(fileName)) {
return null;
}
if (fileName.contains(".properties")) {
fileName = fileName.replace(".properties", "");
}
String path = propertyPath + File.separator + fileName + ".properties";
Properties prop = new Properties();
Map<String, Object> map = new HashMap<>();
InputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(path));
prop.load(inputStream);
Enumeration<?> enumeration = prop.propertyNames();
while (enumeration.hasMoreElements()) {
String key = String.valueOf(enumeration.nextElement());
map.put(key, prop.getProperty(key));
}
} catch (IOException e) {
throw new RuntimeException("找不到文件:" + path);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
}

View File

@ -1,59 +1,59 @@
package weaver.xiao.commons.utils;
import lombok.Data;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2021/8/23 16:34
*/
@Data
public class RequestBaseInfo{
private String type;
private String url;
private Object params;
private InputStream[] inputStreams;
private String[] fileNames;
private String fileField;
private Map<String,String > headers;
private static final Map<String,String > HEADER_NORMAL = new HashMap<>();
private static final Map<String,Object > PARAMS_NORMAL = new HashMap<>();
public static RequestBaseInfo create(String type, String url){
return create(type,url,HEADER_NORMAL,PARAMS_NORMAL);
}
public static RequestBaseInfo create(String type, String url, Map<String, String> headers){
return create(type,url,headers,PARAMS_NORMAL);
}
public static RequestBaseInfo create(String type, String url, Map<String, String> headers, Object params){
RequestBaseInfo requestInfo = new RequestBaseInfo();
requestInfo.setType(type.toUpperCase());
requestInfo.setUrl(url);
requestInfo.setParams(params);
requestInfo.setHeaders(headers);
return requestInfo;
}
public static RequestBaseInfo createByFile(String type, String url, Map<String, String> headers, Object params, InputStream[] inputStreams, String fileField, String[] fileNames){
RequestBaseInfo requestInfo = new RequestBaseInfo();
requestInfo.setType(type.toUpperCase());
requestInfo.setUrl(url);
requestInfo.setParams(params);
requestInfo.setHeaders(headers);
requestInfo.setInputStreams(inputStreams);
requestInfo.setFileNames(fileNames);
requestInfo.setFileField(fileField);
return requestInfo;
}
}
package weaver.xiao.commons.utils;
import lombok.Data;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2021/8/23 16:34
*/
@Data
public class RequestBaseInfo{
private String type;
private String url;
private Object params;
private InputStream[] inputStreams;
private String[] fileNames;
private String fileField;
private Map<String,String > headers;
private static final Map<String,String > HEADER_NORMAL = new HashMap<>();
private static final Map<String,Object > PARAMS_NORMAL = new HashMap<>();
public static RequestBaseInfo create(String type, String url){
return create(type,url,HEADER_NORMAL,PARAMS_NORMAL);
}
public static RequestBaseInfo create(String type, String url, Map<String, String> headers){
return create(type,url,headers,PARAMS_NORMAL);
}
public static RequestBaseInfo create(String type, String url, Map<String, String> headers, Object params){
RequestBaseInfo requestInfo = new RequestBaseInfo();
requestInfo.setType(type.toUpperCase());
requestInfo.setUrl(url);
requestInfo.setParams(params);
requestInfo.setHeaders(headers);
return requestInfo;
}
public static RequestBaseInfo createByFile(String type, String url, Map<String, String> headers, Object params, InputStream[] inputStreams, String fileField, String[] fileNames){
RequestBaseInfo requestInfo = new RequestBaseInfo();
requestInfo.setType(type.toUpperCase());
requestInfo.setUrl(url);
requestInfo.setParams(params);
requestInfo.setHeaders(headers);
requestInfo.setInputStreams(inputStreams);
requestInfo.setFileNames(fileNames);
requestInfo.setFileField(fileField);
return requestInfo;
}
}

View File

@ -1,165 +1,165 @@
package weaver.xiao.commons.utils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import weaver.xiao.commons.exception.RequestException;
import weaver.zwl.common.ToolUtil;
import weaver.wechat.request.HttpManager;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2021/8/9 10:09
*/
public class RequestUtil {
public static <T> T apiRequest(RequestBaseInfo requestInfo, Class<T> tClass){
Map<String,String> headers = requestInfo.getHeaders();
T result = null;
switch(requestInfo.getType()){
case "GET" :{
String sendUrl = serializableUrl(requestInfo.getUrl(), (Map<String, Object>) requestInfo.getParams());
HttpGet httpGet = new HttpGet(sendUrl);
headers.forEach(httpGet::setHeader);
result = apiSend(httpGet,tClass);
}break;
case "POST" :{
HttpPost httpPost = new HttpPost(requestInfo.getUrl());
headers.forEach(httpPost::setHeader);
httpPost.setEntity(new StringEntity(JSON.toJSONString(requestInfo.getParams()),"UTF-8"));
new ToolUtil().writeErrorLog("请求信息url:"+requestInfo.getUrl()+" params:"+JSON.toJSONString(requestInfo.getParams()));
result = apiSend(httpPost,tClass);}break;
case "PUT" :{
HttpPut httpPut = new HttpPut(requestInfo.getUrl());
headers.forEach(httpPut::setHeader);
httpPut.setEntity(new StringEntity(JSON.toJSONString(requestInfo.getParams()),"UTF-8"));
result = apiSend(httpPut,tClass);}break;
}
return result;
}
public static <T> T POSTBySerializableUrl(RequestBaseInfo requestInfo, Class<T> tClass){
T result = null;
Map<String,String> headers = requestInfo.getHeaders();
String url = serializableUrl(requestInfo.getUrl(), (Map<String, Object>) requestInfo.getParams());
HttpPost httpPost = new HttpPost(url);
headers.forEach(httpPost::setHeader);
new ToolUtil().writeErrorLog("请求信息url:"+requestInfo.getUrl()+" params:"+JSON.toJSONString(requestInfo.getParams()));
result = apiSend(httpPost,tClass);
return result;
}
public static <T> T apiUploadFileByInputStream(RequestBaseInfo requestInfo, Class<T> tClass){
Map<String,Object> params = (Map<String, Object>) requestInfo.getParams();
HttpPost httpPost = new HttpPost(requestInfo.getUrl());
requestInfo.getHeaders().forEach(httpPost::setHeader);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
InputStream[] inputStreams = requestInfo.getInputStreams();
String[] fileNames = requestInfo.getFileNames();
for (int i = 0; i < inputStreams.length; i++) {
builder.addBinaryBody(requestInfo.getFileField(),inputStreams[i],ContentType.MULTIPART_FORM_DATA,fileNames[i]);
}
params.forEach((k,v)->{
builder.addTextBody(k,JSON.toJSONString(v),ContentType.create(MediaType.TEXT_PLAIN,"UTF-8"));
});
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return apiSend(httpPost,tClass);
}
public static <T> T apiSend(
HttpUriRequest httpRequest,
Class<T> resClass
){
DefaultHttpClient httpClient = HttpManager.getHttpClient();
CloseableHttpResponse execute = null;
T res = null;
try {
new ToolUtil().writeDebuggerLog("开始发送请求request start -----------------");
execute = httpClient.execute(httpRequest);
if(execute.getStatusLine().getStatusCode() == 200){
new ToolUtil().writeDebuggerLog("请求发送成功request send success -----------------");
HttpEntity entity = execute.getEntity();
String response= EntityUtils.toString(entity,"utf-8");
// ObjectMapper mapper = new ObjectMapper();
// CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Map.class);
// List<Map<String,Object>> list = mapper.readValue(response, listType);
// result.put("res",list);
if(resClass.equals(String.class)){
return (T) response;
}else {
ObjectMapper objectMapper = new ObjectMapper();
res = objectMapper.readValue(response, resClass);
}
}else {
HttpEntity entity = execute.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
new ToolUtil().writeDebuggerLog("请求状态不为200返回信息为"+response);
throw new RequestException("请求状态异常:"+response);
}
} catch (IOException e) {
new ToolUtil().writeDebuggerLog("请求发生异常 request error>>>"+e);
try {
if(execute != null) {
execute.close();
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
e.printStackTrace();
throw new RequestException("请求调用异常:"+e);
}
return res;
}
public static String serializableUrl(String url,Map<String,Object> params){
if(params == null || params.isEmpty()){
return url;
}
url += "?";
for (Map.Entry entry: params.entrySet()){
url += entry.getKey() + "=" + entry.getValue() + "&";
}
return url.substring(0,url.length()-1);
}
/**
*
* @param throwable
* @return
*/
public static String getExceptionStr(Throwable throwable){
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter,true));
String s = stringWriter.getBuffer().toString();
try{
stringWriter.close();
}catch (Exception ignored){
ignored.printStackTrace();
}
return s;
}
}
package weaver.xiao.commons.utils;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import weaver.xiao.commons.exception.RequestException;
import weaver.zwl.common.ToolUtil;
import weaver.wechat.request.HttpManager;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author XiaoBokang
* @create 2021/8/9 10:09
*/
public class RequestUtil {
public static <T> T apiRequest(RequestBaseInfo requestInfo, Class<T> tClass){
Map<String,String> headers = requestInfo.getHeaders();
T result = null;
switch(requestInfo.getType()){
case "GET" :{
String sendUrl = serializableUrl(requestInfo.getUrl(), (Map<String, Object>) requestInfo.getParams());
HttpGet httpGet = new HttpGet(sendUrl);
headers.forEach(httpGet::setHeader);
result = apiSend(httpGet,tClass);
}break;
case "POST" :{
HttpPost httpPost = new HttpPost(requestInfo.getUrl());
headers.forEach(httpPost::setHeader);
httpPost.setEntity(new StringEntity(JSON.toJSONString(requestInfo.getParams()),"UTF-8"));
new ToolUtil().writeErrorLog("请求信息url:"+requestInfo.getUrl()+" params:"+JSON.toJSONString(requestInfo.getParams()));
result = apiSend(httpPost,tClass);}break;
case "PUT" :{
HttpPut httpPut = new HttpPut(requestInfo.getUrl());
headers.forEach(httpPut::setHeader);
httpPut.setEntity(new StringEntity(JSON.toJSONString(requestInfo.getParams()),"UTF-8"));
result = apiSend(httpPut,tClass);}break;
}
return result;
}
public static <T> T POSTBySerializableUrl(RequestBaseInfo requestInfo, Class<T> tClass){
T result = null;
Map<String,String> headers = requestInfo.getHeaders();
String url = serializableUrl(requestInfo.getUrl(), (Map<String, Object>) requestInfo.getParams());
HttpPost httpPost = new HttpPost(url);
headers.forEach(httpPost::setHeader);
new ToolUtil().writeErrorLog("请求信息url:"+requestInfo.getUrl()+" params:"+JSON.toJSONString(requestInfo.getParams()));
result = apiSend(httpPost,tClass);
return result;
}
public static <T> T apiUploadFileByInputStream(RequestBaseInfo requestInfo, Class<T> tClass){
Map<String,Object> params = (Map<String, Object>) requestInfo.getParams();
HttpPost httpPost = new HttpPost(requestInfo.getUrl());
requestInfo.getHeaders().forEach(httpPost::setHeader);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
InputStream[] inputStreams = requestInfo.getInputStreams();
String[] fileNames = requestInfo.getFileNames();
for (int i = 0; i < inputStreams.length; i++) {
builder.addBinaryBody(requestInfo.getFileField(),inputStreams[i],ContentType.MULTIPART_FORM_DATA,fileNames[i]);
}
params.forEach((k,v)->{
builder.addTextBody(k,JSON.toJSONString(v),ContentType.create(MediaType.TEXT_PLAIN,"UTF-8"));
});
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return apiSend(httpPost,tClass);
}
public static <T> T apiSend(
HttpUriRequest httpRequest,
Class<T> resClass
){
DefaultHttpClient httpClient = HttpManager.getHttpClient();
CloseableHttpResponse execute = null;
T res = null;
try {
new ToolUtil().writeDebuggerLog("开始发送请求request start -----------------");
execute = httpClient.execute(httpRequest);
if(execute.getStatusLine().getStatusCode() == 200){
new ToolUtil().writeDebuggerLog("请求发送成功request send success -----------------");
HttpEntity entity = execute.getEntity();
String response= EntityUtils.toString(entity,"utf-8");
// ObjectMapper mapper = new ObjectMapper();
// CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Map.class);
// List<Map<String,Object>> list = mapper.readValue(response, listType);
// result.put("res",list);
if(resClass.equals(String.class)){
return (T) response;
}else {
ObjectMapper objectMapper = new ObjectMapper();
res = objectMapper.readValue(response, resClass);
}
}else {
HttpEntity entity = execute.getEntity();
String response = EntityUtils.toString(entity,"utf-8");
new ToolUtil().writeDebuggerLog("请求状态不为200返回信息为"+response);
throw new RequestException("请求状态异常:"+response);
}
} catch (IOException e) {
new ToolUtil().writeDebuggerLog("请求发生异常 request error>>>"+e);
try {
if(execute != null) {
execute.close();
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
e.printStackTrace();
throw new RequestException("请求调用异常:"+e);
}
return res;
}
public static String serializableUrl(String url,Map<String,Object> params){
if(params == null || params.isEmpty()){
return url;
}
url += "?";
for (Map.Entry entry: params.entrySet()){
url += entry.getKey() + "=" + entry.getValue() + "&";
}
return url.substring(0,url.length()-1);
}
/**
*
* @param throwable
* @return
*/
public static String getExceptionStr(Throwable throwable){
StringWriter stringWriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringWriter,true));
String s = stringWriter.getBuffer().toString();
try{
stringWriter.close();
}catch (Exception ignored){
ignored.printStackTrace();
}
return s;
}
}

View File

@ -1,260 +1,260 @@
package weaver.xiao.commons.utils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author XiaoBokang
* @create 2021/12/7 14:19
*/
public class SqlUtil {
private final Logger logger = LogUtil.getSqlLogger();
ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance();
ModeRightInfo mri = new ModeRightInfo();
/**
*
* @param recordSet
* @param tClass
* @param <T>
* @return
*/
public <T> T recordSetToEntityByEntity(RecordSet recordSet, Class<T> tClass){
T res = null;
try{
String[] columnNames = recordSet.getColumnName();
if(tClass.equals(Map.class)){
Map<String,Object> tempRes = new HashMap<>();
for (String columnName : columnNames) {
tempRes.put(columnName,recordSet.getString(columnName));
}
res = (T) tempRes;
}else {
Field[] declaredFields = tClass.getDeclaredFields();
res = tClass.newInstance();
for (Field field : declaredFields) {
field.setAccessible(true);
SqlFieldMapping annotation = field.getAnnotation(SqlFieldMapping.class);
Class<?> fieldType = field.getType();
if(annotation != null){
String value = annotation.value();
int type = annotation.type();
Object valueText = null;
switch (type){
case 1:{
String tempValue = Util.null2String(recordSet.getString(value));
valueText = this.getFieldVal(fieldType,tempValue);
}break;
case 2:{
valueText = this.getFieldVal(fieldType,value);
}break;
}
field.set(res,valueText);
}
}
}
}catch (Exception e){
logger.info("转换实体类异常:"+e);
}
return res;
}
/**
*
* @param fieldType
* @param tempValue
* @return
*/
public Object getFieldVal(Class<?> fieldType,String tempValue){
Object fieldVal = null;
if(fieldType.equals(int.class)){
fieldVal = Util.getIntValue(tempValue);
}else if(fieldType.equals(String.class)){
fieldVal = Util.null2String(tempValue);
}else if(fieldType.equals(boolean.class)){
fieldVal = Boolean.parseBoolean(tempValue);
}else {
fieldVal = "";
}
return fieldVal;
}
/**
*
* @param tableName
* @param updateParam
* @param whereParam
* @return
*/
public boolean updateMode(String tableName, Map<String, Object> updateParam, Map<String, Object> whereParam) {
RecordSet recordSet = new RecordSet();
List<Object> paramList = new ArrayList<>();
String updateSql = buildUpdateSql(tableName, updateParam, whereParam, paramList);
logger.info("向表"+tableName+"更新数据>>>" + updateSql + " param:" + paramList);
boolean updateFlag = recordSet.executeUpdate(updateSql, paramList);
logger.info("更新标识:" + updateFlag);
return updateFlag;
}
/**
* sql,
* @param tableName
* @param updateParam
* @param whereParam
* @param paramList
* @return
*/
public String buildUpdateSql(String tableName, Map<String, Object> updateParam, Map<String, Object> whereParam,List<Object> paramList){
StringBuilder updateBuilder = new StringBuilder("update ");
updateBuilder.append(tableName).append(" set ");
Set<Map.Entry<String, Object>> updateEntries = updateParam.entrySet();
for (Map.Entry<String, Object> updateEntry : updateEntries) {
updateBuilder.append(updateEntry.getKey())
.append(" = ?,");
paramList.add(updateEntry.getValue());
}
StringBuilder whereBuilder = new StringBuilder();
Set<Map.Entry<String, Object>> whereEntries = whereParam.entrySet();
for (Map.Entry<String, Object> whereEntry : whereEntries) {
whereBuilder.append(" and ")
.append(whereEntry.getKey())
.append(" = ? ");
paramList.add(whereEntry.getValue());
}
String preStr = updateBuilder.substring(0, updateBuilder.length() - 1) + " ";
String fixStr = whereBuilder.toString();
if(!"".equals(fixStr)){
fixStr = fixStr.replaceFirst(" and "," where ");
}
return preStr + fixStr;
}
/**
*
* @param tableName
* @param insertParam
* @return
*/
public boolean insertTable(String tableName, Map<String, Object> insertParam) {
RecordSet recordSet = new RecordSet();
//构建新建sql语句,收集参数信息
List<Object> paramList = new ArrayList<>();
String insertSql = buildInsetSql(tableName, insertParam, paramList);
logger.info("向表"+tableName+"插入数据>>>" + insertSql + " param:" + paramList);
boolean flag = recordSet.executeUpdate(insertSql, paramList);
logger.info("插入标识:" + flag);
return flag;
}
/**
* sql,
* @param tableName
* @param insertParam
* @param paramList
* @return
*/
public String buildInsetSql(String tableName, Map<String, Object> insertParam,List<Object> paramList){
StringBuilder suffixBuilder = new StringBuilder();
StringBuilder prefixBuilder = new StringBuilder();
prefixBuilder.append("insert into ")
.append(tableName).append("(");
suffixBuilder.append(" values (");
Set<Map.Entry<String, Object>> entries = insertParam.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
prefixBuilder.append(key).append(",");
suffixBuilder.append("?,");
paramList.add(value);
}
String suffixString = suffixBuilder.substring(0, suffixBuilder.length() - 1);
String prefixString = prefixBuilder.substring(0, prefixBuilder.length() - 1);
String insertSql = prefixString + ")" + suffixString+")";
return insertSql;
}
/**
*
* @param tableName
* @param param
* @param modeId id
* @return
*/
public int insertToMode(String tableName,Map<String,Object> param,String modeId){
logger.info("=====插入建模信息====");
if(modeId == null || "".equals(modeId)) {
modeId = this.getModeIdByTableName(tableName);
}
logger.info("通过表名获取modeId ==>modeId"+modeId+" tableName==>"+tableName);
Map<String,Object> whereParam = new HashMap<>();
int dataId = mdu.getModeDataNewId(tableName, Util.getIntValue(modeId,-1), 1, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString());
whereParam.put("id",dataId);
boolean updateFlag = this.updateMode(tableName, param, whereParam);
if(updateFlag){
mri.rebuildModeDataShareByEdit(1, Util.getIntValue(modeId,-1),dataId);
}else {
logger.info("更新失败,从表==>"+tableName+" 删除数据:"+dataId);
String deleteSql = "delete from "+tableName+" where id = ?";
RecordSet deleteRecordSet = new RecordSet();
deleteRecordSet.executeUpdate(deleteSql,dataId);
}
return dataId;
}
/**
*
* @param tableName
* @param param
* @param modeId id
* @return
*/
public int insertToModeNoRight(String tableName,Map<String,Object> param,String modeId){
logger.info("=====插入建模信息====");
if(modeId == null || "".equals(modeId)) {
modeId = this.getModeIdByTableName(tableName);
}
logger.info("通过表名获取modeId ==>modeId"+modeId+" tableName==>"+tableName);
Map<String,Object> whereParam = new HashMap<>();
int dataId = mdu.getModeDataNewId(tableName, Util.getIntValue(modeId,-1), 1, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString());
whereParam.put("id",dataId);
boolean updateFlag = this.updateMode(tableName, param, whereParam);
if(updateFlag){
return dataId;
}else {
logger.info("更新失败,从表==>"+tableName+" 删除数据:"+dataId);
String deleteSql = "delete from "+tableName+" where id = ?";
RecordSet deleteRecordSet = new RecordSet();
deleteRecordSet.executeUpdate(deleteSql,dataId);
}
return -1;
}
/**
* id
* @param tableName
* @return
*/
public String getModeIdByTableName(String tableName){
String modeId = "";
String querySql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = ?)";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(querySql,tableName);
if(recordSet.next()){
modeId = Util.null2String(recordSet.getString("id"));
}
return modeId;
}
}
package weaver.xiao.commons.utils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.xiao.commons.utils.annotation.SqlFieldMapping;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author XiaoBokang
* @create 2021/12/7 14:19
*/
public class SqlUtil {
private final Logger logger = LogUtil.getSqlLogger();
ModeDataIdUpdate mdu = ModeDataIdUpdate.getInstance();
ModeRightInfo mri = new ModeRightInfo();
/**
*
* @param recordSet
* @param tClass
* @param <T>
* @return
*/
public <T> T recordSetToEntityByEntity(RecordSet recordSet, Class<T> tClass){
T res = null;
try{
String[] columnNames = recordSet.getColumnName();
if(tClass.equals(Map.class)){
Map<String,Object> tempRes = new HashMap<>();
for (String columnName : columnNames) {
tempRes.put(columnName,recordSet.getString(columnName));
}
res = (T) tempRes;
}else {
Field[] declaredFields = tClass.getDeclaredFields();
res = tClass.newInstance();
for (Field field : declaredFields) {
field.setAccessible(true);
SqlFieldMapping annotation = field.getAnnotation(SqlFieldMapping.class);
Class<?> fieldType = field.getType();
if(annotation != null){
String value = annotation.value();
int type = annotation.type();
Object valueText = null;
switch (type){
case 1:{
String tempValue = Util.null2String(recordSet.getString(value));
valueText = this.getFieldVal(fieldType,tempValue);
}break;
case 2:{
valueText = this.getFieldVal(fieldType,value);
}break;
}
field.set(res,valueText);
}
}
}
}catch (Exception e){
logger.info("转换实体类异常:"+e);
}
return res;
}
/**
*
* @param fieldType
* @param tempValue
* @return
*/
public Object getFieldVal(Class<?> fieldType,String tempValue){
Object fieldVal = null;
if(fieldType.equals(int.class)){
fieldVal = Util.getIntValue(tempValue);
}else if(fieldType.equals(String.class)){
fieldVal = Util.null2String(tempValue);
}else if(fieldType.equals(boolean.class)){
fieldVal = Boolean.parseBoolean(tempValue);
}else {
fieldVal = "";
}
return fieldVal;
}
/**
*
* @param tableName
* @param updateParam
* @param whereParam
* @return
*/
public boolean updateMode(String tableName, Map<String, Object> updateParam, Map<String, Object> whereParam) {
RecordSet recordSet = new RecordSet();
List<Object> paramList = new ArrayList<>();
String updateSql = buildUpdateSql(tableName, updateParam, whereParam, paramList);
logger.info("向表"+tableName+"更新数据>>>" + updateSql + " param:" + paramList);
boolean updateFlag = recordSet.executeUpdate(updateSql, paramList);
logger.info("更新标识:" + updateFlag);
return updateFlag;
}
/**
* sql,
* @param tableName
* @param updateParam
* @param whereParam
* @param paramList
* @return
*/
public String buildUpdateSql(String tableName, Map<String, Object> updateParam, Map<String, Object> whereParam,List<Object> paramList){
StringBuilder updateBuilder = new StringBuilder("update ");
updateBuilder.append(tableName).append(" set ");
Set<Map.Entry<String, Object>> updateEntries = updateParam.entrySet();
for (Map.Entry<String, Object> updateEntry : updateEntries) {
updateBuilder.append(updateEntry.getKey())
.append(" = ?,");
paramList.add(updateEntry.getValue());
}
StringBuilder whereBuilder = new StringBuilder();
Set<Map.Entry<String, Object>> whereEntries = whereParam.entrySet();
for (Map.Entry<String, Object> whereEntry : whereEntries) {
whereBuilder.append(" and ")
.append(whereEntry.getKey())
.append(" = ? ");
paramList.add(whereEntry.getValue());
}
String preStr = updateBuilder.substring(0, updateBuilder.length() - 1) + " ";
String fixStr = whereBuilder.toString();
if(!"".equals(fixStr)){
fixStr = fixStr.replaceFirst(" and "," where ");
}
return preStr + fixStr;
}
/**
*
* @param tableName
* @param insertParam
* @return
*/
public boolean insertTable(String tableName, Map<String, Object> insertParam) {
RecordSet recordSet = new RecordSet();
//构建新建sql语句,收集参数信息
List<Object> paramList = new ArrayList<>();
String insertSql = buildInsetSql(tableName, insertParam, paramList);
logger.info("向表"+tableName+"插入数据>>>" + insertSql + " param:" + paramList);
boolean flag = recordSet.executeUpdate(insertSql, paramList);
logger.info("插入标识:" + flag);
return flag;
}
/**
* sql,
* @param tableName
* @param insertParam
* @param paramList
* @return
*/
public String buildInsetSql(String tableName, Map<String, Object> insertParam,List<Object> paramList){
StringBuilder suffixBuilder = new StringBuilder();
StringBuilder prefixBuilder = new StringBuilder();
prefixBuilder.append("insert into ")
.append(tableName).append("(");
suffixBuilder.append(" values (");
Set<Map.Entry<String, Object>> entries = insertParam.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
Object value = entry.getValue();
prefixBuilder.append(key).append(",");
suffixBuilder.append("?,");
paramList.add(value);
}
String suffixString = suffixBuilder.substring(0, suffixBuilder.length() - 1);
String prefixString = prefixBuilder.substring(0, prefixBuilder.length() - 1);
String insertSql = prefixString + ")" + suffixString+")";
return insertSql;
}
/**
*
* @param tableName
* @param param
* @param modeId id
* @return
*/
public int insertToMode(String tableName,Map<String,Object> param,String modeId){
logger.info("=====插入建模信息====");
if(modeId == null || "".equals(modeId)) {
modeId = this.getModeIdByTableName(tableName);
}
logger.info("通过表名获取modeId ==>modeId"+modeId+" tableName==>"+tableName);
Map<String,Object> whereParam = new HashMap<>();
int dataId = mdu.getModeDataNewId(tableName, Util.getIntValue(modeId,-1), 1, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString());
whereParam.put("id",dataId);
boolean updateFlag = this.updateMode(tableName, param, whereParam);
if(updateFlag){
mri.rebuildModeDataShareByEdit(1, Util.getIntValue(modeId,-1),dataId);
}else {
logger.info("更新失败,从表==>"+tableName+" 删除数据:"+dataId);
String deleteSql = "delete from "+tableName+" where id = ?";
RecordSet deleteRecordSet = new RecordSet();
deleteRecordSet.executeUpdate(deleteSql,dataId);
}
return dataId;
}
/**
*
* @param tableName
* @param param
* @param modeId id
* @return
*/
public int insertToModeNoRight(String tableName,Map<String,Object> param,String modeId){
logger.info("=====插入建模信息====");
if(modeId == null || "".equals(modeId)) {
modeId = this.getModeIdByTableName(tableName);
}
logger.info("通过表名获取modeId ==>modeId"+modeId+" tableName==>"+tableName);
Map<String,Object> whereParam = new HashMap<>();
int dataId = mdu.getModeDataNewId(tableName, Util.getIntValue(modeId,-1), 1, 0, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString());
whereParam.put("id",dataId);
boolean updateFlag = this.updateMode(tableName, param, whereParam);
if(updateFlag){
return dataId;
}else {
logger.info("更新失败,从表==>"+tableName+" 删除数据:"+dataId);
String deleteSql = "delete from "+tableName+" where id = ?";
RecordSet deleteRecordSet = new RecordSet();
deleteRecordSet.executeUpdate(deleteSql,dataId);
}
return -1;
}
/**
* id
* @param tableName
* @return
*/
public String getModeIdByTableName(String tableName){
String modeId = "";
String querySql = "select id from modeinfo where formid = (select id from workflow_bill where tablename = ?)";
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(querySql,tableName);
if(recordSet.next()){
modeId = Util.null2String(recordSet.getString("id"));
}
return modeId;
}
}

View File

@ -1,21 +1,21 @@
package weaver.xiao.commons.utils.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author XiaoBokang
* @create 2022/5/10 18:22
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SqlFieldMapping {
/** 字段所属 1:数据库值2:默认值 */
int type() default 1;
/** 数据库字段名或默认值 */
String value();
}
package weaver.xiao.commons.utils.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author XiaoBokang
* @create 2022/5/10 18:22
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SqlFieldMapping {
/** 字段所属 1:数据库值2:默认值 */
int type() default 1;
/** 数据库字段名或默认值 */
String value();
}

View File

@ -6,7 +6,7 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <h1></h1>
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/11/25 15:55
@ -14,6 +14,12 @@ import java.lang.annotation.Target;
@Target({ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CusDateFormat {
/**
* <h2></h2>
**/
String from();
/**
* <h2></h2>
**/
String to() default "yyyy-MM-dd";
}

View File

@ -1,11 +1,9 @@
package weaver.xuanran.wang.common.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 java.util.List;
import java.util.Map;
/**
* @Author xuanran.wang
@ -43,4 +41,13 @@ public interface CommonMapper {
@Delete("delete from $t{tableName} where id in (${ids})")
boolean deleteModelDataByIds(@ParamMapper("tableName") String tableName,
@ParamMapper("ids") List<String> ids);
@Select("SELECT mp.id,m.formId,mpd.triggerWorkflowSetId " +
"FROM MODE_PageExpand mp " +
"INNER JOIN modeInfo m " +
"on mp.modeId = m.id " +
"LEFT JOIN mode_pageExpandDetail mpd " +
"ON mp.id = mpd.mainId " +
"WHERE mp.modeid = #{modelId} AND mp.isSystem = 1 AND mp.iSSystemFlag = 1")
Map<String, Integer> getExpendConfigByModeId(@ParamMapper("modelId") int modelId);
}

View File

@ -2,16 +2,24 @@ package weaver.xuanran.wang.common.util;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataApproval;
import weaver.hrm.User;
import weaver.xuanran.wang.common.annocation.CusDateFormat;
import weaver.xuanran.wang.common.annocation.ParamNotNull;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@ -26,12 +34,26 @@ import java.util.zip.ZipFile;
* @Date 2022/11/23 10:25
*/
public class CommonUtil {
private final Logger logger = Util.getLogger();
public static final int SQL_IN_PAGE_SIZE = 100;
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
/**
* <h2></h2>
**/
private static final Logger logger = Util.getLogger(CommonUtil.class.getName());
/**
* <h2>sqlin</h2>
**/
public static int SQL_IN_PAGE_SIZE = 100;
/**
* <h2></h2>
**/
public static int DEL_MAX_COUNT = 5;
/**
* <h2>线</h2>
**/
public static int THREAD_SLEEP = 200;
/**
* <h2>mapper</h2>
**/
private static final CommonMapper commonMapper = Util.getMapper(CommonMapper.class);
/**
* <h1></h1>
@ -47,6 +69,8 @@ public class CommonUtil {
}
// 开始解压
ZipFile zipFile = null;
InputStream is = null;
FileOutputStream fos = null;
try {
zipFile = new ZipFile(new File(srcFilePath), Charset.forName("GBK"));
Enumeration<?> entries = zipFile.entries();
@ -55,16 +79,25 @@ public class CommonUtil {
if (entry.isDirectory()) {
String dirPath = acceptFilePath + File.separator + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
boolean mkdirs = dir.mkdirs();
if(!mkdirs){
throw new CustomerException("创建文件夹失败!, 文件夹路径:[ " + dirPath + " ]");
}
} else {
String temp = acceptFilePath + File.separator + entry.getName();
File targetFile = new File(temp);
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
boolean mkdirs = targetFile.getParentFile().mkdirs();
if(!mkdirs){
throw new CustomerException("创建文件夹失败!, 文件夹路径:[ " + targetFile.getParentFile() + " ]");
}
}
targetFile.createNewFile();
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
boolean newFile = targetFile.createNewFile();
if(!newFile){
throw new CustomerException("创建文件失败!, 文件路径:[ " + temp + " ]");
}
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
@ -85,6 +118,20 @@ public class CommonUtil {
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@ -102,14 +149,17 @@ public class CommonUtil {
File file = new File(filePath);
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
FileReader fileReader = null;
try {
reader = new BufferedReader(new FileReader(file));
fileReader = new FileReader(file);
reader = new BufferedReader(fileReader);
String tempString = null;
// 一次读入一行直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
builder.append(tempString);
}
reader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
@ -117,6 +167,14 @@ public class CommonUtil {
try {
reader.close();
} catch (IOException ie) {
logger.error("关闭io流异常, " + ie.getMessage());
}
}
if(fileReader != null){
try {
fileReader.close();
} catch (IOException ie) {
logger.error("关闭io流异常, " + ie.getMessage());
}
}
}
@ -129,7 +187,7 @@ public class CommonUtil {
* @dateTime 2022/11/23 15:59
* @param t
**/
public static <T> void checkParamNotNull(T t) throws IllegalAccessException {
public static <T> void checkParamNotNull(T t){
Class<?> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
@ -138,7 +196,12 @@ public class CommonUtil {
continue;
}
field.setAccessible(true);
Object value = field.get(t);
Object value = null;
try {
value = field.get(t);
}catch (IllegalAccessException e){
throw new CustomerException("获取类字段值异常: " + e.getMessage());
}
Class<?> valueClass = field.getType();
boolean isNull = false;
if(valueClass.isAssignableFrom(String.class)){
@ -180,8 +243,10 @@ public class CommonUtil {
return Stream.iterate(0, n -> n + 1)
.limit(maxSize)
.parallel()
.map(a -> list.parallelStream().skip((long) a * splitSize).limit(splitSize).collect(Collectors.toList()))
.filter(b -> !b.isEmpty())
.map(a -> list.parallelStream()
.skip((long) a * splitSize).limit(splitSize)
.collect(Collectors.toList())
).filter(b -> !b.isEmpty())
.collect(Collectors.toList());
}
/**
@ -213,4 +278,245 @@ public class CommonUtil {
throw new RuntimeException(Util.logStr("解析日期失败!当前传入转化格式:[{}],待转化日期:[{}]", to, date));
}
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/11/28 12:07
* @param ids
* @param tableName
* @return true/false
**/
public static boolean deleteDataByIds(List<String> ids, String tableName) {
return deleteDataByIds(ids, tableName, SQL_IN_PAGE_SIZE);
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/11/28 12:07
* @param ids id
* @param modelId id
* @return true/false
**/
public static boolean deleteDataByIds(List<String> ids, int modelId) {
return deleteDataByIds(ids, modelId, SQL_IN_PAGE_SIZE);
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/11/28 12:07
* @param ids
* @param modelId id
* @param pageSize SQL in
* @return true/false
**/
public static boolean deleteDataByIds(List<String> ids, int modelId, int pageSize) {
String tableName = commonMapper.getModelNameByModelId(String.valueOf(modelId));
if(StringUtils.isBlank(tableName)){
throw new CustomerException("模块id : " + modelId + ",表名在系统中没有找到!");
}
return deleteDataByIds(ids, tableName, pageSize);
}
/**
* <h1>id</h1>
* @author xuanran.wang
* @dateTime 2022/11/28 12:08
* @param ids id
* @param tableName
* @param pageSize SQL in
* @return true/false
**/
public static boolean deleteDataByIds(List<String> ids, String tableName,int pageSize) {
List<List<String>> lists = CommonUtil.splitList(ids, pageSize);
for (List<String> list : lists) {
boolean success = commonMapper.deleteModelDataByIds(tableName, list);
if(!success){
logger.error(Util.logStr("删除数据失败, 数据集合 : [{}] ", JSONObject.toJSONString(list)));
}
return success;
}
return false;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 14:55
* @param path
* @return
**/
public static boolean delFile(String path) throws IOException {
File file = new File(path);
if(!file.exists()){
return true;
}
boolean deleteFlag = true;
int n = 0;
while (deleteFlag) {
try {
n++;
System.gc();
if(file.isDirectory()){
FileUtils.deleteDirectory(file);
}else {
Files.delete(Paths.get(path));
}
deleteFlag = false;
} catch (Exception e) {
try {
Thread.sleep(THREAD_SLEEP);
} catch (InterruptedException interruptedException) {
logger.info(Util.logStr("interruptedException : {}",interruptedException.getMessage()));
}
if (n > DEL_MAX_COUNT) {
deleteFlag = false;
logger.error("临时文件删除失败!路径: " + path);
}
}
}
return false;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/15 22:20
* @param map map
* @param clazz class
* @return
**/
public static <T> T getInstance(Map<String, Object> map, Class<T> clazz) {
if(MapUtils.isEmpty(map)){
throw new CustomerException("getInstance参数map不能为空!");
}
T res = null;
try {
res = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// 判断字段类型
if (field.getType().isAssignableFrom(List.class) || field.getType().isAssignableFrom(Map.class)) {
continue;
}
field.setAccessible(true);
String fieldName = field.getName();
String value = Util.null2String(map.get(fieldName));
// oracle数据库大写
if(StringUtils.isBlank(value)){
value = Util.null2String(map.get(fieldName.toUpperCase()));
}
field.set(res, value);
}
} catch (Exception e) {
throw new RuntimeException("实体类生成异常");
}
return res;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/15 22:20
* @param queryRs
* @param clazz class
* @return
**/
public static <T> T getInstance(RecordSet queryRs, Class<T> clazz) {
T res = null;
try {
res = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
// 判断字段类型
if (field.getType().isAssignableFrom(List.class) || field.getType().isAssignableFrom(Map.class)) {
continue;
}
field.setAccessible(true);
String fieldName = field.getName();
if ("oracle".equals(queryRs.getDBType())) {
fieldName = fieldName.toUpperCase();
}
String value = weaver.general.Util.null2String(queryRs.getString(fieldName));
field.set(res, value);
}
} catch (Exception e) {
throw new RuntimeException("实体类生成异常");
}
return res;
}
/**
* <h2>Date</h2>
*
* @param dateStr
* @return
*/
public static Date parseDate(String dateStr) {
ThreadLocal<SimpleDateFormat> SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
if (dateStr == null || dateStr.length() == 0) {
return null;
}
String regex = "\\/|\\.|年|月|日";
Date date = null;
try {
date = SIMPLE_DATE_FORMAT.get().parse(dateStr.replaceAll(regex, "-"));
return date;
} catch (ParseException e) {
throw new CustomerException("无法将" + dateStr + "转换为日期对象!", e);
}
}
/**
* <h2></h2>
*
* @param date
* @param tempStr
* @return
*/
public static String diyDateFortMat(Date date, String tempStr) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(tempStr);
return simpleDateFormat.format(date);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 21:14
* @param modeId id
* @param dataIds id
**/
public static List<String> doCreateWorkFlow(int modeId, List<String> dataIds){
if(modeId < 0){
throw new CustomerException("模块id不能小于0!");
}
if(org.springframework.util.CollectionUtils.isEmpty(dataIds)){
logger.info("暂无数据要生成流程!");
return Collections.emptyList();
}
Map<String, Integer> expendConfig = commonMapper.getExpendConfigByModeId(modeId);
logger.info(Util.logStr("expendConfig {}", JSONObject.toJSONString(expendConfig)));
int expendId = expendConfig.get("id");
int formId = expendConfig.get("formId");
int triggerWorkflowSetId = expendConfig.get("triggerWorkflowSetId");
ArrayList<String> requestIds = new ArrayList<>();
if(expendId > 0 && triggerWorkflowSetId > 0){
for (String daId : dataIds) {
ModeDataApproval modeDataApproval = new ModeDataApproval();
modeDataApproval.setUser(new User(1));
modeDataApproval.setBillid(Util.getIntValue(daId));
modeDataApproval.setFormid(formId);
modeDataApproval.setModeid(modeId);
modeDataApproval.setTriggerWorkflowSetId(triggerWorkflowSetId);
modeDataApproval.setPageexpandid(expendId);
Map<String, String> resMap = modeDataApproval.approvalDataResult();
logger.info(Util.logStr("模块数据id : {}, 创建流程结果 : {}", daId, JSONObject.toJSONString(resMap)));
requestIds.add(Util.null2String(resMap.get("requestid")));
}
}
return requestIds;
}
}

View File

@ -2,9 +2,11 @@ package weaver.xuanran.wang.common.util;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
@ -13,8 +15,7 @@ import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* @Author xuanran.wang
@ -25,7 +26,21 @@ public class CusInfoToOAUtil {
private static final ModeDataIdUpdate modeDataIdUpdate = ModeDataIdUpdate.getInstance();
private static final ModeRightInfo moderightinfo = new ModeRightInfo();
private static final Logger log = Util.getLogger();
public static final String TABLE_NAME_PLACEHOLDER = "#\\{table}";
public static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}";
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 17:00
* @param modelId id
* @param params map
* @return id
**/
public static String getDataId(int modelId,
Map<String, Object> params) {
return getDataId(modelId, params, "", Collections.emptyList());
}
/**
* <h1></h1>
* @author xuanran.wang
@ -36,10 +51,61 @@ public class CusInfoToOAUtil {
* @param whereParams
* @return id
**/
public static int execute(int modelId,
Map<String, Object> params,
String whereSql,
List<String> whereParams) {
public static String getDataId(int modelId,
Map<String, Object> params,
String whereSql,
List<String> whereParams) {
return getDataId(modelId, params, whereSql, whereParams, true);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 17:00
* @param modelId id
* @param params map
* @param whereSql sql
* @param whereParams
* @param needDel
* @return id
**/
public static String getDataId(int modelId,
Map<String, Object> params,
String whereSql,
List<String> whereParams,
boolean needDel) {
return executeBatch(modelId, Collections.singletonList(new LinkedHashMap<>(params)), whereSql, whereParams, needDel).get(0);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 17:00
* @param modelId id
* @param params map
* @return id
**/
public static List<String> executeBatch( int modelId,
List<LinkedHashMap<String, Object>> params) {
return executeBatch(modelId, params, "", Collections.emptyList(), true);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 17:00
* @param modelId id
* @param params map
* @param whereSql sql
* @param whereParams
* @param needDel
* @return id
**/
public static List<String> executeBatch( int modelId,
List<LinkedHashMap<String, Object>> params,
String whereSql,
List<String> whereParams,
boolean needDel) {
if(modelId < 0){
throw new RuntimeException("建模模块id不能小于0!");
}
@ -47,37 +113,74 @@ public class CusInfoToOAUtil {
if(StringUtils.isBlank(tableName)){
throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!");
}
RecordSet rs = new RecordSet();
int mainId = -1;
boolean needModeRight = false;
return executeBatch(modelId, tableName, params, whereSql, whereParams, needDel);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/11/23 17:00
* @param modelId id
* @param tableName
* @param params map
* @param whereSql sql
* @param whereParams
* @param needDel
* @return id
**/
public static List<String> executeBatch( int modelId,
String tableName,
List<LinkedHashMap<String, Object>> params,
String whereSql,
List<String> whereParams,
boolean needDel) {
// 如果要对模块数据中重复的进行更新则判断待插入的集合大小和判断重复的集合大小参数长度是否一致
if(StringUtils.isNotBlank(whereSql)){
whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName);
if (rs.executeQuery(whereSql, whereParams) && rs.next()) {
mainId = Util.getIntValue(rs.getString(1),-1);
if(CollectionUtils.isEmpty(whereParams) || CollectionUtils.isEmpty(params) || whereParams.size() != params.size()){
throw new CustomerException("使用批量更新时如果需要对重复数据进行更新,参数集合和判断重复参数集合大小必须相等!");
}
}
if(mainId < 0){
mainId = getNewIdByModelInfo(tableName, modelId);
needModeRight = true;
RecordSet rs = new RecordSet();
List<String> dataIds = new ArrayList<>();
List<Where> wheres = new ArrayList<>();
for (int i = 0; i < params.size(); i++) {
int mainId = -1;
if(StringUtils.isNotBlank(whereSql)){
whereSql = Util.sbc2dbcCase(whereSql);
whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName);
log.info("whereSql : " + whereSql);
log.info("参数 : " + whereParams);
if (rs.executeQuery(whereSql, whereParams) && rs.next()) {
mainId = Util.getIntValue(rs.getString(1),-1);
}
}
if(mainId < 0){
mainId = getNewIdByModelInfo(tableName, modelId);
}
dataIds.add(String.valueOf(mainId));
wheres.add(Util.createPrepWhereImpl().whereAnd("id").whereEqual(mainId));
}
Where where = Util.createPrepWhereImpl()
.whereAnd("id").whereEqual(mainId);
PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(
tableName,
params,
where
);
if (!rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs())) {
String error = Util.logStr("错误信息写入建模后置处理执行更新sql失败!" +
" 当前sql [{}], 当前参数 [{}], where条件[{}]", sqlResult.getSqlStr(),
JSONObject.toJSONString(sqlResult.getArgs()), mainId);
log.error(error);
throw new CustomerException(error);
BatchSqlResultImpl batchSql = Util.createSqlBuilder().updateBatchSql(tableName, params, wheres);
String sqlStr = batchSql.getSqlStr();
List<List> batchList = batchSql.getBatchList();
if(!rs.executeBatchSql(sqlStr, batchList)){
log.error(Util.logStr("batchSql:{}", sqlStr));
log.error(Util.logStr("batchList:{}", JSONObject.toJSONString(batchList)));
log.error(Util.logStr("whereList:{}", JSONObject.toJSONString(wheres)));
if(needDel){
if (!deleteModelDataByIds(String.valueOf(modelId), dataIds)) {
log.error(Util.logStr("删除数据失败!未删除数据集合:{}", JSONObject.toJSONString(dataIds)));
}
}
throw new CustomerException("执行批量更新sql失败!");
}
if(needModeRight){
moderightinfo.rebuildModeDataShareByEdit(1, modelId, mainId);
if(CollectionUtils.isEmpty(dataIds)){
throw new CustomerException("建模数据生成失败!");
}
return mainId;
for (String dataId : dataIds) {
moderightinfo.rebuildModeDataShareByEdit(1, modelId, Integer.parseInt(dataId));
}
return dataIds;
}
/**

View File

@ -0,0 +1,51 @@
package weaver.xuanran.wang.saic_travel.model_data_async.config.eneity;
import lombok.*;
import java.sql.Timestamp;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:01
*/
@Data
public class DataAsyncDetail {
/**
* <h2></h2>
**/
private String asyncModelTable;
/**
* <h2></h2>
**/
private String dataType;
/**
* <h2></h2>
**/
private String dataSourceModelFiled;
/**
* <h2></h2>
**/
private String cusTableField;
/**
* <h2></h2>
**/
private String convertRules;
/**
* <h2></h2>
**/
private String cusText;
/**
* <h2></h2>
**/
private String enable;
/**
* <h2></h2>
**/
private String asyncModelTableField;
/**
* <h2></h2>
**/
private String dataSourceModelFiledName;
}

View File

@ -0,0 +1,26 @@
package weaver.xuanran.wang.saic_travel.model_data_async.config.eneity;
import lombok.*;
import java.util.List;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:00
*/
@Data
public class DataAsyncMain {
private String id;
private String uniqueCode;
private String enable;
private String dataSource;
private String modelType;
private String cusTable;
private String asyncTargetModel;
private String cusWhere;
private String modelTypeTableName;
private String asyncTargetModelTableName;
private List<DataAsyncDetail> dataAsyncDetailList;
}

View File

@ -0,0 +1,50 @@
package weaver.xuanran.wang.saic_travel.model_data_async.config.mapper;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import java.util.List;
import java.util.Map;
/**
* <h1>mapper</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:35
*/
@SqlMapper
public interface DataAsyncConfigMapper {
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 14:39
* @param uniqueCode
* @return
**/
@Select("select a.*,b.tablename asyncTargetModelTableName,c.tablename modelTypeTableName " +
"from uf_data_async a " +
"left join mode_bill_info_view b " +
"on a.asyncTargetModel = b.id " +
"left join mode_bill_info_view c " +
"on a.modelType = c.id " +
"where uniqueCode = #{uniqueCode} and enable = #{enable}")
Map<String, Object> getDataAsyncMainConfig(@ParamMapper("uniqueCode") String uniqueCode, @ParamMapper("enable") String enable);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 14:40
* @param mainId id
* @return
**/
@Select("select a.*,b.fieldname asyncModelTableField,c.fieldname dataSourceModelFiledName " +
"from uf_data_async_dt1 a " +
"left join workflow_field_table_view b " +
"on a.asyncModelTable = b.id " +
"left join workflow_field_table_view c " +
"on a.dataSourceModelFiled = c.id " +
"where mainid = #{mainId} and enable = #{enable}")
List<Map<String, Object>> getDataAsyncDetailConfig(@ParamMapper("mainId") String mainId,@ParamMapper("enable") String enable);
}

View File

@ -0,0 +1,79 @@
package weaver.xuanran.wang.saic_travel.model_data_async.constant;
/**
* <h1>uf_data_async</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:18
*/
public class DataAsyncConstant {
public static final String MODEL_TABLE_NAME = "uf_data_async";
/**
* <h2>-</h2>
**/
public static final String DATA_SOURCE_MODEL = "0";
/**
* <h2>-</h2>
**/
public static final String DATA_SOURCE_CUS_TABLE = "1";
/**
* <h2></h2>
**/
public static final String CONFIG_ENABLE = "0";
/**
* <h2></h2>
**/
public static final String CONFIG_NOT_ENABLE = "1";
/**
* <h2>-String</h2>
**/
public static final String DATA_TYPE_STRING = "0";
/**
* <h2>-Int</h2>
**/
public static final String DATA_TYPE_INT = "1";
/**
* <h2>-Double</h2>
**/
public static final String DATA_TYPE_DOUBLE = "2";
/**
* <h2>-Date</h2>
**/
public static final String DATA_TYPE_DATE = "3";
/**
* <h2>-DateTime</h2>
**/
public static final String DATA_TYPE_DATE_TIME = "4";
/**
* <h2>-</h2>
**/
public static final String DATA_TYPE_CUS_DATE = "5";
/**
* <h2>-</h2>
**/
public static final String DATA_TYPE_TIME_TIMESTAMP = "6";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_TABLE_FIELD = "0";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_DEFAULT = "1";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_NOW_TIME = "2";
/**
* <h2>-SQL</h2>
**/
public static final String CONVERT_RULES_CUS_SQL = "3";
/**
* <h2>-id</h2>
**/
public static final String CONVERT_RULES_DATA_ID = "4";
/**
* <h2>-</h2>
**/
public static final String CONVERT_RULES_SPLIT_COPY = "5";
}

View File

@ -0,0 +1,41 @@
package weaver.xuanran.wang.saic_travel.model_data_async.job;
import aiyh.utils.Util;
import org.apache.log4j.Logger;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.xuanran.wang.common.annocation.ParamNotNull;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain;
import weaver.xuanran.wang.saic_travel.model_data_async.service.DataAsyncConfigService;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 15:20
*/
public class HrmDataToModelAsync extends BaseCronJob {
private final Logger logger = Util.getLogger();
private final DataAsyncConfigService asyncConfigService = new DataAsyncConfigService();
@ParamNotNull
private String uniqueCode;
@ParamNotNull
private String modelId;
@Override
public void execute() {
try {
CommonUtil.checkParamNotNull(this);
DataAsyncMain dataAsyncConfigByUniqueCode = asyncConfigService.getDataAsyncConfigByUniqueCode(uniqueCode);
asyncConfigService.asyncModelData(dataAsyncConfigByUniqueCode, Util.getIntValue(modelId, -1));
}catch (Exception e){
logger.error(Util.logStr("执行数据同步计划任务失败!异常信息 : {}", e.getMessage()));
}
}
}

View File

@ -0,0 +1,23 @@
package weaver.xuanran.wang.saic_travel.model_data_async.mapper;
import aiyh.utils.annotation.recordset.*;
import weaver.conn.RecordSet;
import java.util.Map;
/**
* <h1>mapper</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 16:55
*/
@SqlMapper
public interface DataAsyncMapper {
@Select(custom = true)
@CaseConversion(false)
RecordSet getRecordSetByCusSql(@SqlString String sql);
}

View File

@ -0,0 +1,265 @@
package weaver.xuanran.wang.saic_travel.model_data_async.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.xuanran.wang.common.util.CommonUtil;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncDetail;
import weaver.xuanran.wang.saic_travel.model_data_async.config.eneity.DataAsyncMain;
import weaver.xuanran.wang.saic_travel.model_data_async.config.mapper.DataAsyncConfigMapper;
import weaver.xuanran.wang.saic_travel.model_data_async.constant.DataAsyncConstant;
import weaver.xuanran.wang.saic_travel.model_data_async.mapper.DataAsyncMapper;
import weaver.zwl.common.ToolUtil;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1>service</h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 14:33
*/
public class DataAsyncConfigService {
private final Logger logger = Util.getLogger();
private final RecordSet tempRs = new RecordSet();
private final DataAsyncConfigMapper dataAsyncConfigMapper = Util.getMapper(DataAsyncConfigMapper.class);
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/1 15:09
* @param uniqueCode
* @return
**/
public DataAsyncMain getDataAsyncConfigByUniqueCode(String uniqueCode){
Map<String, Object> mainConfigMap = dataAsyncConfigMapper.getDataAsyncMainConfig(uniqueCode, DataAsyncConstant.CONFIG_ENABLE);
DataAsyncMain dataAsyncMain = CommonUtil.getInstance(mainConfigMap, DataAsyncMain.class);
List<Map<String, Object>> asyncDetailConfig = dataAsyncConfigMapper.getDataAsyncDetailConfig(dataAsyncMain.getId(), DataAsyncConstant.CONFIG_ENABLE);
List<DataAsyncDetail> detailList = asyncDetailConfig.stream().map(item -> CommonUtil.getInstance(item, DataAsyncDetail.class)).collect(Collectors.toList());
Assert.notEmpty(detailList, "明细表配置集合获取为空, 请检查!");
dataAsyncMain.setDataAsyncDetailList(detailList);
return dataAsyncMain;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/2 13:28
* @param asyncConfig
* @param modelId id
**/
public List<String> asyncModelData(DataAsyncMain asyncConfig, int modelId){
String dataSource = asyncConfig.getDataSource();
String selectSql = getSelectSql(asyncConfig);
List<DataAsyncDetail> asyncDetailList = asyncConfig.getDataAsyncDetailList();
RecordSet rs = new RecordSet();
if (!rs.executeQuery(selectSql)) {
throw new CustomerException(Util.logStr("执行查询数据源sql失败! 当前sql:{}", selectSql));
}
logger.info("selectSql : " + selectSql);
List<LinkedHashMap<String, Object>> linkedHashMapList = new ArrayList<>();
int splitCopy = -1;
String splitCopyFiledName = "";
// 复制个数
List<DataAsyncDetail> splitCopyList = asyncDetailList.stream().filter(item -> DataAsyncConstant.CONVERT_RULES_SPLIT_COPY.equals(item.getConvertRules())).collect(Collectors.toList());
if(!CollectionUtils.isEmpty(splitCopyList)){
DataAsyncDetail detail = splitCopyList.get(0);
splitCopy = Util.getIntValue(detail.getCusText(),-1);
splitCopyFiledName = Util.null2DefaultStr(detail.getAsyncModelTableField(),"");
}
while (rs.next()){
LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
int tempCount = 0;
for (DataAsyncDetail dataAsyncDetail : asyncDetailList) {
String field = "";
switch (dataSource){
case DataAsyncConstant.DATA_SOURCE_MODEL:{
field = dataAsyncDetail.getDataSourceModelFiledName();
}break;
case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{
field = dataAsyncDetail.getCusTableField();
}break;
default:throw new CustomerException("暂不支持的数据来源");
}
Object value = getFieldValue(rs, field, dataAsyncDetail, tempCount);
linkedHashMap.put(dataAsyncDetail.getAsyncModelTableField(), value);
}
linkedHashMapList.add(linkedHashMap);
// 记录复制
while (++tempCount < splitCopy) {
LinkedHashMap<String, Object> copyMap = new LinkedHashMap<>(linkedHashMap);
copyMap.put(splitCopyFiledName, tempCount);
linkedHashMapList.add(copyMap);
}
}
List<String> list = CusInfoToOAUtil.executeBatch(modelId, linkedHashMapList);
return list;
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/5 10:50
* @param recordSet
* @param field
* @param dataAsyncDetail
* @param count
* @return
**/
public Object getFieldValue(RecordSet recordSet, String field, DataAsyncDetail dataAsyncDetail, int count){
String convertRules = dataAsyncDetail.getConvertRules();
String dataType = dataAsyncDetail.getDataType();
String cusText = dataAsyncDetail.getCusText();
Object value = "";
switch (convertRules) {
// 表单字段
case DataAsyncConstant.CONVERT_RULES_TABLE_FIELD: {
if(!StringUtils.isBlank(field)){
value = Util.null2String(recordSet.getString(field));
}
}break;
// 默认值
case DataAsyncConstant.CONVERT_RULES_DEFAULT: {
value = cusText;
}break;
// 当前时间
case DataAsyncConstant.CONVERT_RULES_NOW_TIME: {
value = new Date();
}break;
// 自定义sql查询
case DataAsyncConstant.CONVERT_RULES_CUS_SQL: {
if(!StringUtils.isBlank(cusText)){
String cusSql = Util.sbc2dbcCase(cusText);
String where = "";
if(StringUtils.isNotBlank(field)){
where = Util.null2DefaultStr(recordSet.getString(field),"");
}
tempRs.executeQuery(cusSql, where);
if (!tempRs.next()) {
logger.error(Util.logStr("执行自定义sql失败!当前sql:{}, 当前参数:{}", cusSql, where));
break;
}
value = tempRs.getString(1);
}
}break;
case DataAsyncConstant.CONVERT_RULES_DATA_ID: {
value = recordSet.getString("id");
}break;
case DataAsyncConstant.CONVERT_RULES_SPLIT_COPY: {
value = count;
}break;
default: throw new CustomerException("不支持的取值方式!");
}
switch (dataType) {
// String类型
case DataAsyncConstant.DATA_TYPE_STRING: {
value = Util.null2DefaultStr(String.valueOf(value), "");
}
break;
// int类型
case DataAsyncConstant.DATA_TYPE_INT: {
value = Util.getIntValue(Util.null2DefaultStr(value, ""), 0);
}
break;
// double类型
case DataAsyncConstant.DATA_TYPE_DOUBLE: {
value = Util.getDoubleValue(Util.null2DefaultStr(value, ""), 0);
}
break;
// 日期类型
case DataAsyncConstant.DATA_TYPE_DATE: {
if (StringUtils.isBlank(Util.null2DefaultStr(value, ""))) {
break;
}
try {
Date date = value instanceof Date ? (Date) value : CommonUtil.parseDate(String.valueOf(value));
value = CommonUtil.diyDateFortMat(date, "yyyy-MM-dd");
} catch (Exception e) {
logger.error(Util.logStr("转换日期类型异常, 当前字段:{},当前值:{}", field, value));
}
}
break;
// 时间日期类型
case DataAsyncConstant.DATA_TYPE_DATE_TIME: {
if (StringUtils.isBlank(Util.null2DefaultStr(value, ""))) {
break;
}
try {
Date date = value instanceof Date ? (Date) value : CommonUtil.parseDate(String.valueOf(value));
value = CommonUtil.diyDateFortMat(date, "yyyy-MM-dd HH:mm:ss");
} catch (Exception e) {
logger.error(Util.logStr("转换日期类型异常, 当前字段:{},当前值:{}", field, value));
}
}
break;
// 自定义时间格式化类型
case DataAsyncConstant.DATA_TYPE_CUS_DATE: {
if (StringUtils.isBlank(Util.null2DefaultStr(value, "")) || StringUtils.isBlank(cusText)) {
break;
}
try {
Date date = value instanceof Date ? (Date) value : CommonUtil.parseDate(String.valueOf(value));
value = CommonUtil.diyDateFortMat(date, cusText);
} catch (Exception e) {
logger.error(Util.logStr("转换日期类型异常, 当前字段:{},当前值:{}", field, value));
}
}
break;
// 时间戳类型
case DataAsyncConstant.DATA_TYPE_TIME_TIMESTAMP: {
if (StringUtils.isBlank(Util.null2DefaultStr(value, "")) || StringUtils.isBlank(cusText)) {
break;
}
try {
Date date = value instanceof Date ? (Date) value : CommonUtil.parseDate(String.valueOf(value));
value = date.getTime();
} catch (Exception e) {
logger.error(Util.logStr("转换日期类型异常, 当前字段:{},当前值:{}", field, value));
}
}break;
default: throw new CustomerException("不支持的字段类型!");
}
return value;
}
/**
* <h1>sql</h1>
* @author xuanran.wang
* @dateTime 2022/12/2 12:56
* @param asyncConfig
* @return sql
**/
public String getSelectSql(DataAsyncMain asyncConfig){
String dataSource = asyncConfig.getDataSource();
String cusWhere = Util.null2DefaultStr(asyncConfig.getCusWhere(), "");
String dataSourceTableName = "";
List<DataAsyncDetail> asyncDetailList = asyncConfig.getDataAsyncDetailList();
String selectSql = "select ";
List<String> modelFieldList = new ArrayList<>();
// 判断数据来源拼接查询sql
switch (dataSource) {
case DataAsyncConstant.DATA_SOURCE_MODEL:{
modelFieldList = asyncDetailList.stream().map(DataAsyncDetail::getDataSourceModelFiledName).filter(StringUtils::isNotBlank).collect(Collectors.toList());
dataSourceTableName = asyncConfig.getModelTypeTableName();
}break;
case DataAsyncConstant.DATA_SOURCE_CUS_TABLE:{
modelFieldList = asyncDetailList.stream().map(DataAsyncDetail::getCusTableField).filter(StringUtils::isNotBlank).collect(Collectors.toList());
dataSourceTableName = asyncConfig.getCusTable();
}break;
default:throw new CustomerException("暂不支持的数据来源!");
}
// 拼接数据源查询sql
selectSql += StringUtils.join(modelFieldList, ",") + " from " + dataSourceTableName;
if(StringUtils.isNotBlank(cusWhere)){
selectSql += " where " + cusWhere;
}
return selectSql;
}
}

View File

@ -0,0 +1,53 @@
package weaver.xuanran.wang.schroeder.action;
import aiyh.utils.Util;
import aiyh.utils.action.CusBaseAction;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.excention.CustomerException;
import weaver.conn.RecordSetTrans;
import weaver.hrm.User;
import weaver.workflow.request.RequestManager;
import weaver.xuanran.wang.schroeder.service.SchroederQRCodeService;
/**
* <h1>action</h1>
*
* @Author xuanran.wang
* @Date 2022/11/30 16:08
*/
public class PushSealTaskAction extends CusBaseAction {
/**
* <h2></h2>
**/
@RequiredMark
private String onlyMark;
/**
* <h2></h2>
**/
@RequiredMark
private String QRCodeField;
private final SchroederQRCodeService schroederQRCodeService = new SchroederQRCodeService();
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestManager requestManager) {
log.info("---------- PushSealTaskSealValue Begin " + requestId + "----------");
String scanNum = schroederQRCodeService.pushSealTask(onlyMark, billTable, requestId);
RecordSetTrans trans = requestManager.getRsTrans();
trans.setAutoCommit(false);
String updateSql = "update " + billTable + " set " + QRCodeField + " = ? where requestid = ?";
try{
if(!trans.executeUpdate(updateSql, scanNum, requestId)){
throw new CustomerException(Util.logStr("更新表单sql执行失败!sql : {}, 参数 scanNum : {}, requestId : {}", scanNum, requestId));
}
}catch (Exception e){
trans.rollback();
throw new CustomerException(Util.logStr("执行提交方法异常:{}", e.getMessage()));
}
trans.commit();
}
}

View File

@ -0,0 +1,71 @@
package weaver.xuanran.wang.schroeder.cus_field_value;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.xiao.commons.config.interfacies.CusInterfaceGetValue;
import weaver.zwl.common.ToolUtil;
import java.util.*;
import java.util.stream.Collectors;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/2 16:10
*/
public class PushSealTaskSealValue implements CusInterfaceGetValue {
private final ToolUtil toolUtil = new ToolUtil();
private final Logger logger = Util.getLogger();
@Override
public Object execute(Map<String, Object> mainMap, Map<String, Object> detailMap, String currentValue, Map<String, String> pathParam) {
logger.info(Util.logStr("路径参数:[{}]", JSONObject.toJSONString(pathParam)));
// 接口字段
String sealSnField = pathParam.get("sealSnField");
String sealNumField = pathParam.get("sealNumField");
// 表单字段
String workFlowSealNumField = pathParam.get("workFlowSealNumField");
String workFlowSealSnField = pathParam.get("workFlowSealSnField");
// 自定义sql业务印章类型
String sealSnCusSql = pathParam.get("sealSnCusSql");
// 使用次数
String sealNumCusSql = pathParam.get("sealNumCusSql");
// 非空校验
if(checkBlank(sealSnField, sealNumField, sealSnCusSql, sealNumCusSql, workFlowSealNumField, workFlowSealSnField)){
throw new CustomerException(Util.logStr("自定义类路径中必要参数为空,请检查!当前pathParam : {}", JSONObject.toJSONString(pathParam)));
}
// 表单印章使用类型值
String sealSnVal = Util.null2String(String.valueOf(detailMap.get(sealSnField)),"");
// 如果为空返回空集合
if(StringUtils.isBlank(sealSnVal)){
return Collections.emptyList();
}
ArrayList<Map<String, Object>> list = new ArrayList<>();
logger.info(Util.logStr("当前值 : {}", currentValue));
int detailId = -1;
if(MapUtils.isNotEmpty(detailMap)){
detailId = Util.getIntValue(String.valueOf(detailMap.get("id")), -1);
}
for (String val : sealSnVal.split(",")) {
// 印章类型转换执行自定义sql
String inSealVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealSnCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),"");
String inSealNumVal = Util.null2DefaultStr(toolUtil.getValueByChangeRule(sealNumCusSql, val, String.valueOf(mainMap.get("requestid")), detailId),"");
HashMap<String, Object> map = new HashMap<>();
map.put(sealSnField, inSealVal);
map.put(sealNumField, inSealNumVal);
list.add(map);
}
return list;
}
public boolean checkBlank(String ... args){
return Arrays.stream(args).anyMatch(StringUtils::isBlank);
}
}

View File

@ -0,0 +1,114 @@
package weaver.xuanran.wang.schroeder.service;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.zxing.qrcode.encoder.QRCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.mobile.plugin.ecology.QRCodeComInfo;
import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.service.DealWithMapping;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Map;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/12/1 10:58
*/
public class SchroederQRCodeService {
private static final int SUCCESS_CODE = 200;
/**
* <h2></h2>
**/
private static final int SUCCESS_STATUS= 0;
/**
* <h2></h2>
**/
private static final String MESSAGE_FIELD = "message";
/**
* <h2></h2>
**/
private static final String SCAN_NUM_FIELD = "scanNum";
/**
* <h2></h2>
**/
private static final String STATUS_FIELD = "status";
private final DealWithMapping dealWithMapping = new DealWithMapping();
private final Logger log = Util.getLogger();
private final HttpUtils httpUtils = new HttpUtils();
{
httpUtils.getGlobalCache().header.put("Content-Type", MediaType.APPLICATION_JSON);
}
/**
* <h1></h1>
* @author xuanran.wang
* @dateTime 2022/12/5 17:05
* @param onlyMark
* @param billTable
* @param requestId id
* @return
**/
public String pushSealTask(String onlyMark, String billTable, String requestId){
String res = "";
RequestMappingConfig requestMappingConfig = dealWithMapping.treeDealWithUniqueCode(onlyMark);
String cusWhere = Util.null2DefaultStr(requestMappingConfig.getCusWhereSql(),"");
if(StringUtils.isNotBlank(cusWhere)){
cusWhere = DealWithMapping.sbc2dbcCase(cusWhere);
}
String selectMainSql = "select * from " + billTable + " where requestid = ? " + cusWhere;
log.info("查询主表数据sql { " + selectMainSql + " }, requestId { " + requestId + " }");
RecordSet recordSet = new RecordSet();
recordSet.executeQuery(selectMainSql, requestId);
if (recordSet.next()) {
dealWithMapping.setMainTable(billTable);
Map<String, Object> requestParam = dealWithMapping.getRequestParam(recordSet, requestMappingConfig);
log.info(Util.logStr("请求json : {}", JSONObject.toJSONString(requestParam)));
String url = requestMappingConfig.getRequestUrl();
ResponeVo responeVo = null;
try {
responeVo = httpUtils.apiPost(url, requestParam);
} catch (IOException e) {
throw new CustomerException(Util.logStr("发送印章请求发生异常! : {}", e.getMessage()));
}
Map<String, String> headers = httpUtils.getGlobalCache().header;
if (responeVo.getCode() != SUCCESS_CODE) {
log.error(Util.logStr("can not fetch [{}]this request params is [{}]" +
"this request heard is [{}]but response status code is [{}]" +
"this response is [{}]", url, JSON.toJSON(requestParam), JSON.toJSONString(headers), responeVo.getCode(),
responeVo.getEntityString()));
throw new CustomerException(Util.logStr("can not fetch [{}]", url));
}
Map<String, Object> response;
log.info(Util.logStr("this response is [{}]", responeVo.getEntityString()));
try {
response = responeVo.getEntityMap();
log.info(Util.logStr("接口响应:{}", JSONObject.toJSONString(response)));
} catch (JsonProcessingException e) {
log.error(Util.logStr("push data error, can not parse response to map" +
"this response is [{}], url is [{}]request params is [{}] request heard is [{}];",
responeVo.getEntityString(), url, JSON.toJSONString(requestParam), JSON.toJSONString(headers)));
throw new CustomerException(Util.logStr("push data error, can not parse response to map"));
}
int status = (int) response.get(STATUS_FIELD);
if(SUCCESS_STATUS != status){
throw new CustomerException(Util.logStr("接口响应码不为0,接口响应信息:{}", Util.null2DefaultStr(response.get(MESSAGE_FIELD),"")));
}
res = Util.null2DefaultStr(response.get(SCAN_NUM_FIELD),"");
}
if(StringUtils.isBlank(res)){
throw new CustomerException("获取接口中响应任务字段为空, 请检查!");
}
return res;
}
}

View File

@ -0,0 +1,17 @@
package weaver.xuanran.wang.traffic_bank.waco_first.annocation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/11/30 11:35
*/
@Target({ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Attachments {
}

View File

@ -0,0 +1,14 @@
package weaver.xuanran.wang.traffic_bank.waco_first.entity;
import lombok.Data;
/**
* <h1></h1>
*
* @Author xuanran.wang
* @Date 2022/11/25 17:56
*/
@Data
public class Attachment {
private String src;
}

View File

@ -4,6 +4,8 @@ import lombok.Data;
import weaver.xuanran.wang.common.annocation.CusDateFormat;
import weaver.xuanran.wang.traffic_bank.waco_first.annocation.BodyPath;
import java.util.List;
/**
* <h1></h1>
*
@ -29,4 +31,5 @@ public class Info {
private String punishmentAmount;
@BodyPath
private String bodyPath;
private List<Attachment> attachments;
}

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