Compare commits

..

No commits in common. "dev" and "main" have entirely different histories.
dev ... main

124 changed files with 7511 additions and 9003 deletions

4
.gitignore vendored
View File

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

8
ecology-9-dev.iml Normal file
View File

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

View File

@ -1,40 +1,40 @@
package aiyh.utils; package aiyh.utils;
import org.apache.ibatis.io.Resources; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionManager; import org.apache.ibatis.session.SqlSessionManager;
import java.io.File; import java.io.File;
import java.io.Reader; import java.io.Reader;
/** /**
* @author EBU7-dev1-ayh * @author EBU7-dev1-ayh
* create 2021/12/14 0014 15:57 * create 2021/12/14 0014 15:57
*/ */
public class MybatisUtil { public class MybatisUtil {
private static SqlSessionManager sqlSessionManager = null; private static SqlSessionManager sqlSessionManager = null;
private synchronized static void init(String config){ private synchronized static void init(String config){
try { try {
Reader resourceAsReader = Resources.getResourceAsReader("WEB-INF" + File.separator +config); Reader resourceAsReader = Resources.getResourceAsReader("WEB-INF" + File.separator +config);
sqlSessionManager = SqlSessionManager.newInstance(resourceAsReader); sqlSessionManager = SqlSessionManager.newInstance(resourceAsReader);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static SqlSessionManager getSessionManager(String config){ public static SqlSessionManager getSessionManager(String config){
if(sqlSessionManager == null){ if(sqlSessionManager == null){
synchronized (MybatisUtil.class) { synchronized (MybatisUtil.class) {
if (sqlSessionManager == null) { if (sqlSessionManager == null) {
init(config); init(config);
} }
} }
} }
return sqlSessionManager; return sqlSessionManager;
} }
public static <T> T getMapper(Class<T> tClass){ public static <T> T getMapper(Class<T> tClass){
return sqlSessionManager.getMapper(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)); throw new CustomerException("计划任务执行异常!异常信息:\n" + Util.getErrString(e));
} }
getLogger().info(Util.logStr("\n\t计划任务 [{}] getDataId success!\n", cronJobClass.getName())); getLogger().info(Util.logStr("\n\t计划任务 [{}] execute success!\n", cronJobClass.getName()));
} }
@ -3358,7 +3358,7 @@ public class Util extends weaver.general.Util {
if (Action.FAILURE_AND_CONTINUE.equals(execute)) { if (Action.FAILURE_AND_CONTINUE.equals(execute)) {
throw new CustomerException("action执行失败失败原因\n" + requestInfo.getRequestManager().getMessagecontent()); throw new CustomerException("action执行失败失败原因\n" + requestInfo.getRequestManager().getMessagecontent());
} }
getLogger().info(Util.logStr("\n\n\tAction [{}] getDataId success!\n", actionClass.getName())); getLogger().info(Util.logStr("\n\n\tAction [{}] execute success!\n", actionClass.getName()));
} }
public static String getSetMethodName(String fieldName) { public static String getSetMethodName(String fieldName) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,134 +1,134 @@
package aiyh.utils.mapper; package aiyh.utils.mapper;
import aiyh.utils.annotation.recordset.*; import aiyh.utils.annotation.recordset.*;
import aiyh.utils.entity.DocImageInfo; import aiyh.utils.entity.DocImageInfo;
import aiyh.utils.entity.SelectValueEntity; import aiyh.utils.entity.SelectValueEntity;
import aiyh.utils.entity.WorkflowNodeConfig; import aiyh.utils.entity.WorkflowNodeConfig;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* <p>SQL</p> * <p>SQL</p>
* <p>create 2022/1/27 0027 12:01</p> * <p>create 2022/1/27 0027 12:01</p>
* *
* @author EBU7-dev1-ayh * @author EBU7-dev1-ayh
*/ */
@SqlMapper @SqlMapper
public interface UtilMapper { public interface UtilMapper {
/** /**
* Debug * Debug
* *
* @return Debug * @return Debug
*/ */
@Select("select param_value from $t{configTableName} where only_mark = 'enableDebugLog'") @Select("select param_value from $t{configTableName} where only_mark = 'enableDebugLog'")
public Boolean selectLogLevel(@ParamMapper("configTableName") String configTableName); public Boolean selectLogLevel(@ParamMapper("configTableName") String configTableName);
/** /**
* *
* *
* @param onlyMark * @param onlyMark
* @return * @return
*/ */
@Select("select param_value from $t{configTableName} where only_mark = #{onlyMark} and enable_param = 1") @Select("select param_value from $t{configTableName} where only_mark = #{onlyMark} and enable_param = 1")
public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark, public String selectCusConfigParam(@ParamMapper("onlyMark") String onlyMark,
@ParamMapper("configTableName") String cusConfigTableName); @ParamMapper("configTableName") String cusConfigTableName);
/** /**
* *
* *
* @param imageFileId * @param imageFileId
* @return * @return
*/ */
@Select("select imagefilename from imagefile where imagefileid = #{imageFileId}") @Select("select imagefilename from imagefile where imagefileid = #{imageFileId}")
String selectFileNameByImageFileId(@ParamMapper("imageFileId") int imageFileId); String selectFileNameByImageFileId(@ParamMapper("imageFileId") int imageFileId);
/** /**
* *
* *
* @param workflowId id * @param workflowId id
* @return * @return
*/ */
@Select("select bill.tablename from workflow_bill bill join workflow_base base on base.formid = bill.id where base.id = #{workflowId}") @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); 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}") @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); 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}") @Select("select id,workflow_type,mark_only,workflow_nodes,enable_nodes from uf_node_config where enable_nodes = 1 and workflow_type in ($t{allVersion}) and mark_only = #{markOnly}")
WorkflowNodeConfig selectNodeConfig(@ParamMapper("allVersion") String allVersion, @ParamMapper("markOnly") String markOnly); WorkflowNodeConfig selectNodeConfig(@ParamMapper("allVersion") String allVersion, @ParamMapper("markOnly") String markOnly);
/** /**
* *
* *
* @param tableName * @param tableName
* @param fileName * @param fileName
* @return * @return
*/ */
@Select("select wbf.id,wbf.fieldname,wbf.fieldlabel,wb.tablename, ws.selectname,ws.selectvalue " + @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 " + "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}") "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); List<SelectValueEntity> selectSelectFieldValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName);
@Select("select ws.selectname " + @Select("select ws.selectname " +
"from workflow_billfield wbf left join workflow_bill wb on wbf.billid = wb.id " + "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}") "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, String selectSelectFieldValueByValue(@ParamMapper("tableName") String tableName, @ParamMapper("fileName") String fileName,
@ParamMapper("value") String value); @ParamMapper("value") String value);
/** /**
* *
* *
* @param imageFileId * @param imageFileId
* @return * @return
*/ */
@Select("select * from imagefile where imagefileid = #{imageFileId}") @Select("select * from imagefile where imagefileid = #{imageFileId}")
Map<String, Object> selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId); Map<String, Object> selectFileInfoByImageFileId(@ParamMapper("imageFileId") int imageFileId);
/** /**
* *
* *
* @param imageFileId ID * @param imageFileId ID
* @return * @return
*/ */
@Delete("delete from imagefile where imagefileid = #{imageFileId}") @Delete("delete from imagefile where imagefileid = #{imageFileId}")
boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId); boolean deleteImageFileInfo(@ParamMapper("imageFileId") Integer imageFileId);
/** /**
* <h2></h2> * <h2></h2>
* *
* @param onlyMark * @param onlyMark
* @param value * @param value
* @param desc * @param desc
* @return * @return
*/ */
@Update("update $t{configTableName} set only_mark = #{onlyMark},param_value = #{paramValue}, \n" + @Update("update $t{configTableName} set only_mark = #{onlyMark},param_value = #{paramValue}, \n" +
"param_desc = #{paramDesc} where id = #{id}") "param_desc = #{paramDesc} where id = #{id}")
boolean updateConfigValueById(@ParamMapper("onlyMark") String onlyMark, boolean updateConfigValueById(@ParamMapper("onlyMark") String onlyMark,
@ParamMapper("paramValue") String value, @ParamMapper("paramValue") String value,
@ParamMapper("paramDesc") String desc, @ParamMapper("paramDesc") String desc,
@ParamMapper("id") String id, @ParamMapper("id") String id,
@ParamMapper("configTableName") String configTableName); @ParamMapper("configTableName") String configTableName);
/** /**
* <h2></h2> * <h2></h2>
* *
* @param onlyMark * @param onlyMark
* @param value * @param value
* @param desc * @param desc
* @return * @return
*/ */
@Update("update $t{configTableName} set param_value = #{paramValue}, \n" + @Update("update $t{configTableName} set param_value = #{paramValue}, \n" +
"param_desc = #{paramDesc} where only_mark = #{onlyMark}") "param_desc = #{paramDesc} where only_mark = #{onlyMark}")
boolean updateConfigValueByOnlyMark(@ParamMapper("onlyMark") String onlyMark, boolean updateConfigValueByOnlyMark(@ParamMapper("onlyMark") String onlyMark,
@ParamMapper("paramValue") String value, @ParamMapper("paramValue") String value,
@ParamMapper("paramDesc") String desc, @ParamMapper("paramDesc") String desc,
@ParamMapper("configTableName") String configTableName); @ParamMapper("configTableName") String configTableName);
} }

View File

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

View File

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

View File

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

View File

@ -1,211 +1,211 @@
package aiyh.utils.recordset; package aiyh.utils.recordset;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.annotation.recordset.*; import aiyh.utils.annotation.recordset.*;
import aiyh.utils.excention.BindingException; import aiyh.utils.excention.BindingException;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import weaver.conn.RecordSet; import weaver.conn.RecordSet;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
/** /**
* @author EBU7-dev1-ayh * @author EBU7-dev1-ayh
* create 2021/12/19 0019 14:39 * create 2021/12/19 0019 14:39
*/ */
public class RecordsetUtil implements InvocationHandler { public class RecordsetUtil implements InvocationHandler {
private final RecordSet recordSet = new RecordSet(); private final RecordSet recordSet = new RecordSet();
public <T> T getMapper(Class<T> tClass) { public <T> T getMapper(Class<T> tClass) {
if (tClass == null) { if (tClass == null) {
throw new BindingException("class is null!"); throw new BindingException("class is null!");
} }
if (tClass.getAnnotation(SqlMapper.class) == null) { if (tClass.getAnnotation(SqlMapper.class) == null) {
throw new BindingException("can not find SqlMapper annotation!"); throw new BindingException("can not find SqlMapper annotation!");
} }
return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this); return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, this);
} }
@Override @Override
public Object invoke(Object proxy, Method method, Object[] args) { public Object invoke(Object proxy, Method method, Object[] args) {
SqlHandler sqlHandler = new SqlHandler(); SqlHandler sqlHandler = new SqlHandler();
ResultMapper resultMapper = new ResultMapper(); ResultMapper resultMapper = new ResultMapper();
Select select = method.getAnnotation(Select.class); Select select = method.getAnnotation(Select.class);
if (select != null) { if (select != null) {
// 查询 // 查询
RecordSet rs = new RecordSet(); RecordSet rs = new RecordSet();
String sql = select.value(); String sql = select.value();
boolean custom = select.custom(); boolean custom = select.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("select ")) { 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!"); 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); Util.getLogger("sql_log").info("解析sql===>" + handler);
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
rs.executeQuery(handler.getSqlStr()); rs.executeQuery(handler.getSqlStr());
} else { } else {
rs.executeQuery(handler.getSqlStr(), handler.getArgs()); rs.executeQuery(handler.getSqlStr(), handler.getArgs());
} }
return resultMapper.mapperResult(rs, method, method.getReturnType()); return resultMapper.mapperResult(rs, method, method.getReturnType());
} }
Update update = method.getAnnotation(Update.class); Update update = method.getAnnotation(Update.class);
if (update != null) { if (update != null) {
// 查询 // 查询
String sql = update.value(); String sql = update.value();
boolean custom = update.custom(); boolean custom = update.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("update ")) { 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!"); 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()); Util.getLogger("sql_log").info(handler.toString());
Class<?> returnType = method.getReturnType(); Class<?> returnType = method.getReturnType();
boolean b; boolean b;
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
b = recordSet.executeUpdate(handler.getSqlStr()); b = recordSet.executeUpdate(handler.getSqlStr());
} else { } else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs()); b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
} }
if (returnType.equals(void.class)) { if (returnType.equals(void.class)) {
return null; return null;
} }
if (returnType.equals(int.class) || returnType.equals(Integer.class)) { if (returnType.equals(int.class) || returnType.equals(Integer.class)) {
if (b) { if (b) {
return 1; return 1;
} else { } else {
return 0; return 0;
} }
} }
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b; return b;
} }
} }
Insert insert = method.getAnnotation(Insert.class); Insert insert = method.getAnnotation(Insert.class);
if (insert != null) { if (insert != null) {
// 查询 // 查询
String sql = insert.value(); String sql = insert.value();
boolean custom = insert.custom(); boolean custom = insert.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("insert ")) { 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!"); 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()); Util.getLogger("sql_log").info(handler.toString());
Class<?> returnType = method.getReturnType(); Class<?> returnType = method.getReturnType();
boolean b; boolean b;
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
b = recordSet.executeUpdate(handler.getSqlStr()); b = recordSet.executeUpdate(handler.getSqlStr());
} else { } else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs()); b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
} }
if (returnType.equals(void.class)) { if (returnType.equals(void.class)) {
return null; return null;
} }
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b; return b;
} }
} }
Delete delete = method.getAnnotation(Delete.class); Delete delete = method.getAnnotation(Delete.class);
if (delete != null) { if (delete != null) {
// 查询 // 查询
String sql = delete.value(); String sql = delete.value();
boolean custom = delete.custom(); boolean custom = delete.custom();
PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args); PrepSqlResultImpl handler = sqlHandler.handler(sql, custom, method, args);
if (!handler.getSqlStr().trim().toLowerCase().startsWith("delete ")) { 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!"); 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()); Util.getLogger("sql_log").info(handler.toString());
Class<?> returnType = method.getReturnType(); Class<?> returnType = method.getReturnType();
boolean b; boolean b;
if (handler.getArgs().isEmpty()) { if (handler.getArgs().isEmpty()) {
b = recordSet.executeUpdate(handler.getSqlStr()); b = recordSet.executeUpdate(handler.getSqlStr());
} else { } else {
b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs()); b = recordSet.executeUpdate(handler.getSqlStr(), handler.getArgs());
} }
if (returnType.equals(void.class)) { if (returnType.equals(void.class)) {
return null; return null;
} }
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b; return b;
} }
} }
boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class); boolean hasBatchInsert = method.isAnnotationPresent(BatchInsert.class);
if (hasBatchInsert) { if (hasBatchInsert) {
BatchInsert batchInsert = method.getAnnotation(BatchInsert.class); BatchInsert batchInsert = method.getAnnotation(BatchInsert.class);
String sql = batchInsert.value(); String sql = batchInsert.value();
Class<?> returnType = method.getReturnType(); Class<?> returnType = method.getReturnType();
boolean custom = batchInsert.custom(); boolean custom = batchInsert.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger("sql_log").info(batchSqlResult.toString()); Util.getLogger("sql_log").info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) { if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); throw new CustomerException("execute batch sql error , batch sql args is empty!");
} }
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("insert ")) { 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!"); 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()); boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
if (returnType.equals(void.class)) { if (returnType.equals(void.class)) {
return null; return null;
} }
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b; return b;
} }
} }
boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class); boolean hasBatchUpdate = method.isAnnotationPresent(BatchUpdate.class);
if (hasBatchUpdate) { if (hasBatchUpdate) {
BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class); BatchUpdate batchUpdate = method.getAnnotation(BatchUpdate.class);
String sql = batchUpdate.value(); String sql = batchUpdate.value();
Class<?> returnType = method.getReturnType(); Class<?> returnType = method.getReturnType();
boolean custom = batchUpdate.custom(); boolean custom = batchUpdate.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger("sql_log").info(batchSqlResult.toString()); Util.getLogger("sql_log").info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) { if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); throw new CustomerException("execute batch sql error , batch sql args is empty!");
} }
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("update ")) { 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!"); 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()); boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
if (returnType.equals(void.class)) { if (returnType.equals(void.class)) {
return null; return null;
} }
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b; return b;
} }
} }
boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class); boolean hasBatchDelete = method.isAnnotationPresent(BatchDelete.class);
if (hasBatchDelete) { if (hasBatchDelete) {
BatchDelete batchDelete = method.getAnnotation(BatchDelete.class); BatchDelete batchDelete = method.getAnnotation(BatchDelete.class);
String sql = batchDelete.value(); String sql = batchDelete.value();
Class<?> returnType = method.getReturnType(); Class<?> returnType = method.getReturnType();
boolean custom = batchDelete.custom(); boolean custom = batchDelete.custom();
BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args); BatchSqlResultImpl batchSqlResult = sqlHandler.handlerBatch(sql, custom, method, args);
Util.getLogger("sql_log").info(batchSqlResult.toString()); Util.getLogger("sql_log").info(batchSqlResult.toString());
if (batchSqlResult.getBatchList().isEmpty()) { if (batchSqlResult.getBatchList().isEmpty()) {
throw new CustomerException("getDataId batch sql error , batch sql args is empty!"); throw new CustomerException("execute batch sql error , batch sql args is empty!");
} }
if (!batchSqlResult.getSqlStr().trim().toLowerCase().startsWith("delete ")) { 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!"); 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()); boolean b = recordSet.executeBatchSql(batchSqlResult.getSqlStr(), batchSqlResult.getBatchList());
if (returnType.equals(void.class)) { if (returnType.equals(void.class)) {
return null; return null;
} }
if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) { if (returnType.equals(boolean.class) || returnType.equals(Boolean.class)) {
return b; return b;
} }
} }
throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete"); throw new CustomerException("该方法没有添加注解!请检查是否正确添加注解!@Select、@Update、@Insert、@Delete、@BatchUpdate、@BatchInsert、@BatchDelete");
} }
} }

View File

@ -1,278 +1,278 @@
package aiyh.utils.recordset; package aiyh.utils.recordset;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.annotation.recordset.CaseConversion; import aiyh.utils.annotation.recordset.CaseConversion;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import aiyh.utils.excention.TypeNonsupportException; import aiyh.utils.excention.TypeNonsupportException;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import weaver.conn.RecordSet; import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans; import weaver.conn.RecordSetTrans;
import java.beans.BeanInfo; import java.beans.BeanInfo;
import java.beans.Introspector; import java.beans.Introspector;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.*; import java.util.*;
/** /**
* @author EBU7-dev1-ayh * @author EBU7-dev1-ayh
* create 2021/12/21 0021 11:03 * create 2021/12/21 0021 11:03
*/ */
public class ResultMapper { public class ResultMapper {
private static Map<Class<?>, TypeHandler> typeHandler = new HashMap<>(); private static Map<Class<?>, TypeHandler> typeHandler = new HashMap<>();
static { static {
IntegerTypeHandler integerTypeHandler = new IntegerTypeHandler(); IntegerTypeHandler integerTypeHandler = new IntegerTypeHandler();
typeHandler.put(String.class, new StringTypeHandler()); typeHandler.put(String.class, new StringTypeHandler());
typeHandler.put(Integer.class, integerTypeHandler); typeHandler.put(Integer.class, integerTypeHandler);
typeHandler.put(int.class, integerTypeHandler); typeHandler.put(int.class, integerTypeHandler);
typeHandler.put(byte.class, integerTypeHandler); typeHandler.put(byte.class, integerTypeHandler);
typeHandler.put(short.class, integerTypeHandler); typeHandler.put(short.class, integerTypeHandler);
typeHandler.put(long.class, integerTypeHandler); typeHandler.put(long.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(boolean.class, new BooleanTypeHandler()); typeHandler.put(boolean.class, new BooleanTypeHandler());
typeHandler.put(Date.class, new DataTypeHandler()); typeHandler.put(Date.class, new DataTypeHandler());
typeHandler.put(Float.class, new FloatTypeHandler()); typeHandler.put(Float.class, new FloatTypeHandler());
typeHandler.put(float.class, new FloatTypeHandler()); typeHandler.put(float.class, new FloatTypeHandler());
} }
public <T> T mapperResult(RecordSet rs, Method method, Class<T> tClass) { public <T> T mapperResult(RecordSet rs, Method method, Class<T> tClass) {
if (tClass.equals(void.class)) { if (tClass.equals(void.class)) {
return null; return null;
} }
if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) { if (tClass.equals(RecordSet.class) || tClass.equals(RecordSetTrans.class)) {
return (T) rs; return (T) rs;
} }
try { try {
if (tClass.equals(List.class)) { if (tClass.equals(List.class)) {
tClass = (Class<T>) ArrayList.class; tClass = (Class<T>) ArrayList.class;
} }
if (tClass.equals(Map.class)) { if (tClass.equals(Map.class)) {
tClass = (Class<T>) HashMap.class; tClass = (Class<T>) HashMap.class;
} }
if (ResultMapper.typeHandler.containsKey(tClass)) { if (ResultMapper.typeHandler.containsKey(tClass)) {
rs.next(); rs.next();
return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null); return (T) ResultMapper.typeHandler.get(tClass).getValue(rs, 1, null);
} }
T t = tClass.newInstance(); T t = tClass.newInstance();
if (t instanceof Collection) { if (t instanceof Collection) {
// 集合求出泛型 // 集合求出泛型
//获取返回值的类型 //获取返回值的类型
Type genericReturnType = method.getGenericReturnType(); Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument); Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(Map.class)) { if (rawType.equals(Map.class)) {
rawType = HashMap.class; rawType = HashMap.class;
} }
while (rs.next()) { while (rs.next()) {
Object o = null; Object o = null;
try { try {
Constructor<?> constructor = rawType.getConstructor(); Constructor<?> constructor = rawType.getConstructor();
o = constructor.newInstance(); o = constructor.newInstance();
} catch (NoSuchMethodException | InvocationTargetException ignored) { } catch (NoSuchMethodException | InvocationTargetException ignored) {
if (Number.class.isAssignableFrom(rawType)) { if (Number.class.isAssignableFrom(rawType)) {
Constructor<?> constructor; Constructor<?> constructor;
try { try {
constructor = rawType.getConstructor(String.class); constructor = rawType.getConstructor(String.class);
o = constructor.newInstance("-1"); o = constructor.newInstance("-1");
} catch (NoSuchMethodException | InvocationTargetException e) { } catch (NoSuchMethodException | InvocationTargetException e) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e);
} }
} }
} }
if (o == null) { if (o == null) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]");
} }
Object object = getObject(rs, o, method); Object object = getObject(rs, o, method);
((Collection<? super Object>) t).add(object); ((Collection<? super Object>) t).add(object);
} }
return t; return t;
} }
if (t instanceof Map) { if (t instanceof Map) {
// map // map
Type genericReturnType = method.getGenericReturnType(); Type genericReturnType = method.getGenericReturnType();
Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; Type actualTypeArgument = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
Class<?> rawType = this.getRawType(actualTypeArgument); Class<?> rawType = this.getRawType(actualTypeArgument);
if (rawType.equals(List.class)) { if (rawType.equals(List.class)) {
rawType = (Class<T>) ArrayList.class; rawType = (Class<T>) ArrayList.class;
} }
if (rawType.equals(Map.class)) { if (rawType.equals(Map.class)) {
rawType = HashMap.class; rawType = HashMap.class;
} }
// Object o = rawType.newInstance(); // Object o = rawType.newInstance();
Object o = null; Object o = null;
try { try {
Constructor<?> constructor = rawType.getConstructor(); Constructor<?> constructor = rawType.getConstructor();
o = constructor.newInstance(); o = constructor.newInstance();
} catch (NoSuchMethodException | InvocationTargetException ignored) { } catch (NoSuchMethodException | InvocationTargetException ignored) {
if (Number.class.isAssignableFrom(rawType)) { if (Number.class.isAssignableFrom(rawType)) {
Constructor<?> constructor; Constructor<?> constructor;
try { try {
constructor = rawType.getConstructor(String.class); constructor = rawType.getConstructor(String.class);
o = constructor.newInstance("-1"); o = constructor.newInstance("-1");
} catch (NoSuchMethodException | InvocationTargetException e) { } catch (NoSuchMethodException | InvocationTargetException e) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e); throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]", e);
} }
} }
} }
if (o == null) { if (o == null) {
throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]"); throw new CustomerException("can not Initialization " + t.getClass() + " [" + rawType + "]");
} }
if (o instanceof Map || o instanceof Collection) { if (o instanceof Map || o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!"); throw new TypeNonsupportException("An unsupported return type!");
} }
if (rs.next()) { if (rs.next()) {
return (T) getObject(rs, t, method); return (T) getObject(rs, t, method);
} }
return null; return null;
} }
if (t.getClass().isArray()) { if (t.getClass().isArray()) {
throw new TypeNonsupportException("An unsupported return type!"); throw new TypeNonsupportException("An unsupported return type!");
} }
if (rs.next()) { if (rs.next()) {
return (T) getObject(rs, t, method); return (T) getObject(rs, t, method);
} }
return null; return null;
} catch (InstantiationException | IllegalAccessException e) { } catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public Object getObject(RecordSet rs, Object o, Method method) { public Object getObject(RecordSet rs, Object o, Method method) {
CaseConversion annotation = method.getAnnotation(CaseConversion.class); CaseConversion annotation = method.getAnnotation(CaseConversion.class);
boolean enable = annotation == null ? true : annotation.value(); boolean enable = annotation == null ? true : annotation.value();
String[] columnName = rs.getColumnName(); String[] columnName = rs.getColumnName();
String[] columnTypeName = rs.getColumnTypeName(); String[] columnTypeName = rs.getColumnTypeName();
int[] columnTypes = rs.getColumnType(); int[] columnTypes = rs.getColumnType();
if (columnTypeName == null) { if (columnTypeName == null) {
columnTypeName = new String[columnTypes.length]; columnTypeName = new String[columnTypes.length];
for (int i = 0; i < columnTypes.length; i++) { for (int i = 0; i < columnTypes.length; i++) {
int type = columnTypes[i]; int type = columnTypes[i];
switch (type) { switch (type) {
case -1: case -1:
columnTypeName[i] = "TEXT"; columnTypeName[i] = "TEXT";
break; break;
case 4: case 4:
columnTypeName[i] = "INT"; columnTypeName[i] = "INT";
break; break;
case 12: case 12:
columnTypeName[i] = "VARCHAR"; columnTypeName[i] = "VARCHAR";
break; break;
default: default:
columnTypeName[i] = "VARCHAR"; columnTypeName[i] = "VARCHAR";
} }
} }
} }
try { try {
if (o instanceof Map) { if (o instanceof Map) {
for (int i = 0; i < columnName.length; i++) { for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[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 ("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) { if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1)); ((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getInt(i + 1));
continue; continue;
} }
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getInt(i + 1)); ((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getInt(i + 1));
continue; continue;
} }
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
if (enable) { if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1)); ((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getFloat(i + 1));
continue; continue;
} }
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getFloat(i + 1)); ((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getFloat(i + 1));
continue; continue;
} }
if (enable) { if (enable) {
((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1)); ((Map<? super Object, ? super Object>) o).put(Util.toCamelCase(columnName[i]), rs.getString(i + 1));
continue; continue;
} }
((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getString(i + 1)); ((Map<? super Object, ? super Object>) o).put(columnName[i], rs.getString(i + 1));
continue; continue;
} }
return o; return o;
} }
if (o instanceof Collection) { if (o instanceof Collection) {
throw new TypeNonsupportException("An unsupported return type!"); throw new TypeNonsupportException("An unsupported return type!");
} }
if (o instanceof Number) { if (o instanceof Number) {
for (int i = 0; i < columnName.length; i++) { for (int i = 0; i < columnName.length; i++) {
String columnType = columnTypeName[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 ("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); return rs.getInt(i + 1);
} }
if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) { if ("FLOAT".equalsIgnoreCase(columnType) || "DOUBLE".equalsIgnoreCase(columnType) || "DECIMAL".equalsIgnoreCase(columnType)) {
return rs.getFloat(i + 1); return rs.getFloat(i + 1);
} }
} }
return o; return o;
} }
if (o instanceof String) { if (o instanceof String) {
for (int i = 0; i < columnName.length; i++) { for (int i = 0; i < columnName.length; i++) {
return rs.getString(i + 1); return rs.getString(i + 1);
} }
return o; return o;
} }
if (o instanceof Boolean) { if (o instanceof Boolean) {
for (int i = 0; i < columnName.length; i++) { for (int i = 0; i < columnName.length; i++) {
return rs.getBoolean(i + 1); return rs.getBoolean(i + 1);
} }
return o; return o;
} }
// Util.getLogger().info("获取对象:" + o.toString()); // Util.getLogger().info("获取对象:" + o.toString());
BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Class<?> propertyType = propertyDescriptor.getPropertyType(); Class<?> propertyType = propertyDescriptor.getPropertyType();
Object value = null; Object value = null;
String fieldName = propertyDescriptor.getName(); String fieldName = propertyDescriptor.getName();
if (Strings.isNullOrEmpty(fieldName)) { if (Strings.isNullOrEmpty(fieldName)) {
fieldName = propertyDescriptor.getDisplayName(); fieldName = propertyDescriptor.getDisplayName();
} }
// Util.getLogger().info("获取类字段:" + fieldName); // Util.getLogger().info("获取类字段:" + fieldName);
// Util.getLogger().info("获取类字段1" + propertyDescriptor.getDisplayName()); // Util.getLogger().info("获取类字段1" + propertyDescriptor.getDisplayName());
// Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName)); // Util.getLogger().info("获取的数据库数据:" + rs.getString(fieldName));
Field declaredField = o.getClass().getDeclaredField(fieldName); Field declaredField = o.getClass().getDeclaredField(fieldName);
if (enable) { if (enable) {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField); value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, Util.toUnderlineCase(fieldName), declaredField);
} else { } else {
value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField); value = ResultMapper.typeHandler.get(propertyType) == null ? null : ResultMapper.typeHandler.get(propertyType).getValue(rs, fieldName, declaredField);
} }
propertyDescriptor.getWriteMethod().invoke(o, value); propertyDescriptor.getWriteMethod().invoke(o, value);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e)); Util.getLogger().error("报错了,写入数据到实体类报错!\n" + Util.getErrString(e));
} }
return o; return o;
} }
public Class<?> getRawType(Type type) { public Class<?> getRawType(Type type) {
if (type instanceof Class) { if (type instanceof Class) {
return (Class) type; return (Class) type;
} else if (type instanceof ParameterizedType) { } else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type; ParameterizedType parameterizedType = (ParameterizedType) type;
Type rawType = parameterizedType.getRawType(); Type rawType = parameterizedType.getRawType();
return (Class) rawType; return (Class) rawType;
} else if (type instanceof GenericArrayType) { } else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType(); Type componentType = ((GenericArrayType) type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass(); return Array.newInstance(getRawType(componentType), 0).getClass();
} else if (type instanceof TypeVariable) { } else if (type instanceof TypeVariable) {
return Object.class; return Object.class;
} else if (type instanceof WildcardType) { } else if (type instanceof WildcardType) {
return getRawType(((WildcardType) type).getUpperBounds()[0]); return getRawType(((WildcardType) type).getUpperBounds()[0]);
} else { } else {
String className = type == null ? "null" : type.getClass().getName(); String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className); 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; package aiyh.utils.recordset;
import aiyh.utils.annotation.recordset.BatchSqlArgs; import aiyh.utils.annotation.recordset.BatchSqlArgs;
import aiyh.utils.annotation.recordset.ParamMapper; import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.SqlString; import aiyh.utils.annotation.recordset.SqlString;
import aiyh.utils.excention.BindingException; import aiyh.utils.excention.BindingException;
import aiyh.utils.excention.MethodNotFindException; import aiyh.utils.excention.MethodNotFindException;
import aiyh.utils.excention.ParseSqlException; import aiyh.utils.excention.ParseSqlException;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Parameter; import java.lang.reflect.Parameter;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* @author EBU7-dev1-ayh * @author EBU7-dev1-ayh
* create 2021/12/19 0019 15:28 * create 2021/12/19 0019 15:28
*/ */
public class SqlHandler { public class SqlHandler {
List<Object> sqlArgs = new ArrayList<>(); List<Object> sqlArgs = new ArrayList<>();
List<List> batchSqlArgs = new ArrayList<>(); List<List> batchSqlArgs = new ArrayList<>();
List<Object> batchSqlArgsList = new ArrayList(); List<Object> batchSqlArgsList = new ArrayList();
private Object batchObj = null; private Object batchObj = null;
public PrepSqlResultImpl handler(String sql, boolean custom, Method method, Object[] args) { public PrepSqlResultImpl handler(String sql, boolean custom, Method method, Object[] args) {
String findSql = findSql(sql, custom, method, args); String findSql = findSql(sql, custom, method, args);
Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args); Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args);
// 处理基本类型以及包装类 // 处理基本类型以及包装类
String parse; String parse;
if (methodArgNameMap.size() == 0) { if (methodArgNameMap.size() == 0) {
return new PrepSqlResultImpl(findSql, sqlArgs); return new PrepSqlResultImpl(findSql, sqlArgs);
} }
if (methodArgNameMap.size() == 1) { if (methodArgNameMap.size() == 1) {
Optional<Object> first = methodArgNameMap.values().stream().findFirst(); Optional<Object> first = methodArgNameMap.values().stream().findFirst();
parse = parse(findSql, first.orElse(null)); parse = parse(findSql, first.orElse(null));
} else { } else {
parse = parse(findSql, methodArgNameMap); parse = parse(findSql, methodArgNameMap);
} }
return new PrepSqlResultImpl(parse, sqlArgs); return new PrepSqlResultImpl(parse, sqlArgs);
} }
private String parseBatch(String findSql, Object o) { private String parseBatch(String findSql, Object o) {
String parse = ""; String parse = "";
if (!batchSqlArgsList.isEmpty()) { if (!batchSqlArgsList.isEmpty()) {
for (Object o1 : batchSqlArgsList) { for (Object o1 : batchSqlArgsList) {
Map<String, Object> map = new HashMap<>(8); Map<String, Object> map = new HashMap<>(8);
map.put("item", o1); map.put("item", o1);
map.putAll((Map<String, Object>) o); map.putAll((Map<String, Object>) o);
parse = parse(findSql, map); parse = parse(findSql, map);
List<Object> tempArgs = new ArrayList<>(); List<Object> tempArgs = new ArrayList<>();
tempArgs.addAll(sqlArgs); tempArgs.addAll(sqlArgs);
batchSqlArgs.add(tempArgs); batchSqlArgs.add(tempArgs);
sqlArgs.clear(); sqlArgs.clear();
} }
} }
if ("".equals(parse)) { if ("".equals(parse)) {
parse = findSql; parse = findSql;
} }
return parse; return parse;
} }
public BatchSqlResultImpl handlerBatch(String sql, boolean custom, Method method, Object[] args) { public BatchSqlResultImpl handlerBatch(String sql, boolean custom, Method method, Object[] args) {
String findSql = findSql(sql, custom, method, args); String findSql = findSql(sql, custom, method, args);
Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args); Map<String, Object> methodArgNameMap = buildMethodArgNameMap(method, args);
// 处理基本类型以及包装类 // 处理基本类型以及包装类
String parse; String parse;
if (methodArgNameMap.size() == 0) { if (methodArgNameMap.size() == 0) {
Object o = batchSqlArgsList.get(0); Object o = batchSqlArgsList.get(0);
if (o instanceof List) { if (o instanceof List) {
return new BatchSqlResultImpl(findSql, batchSqlArgs); return new BatchSqlResultImpl(findSql, batchSqlArgs);
} }
} }
parse = parseBatch(findSql, methodArgNameMap); parse = parseBatch(findSql, methodArgNameMap);
return new BatchSqlResultImpl(parse, batchSqlArgs); return new BatchSqlResultImpl(parse, batchSqlArgs);
} }
private String findSql(String sql, boolean custom, Method method, Object[] args) { private String findSql(String sql, boolean custom, Method method, Object[] args) {
String parsing = sql; String parsing = sql;
if (custom) { if (custom) {
// 自定义 // 自定义
Parameter[] parameters = method.getParameters(); Parameter[] parameters = method.getParameters();
try { try {
if (parameters.length == 0) { if (parameters.length == 0) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!"); throw new BindingException("cant not find sql parameter! this parameters is nothing!");
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!"); throw new BindingException("cant not find sql parameter! this parameters is nothing!");
} }
for (int i = 0; i < parameters.length; i++) { for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i]; Parameter parameter = parameters[i];
Object arg = args[i]; Object arg = args[i];
Class<?> type = parameter.getType(); Class<?> type = parameter.getType();
SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class); SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class);
if (sqlAnnotation != null && type.equals(String.class)) { if (sqlAnnotation != null && type.equals(String.class)) {
try { try {
parsing = arg.toString(); parsing = arg.toString();
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new BindingException("sql String param is null!"); throw new BindingException("sql String param is null!");
} }
break; break;
} }
} }
} }
return parsing; return parsing;
} }
private Map<String, Object> buildMethodArgNameMap(Method method, Object[] args) { private Map<String, Object> buildMethodArgNameMap(Method method, Object[] args) {
Parameter[] parameters = method.getParameters(); Parameter[] parameters = method.getParameters();
Map<String, Object> params = new HashMap<>(); Map<String, Object> params = new HashMap<>();
// 参数处理 // 参数处理
try { try {
for (int i = 0; i < parameters.length; i++) { for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i]; Parameter parameter = parameters[i];
Object arg = args[i]; Object arg = args[i];
String name = parameter.getName(); String name = parameter.getName();
Class<?> type = parameter.getType(); Class<?> type = parameter.getType();
SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class); SqlString sqlAnnotation = parameter.getAnnotation(SqlString.class);
ParamMapper paramAnnotation = parameter.getAnnotation(ParamMapper.class); ParamMapper paramAnnotation = parameter.getAnnotation(ParamMapper.class);
if (sqlAnnotation != null && type.equals(String.class)) { if (sqlAnnotation != null && type.equals(String.class)) {
continue; continue;
} }
if (paramAnnotation != null) { if (paramAnnotation != null) {
params.put(paramAnnotation.value(), arg); params.put(paramAnnotation.value(), arg);
continue; continue;
} }
BatchSqlArgs batchSqlArgs = parameter.getAnnotation(BatchSqlArgs.class); BatchSqlArgs batchSqlArgs = parameter.getAnnotation(BatchSqlArgs.class);
if (batchSqlArgs != null) { if (batchSqlArgs != null) {
try { try {
this.batchSqlArgsList = (List<Object>) arg; this.batchSqlArgsList = (List<Object>) arg;
} catch (Exception e) { } catch (Exception e) {
throw new BindingException("can not parse batchSqlArgs for " + parameter.getName() + ", param index is " + i); throw new BindingException("can not parse batchSqlArgs for " + parameter.getName() + ", param index is " + i);
} }
continue; continue;
} }
params.put(name, arg); params.put(name, arg);
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
throw new BindingException("cant not find sql parameter! this parameters is nothing!"); throw new BindingException("cant not find sql parameter! this parameters is nothing!");
} }
return params; return params;
} }
private String parse(String sql, Object arg) { private String parse(String sql, Object arg) {
String parseSql = sql; String parseSql = sql;
String pattern = "\\$t\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}"; String pattern = "\\$t\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
Pattern compile = Pattern.compile(pattern); Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(parseSql); Matcher matcher = compile.matcher(parseSql);
while (matcher.find()) { while (matcher.find()) {
String regx = matcher.group("regx"); String regx = matcher.group("regx");
String field = matcher.group("field"); String field = matcher.group("field");
String other = matcher.group("other"); String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, true); Object value = getValueByRegx(regx, field, other, arg, true);
parseSql = parseSql.replaceFirst(pattern, value.toString()); parseSql = parseSql.replaceFirst(pattern, value.toString());
} }
pattern = "\\$\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}"; pattern = "\\$\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
compile = Pattern.compile(pattern); compile = Pattern.compile(pattern);
matcher = compile.matcher(parseSql); matcher = compile.matcher(parseSql);
while (matcher.find()) { while (matcher.find()) {
String regx = matcher.group("regx"); String regx = matcher.group("regx");
String field = matcher.group("field"); String field = matcher.group("field");
String other = matcher.group("other"); String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, false); Object value = getValueByRegx(regx, field, other, arg, false);
parseSql = parseSql.replaceFirst(pattern, value.toString()); parseSql = parseSql.replaceFirst(pattern, value.toString());
} }
// pattern = "#\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}"; // pattern = "#\\{\\s*(?<regx>(?<field>\\w+)(\\.?(?<other>\\S+))*)\\s*}";
pattern = "#\\{\\s*(?<regx>(?<field>\\w+)\\.*(?<other>\\w+)*)\\s*}"; pattern = "#\\{\\s*(?<regx>(?<field>\\w+)\\.*(?<other>\\w+)*)\\s*}";
compile = Pattern.compile(pattern); compile = Pattern.compile(pattern);
matcher = compile.matcher(parseSql); matcher = compile.matcher(parseSql);
while (matcher.find()) { while (matcher.find()) {
String regx = matcher.group("regx"); String regx = matcher.group("regx");
String field = matcher.group("field"); String field = matcher.group("field");
String other = matcher.group("other"); String other = matcher.group("other");
Object value = getValueByRegx(regx, field, other, arg, true); Object value = getValueByRegx(regx, field, other, arg, true);
parseSql = parseSql.replaceFirst(pattern, "?"); parseSql = parseSql.replaceFirst(pattern, "?");
sqlArgs.add(value); sqlArgs.add(value);
} }
return parseSql; return parseSql;
} }
private Object getValueByRegx(String regx, String field, String other, Object arg, boolean isEscape) { private Object getValueByRegx(String regx, String field, String other, Object arg, boolean isEscape) {
if (!regx.contains(".")) { if (!regx.contains(".")) {
return valueHandler(arg, field, isEscape); return valueHandler(arg, field, isEscape);
} }
String pattern = "(?<field>\\w+)\\.*(?<other>(\\S+)*)"; String pattern = "(?<field>\\w+)\\.*(?<other>(\\S+)*)";
Pattern compile = Pattern.compile(pattern); Pattern compile = Pattern.compile(pattern);
Matcher matcher = compile.matcher(other); Matcher matcher = compile.matcher(other);
Object o = valueHandler(arg, field, isEscape); Object o = valueHandler(arg, field, isEscape);
if (matcher.find()) { if (matcher.find()) {
String innerField = matcher.group("field"); String innerField = matcher.group("field");
String innerOther = matcher.group("other"); String innerOther = matcher.group("other");
return getValueByRegx(other, innerField, innerOther, o, isEscape); return getValueByRegx(other, innerField, innerOther, o, isEscape);
} }
// return getValueByRegx(other,) // return getValueByRegx(other,)
throw new BindingException("Unable to find value " + other); throw new BindingException("Unable to find value " + other);
} }
private Object valueHandler(Object arg, String key, boolean isEscape) { private Object valueHandler(Object arg, String key, boolean isEscape) {
if (arg == null) { if (arg == null) {
return null; return null;
// throw new CustomerException(String.format("sql参数{%s} 为null请检查",key)); // throw new CustomerException(String.format("sql参数{%s} 为null请检查",key));
} }
if (arg instanceof Number) { if (arg instanceof Number) {
// 处理数字类型 // 处理数字类型
return arg; return arg;
} }
if (arg instanceof Boolean) { if (arg instanceof Boolean) {
// 处理布尔类型 // 处理布尔类型
return arg; return arg;
} }
if (arg instanceof Character || arg instanceof String) { if (arg instanceof Character || arg instanceof String) {
// 处理字符类型 // 处理字符类型
if (isEscape) { if (isEscape) {
return arg; return arg;
} else { } else {
return "'" + arg + "'"; return "'" + arg + "'";
} }
} }
if (arg.getClass().isArray()) { if (arg.getClass().isArray()) {
// throw new TypeNonsupportException("A value is expected, but a set is received"); // throw new TypeNonsupportException("A value is expected, but a set is received");
return StringUtils.join((Object[]) arg, ","); return StringUtils.join((Object[]) arg, ",");
} }
// 判断参数类型 // 判断参数类型
if (arg instanceof Collection) { if (arg instanceof Collection) {
// list // list
// throw new TypeNonsupportException("A value is expected, but a set is received"); // throw new TypeNonsupportException("A value is expected, but a set is received");
return StringUtils.join((Collection<?>) arg, ","); return StringUtils.join((Collection<?>) arg, ",");
} }
if (arg instanceof Map) { if (arg instanceof Map) {
// map // map
if (!((Map<?, ?>) arg).containsKey(key)) { if (!((Map<?, ?>) arg).containsKey(key)) {
throw new ParseSqlException("Failed to find {" + key + "} related field after parsing exception!"); throw new ParseSqlException("Failed to find {" + key + "} related field after parsing exception!");
} }
Object o = ((Map<?, ?>) arg).get(key); Object o = ((Map<?, ?>) arg).get(key);
if (null == o) { if (null == o) {
return ""; return "";
} }
if (o instanceof Character || o instanceof String) { if (o instanceof Character || o instanceof String) {
// 处理字符类型 // 处理字符类型
if (isEscape) { if (isEscape) {
return o; return o;
} else { } else {
return "'" + o + "'"; return "'" + o + "'";
} }
} }
if (o instanceof Collection) { if (o instanceof Collection) {
return valueHandler(o, key, isEscape); return valueHandler(o, key, isEscape);
} }
if (o.getClass().isArray()) { if (o.getClass().isArray()) {
return valueHandler(o, key, isEscape); return valueHandler(o, key, isEscape);
} }
if (o instanceof Number) { if (o instanceof Number) {
// 处理数字类型 // 处理数字类型
return valueHandler(o, key, isEscape); return valueHandler(o, key, isEscape);
} }
if (o instanceof Boolean) { if (o instanceof Boolean) {
// 处理布尔类型 // 处理布尔类型
return valueHandler(o, key, isEscape); return valueHandler(o, key, isEscape);
} }
if (o instanceof Character || o instanceof String) { if (o instanceof Character || o instanceof String) {
// 处理字符类型 // 处理字符类型
return valueHandler(o, key, isEscape); return valueHandler(o, key, isEscape);
} }
return o; return o;
} }
String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1); String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
// 当做javaBean处理 // 当做javaBean处理
try { try {
Method method = arg.getClass().getMethod(methodName); Method method = arg.getClass().getMethod(methodName);
Object invoke = method.invoke(arg); Object invoke = method.invoke(arg);
if (invoke instanceof Character || invoke instanceof String) { if (invoke instanceof Character || invoke instanceof String) {
// 处理字符类型 // 处理字符类型
if (isEscape) { if (isEscape) {
return invoke; return invoke;
} else { } else {
return "'" + invoke + "'"; return "'" + invoke + "'";
} }
} }
return invoke; return invoke;
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
// e.printStackTrace(); // e.printStackTrace();
throw new MethodNotFindException(methodName + " is not find!"); throw new MethodNotFindException(methodName + " is not find!");
} catch (InvocationTargetException | IllegalAccessException e) { } catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace(); e.printStackTrace();
throw new RuntimeException(e.toString()); throw new RuntimeException(e.toString());
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,6 @@
package com.api.youhong.ai.pcn.organization.orgchart.service; package com.api.youhong.ai.pcn.organization.orgchart.service;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import com.api.youhong.ai.pcn.organization.orgchart.dto.HrmResourceDto; import com.api.youhong.ai.pcn.organization.orgchart.dto.HrmResourceDto;
import com.api.youhong.ai.pcn.organization.orgchart.mapper.OrgChartMapper; import com.api.youhong.ai.pcn.organization.orgchart.mapper.OrgChartMapper;
@ -46,17 +45,28 @@ public class OrgChartService {
String lastNameEnField = Util.getCusConfigValue("lastNameEnField"); String lastNameEnField = Util.getCusConfigValue("lastNameEnField");
Assert.notBlank(lastNameEnField, "config [lastNameEnField] is null or blank!"); Assert.notBlank(lastNameEnField, "config [lastNameEnField] is null or blank!");
List<HrmResource> hrmResourceList = mapper.selectAll(typeOfEmploymentField, lastNameEnField); List<HrmResource> hrmResourceList = mapper.selectAll(typeOfEmploymentField, lastNameEnField);
if (Objects.isNull(hrmResourceList) || hrmResourceList.isEmpty()) {
throw new CustomerException("查询不到相关人员!");
}
//List<HrmResourceDto> hrmResourceDtoList = new ArrayList(); //List<HrmResourceDto> hrmResourceDtoList = new ArrayList();
AtomicReference<HrmResourceDto> currentUser = new AtomicReference<>(); AtomicReference<HrmResourceDto> currentUser = new AtomicReference<>();
/* ******************* 将pojo转换为Dto对象对节点属性默认值赋值找出当前用户并设置显示 ******************* */ /* ******************* 将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()); List<HrmResourceDto> hrmResourceDtoList = hrmResourceList.stream()
hrmResourceDtoList.stream().filter(item -> item.getId() == userId).forEach(item -> { .map(struct::hrmResourceToDto)
Builder.startSet(item).with(HrmResourceDto::setShow, 1).with(HrmResourceDto::setShowBrother, 1).with(HrmResourceDto::setShowChildren, 1).with(HrmResourceDto::setCurrent, true).endSet(); .peek(item -> Builder.startSet(item)
currentUser.set(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!"); Assert.notNull(currentUser, "not find current login user info!");
/* ******************* 查找当前登陆人员的所有上级 ******************* */ /* ******************* 查找当前登陆人员的所有上级 ******************* */
String currentUserManagerStr = currentUser.get().getManagerStr(); String currentUserManagerStr = currentUser.get().getManagerStr();
@ -64,9 +74,16 @@ public class OrgChartService {
currentUserManagerStr = ""; currentUserManagerStr = "";
} }
currentUserManagerStr = Util.removeSeparator(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); ShowPointOrAll showPointOrAll = mapper.selectShowPointOrAll(userId);
@ -75,21 +92,34 @@ public class OrgChartService {
/* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */
orgChartNodeVoList = hrmResourceDtoList.stream() orgChartNodeVoList = hrmResourceDtoList.stream()
.map(struct::hrmResourceDtoToVo) .map(struct::hrmResourceDtoToVo)
.peek(item -> item.setType(-1))
.collect(Collectors.toList()); .collect(Collectors.toList());
} else { } else {
/* ******************* 转换dto为Vo并且设置根节点标识 ******************* */ /* ******************* 转换dto为Vo并且设置根节点标识 ******************* */
orgChartNodeVoList = hrmResourceDtoList.stream().map(struct::hrmResourceDtoToVo).peek(item -> { orgChartNodeVoList = hrmResourceDtoList.stream()
if (showPointOrAll.isShowAll()) { .map(struct::hrmResourceDtoToVo)
Builder.startSet(item).with(OrgChartNodeVo::setShow, 1).with(OrgChartNodeVo::setShowBrother, 1).with(OrgChartNodeVo::setShowChildren, 1).endSet(); .peek(item -> {
} if (showPointOrAll.isShowAll()) {
if (!showPointOrAll.isShowType()) { Builder.startSet(item)
item.setType(-1); .with(OrgChartNodeVo::setShow, 1)
} .with(OrgChartNodeVo::setShowBrother, 1)
}).collect(Collectors.toList()); .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; package weaver.xiao.commons.config.dao;
import weaver.conn.RecordSet; import weaver.conn.RecordSet;
import weaver.general.Util; import weaver.general.Util;
import weaver.xiao.commons.config.entity.DocImageFile; import weaver.xiao.commons.config.entity.DocImageFile;
import weaver.xiao.commons.config.entity.FieldMessage; import weaver.xiao.commons.config.entity.FieldMessage;
import weaver.xiao.commons.config.entity.MappingDetail; import weaver.xiao.commons.config.entity.MappingDetail;
import weaver.xiao.commons.config.entity.RequestMappingConfig; import weaver.xiao.commons.config.entity.RequestMappingConfig;
import weaver.xiao.commons.config.enumtype.DataSourceEnum; import weaver.xiao.commons.config.enumtype.DataSourceEnum;
import weaver.xiao.commons.exception.ValueDealException; import weaver.xiao.commons.exception.ValueDealException;
import weaver.xiao.commons.utils.SqlUtil; import weaver.xiao.commons.utils.SqlUtil;
import weaver.zwl.common.ToolUtil; import weaver.zwl.common.ToolUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
/** /**
* @author XiaoBokang * @author XiaoBokang
* @create 2021/12/29 9:46 * @create 2021/12/29 9:46
*/ */
public class ConfigMappingCMD { public class ConfigMappingCMD {
private final ToolUtil toolUtil = new ToolUtil(); private final ToolUtil toolUtil = new ToolUtil();
private final String configTableName = "uf_request_config"; private final String configTableName = "uf_request_config";
private final SqlUtil sqlUtil = new SqlUtil(); private final SqlUtil sqlUtil = new SqlUtil();
public RequestMappingConfig selectByUniqueCode(String uniqueCode) { public RequestMappingConfig selectByUniqueCode(String uniqueCode) {
toolUtil.writeDebuggerLog("=======================查询配置列表======================="); toolUtil.writeDebuggerLog("=======================查询配置列表=======================");
RequestMappingConfig requestMappingConfig = new RequestMappingConfig(); RequestMappingConfig requestMappingConfig = new RequestMappingConfig();
RecordSet recordSet = new RecordSet(); RecordSet recordSet = new RecordSet();
String querySql = "select id,workflow,requestUrl,dataSource,uniqueCode, relationWorkFlow,cusWhereSql from " + configTableName + " where uniqueCode = ?"; 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); toolUtil.writeDebuggerLog("执行查询的sql query mainRequestMappingConfig list sql new>>>>" + querySql + " uniqueCode >>" + uniqueCode);
recordSet.executeQuery(querySql, uniqueCode); recordSet.executeQuery(querySql, uniqueCode);
if (recordSet.next()) { if (recordSet.next()) {
int mainId = Util.getIntValue(recordSet.getString("id")); int mainId = Util.getIntValue(recordSet.getString("id"));
requestMappingConfig = sqlUtil.recordSetToEntityByEntity(recordSet, RequestMappingConfig.class); requestMappingConfig = sqlUtil.recordSetToEntityByEntity(recordSet, RequestMappingConfig.class);
this.setDetailMapping(mainId, requestMappingConfig); this.setDetailMapping(mainId, requestMappingConfig);
} }
return requestMappingConfig; return requestMappingConfig;
} }
private void setDetailMapping(int mainId, RequestMappingConfig requestMappingConfig) { private void setDetailMapping(int mainId, RequestMappingConfig requestMappingConfig) {
// 查询明细1的信息 // 查询明细1的信息
RecordSet detail1RecordSet = new RecordSet(); RecordSet detail1RecordSet = new RecordSet();
String dataSource = requestMappingConfig.getDataSource(); String dataSource = requestMappingConfig.getDataSource();
if (Objects.isNull(dataSource) || "".equals(dataSource)) { if (Objects.isNull(dataSource) || "".equals(dataSource)) {
dataSource = "0"; dataSource = "0";
} }
DataSourceEnum anEnum = DataSourceEnum.getEnum(dataSource); DataSourceEnum anEnum = DataSourceEnum.getEnum(dataSource);
String queryDetail1Sql = ""; String queryDetail1Sql = "";
switch (anEnum) { switch (anEnum) {
case CUS_TABLE: case CUS_TABLE:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext," + queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext," +
" from " + configTableName + "_dt1 config "; " from " + configTableName + "_dt1 config ";
break; break;
case WORKFLOW: case WORKFLOW:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,valueContext,relationWorkFlowField, " + queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,valueContext,relationWorkFlowField, " +
" fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " + " fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " +
" from " + configTableName + "_dt1 config " + " from " + configTableName + "_dt1 config " +
" left join workflow_field_table_view fv " + " left join workflow_field_table_view fv " +
" on config.workflowField = fv.id or config.relationWorkFlowField = fv.id" + " on config.workflowField = fv.id or config.relationWorkFlowField = fv.id" +
" where mainid = ? "; " where mainid = ? ";
break; break;
case MODEL: case MODEL:
queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext, " + queryDetail1Sql = "select paramName,paramType,getValueType,dataSource,belongTo,workflowField,modelField,fieldName,valueContext, " +
" fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " + " fv.id fieldId,fv.fieldname,fv.tablename,fv.indexdesc " +
" from " + configTableName + "_dt1 config " + " from " + configTableName + "_dt1 config " +
" left join workflow_field_table_view fv on config.modelField = fv.id " + " left join workflow_field_table_view fv on config.modelField = fv.id " +
" where mainid = ? "; " where mainid = ? ";
break; break;
default: default:
throw new ValueDealException("不支持的数据来源"); throw new ValueDealException("不支持的数据来源");
} }
toolUtil.writeDebuggerLog("执行查询的明细1sql query detail1Sql >>>>" + queryDetail1Sql + " mainId:" + mainId); toolUtil.writeDebuggerLog("执行查询的明细1sql query detail1Sql >>>>" + queryDetail1Sql + " mainId:" + mainId);
detail1RecordSet.executeQuery(queryDetail1Sql, mainId); detail1RecordSet.executeQuery(queryDetail1Sql, mainId);
List<MappingDetail> mappingDetails = new ArrayList<>(); List<MappingDetail> mappingDetails = new ArrayList<>();
while (detail1RecordSet.next()) { while (detail1RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, MappingDetail.class); MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, MappingDetail.class);
String getValueType = mappingDetail.getGetValueType(); String getValueType = mappingDetail.getGetValueType();
// 设置流程字段相关信息 // 设置流程字段相关信息
// if("0".equals(getValueType) || "4".equals(getValueType)){ // if("0".equals(getValueType) || "4".equals(getValueType)){
FieldMessage fieldMessage = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, FieldMessage.class); FieldMessage fieldMessage = sqlUtil.recordSetToEntityByEntity(detail1RecordSet, FieldMessage.class);
mappingDetail.setFieldMassage(fieldMessage); mappingDetail.setFieldMassage(fieldMessage);
// } // }
mappingDetails.add(mappingDetail); mappingDetails.add(mappingDetail);
} }
// 查询明细2的信息 // 查询明细2的信息
RecordSet detail2RecordSet = new RecordSet(); RecordSet detail2RecordSet = new RecordSet();
String queryDetail2Sql = "select paramName,belongTo,childType,dataSource,detailId,cusWhereSql from uf_request_config_dt2 where mainid = ?"; String queryDetail2Sql = "select paramName,belongTo,childType,dataSource,detailId,cusWhereSql from uf_request_config_dt2 where mainid = ?";
toolUtil.writeDebuggerLog("执行查询的明细sql query detail2Sql >>>>" + queryDetail2Sql + " mainId:" + mainId); toolUtil.writeDebuggerLog("执行查询的明细sql query detail2Sql >>>>" + queryDetail2Sql + " mainId:" + mainId);
detail2RecordSet.executeQuery(queryDetail2Sql, mainId); detail2RecordSet.executeQuery(queryDetail2Sql, mainId);
while (detail2RecordSet.next()) { while (detail2RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail2RecordSet, MappingDetail.class); MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail2RecordSet, MappingDetail.class);
mappingDetail.setParamType("6");// 设置参数类型为List mappingDetail.setParamType("6");// 设置参数类型为List
mappingDetails.add(mappingDetail); mappingDetails.add(mappingDetail);
} }
// 查询明细3的信息 // 查询明细3的信息
RecordSet detail3RecordSet = new RecordSet(); RecordSet detail3RecordSet = new RecordSet();
String queryDetail3Sql = "select paramName,belongTo from uf_request_config_dt3 where mainid = ?"; String queryDetail3Sql = "select paramName,belongTo from uf_request_config_dt3 where mainid = ?";
toolUtil.writeDebuggerLog("执行查询的明细sql query detail3Sql >>>>" + queryDetail3Sql + " mainId:" + mainId); toolUtil.writeDebuggerLog("执行查询的明细sql query detail3Sql >>>>" + queryDetail3Sql + " mainId:" + mainId);
detail3RecordSet.executeQuery(queryDetail3Sql, mainId); detail3RecordSet.executeQuery(queryDetail3Sql, mainId);
while (detail3RecordSet.next()) { while (detail3RecordSet.next()) {
MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail3RecordSet, MappingDetail.class); MappingDetail mappingDetail = sqlUtil.recordSetToEntityByEntity(detail3RecordSet, MappingDetail.class);
mappingDetail.setParamType("5");// 设置参数类型为Object mappingDetail.setParamType("5");// 设置参数类型为Object
mappingDetails.add(mappingDetail); mappingDetails.add(mappingDetail);
} }
requestMappingConfig.setConfigDetail(mappingDetails); requestMappingConfig.setConfigDetail(mappingDetails);
// //查询明细4的信息 // //查询明细4的信息
// RecordSet detail4RecordSet = new RecordSet(); // RecordSet detail4RecordSet = new RecordSet();
// List<ResponseMapping> responseMappingList = new ArrayList<>(); // List<ResponseMapping> responseMappingList = new ArrayList<>();
// String queryDetail4Sql = "select responseFieldName,workflowField,mainOrDetail,detailTableId,workflowFieldName from uf_request_config_dt4 where mainid = ?"; // String queryDetail4Sql = "select responseFieldName,workflowField,mainOrDetail,detailTableId,workflowFieldName from uf_request_config_dt4 where mainid = ?";
// toolUtil.writeDebuggerLog("执行查询的明细sql query detail4Sql >>>>"+queryDetail4Sql+" mainId:"+mainId); // toolUtil.writeDebuggerLog("执行查询的明细sql query detail4Sql >>>>"+queryDetail4Sql+" mainId:"+mainId);
// detail4RecordSet.executeQuery(queryDetail4Sql,mainId); // detail4RecordSet.executeQuery(queryDetail4Sql,mainId);
// while (detail4RecordSet.next()){ // while (detail4RecordSet.next()){
// ResponseMapping responseMapping = sqlUtil.recordSetToEntityByEntity(detail4RecordSet, ResponseMapping.class); // ResponseMapping responseMapping = sqlUtil.recordSetToEntityByEntity(detail4RecordSet, ResponseMapping.class);
// responseMappingList.add(responseMapping); // responseMappingList.add(responseMapping);
// } // }
// requestMappingConfig.setResponseMappingList(responseMappingList); // requestMappingConfig.setResponseMappingList(responseMappingList);
requestMappingConfig.setConfigDetail(mappingDetails); requestMappingConfig.setConfigDetail(mappingDetails);
} }
/** /**
* <h2></h2> * <h2></h2>
* *
* @param docIds id * @param docIds id
* @return * @return
* @author YouHong.ai * @author YouHong.ai
*/ */
public List<DocImageFile> selectDocImageFileList(String docIds) { public List<DocImageFile> selectDocImageFileList(String docIds) {
String sql = "select docfile.IMAGEFILEID,docfile.IMAGEFILENAME,docfile.DOCID,docfile.ID, " + String sql = "select docfile.IMAGEFILEID,docfile.IMAGEFILENAME,docfile.DOCID,docfile.ID, " +
" imf.FILESIZE " + " imf.FILESIZE " +
"from docimagefile docfile " + "from docimagefile docfile " +
"left join imagefile imf on imf.IMAGEFILEID = docfile.IMAGEFILEID " + "left join imagefile imf on imf.IMAGEFILEID = docfile.IMAGEFILEID " +
"where docid in (" + docIds + ")"; "where docid in (" + docIds + ")";
RecordSet rs = new RecordSet(); RecordSet rs = new RecordSet();
rs.executeQuery(sql); rs.executeQuery(sql);
List<DocImageFile> docImageFileList = new ArrayList<>(); List<DocImageFile> docImageFileList = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
String IMAGEFILEID = rs.getString("IMAGEFILEID"); String IMAGEFILEID = rs.getString("IMAGEFILEID");
String IMAGEFILENAME = rs.getString("IMAGEFILENAME"); String IMAGEFILENAME = rs.getString("IMAGEFILENAME");
String DOCID = rs.getString("DOCID"); String DOCID = rs.getString("DOCID");
String ID = rs.getString("ID"); String ID = rs.getString("ID");
String fileSize = rs.getString("FILESIZE"); String fileSize = rs.getString("FILESIZE");
DocImageFile docImageFile = new DocImageFile(); DocImageFile docImageFile = new DocImageFile();
docImageFile.setImageFileId(Util.getIntValue(IMAGEFILEID)); docImageFile.setImageFileId(Util.getIntValue(IMAGEFILEID));
docImageFile.setImageFileName(IMAGEFILENAME); docImageFile.setImageFileName(IMAGEFILENAME);
docImageFile.setDocId(Util.getIntValue(DOCID)); docImageFile.setDocId(Util.getIntValue(DOCID));
docImageFile.setId(Util.getIntValue(ID)); docImageFile.setId(Util.getIntValue(ID));
docImageFile.setFileSize(Util.getIntValue(fileSize) / 1024L); docImageFile.setFileSize(Util.getIntValue(fileSize) / 1024L);
docImageFileList.add(docImageFile); docImageFileList.add(docImageFile);
} }
if (docImageFileList.isEmpty()) { if (docImageFileList.isEmpty()) {
throw new NullPointerException("附件字段不存在值!请检查数据表或配置表数据类型是否正确!"); throw new NullPointerException("附件字段不存在值!请检查数据表或配置表数据类型是否正确!");
} }
return docImageFileList; return docImageFileList;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,9 +1,11 @@
package weaver.xuanran.wang.common.mapper; package weaver.xuanran.wang.common.mapper;
import aiyh.utils.annotation.recordset.*; 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 java.util.List; import java.util.List;
import java.util.Map;
/** /**
* @Author xuanran.wang * @Author xuanran.wang
@ -41,13 +43,4 @@ public interface CommonMapper {
@Delete("delete from $t{tableName} where id in (${ids})") @Delete("delete from $t{tableName} where id in (${ids})")
boolean deleteModelDataByIds(@ParamMapper("tableName") String tableName, boolean deleteModelDataByIds(@ParamMapper("tableName") String tableName,
@ParamMapper("ids") List<String> ids); @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,24 +2,16 @@ package weaver.xuanran.wang.common.util;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger; 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.CusDateFormat;
import weaver.xuanran.wang.common.annocation.ParamNotNull; import weaver.xuanran.wang.common.annocation.ParamNotNull;
import weaver.xuanran.wang.common.mapper.CommonMapper;
import java.io.*; import java.io.*;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
@ -34,26 +26,12 @@ import java.util.zip.ZipFile;
* @Date 2022/11/23 10:25 * @Date 2022/11/23 10:25
*/ */
public class CommonUtil { public class CommonUtil {
/**
* <h2></h2> private final Logger logger = Util.getLogger();
**/
private static final Logger logger = Util.getLogger(CommonUtil.class.getName()); public static final int SQL_IN_PAGE_SIZE = 100;
/**
* <h2>sqlin</h2> private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
**/
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> * <h1></h1>
@ -69,8 +47,6 @@ public class CommonUtil {
} }
// 开始解压 // 开始解压
ZipFile zipFile = null; ZipFile zipFile = null;
InputStream is = null;
FileOutputStream fos = null;
try { try {
zipFile = new ZipFile(new File(srcFilePath), Charset.forName("GBK")); zipFile = new ZipFile(new File(srcFilePath), Charset.forName("GBK"));
Enumeration<?> entries = zipFile.entries(); Enumeration<?> entries = zipFile.entries();
@ -79,25 +55,16 @@ public class CommonUtil {
if (entry.isDirectory()) { if (entry.isDirectory()) {
String dirPath = acceptFilePath + File.separator + entry.getName(); String dirPath = acceptFilePath + File.separator + entry.getName();
File dir = new File(dirPath); File dir = new File(dirPath);
boolean mkdirs = dir.mkdirs(); dir.mkdirs();
if(!mkdirs){
throw new CustomerException("创建文件夹失败!, 文件夹路径:[ " + dirPath + " ]");
}
} else { } else {
String temp = acceptFilePath + File.separator + entry.getName(); String temp = acceptFilePath + File.separator + entry.getName();
File targetFile = new File(temp); File targetFile = new File(temp);
if(!targetFile.getParentFile().exists()){ if(!targetFile.getParentFile().exists()){
boolean mkdirs = targetFile.getParentFile().mkdirs(); targetFile.getParentFile().mkdirs();
if(!mkdirs){
throw new CustomerException("创建文件夹失败!, 文件夹路径:[ " + targetFile.getParentFile() + " ]");
}
} }
boolean newFile = targetFile.createNewFile(); targetFile.createNewFile();
if(!newFile){ InputStream is = zipFile.getInputStream(entry);
throw new CustomerException("创建文件失败!, 文件路径:[ " + temp + " ]"); FileOutputStream fos = new FileOutputStream(targetFile);
}
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(targetFile);
int len; int len;
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) { while ((len = is.read(buf)) != -1) {
@ -118,20 +85,6 @@ public class CommonUtil {
e.printStackTrace(); e.printStackTrace();
} }
} }
if(fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
} }
@ -149,17 +102,14 @@ public class CommonUtil {
File file = new File(filePath); File file = new File(filePath);
BufferedReader reader = null; BufferedReader reader = null;
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
FileReader fileReader = null;
try { try {
fileReader = new FileReader(file); reader = new BufferedReader(new FileReader(file));
reader = new BufferedReader(fileReader);
String tempString = null; String tempString = null;
// 一次读入一行直到读入null为文件结束 // 一次读入一行直到读入null为文件结束
while ((tempString = reader.readLine()) != null) { while ((tempString = reader.readLine()) != null) {
builder.append(tempString); builder.append(tempString);
} }
reader.close(); reader.close();
fileReader.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
@ -167,14 +117,6 @@ public class CommonUtil {
try { try {
reader.close(); reader.close();
} catch (IOException ie) { } catch (IOException ie) {
logger.error("关闭io流异常, " + ie.getMessage());
}
}
if(fileReader != null){
try {
fileReader.close();
} catch (IOException ie) {
logger.error("关闭io流异常, " + ie.getMessage());
} }
} }
} }
@ -187,7 +129,7 @@ public class CommonUtil {
* @dateTime 2022/11/23 15:59 * @dateTime 2022/11/23 15:59
* @param t * @param t
**/ **/
public static <T> void checkParamNotNull(T t){ public static <T> void checkParamNotNull(T t) throws IllegalAccessException {
Class<?> clazz = t.getClass(); Class<?> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields(); Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) { for (Field field : fields) {
@ -196,12 +138,7 @@ public class CommonUtil {
continue; continue;
} }
field.setAccessible(true); field.setAccessible(true);
Object value = null; Object value = field.get(t);
try {
value = field.get(t);
}catch (IllegalAccessException e){
throw new CustomerException("获取类字段值异常: " + e.getMessage());
}
Class<?> valueClass = field.getType(); Class<?> valueClass = field.getType();
boolean isNull = false; boolean isNull = false;
if(valueClass.isAssignableFrom(String.class)){ if(valueClass.isAssignableFrom(String.class)){
@ -243,10 +180,8 @@ public class CommonUtil {
return Stream.iterate(0, n -> n + 1) return Stream.iterate(0, n -> n + 1)
.limit(maxSize) .limit(maxSize)
.parallel() .parallel()
.map(a -> list.parallelStream() .map(a -> list.parallelStream().skip((long) a * splitSize).limit(splitSize).collect(Collectors.toList()))
.skip((long) a * splitSize).limit(splitSize) .filter(b -> !b.isEmpty())
.collect(Collectors.toList())
).filter(b -> !b.isEmpty())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
/** /**
@ -278,245 +213,4 @@ public class CommonUtil {
throw new RuntimeException(Util.logStr("解析日期失败!当前传入转化格式:[{}],待转化日期:[{}]", to, date)); 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,11 +2,9 @@ package weaver.xuanran.wang.common.util;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
import aiyh.utils.sqlUtil.sqlResult.impl.BatchSqlResultImpl; import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.sqlUtil.whereUtil.Where; import aiyh.utils.sqlUtil.whereUtil.Where;
import com.alibaba.fastjson.JSONObject; 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.commons.lang3.StringUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import weaver.conn.RecordSet; import weaver.conn.RecordSet;
@ -15,7 +13,8 @@ import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil; import weaver.general.TimeUtil;
import weaver.xuanran.wang.common.mapper.CommonMapper; import weaver.xuanran.wang.common.mapper.CommonMapper;
import java.util.*; import java.util.List;
import java.util.Map;
/** /**
* @Author xuanran.wang * @Author xuanran.wang
@ -26,21 +25,7 @@ public class CusInfoToOAUtil {
private static final ModeDataIdUpdate modeDataIdUpdate = ModeDataIdUpdate.getInstance(); private static final ModeDataIdUpdate modeDataIdUpdate = ModeDataIdUpdate.getInstance();
private static final ModeRightInfo moderightinfo = new ModeRightInfo(); private static final ModeRightInfo moderightinfo = new ModeRightInfo();
private static final Logger log = Util.getLogger(); private static final Logger log = Util.getLogger();
public static final String TABLE_NAME_PLACEHOLDER = "#\\{tableName}"; public static final String TABLE_NAME_PLACEHOLDER = "#\\{table}";
/**
* <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> * <h1></h1>
* @author xuanran.wang * @author xuanran.wang
@ -51,61 +36,10 @@ public class CusInfoToOAUtil {
* @param whereParams * @param whereParams
* @return id * @return id
**/ **/
public static String getDataId(int modelId, public static int execute(int modelId,
Map<String, Object> params, Map<String, Object> params,
String whereSql, String whereSql,
List<String> whereParams) { 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){ if(modelId < 0){
throw new RuntimeException("建模模块id不能小于0!"); throw new RuntimeException("建模模块id不能小于0!");
} }
@ -113,74 +47,37 @@ public class CusInfoToOAUtil {
if(StringUtils.isBlank(tableName)){ if(StringUtils.isBlank(tableName)){
throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!"); throw new CustomerException("模块id为 " + modelId + ", 在系统中暂没查询到对应表单!");
} }
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)){
if(CollectionUtils.isEmpty(whereParams) || CollectionUtils.isEmpty(params) || whereParams.size() != params.size()){
throw new CustomerException("使用批量更新时如果需要对重复数据进行更新,参数集合和判断重复参数集合大小必须相等!");
}
}
RecordSet rs = new RecordSet(); RecordSet rs = new RecordSet();
List<String> dataIds = new ArrayList<>(); int mainId = -1;
List<Where> wheres = new ArrayList<>(); boolean needModeRight = false;
for (int i = 0; i < params.size(); i++) { if(StringUtils.isNotBlank(whereSql)){
int mainId = -1; whereSql = whereSql.replaceAll(TABLE_NAME_PLACEHOLDER, tableName);
if(StringUtils.isNotBlank(whereSql)){ if (rs.executeQuery(whereSql, whereParams) && rs.next()) {
whereSql = Util.sbc2dbcCase(whereSql); mainId = Util.getIntValue(rs.getString(1),-1);
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));
} }
BatchSqlResultImpl batchSql = Util.createSqlBuilder().updateBatchSql(tableName, params, wheres); if(mainId < 0){
String sqlStr = batchSql.getSqlStr(); mainId = getNewIdByModelInfo(tableName, modelId);
List<List> batchList = batchSql.getBatchList(); needModeRight = true;
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(CollectionUtils.isEmpty(dataIds)){ Where where = Util.createPrepWhereImpl()
throw new CustomerException("建模数据生成失败!"); .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);
} }
for (String dataId : dataIds) { if(needModeRight){
moderightinfo.rebuildModeDataShareByEdit(1, modelId, Integer.parseInt(dataId)); moderightinfo.rebuildModeDataShareByEdit(1, modelId, mainId);
} }
return dataIds; return mainId;
} }
/** /**

View File

@ -1,51 +0,0 @@
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

@ -1,26 +0,0 @@
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

@ -1,50 +0,0 @@
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

@ -1,79 +0,0 @@
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

@ -1,41 +0,0 @@
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

@ -1,23 +0,0 @@
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

@ -1,265 +0,0 @@
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

@ -1,53 +0,0 @@
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

@ -1,71 +0,0 @@
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

@ -1,114 +0,0 @@
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

@ -1,17 +0,0 @@
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

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

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