极兔ncc 自定义sql用{mainTable}代替当前表名代码同步

jingwei
wangxuanran 2023-05-31 10:07:27 +08:00
parent 7e6fa007e0
commit 685240f2f8
30 changed files with 1058 additions and 473 deletions

View File

@ -8,8 +8,8 @@ const threeMonthIndex = 1;
const submitWaitNode = WfForm.convertFieldNameToId("sftjddjd");
// 下次超时提醒日期
const timeoutRemindDateFiled = WfForm.convertFieldNameToId("cstxrq");
// 跟踪天数
const trackingDays = WfForm.getFieldValue(trackTimeField) <= 1 ? 15 : 30;
// 跟踪天数 <= 1 ? 15 : 30;
const trackingDaysField = WfForm.convertFieldNameToId("gzts")
// 跟踪触发行数
const trackingLineField = WfForm.convertFieldNameToId("gzcfxs");
$(() => {
@ -44,6 +44,7 @@ function getNodeNum(){
let currentDate = getCurrentDate();
let dayDiff = getDaysDiff(firstSaleDate, currentDate);
console.log('当前天数与首台销售日期相差天数 : ', dayDiff)
let trackingDays = WfForm.getFieldValue(trackingDaysField);
return Math.floor(dayDiff / trackingDays) + 1;
}
@ -52,6 +53,7 @@ function initTimeoutDate(){
let firstSaleDate = WfForm.getFieldValue(firstSaleDateField);
const nodeNum = getNodeNum();
console.log('到达节点次数 ', nodeNum);
let trackingDays = WfForm.getFieldValue(trackingDaysField);
console.log('跟踪天数 ', trackingDays);
let computeTimeoutDate = addDays(firstSaleDate, nodeNum * trackingDays);
console.log('计算下次超时日期 ', computeTimeoutDate);

View File

@ -45,12 +45,12 @@ public class OtherSystemToOAController {
// 获取重定向地址和secret
Map<String, String> redirectUrlAndCorpsecret = service.getRedirectUrlAndCorpsecret(appId);
String redirectUrl = Util.null2DefaultStr(redirectUrlAndCorpsecret.get("REDIRECTURL"),"");
log.info("successSendRedirectUrl : " + redirectUrl);
if(StringUtils.isBlank(redirectUrl)){
throw new CustomerException("redirectUrl is null! " + JSONObject.toJSONString(redirectUrlAndCorpsecret));
}
int userId = service.getUserFromOtherSys(code, redirectUrlAndCorpsecret);
SessionUtil.createSession(userId + "", request, response);
SessionUtil.createSession(String.valueOf(userId), request, response);
log.info("successSendRedirectUrl : " + redirectUrl);
response.sendRedirect(redirectUrl);
}catch (Exception e){
log.error("sso error : " + e.getMessage());

View File

@ -1,8 +1,11 @@
package com.api.xuanran.wang.sh_bigdata.sso.mapper;
import aiyh.utils.Util;
import aiyh.utils.annotation.recordset.ParamMapper;
import aiyh.utils.annotation.recordset.Select;
import aiyh.utils.annotation.recordset.SqlMapper;
import aiyh.utils.annotation.recordset.SqlString;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import java.util.Map;
@ -21,8 +24,8 @@ public interface OtherSystemToOAMapper {
* @param outKey id
* @return oa ID
**/
@Select("select id from hrmresource where outkey = #{outKey}")
int selectUserIdByOutKey(@ParamMapper("outKey") String outKey);
@Select(custom = true)
int selectUserIdByOutKey(@SqlString String sql, @ParamMapper("outKey") String outKey);
/**
* <h1>appId </h1>
* @author xuanran.wang

View File

@ -21,7 +21,7 @@ public interface OtherSystemToOAService {
* @param cusSuccess /
* @return
**/
int getUserIdByCode(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess, Map<String, String> redirectUrlSecret);
Object getUserIdByCode(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess, Map<String, String> redirectUrlSecret);
/**
* <h1>codeoaid</h1>
* @author xuanran.wang

View File

@ -28,12 +28,13 @@ public class OtherSystemToOAServiceImpl implements OtherSystemToOAService {
.successField("code")
.successValue(0)
.errorMsg("msg")
.dataKey("data.id")
.dataKey("data." + Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("ssoInterfaceCompareField"), "id"))
.build();
private final OtherSystemToOAMapper otherSystemToOAMapper = Util.getMapper(OtherSystemToOAMapper.class);
private final Logger log = Util.getLogger();
@Override
public int getUserIdByCode(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess, Map<String, String> redirectUrlSecret) {
public Object getUserIdByCode(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess, Map<String, String> redirectUrlSecret) {
String secret = Util.null2DefaultStr(redirectUrlSecret.get("SECRET"), "");
log.info("secret : " + secret);
if(StringUtils.isBlank(secret)){
@ -48,7 +49,7 @@ public class OtherSystemToOAServiceImpl implements OtherSystemToOAService {
params.put("code", code);
// 获取第三方系统id
String getUserInfoByCodeUrl = ShBigDataUtil.getPropertiesValByKey("getUserInfoByCodeUrl");
int codeId;
Object codeId;
try {
codeId = getUserIdByCode(getUserInfoByCodeUrl, params, new HashMap<>(), cusSuccess, redirectUrlSecret);
}catch (Exception e){
@ -61,10 +62,12 @@ public class OtherSystemToOAServiceImpl implements OtherSystemToOAService {
throw new CustomerException(e.getMessage());
}
}
if(codeId < 0){
String oaOutKey = Util.null2DefaultStr(codeId, "");
if(StringUtils.isBlank(oaOutKey)){
throw new CustomerException(Util.logStr("code : {}, not found in {} .", code, getUserInfoByCodeUrl));
}
int id = otherSystemToOAMapper.selectUserIdByOutKey(codeId + "");
String sql = "select id from hrmresource where " + Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("ssoOaCompareField"),"outkey") + " = #{outKey}";
int id = otherSystemToOAMapper.selectUserIdByOutKey(sql, oaOutKey);
if(id < 0){
throw new CustomerException(Util.logStr("code : {} not found in OA!", id));
}

View File

@ -680,6 +680,12 @@ public class DealWithMapping extends ToolUtil {
}
}
}
// 自定义sql用{mainTable}代替当前表名 解决极兔ncc问题
if(StringUtils.isNotBlank(mainTable)){
valueContext = valueContext.replace("{mainTable}", mainTable);
}else {
logger.error("mainTable is null!");
}
String requestId = Util.null2String(mainMap.get("requestid"));
tempValue = "'" + tempValue + "'";
value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId);
@ -1028,6 +1034,12 @@ public class DealWithMapping extends ToolUtil {
tempValue = Util.null2String(tempRs.getString(fieldName));
}
}
// 自定义sql用{mainTable}代替当前表名 解决极兔ncc问题
if(StringUtils.isNotBlank(mainTable)){
valueContext = valueContext.replace("{mainTable}", mainTable);
}else {
logger.error("mainTable is null!");
}
tempValue = "'" + tempValue + "'";
value = this.getValueByChangeRule(valueContext, tempValue, requestId, detailId);
}

View File

@ -1,17 +1,14 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.action;
import aiyh.utils.ThreadPoolConfig;
import aiyh.utils.action.SafeCusBaseAction;
import aiyh.utils.annotation.ActionDesc;
import aiyh.utils.annotation.PrintParamMark;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.annotation.*;
import aiyh.utils.excention.CustomerException;
import weaver.hrm.User;
import weaver.soa.workflow.request.RequestInfo;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.impl.WorkflowToSapServiceImpl;
import java.util.concurrent.ExecutorService;
/**
* <h1>sap</h1>
@ -23,31 +20,53 @@ import java.util.concurrent.ExecutorService;
public class WorkflowToSap extends SafeCusBaseAction {
private final WorkflowToSapService service = new WorkflowToSapServiceImpl();
private final ExecutorService pool = ThreadPoolConfig.createThreadPoolInstance();
@PrintParamMark
@RequiredMark("配置表唯一标识")
@ActionDefaultTestValue(value = "****")
private String uniqueCode;
@PrintParamMark
@RequiredMark("日志表模块id")
@ActionDefaultTestValue(value = "11")
private String modelId;
@PrintParamMark
@RequiredMark("成功失败/标识字段")
@ActionDefaultTestValue(value = "soap-env:Envelope.soap-env:Body.n0:ZFI_OA_DOC_POSTINGResponse.ES_OA_OUTPUT.TYPE")
private String successField;
@PrintParamMark
@RequiredMark("成功时候的值")
@ActionDefaultTestValue(value = "T")
private String successVal;
@PrintParamMark
@RequiredMark("消息提示字段")
@ActionDefaultTestValue(value = "soap-env:Envelope.soap-env:Body.n0:ZFI_OA_DOC_POSTINGResponse.ES_OA_OUTPUT.MESSAGE")
private String messageField;
@Override
public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) {
String xml = "";
String response = "";
String url = "";
String error = "";
boolean success = true;
try {
MainRequestConfig config = service.getRequestConfig(uniqueCode, billTable);
String xml = service.convertXml(config, requestId, billTable);
String response = service.sendToSap();
pool.execute(()->{
url = config.getRequestUrl();
xml = service.convertXml(config, requestId, billTable);
response = service.sendToSap(config.getRequestUrl(), xml);
service.parseResponse(response, successField, successVal, messageField);
}catch (Exception e){
log.error("流程数据推送SAP error : " + e.getMessage());
error = e.getMessage();
success = false;
}
try {
service.logToOA(modelId, config.getRequestUrl(), requestId, xml, response);
service.logToOA(modelId, url, requestId, xml, response, error);
}catch (Exception e){
log.error("日志数据写入建模失败! " + e.getMessage());
}
});
}catch (Exception e){
log.error("流程数据推送SAP error : " + e.getMessage());
if(!success){
throw new CustomerException("WorkflowToSap Action execute error : " + error);
}
}
}

View File

@ -11,6 +11,9 @@ import lombok.Data;
*/
@Data
public class DetailRequestConfig {
@SqlDbFieldAnn("nodeType")
@SqlOracleDbFieldAnn("NODETYPE")
private String nodeType;
@SqlDbFieldAnn("paramName")
@SqlOracleDbFieldAnn("PARAMNAME")
private String paramName;

View File

@ -11,6 +11,7 @@ import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConf
public interface WorkflowToSapService {
MainRequestConfig getRequestConfig(String uniqueCode, String tableName);
String convertXml(MainRequestConfig config, String requestId, String tableName);
String sendToSap();
void logToOA(String modelId, String url, String requestId, String requestXml, String response);
String sendToSap(String url, String xml);
String parseResponse(String response, String responseField, String successField, String messageField);
void logToOA(String modelId, String url, String requestId, String requestXml, String response, String error);
}

View File

@ -1,6 +1,11 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.service.impl;
import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.XML;
import weaver.xuanran.wang.common.util.CusData2OA;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService;
@ -8,6 +13,7 @@ import weaver.xuanran.wang.eighty_five_degreec.sap.util.ReadConfigUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
@ -18,7 +24,7 @@ import java.util.HashMap;
*/
public class WorkflowToSapServiceImpl implements WorkflowToSapService {
private final ReadConfigUtil configUtil = new ReadConfigUtil();
private final Logger log = Util.getLogger();
@Override
public MainRequestConfig getRequestConfig(String uniqueCode, String tableName) {
return configUtil.getConfigByUniqueCode(uniqueCode, tableName);
@ -30,20 +36,40 @@ public class WorkflowToSapServiceImpl implements WorkflowToSapService {
}
@Override
public String sendToSap() {
// TODO sap接口调用方式暂时搞不了
return "";
public String sendToSap(String url, String xml) {
return configUtil.callSap(url, xml);
}
@Override
public String parseResponse(String response, String successField, String successVal, String messageField) {
String responseVal;
JSONObject xmlResponseObj;
try {
xmlResponseObj = XML.toJSONObject(response);
}catch (Exception e){
throw new CustomerException("xml to jsonObj error : " + e.getMessage());
}
Map<String, Object> responseMap = com.alibaba.fastjson.JSONObject.parseObject(xmlResponseObj.toString(), Map.class);
responseVal = configUtil.parseMap(responseMap, successField);
if(!successVal.equals(responseVal)){
throw new CustomerException("successVal not equals responseVal! current responseVal is : "
+ responseVal + ", the successVal is " + successVal + ", responseMsg is " + configUtil.parseMap(responseMap, messageField));
}
return responseVal;
}
@Override
public void logToOA(String modelId, String url, String requestId,
String requestXml, String response) {
String requestXml, String response, String error) {
HashMap<String, Object> params = new HashMap<>();
params.put("requestUrlAndFunName", url);
params.put("requestUrl", url);
params.put("reqId", requestId);
params.put("requestXml", requestXml);
params.put("responseCode","");
params.put("erpResponse", response);
CusInfoToOAUtil.getDataId(Util.getIntValue(modelId, -1), params, "select id from #{tableName} where reqId = ?", Collections.singletonList(requestId));
params.put("sapResponse", response);
params.put("error", error);
log.info("写入日志参数 : " + com.alibaba.fastjson.JSONObject.toJSONString(params));
CusData2OA.writeToModel(modelId, "select id from #{tableName} where reqId = " + requestId, params);
}
}

View File

@ -1,5 +1,6 @@
package weaver.xuanran.wang.eighty_five_degreec.sap.util;
import aiyh.utils.excention.CustomerException;
import com.google.common.base.Strings;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
@ -12,11 +13,10 @@ import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.DetailRequestCo
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.zwl.common.ToolUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.text.ParseException;
@ -55,7 +55,7 @@ public class ReadConfigUtil extends ToolUtil {
}
int mainId = Util.getIntValue(res.getId());
// 配置明细表
sql = "select paramName,paramType,parentName,getValueType,workflowField,valueContext,fv.tableName," +
sql = "select nodeType,paramName,paramType,parentName,getValueType,workflowField,valueContext,fv.tableName," +
" fv.id fieldId,fv.fieldname,fv.indexdesc " +
" from uf_memsic_createXml_dt1 config " +
" left join workflow_field_table_view fv on config.workflowField = fv.id " +
@ -88,7 +88,7 @@ public class ReadConfigUtil extends ToolUtil {
* @return
**/
public static <T> T getInstance(RecordSet queryRs, Class<T> clazz) {
T res = null;
T res;
try {
res = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
@ -443,15 +443,35 @@ public class ReadConfigUtil extends ToolUtil {
// 明细
String[] detailIdArr = detailIndex.split(",");
StringBuilder detailSb = new StringBuilder();
for (String detailId : detailIdArr) {
String nodeName;
List<DetailRequestConfig> nodeList = requestConfigList.stream()
.filter(item -> "0".equals(item.getNodeType())).collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(nodeList)){
nodeName = nodeList.get(0).getParamName();
} else {
nodeName = "";
}
List<DetailRequestConfig> detailCollect = requestConfigList.stream()
.filter(item -> "detailRecord".equals(item.getParentName())
).collect(Collectors.toList());
.filter(item -> {
if(StringUtils.isNotBlank(nodeName)){
return nodeName.equals(item.getParentName());
}else {
return "detailRecord".equals(item.getParentName());
}
}).collect(Collectors.toList());
String detailSql = "select * from " + tableName + "_dt" + detailId + " where mainid = ?";
if (detailRs.executeQuery(detailSql, mainId)) {
int count = 1;
while (detailRs.next()) {
if(StringUtils.isNotBlank(nodeName)){
detailSb.append("<").append(nodeName).append(">\n");
}
appendXml(detailSb, detailCollect, mainRs, detailRs, count++);
if(StringUtils.isNotBlank(nodeName)){
detailSb.append("</").append(nodeName).append(">\n");
}
}
}
}
@ -474,7 +494,7 @@ public class ReadConfigUtil extends ToolUtil {
.append(paramName)
.append(">")
.append(getParamValue(requestConfig, mainRs, detailRs,count))
.append("<")
.append("</")
.append(paramName)
.append(">")
.append("\n");
@ -544,6 +564,7 @@ public class ReadConfigUtil extends ToolUtil {
* @return
*/
public String parseMap(Map<String, Object> responseMap, String responseField){
try {
String[] strArr = responseField.split("\\.");
int i = 0;
while (i < strArr.length - 1){
@ -560,6 +581,63 @@ public class ReadConfigUtil extends ToolUtil {
i++;
}
return Util.null2String(responseMap.get(strArr[strArr.length - 1]));
}catch (Exception e){
throw new CustomerException("parseMap error : " + e.getMessage());
}
}
/**
* <h1>sap</h1>
* @author xuanran.wang
* @dateTime 2023/5/15 14:05
* @param url
* @param xml xml
* @return
**/
public String callSap(String url, String xml){
OutputStreamWriter writer = null;
BufferedReader reader = null;
try {
String userName = aiyh.utils.Util.null2DefaultStr(getSystemParamValue("sapUserName"),"");
String password = aiyh.utils.Util.null2DefaultStr(getSystemParamValue("sapPassword"),"");
log.info("callSap userName : [ " + userName + " ], password : [ " + password + " ]");
String authString = userName + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URL serviceUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setDoOutput(true);
writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
writer.write(xml);
writer.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String line;
StringBuilder responseBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
reader.close();
String response = responseBuilder.toString();
if(StringUtils.isBlank(response)){
throw new CustomerException("sap response is empty!");
}
return response;
}catch (Exception e){
throw new CustomerException("callSap error : " + e.getMessage());
}finally {
try {
if(writer != null){
writer.close();
}
if(reader != null){
reader.close();
}
}catch (Exception e){
log.error("关流异常 : " + e.getMessage());
}
}
}
}

View File

@ -35,6 +35,8 @@ public class ShBigDataUtil {
WHILTE_LIST.add("loginErrorSendRedirectUrl");
WHILTE_LIST.add("getUserIdDebug");
WHILTE_LIST.add("getUserIdDebugOutKey");
WHILTE_LIST.add("ssoInterfaceCompareField");
WHILTE_LIST.add("ssoOaCompareField");
}
/**

View File

@ -0,0 +1,21 @@
package xuanran.wang;
import aiyh.utils.GenerateFileUtil;
import basetest.BaseTest;
import org.junit.Test;
import weaver.xuanran.wang.eighty_five_degreec.sap.action.WorkflowToSap;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/5/19 16:48
*/
public class NormalTest extends BaseTest {
@Test
public void testWord(){
GenerateFileUtil.createActionDocument(WorkflowToSap.class);
}
}

View File

@ -3,6 +3,7 @@ package xuanran.wang.big_data;
import aiyh.utils.Util;
import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject;
import com.api.xuanran.wang.sh_bigdata.sso.mapper.OtherSystemToOAMapper;
import com.icbc.api.internal.apache.http.impl.cookie.S;
import com.weaver.esb.server.cache.ResourceComInfo;
import emo.macro.ob.OB;
@ -13,6 +14,7 @@ import weaver.email.EmailWorkRunnable;
import weaver.general.TimeUtil;
import weaver.xuanran.wang.common.util.CusInfoToOAUtil;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
import weaver.xuanran.wang.sh_bigdata.common.util.ShBigDataUtil;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.OrganizationHrmSyncFromOtherSys;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OrgHrmAsyncConfigMain;
import weaver.xuanran.wang.sh_bigdata.org_hrm_async.entity.OtherSysDepartment;
@ -32,369 +34,366 @@ import java.util.stream.Collectors;
* @date 2023/4/10 10:49
*/
public class BigDataTest extends BaseTest {
private final OrgHrmAsyncServiceImpl orgHrmAsyncService = new OrgHrmAsyncServiceImpl();
private final OrgHrmAsyncApiService orgHrmAsyncApiService = new OrgHrmAsyncApiServiceImpl();
private final List<String> departmentWhiteList;
private final List<String> subCompanyWhiteList;
private final OrgHrmAsyncMapper orgHrmAsyncMapper = Util.getMapper(OrgHrmAsyncMapper.class);
{
departmentWhiteList = orgHrmAsyncMapper.selectCusDepart();
subCompanyWhiteList = orgHrmAsyncMapper.selectCusSubCompany();
}
@Test
public void testA() throws IOException {
// List<OtherSysDepartment> rootDepList = departmentInfo
// .stream()
// .filter(item -> 1 == item.getHasChild())
// .sorted(Comparator.comparing(OtherSysDepartment::getId))
// .collect(Collectors.toList());
// for (OtherSysDepartment department : rootDepList) {
// setChildList(department, departmentInfo);
// private final OrgHrmAsyncServiceImpl orgHrmAsyncService = new OrgHrmAsyncServiceImpl();
// private final OrgHrmAsyncApiService orgHrmAsyncApiService = new OrgHrmAsyncApiServiceImpl();
// private final List<String> departmentWhiteList;
// private final List<String> subCompanyWhiteList;
// private final OrgHrmAsyncMapper orgHrmAsyncMapper = Util.getMapper(OrgHrmAsyncMapper.class);
//
// {
// departmentWhiteList = orgHrmAsyncMapper.selectCusDepart();
// subCompanyWhiteList = orgHrmAsyncMapper.selectCusSubCompany();
// }
// List<OtherSysDepartment> departmentInfo = orgHrmAsyncApiService.getDepartmentInfo();
// List<OtherSysDepartment> convert = Util.listToTree(departmentInfo,
// OtherSysDepartment::getId, OtherSysDepartment::getParentid,
// OtherSysDepartment::getChildList, OtherSysDepartment::setChildList,
// parentid -> parentid == -1);
// System.out.println("convert => " + JSONObject.toJSONString(convert, SerializerFeature.DisableCircularReferenceDetect));
// List<OtherSysDepartment> hrmSubCompany = new ArrayList<>();
// List<OtherSysDepartment> hrmDepartment = new ArrayList<>();
// int maxLevel = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("maxLevel"), 3);
// System.out.println(countNodes(convert.get(0)));
// parseSubCompanyAndDepartment(convert, 0,maxLevel, hrmSubCompany, hrmDepartment);
// parseSubCompanyAndDepartment(convert, hrmSubCompany);
// System.out.println("hrmSubCompany => " + hrmSubCompany.size());
// System.out.println("convertLevel => " + JSONObject.toJSONString(convert, SerializerFeature.DisableCircularReferenceDetect));
// System.out.println("hrmSubCompany => " + JSONObject.toJSONString(hrmSubCompany));
// System.out.println("hrmDepartment => " + JSONObject.toJSONString(hrmDepartment));
// orgHrmAsyncService.asyncDepartment();
Map res = JSONObject.parseObject("{\n" +
"\t\t\"code\":0,\n" +
"\t\t\"msg\":\"ok\",\n" +
"\t\t\"data\":{\n" +
"\t\t\t\"UserId\":\"13800000000\",\n" +
"\t\t\t\"errcode\":0,\n" +
"\t\t\t\"errmsg\":\"ok\",\n" +
"\t\t\t\"id\":109,\n" +
"\t\t\t\"userid\":\"13800000000\",\n" +
"\t\t\t\"name\":\"祝芳\",\n" +
"\t\t\t\"mobile\":\"13800000000\",\n" +
"\t\t\t\"gender\":1,\n" +
"\t\t\t\"department\":[\n" +
"\t\t\t\t539\n" +
"\t\t\t],\n" +
"\t\t\t\"order\":[\n" +
"\t\t\t\t6\n" +
"\t\t\t]\n" +
"\t\t}\n" +
"\t}", Map.class);
System.out.println(getRes(res));
}
public String getRes(Map res){
return (String) parseRes(res, cusSuccess);
}
private final CusSuccess cusSuccess = CusSuccess.builder()
.successField("code")
.successValue(0)
.errorMsg("msg")
.dataKey("data.id")
.build();
public <T> T parseRes(Map<String, Object> response, CusSuccess cusSuccess){
String[] split = Util.null2DefaultStr(cusSuccess.getDataKey(),"").split("\\.");
int len = split.length;
if(len == 0 || StringUtils.isBlank(cusSuccess.getDataKey())){
return (T)response;
}
for (int i = 0; i < len - 1; i++) {
response = (Map) response.get(split[i]);
}
return (T) response.get(split[len - 1]);
}
@Test
public void testMap(){
List<Map<String, Object>> list = orgHrmAsyncApiService.getDepartmentInfoMap();
// 将列表转换为以id为键的Map
List<Map<String, Object>> tree = convertListToTree(list);
List<Map<String, Object>> department = new ArrayList<>();
List<Map<String, Object>> subCompany = new ArrayList<>();
orgHrmAsyncService.parseSubCompanyAndDepartmentMap(tree, 0, 3, department, subCompany);
System.out.println(JSONObject.toJSONString(department));
System.out.println(JSONObject.toJSONString(subCompany));
}
@Test
public void testMapper(){
// System.setProperty("_isDebug", "false");
// System.out.println("分部执行结果 => " + JSONObject.toJSONString(orgHrmAsyncService.asyncOrgDep(0)));
// System.out.println("部门执行结果 => " + JSONObject.toJSONString(orgHrmAsyncService.asyncOrgDep(1)));
// List<OrgHrmAsyncConfigMain> orgHrmAsyncConfigMains = orgHrmAsyncMapper.selectSubCompanyAsyncConfig(2);
// System.out.println(JSONObject.toJSONString(orgHrmAsyncConfigMains));
ArrayList<String> ids = new ArrayList<>();
for (int i = 0; i < 100; i++) {
ids.add("'" + UUID.randomUUID().toString().replace("-","") + "'");
}
String updateDelStatus = "update cus_fielddata set field0 = 1 where " +
weaver.general.Util.getSubINClause(StringUtils.join(ids,","),"field2","not in");
System.out.println(updateDelStatus);
}
@Test
public void testAsync(){
System.out.println(TimeUtil.getCurrentTimeString());
OrganizationHrmSyncFromOtherSys async = new OrganizationHrmSyncFromOtherSys();
async.SynTimingToOASubCompany();
async.SynTimingToOADepartment();
HashMap synResult = async.getSynResult();
System.out.println("res => \n" + JSONObject.toJSONString(synResult));
System.out.println(TimeUtil.getCurrentTimeString());
}
@Test
public void testExtra(){
orgHrmAsyncService.asyncHrm();
}
public List<Map<String, Object>> convertListToTree(List<Map<String, Object>> list){
Map<Integer, Map<String, Object>> map = new HashMap<>();
for (Map<String, Object> item : list) {
map.put((Integer) item.get("id"), item);
}
// 构建树形结构
List<Map<String, Object>> tree = new ArrayList<>();
for (Map<String, Object> item : list) {
int parentId = (Integer) item.get("parentid");
if (parentId == -1) {
// 添加根节点
tree.add(item);
} else {
// 添加子节点
Map<String, Object> parent = map.get(parentId);
if (parent != null) {
List<Map<String, Object>> childList = (List<Map<String, Object>>) parent.get("childList");
if (childList == null) {
childList = new ArrayList<>();
parent.put("childList", childList);
}
childList.add(item);
}
}
}
return tree;
}
public int countNodes(OtherSysDepartment node) {
int count = 1; // 当前节点也算一条数据
List<OtherSysDepartment> childList = node.getChildList();
if (CollectionUtils.isNotEmpty(childList)) {
for (OtherSysDepartment otherSysDepartment : childList) {
count += countNodes(otherSysDepartment);
}
}
return count;
}
public int countNodes(Map<String, Object> node) {
int count = 1; // 当前节点也算一条数据
List<Map<String, Object>> childList = (List<Map<String, Object>>) node.get("childList");
if (CollectionUtils.isNotEmpty(childList)) {
for (Map<String, Object> map : childList) {
count += countNodes(map);
}
}
return count;
}
/**
* <h1>or</h1>
* @author xuanran.wang
* @dateTime 2023/4/10 12:13
* @param list
* @param hrmDepartment
**/
public void parseSubCompanyAndDepartment(List<OtherSysDepartment> list, List<OtherSysDepartment> hrmDepartment){
for (OtherSysDepartment department : list) {
List<OtherSysDepartment> childList = department.getChildList();
if(CollectionUtils.isNotEmpty(childList)){
parseSubCompanyAndDepartment(childList,hrmDepartment);
department.setChildList(null);
}
hrmDepartment.add(department);
}
}
/**
* <h1>or</h1>
* @author xuanran.wang
* @dateTime 2023/4/10 12:13
* @param list
* @param n
* @param hrmSubCompany
* @param hrmDepartment
**/
public void parseSubCompanyAndDepartment(List<OtherSysDepartment> list, int n, int maxLevel,List<OtherSysDepartment> hrmSubCompany, List<OtherSysDepartment> hrmDepartment){
n++;
for (OtherSysDepartment department : list) {
department.setLevel(n);
List<OtherSysDepartment> childList = department.getChildList();
String departmentId = department.getId() + "";
if(CollectionUtils.isNotEmpty(childList)){
List<String> collect = department.getChildList().stream().map(item -> Util.null2DefaultStr(item.getId(), "")).collect(Collectors.toList());
if(departmentWhiteList.contains(departmentId)){
departmentWhiteList.addAll(collect);
}else if(subCompanyWhiteList.contains(departmentId)){
subCompanyWhiteList.addAll(collect);
}
parseSubCompanyAndDepartment(childList, n, maxLevel, hrmSubCompany, hrmDepartment);
department.setChildList(null);
}
if(n > maxLevel || departmentWhiteList.contains(departmentId)){
hrmDepartment.add(department);
}else {
hrmSubCompany.add(department);
}
}
}
@Test
public void testParseObj(){
String json = "{\n" +
" \"code\":0,\n" +
" \"msg\":\"ok\",\n" +
" \"data\":\n" +
" {\n" +
" \"errcode\": 0,\n" +
" \"errmsg\": \"ok\",\n" +
" \"id\": \"1\",\n" +
" \"userid\": \"superAdmin\",\n" +
" \"name\": \"超级管理员\",\n" +
" \"mobile\":\"12345678911\",\n" +
" \"email\":\"123@321.com\",\n" +
" \"gender\":0,\n" +
" \"position\":\"position\",\n" +
" \"avatarImg\":\"avatarImg\",\n" +
" \"workPhone\":\"workPhone\",\n" +
" \"fixedTelephone\":\"fixedTelephone\",\n" +
" \"extName\":\"extName\",\n" +
" \"userType\":0,\n" +
" \"department\": [\n" +
" 1\n" +
" ],\n" +
" \"order\": [\n" +
" 0\n" +
" ],\n" +
" \"rank\":\"rank\"\n" +
" }\n" +
"}";
Map response = JSONObject.parseObject(json, Map.class);
String obj = Util.null2DefaultStr(getObj("data.id", response),"");
System.out.println("obj => " + obj);
}
public <T> T getObj(String dataKey, Map<String, Object> response){
String[] split = Util.null2DefaultStr(dataKey,"").split("\\.");
int len = split.length;
if(len == 0 || StringUtils.isBlank(dataKey)){
return (T)response;
}
for (int i = 0; i < len - 1; i++) {
response = (Map) response.get(split[i]);
}
return (T) response.get(split[len - 1]);
}
@Test
public void testMsg(){
String html = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"\t<title>Investment Calculator</title>\n" +
"\t<style>\n" +
"\t\ttable {\n" +
"\t\t\tborder-collapse: collapse;\n" +
"\t\t\twidth: 80%;\n" +
"\t\t\tmargin: 0 auto;\n" +
"\t\t\tmargin-top: 50px;\n" +
"\t\t\tmargin-bottom: 50px;\n" +
"\t\t}\n" +
"\t\tth, td {\n" +
"\t\t\tborder: 1px solid black;\n" +
"\t\t\tpadding: 10px;\n" +
"\t\t\ttext-align: center;\n" +
"\t\t}\n" +
"\t\tth {\n" +
"\t\t\tbackground-color: #f2f2f2;\n" +
"\t\t}\n" +
"\t\t.first-row {\n" +
"\t\t\ttext-align: center;\n" +
"\t\t\tfont-size: 24px;\n" +
"\t\t\tfont-weight: bold;\n" +
"\t\t\theight: 50px;\n" +
"\t\t\tline-height: 50px;\n" +
"\t\t}\n" +
"\t</style>\n" +
"</head>\n" +
"<body>\n" +
"\t<table>\n" +
"\t\t<tr class=\"first-row\">\n" +
"\t\t\t<td colspan=\"26\">投资试算(场外基金)</td>\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>A</td>\n" +
"\t\t\t<td>B</td>\n" +
"\t\t\t<td>C</td>\n" +
"\t\t\t<td>D</td>\n" +
"\t\t\t<td>E</td>\n" +
"\t\t\t<td>F</td>\n" +
"\t\t\t<td>G</td>\n" +
"\t\t\t<td>H</td>\n" +
"\t\t\t<td>I</td>\n" +
"\t\t\t<td>J</td>\n" +
"\t\t\t<td>K</td>\n" +
"\t\t\t<td>L</td>\n" +
"\t\t\t<td>M</td>\n" +
"\t\t\t\n" +
"\t\t</tr>\n" +
"\t\t<tr>\n" +
"\t\t\t<td>Cell A1</td>\n" +
"\t\t\t<td>Cell B1</td>\n" +
"\t\t\t<td>Cell C1</td>\n" +
"\t\t\t<td>Cell D1</td>\n" +
"\t\t\t<td>Cell E1</td>\n" +
"\t\t\t<td>Cell F1</td>\n" +
"\t\t\t<td>Cell G1</td>\n" +
"\t\t\t<td>Cell H1</td>\n" +
"\t\t\t<td>Cell I1</td>\n" +
"\t\t\t<td>Cell J1</td>\n" +
"\t\t\t<td>Cell K1</td>\n" +
"\t\t\t<td>Cell L1</td>\n" +
"\t\t\t<td>Cell M1</td>\n" +
"\t\t\n" +
"\t\t</tr>\n" +
" \t</table>\n" +
" </body>\n" +
"\n";
EmailWorkRunnable.threadModeReminder("3055088966@qq.com,xuanran.wang@weaver.com.cn", "test11", html);
}
//
// @Test
// public void testA() throws IOException {
//// List<OtherSysDepartment> rootDepList = departmentInfo
//// .stream()
//// .filter(item -> 1 == item.getHasChild())
//// .sorted(Comparator.comparing(OtherSysDepartment::getId))
//// .collect(Collectors.toList());
//// for (OtherSysDepartment department : rootDepList) {
//// setChildList(department, departmentInfo);
//// }
//// List<OtherSysDepartment> departmentInfo = orgHrmAsyncApiService.getDepartmentInfo();
//// List<OtherSysDepartment> convert = Util.listToTree(departmentInfo,
//// OtherSysDepartment::getId, OtherSysDepartment::getParentid,
//// OtherSysDepartment::getChildList, OtherSysDepartment::setChildList,
//// parentid -> parentid == -1);
//// System.out.println("convert => " + JSONObject.toJSONString(convert, SerializerFeature.DisableCircularReferenceDetect));
//// List<OtherSysDepartment> hrmSubCompany = new ArrayList<>();
//// List<OtherSysDepartment> hrmDepartment = new ArrayList<>();
//// int maxLevel = Util.getIntValue(ShBigDataUtil.getPropertiesValByKey("maxLevel"), 3);
//// System.out.println(countNodes(convert.get(0)));
//// parseSubCompanyAndDepartment(convert, 0,maxLevel, hrmSubCompany, hrmDepartment);
//// parseSubCompanyAndDepartment(convert, hrmSubCompany);
//// System.out.println("hrmSubCompany => " + hrmSubCompany.size());
//// System.out.println("convertLevel => " + JSONObject.toJSONString(convert, SerializerFeature.DisableCircularReferenceDetect));
//// System.out.println("hrmSubCompany => " + JSONObject.toJSONString(hrmSubCompany));
//// System.out.println("hrmDepartment => " + JSONObject.toJSONString(hrmDepartment));
//// orgHrmAsyncService.asyncDepartment();
// Map res = JSONObject.parseObject("{\n" +
// "\t\t\"code\":0,\n" +
// "\t\t\"msg\":\"ok\",\n" +
// "\t\t\"data\":{\n" +
// "\t\t\t\"UserId\":\"13800000000\",\n" +
// "\t\t\t\"errcode\":0,\n" +
// "\t\t\t\"errmsg\":\"ok\",\n" +
// "\t\t\t\"id\":109,\n" +
// "\t\t\t\"userid\":\"13800000000\",\n" +
// "\t\t\t\"name\":\"祝芳\",\n" +
// "\t\t\t\"mobile\":\"13800000000\",\n" +
// "\t\t\t\"gender\":1,\n" +
// "\t\t\t\"department\":[\n" +
// "\t\t\t\t539\n" +
// "\t\t\t],\n" +
// "\t\t\t\"order\":[\n" +
// "\t\t\t\t6\n" +
// "\t\t\t]\n" +
// "\t\t}\n" +
// "\t}", Map.class);
// System.out.println(getRes(res));
// }
//
// public String getRes(Map res){
// return (String) parseRes(res, cusSuccess);
// }
//
// private final CusSuccess cusSuccess = CusSuccess.builder()
// .successField("code")
// .successValue(0)
// .errorMsg("msg")
// .dataKey("data.id")
// .build();
//
// public <T> T parseRes(Map<String, Object> response, CusSuccess cusSuccess){
// String[] split = Util.null2DefaultStr(cusSuccess.getDataKey(),"").split("\\.");
// int len = split.length;
// if(len == 0 || StringUtils.isBlank(cusSuccess.getDataKey())){
// return (T)response;
// }
// for (int i = 0; i < len - 1; i++) {
// response = (Map) response.get(split[i]);
// }
// return (T) response.get(split[len - 1]);
// }
//
// @Test
// public void testMap(){
// List<Map<String, Object>> list = orgHrmAsyncApiService.getDepartmentInfoMap();
// // 将列表转换为以id为键的Map
// List<Map<String, Object>> tree = convertListToTree(list);
// List<Map<String, Object>> department = new ArrayList<>();
// List<Map<String, Object>> subCompany = new ArrayList<>();
// orgHrmAsyncService.parseSubCompanyAndDepartmentMap(tree, 0, 3, department, subCompany);
// System.out.println(JSONObject.toJSONString(department));
// System.out.println(JSONObject.toJSONString(subCompany));
// }
//
// @Test
// public void testMapper(){
//// System.setProperty("_isDebug", "false");
//// System.out.println("分部执行结果 => " + JSONObject.toJSONString(orgHrmAsyncService.asyncOrgDep(0)));
//// System.out.println("部门执行结果 => " + JSONObject.toJSONString(orgHrmAsyncService.asyncOrgDep(1)));
//// List<OrgHrmAsyncConfigMain> orgHrmAsyncConfigMains = orgHrmAsyncMapper.selectSubCompanyAsyncConfig(2);
//// System.out.println(JSONObject.toJSONString(orgHrmAsyncConfigMains));
// ArrayList<String> ids = new ArrayList<>();
// for (int i = 0; i < 100; i++) {
// ids.add("'" + UUID.randomUUID().toString().replace("-","") + "'");
// }
// String updateDelStatus = "update cus_fielddata set field0 = 1 where " +
// weaver.general.Util.getSubINClause(StringUtils.join(ids,","),"field2","not in");
// System.out.println(updateDelStatus);
// }
//
// @Test
// public void testAsync(){
// System.out.println(TimeUtil.getCurrentTimeString());
// OrganizationHrmSyncFromOtherSys async = new OrganizationHrmSyncFromOtherSys();
// async.SynTimingToOASubCompany();
// async.SynTimingToOADepartment();
// HashMap synResult = async.getSynResult();
// System.out.println("res => \n" + JSONObject.toJSONString(synResult));
// System.out.println(TimeUtil.getCurrentTimeString());
// }
//
// @Test
// public void testExtra(){
// orgHrmAsyncService.asyncHrm();
// }
//
// public List<Map<String, Object>> convertListToTree(List<Map<String, Object>> list){
// Map<Integer, Map<String, Object>> map = new HashMap<>();
// for (Map<String, Object> item : list) {
// map.put((Integer) item.get("id"), item);
// }
//
// // 构建树形结构
// List<Map<String, Object>> tree = new ArrayList<>();
// for (Map<String, Object> item : list) {
// int parentId = (Integer) item.get("parentid");
// if (parentId == -1) {
// // 添加根节点
// tree.add(item);
// } else {
// // 添加子节点
// Map<String, Object> parent = map.get(parentId);
// if (parent != null) {
// List<Map<String, Object>> childList = (List<Map<String, Object>>) parent.get("childList");
// if (childList == null) {
// childList = new ArrayList<>();
// parent.put("childList", childList);
// }
// childList.add(item);
// }
// }
// }
// return tree;
// }
// public int countNodes(OtherSysDepartment node) {
// int count = 1; // 当前节点也算一条数据
// List<OtherSysDepartment> childList = node.getChildList();
// if (CollectionUtils.isNotEmpty(childList)) {
// for (OtherSysDepartment otherSysDepartment : childList) {
// count += countNodes(otherSysDepartment);
// }
// }
// return count;
// }
//
// public int countNodes(Map<String, Object> node) {
// int count = 1; // 当前节点也算一条数据
// List<Map<String, Object>> childList = (List<Map<String, Object>>) node.get("childList");
// if (CollectionUtils.isNotEmpty(childList)) {
// for (Map<String, Object> map : childList) {
// count += countNodes(map);
// }
// }
// return count;
// }
//
//
// /**
// * <h1>解析部门or分部</h1>
// * @author xuanran.wang
// * @dateTime 2023/4/10 12:13
// * @param list 树形集合
// * @param hrmDepartment 部门
// **/
// public void parseSubCompanyAndDepartment(List<OtherSysDepartment> list, List<OtherSysDepartment> hrmDepartment){
// for (OtherSysDepartment department : list) {
// List<OtherSysDepartment> childList = department.getChildList();
// if(CollectionUtils.isNotEmpty(childList)){
// parseSubCompanyAndDepartment(childList,hrmDepartment);
// department.setChildList(null);
// }
// hrmDepartment.add(department);
// }
// }
//
//
// /**
// * <h1>解析部门or分部</h1>
// * @author xuanran.wang
// * @dateTime 2023/4/10 12:13
// * @param list 树形集合
// * @param n 层级
// * @param hrmSubCompany 分部
// * @param hrmDepartment 部门
// **/
// public void parseSubCompanyAndDepartment(List<OtherSysDepartment> list, int n, int maxLevel,List<OtherSysDepartment> hrmSubCompany, List<OtherSysDepartment> hrmDepartment){
// n++;
// for (OtherSysDepartment department : list) {
// department.setLevel(n);
// List<OtherSysDepartment> childList = department.getChildList();
// String departmentId = department.getId() + "";
// if(CollectionUtils.isNotEmpty(childList)){
// List<String> collect = department.getChildList().stream().map(item -> Util.null2DefaultStr(item.getId(), "")).collect(Collectors.toList());
// if(departmentWhiteList.contains(departmentId)){
// departmentWhiteList.addAll(collect);
// }else if(subCompanyWhiteList.contains(departmentId)){
// subCompanyWhiteList.addAll(collect);
// }
// parseSubCompanyAndDepartment(childList, n, maxLevel, hrmSubCompany, hrmDepartment);
// department.setChildList(null);
// }
// if(n > maxLevel || departmentWhiteList.contains(departmentId)){
// hrmDepartment.add(department);
// }else {
// hrmSubCompany.add(department);
// }
//
// }
// }
//
// @Test
// public void testParseObj(){
// String json = "{\n" +
// " \"code\":0,\n" +
// " \"msg\":\"ok\",\n" +
// " \"data\":\n" +
// " {\n" +
// " \"errcode\": 0,\n" +
// " \"errmsg\": \"ok\",\n" +
// " \"id\": \"1\",\n" +
// " \"userid\": \"superAdmin\",\n" +
// " \"name\": \"超级管理员\",\n" +
// " \"mobile\":\"12345678911\",\n" +
// " \"email\":\"123@321.com\",\n" +
// " \"gender\":0,\n" +
// " \"position\":\"position\",\n" +
// " \"avatarImg\":\"avatarImg\",\n" +
// " \"workPhone\":\"workPhone\",\n" +
// " \"fixedTelephone\":\"fixedTelephone\",\n" +
// " \"extName\":\"extName\",\n" +
// " \"userType\":0,\n" +
// " \"department\": [\n" +
// " 1\n" +
// " ],\n" +
// " \"order\": [\n" +
// " 0\n" +
// " ],\n" +
// " \"rank\":\"rank\"\n" +
// " }\n" +
// "}";
// Map response = JSONObject.parseObject(json, Map.class);
// String obj = Util.null2DefaultStr(getObj("data.id", response),"");
// System.out.println("obj => " + obj);
// }
//
// public <T> T getObj(String dataKey, Map<String, Object> response){
// String[] split = Util.null2DefaultStr(dataKey,"").split("\\.");
// int len = split.length;
// if(len == 0 || StringUtils.isBlank(dataKey)){
// return (T)response;
// }
// for (int i = 0; i < len - 1; i++) {
// response = (Map) response.get(split[i]);
// }
// return (T) response.get(split[len - 1]);
// }
//
// @Test
// public void testMsg(){
// String html = "<!DOCTYPE html>\n" +
// "<html>\n" +
// "<head>\n" +
// "\t<title>Investment Calculator</title>\n" +
// "\t<style>\n" +
// "\t\ttable {\n" +
// "\t\t\tborder-collapse: collapse;\n" +
// "\t\t\twidth: 80%;\n" +
// "\t\t\tmargin: 0 auto;\n" +
// "\t\t\tmargin-top: 50px;\n" +
// "\t\t\tmargin-bottom: 50px;\n" +
// "\t\t}\n" +
// "\t\tth, td {\n" +
// "\t\t\tborder: 1px solid black;\n" +
// "\t\t\tpadding: 10px;\n" +
// "\t\t\ttext-align: center;\n" +
// "\t\t}\n" +
// "\t\tth {\n" +
// "\t\t\tbackground-color: #f2f2f2;\n" +
// "\t\t}\n" +
// "\t\t.first-row {\n" +
// "\t\t\ttext-align: center;\n" +
// "\t\t\tfont-size: 24px;\n" +
// "\t\t\tfont-weight: bold;\n" +
// "\t\t\theight: 50px;\n" +
// "\t\t\tline-height: 50px;\n" +
// "\t\t}\n" +
// "\t</style>\n" +
// "</head>\n" +
// "<body>\n" +
// "\t<table>\n" +
// "\t\t<tr class=\"first-row\">\n" +
// "\t\t\t<td colspan=\"26\">投资试算(场外基金)</td>\n" +
// "\t\t</tr>\n" +
// "\t\t<tr>\n" +
// "\t\t\t<td>A</td>\n" +
// "\t\t\t<td>B</td>\n" +
// "\t\t\t<td>C</td>\n" +
// "\t\t\t<td>D</td>\n" +
// "\t\t\t<td>E</td>\n" +
// "\t\t\t<td>F</td>\n" +
// "\t\t\t<td>G</td>\n" +
// "\t\t\t<td>H</td>\n" +
// "\t\t\t<td>I</td>\n" +
// "\t\t\t<td>J</td>\n" +
// "\t\t\t<td>K</td>\n" +
// "\t\t\t<td>L</td>\n" +
// "\t\t\t<td>M</td>\n" +
// "\t\t\t\n" +
// "\t\t</tr>\n" +
// "\t\t<tr>\n" +
// "\t\t\t<td>Cell A1</td>\n" +
// "\t\t\t<td>Cell B1</td>\n" +
// "\t\t\t<td>Cell C1</td>\n" +
// "\t\t\t<td>Cell D1</td>\n" +
// "\t\t\t<td>Cell E1</td>\n" +
// "\t\t\t<td>Cell F1</td>\n" +
// "\t\t\t<td>Cell G1</td>\n" +
// "\t\t\t<td>Cell H1</td>\n" +
// "\t\t\t<td>Cell I1</td>\n" +
// "\t\t\t<td>Cell J1</td>\n" +
// "\t\t\t<td>Cell K1</td>\n" +
// "\t\t\t<td>Cell L1</td>\n" +
// "\t\t\t<td>Cell M1</td>\n" +
// "\t\t\n" +
// "\t\t</tr>\n" +
// " \t</table>\n" +
// " </body>\n" +
// "\n";
// EmailWorkRunnable.threadModeReminder("3055088966@qq.com,xuanran.wang@weaver.com.cn", "test11", html);
//
// }
private final OtherSystemToOAMapper otherSystemToOAMapper = Util.getMapper(OtherSystemToOAMapper.class);
@Test
public void testG(){
// String sql =" select case '$t{test1}' when '03' then '场外基金' when '04' then '基金赎回' else '测试下' end";
// HashMap<String, Object> param = new HashMap<>();
// param.put("test1","04");
// String s = orgHrmAsyncMapper.selectCustomerSql(sql, param);
// System.out.println("s => " + s);
HashMap<String, Object> map = new HashMap<>();
map.put("tiem", new Date());
System.out.println("map => " + JSONObject.toJSONString(map));
String oaOutKey = "111";
String sql = "select id from hrmresource where " + Util.null2DefaultStr(ShBigDataUtil.getPropertiesValByKey("ssoOaCompareField"),"outkey") + " = #{outKey}";
int id = otherSystemToOAMapper.selectUserIdByOutKey(sql, oaOutKey);
log.info("id => " + id);
}
}

View File

@ -1,6 +1,7 @@
package xuanran.wang.cssc;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.httpUtil.util.HttpUtils;
import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
@ -201,4 +202,9 @@ public class FileTest extends BaseTest {
}
}
@Test
public void testB(){
HttpUtils httpUtils = new HttpUtils();
}
}

View File

@ -1,12 +1,24 @@
package xuanran.wang.eighty_five_degreec;
import aiyh.utils.annotation.PrintParamMark;
import aiyh.utils.annotation.RequiredMark;
import aiyh.utils.excention.CustomerException;
import aiyh.utils.tool.cn.hutool.core.lang.UUID;
import basetest.BaseTest;
import com.alibaba.excel.util.CollectionUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.junit.Test;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.xuanran.wang.common.util.CusData2OA;
import weaver.xuanran.wang.eighty_five_degreec.sap.entity.eneity.MainRequestConfig;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.WorkflowToSapService;
import weaver.xuanran.wang.eighty_five_degreec.sap.service.impl.WorkflowToSapServiceImpl;
import weaver.xuanran.wang.eighty_five_degreec.sap.util.ReadConfigUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -20,15 +32,116 @@ import java.util.Map;
*/
public class SAPTest extends BaseTest {
private final WorkflowToSapService service = new WorkflowToSapServiceImpl();
@Test
public void testXml(){
ReadConfigUtil configUtil = new ReadConfigUtil();
String uniqueCode = "test1";
String tableName = "formtable_main_161";
String billTable = "formtable_main_161";
String requestId = "419420";
MainRequestConfig config = configUtil.getConfigByUniqueCode(uniqueCode, tableName);
String xml = configUtil.getXml(config, requestId, tableName);
System.out.println("xml => \n " + xml);
String response = "";
String url = "";
String error = "";
String xml = "";
boolean success = true;
String modelId = "119";
String successField = "soap-env:Envelope.soap-env:Body.n0:ZFI_OA_DOC_POSTINGResponse.ES_OA_OUTPUT.TYPE";
String successVal = "N";
String messageField = "soap-env:Envelope.soap-env:Body.n0:ZFI_OA_DOC_POSTINGResponse.ES_OA_OUTPUT.MESSAGE";
try {
MainRequestConfig config = service.getRequestConfig(uniqueCode, billTable);
url = config.getRequestUrl();
xml = service.convertXml(config, requestId, billTable);
// response = service.sendToSap(config.getRequestUrl(), xml);
response = "<soap-env:Envelope\n" +
" xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap-env:Header/>\n" +
" <soap-env:Body>\n" +
" <n0:ZFI_OA_DOC_POSTINGResponse\n" +
" xmlns:n0=\"urn:sap-com:document:sap:rfc:functions\">\n" +
" <ES_OA_OUTPUT>\n" +
" <ZOAPZ>clbx000003</ZOAPZ>\n" +
" <BELNR/>\n" +
" <BUKRS>1200</BUKRS>\n" +
" <BUDAT>2023-05-01</BUDAT>\n" +
" <BKTXT>t?·???????é??è????¨</BKTXT>\n" +
" <TYPE>E</TYPE>\n" +
" <MESSAGE> 1000 上不存在成本中心 1200180001/2023/05/01 。</MESSAGE>\n" +
" <ERDAT>2023-05-15</ERDAT>\n" +
" <ERZET>13:46:11</ERZET>\n" +
" </ES_OA_OUTPUT>\n" +
" <IT_OA_ITEMS>\n" +
" <item>\n" +
" <ZOAPZ>clbx000002</ZOAPZ>\n" +
" <ZOAXM>1</ZOAXM>\n" +
" <SGTXT>item1</SGTXT>\n" +
" <LIFNR>CN07010001</LIFNR>\n" +
" <HKONT/>\n" +
" <KOSTL/>\n" +
" <PSWBT>123.23</PSWBT>\n" +
" <PSWSL>CNY</PSWSL>\n" +
" <SHKZG>H</SHKZG>\n" +
" <BOAPZ>string..............</BOAPZ>\n" +
" <RESE_FIELD_1>string..............</RESE_FIELD_1>\n" +
" <RESE_FIELD_2>string..............</RESE_FIELD_2>\n" +
" <RESE_FIELD_3>string..............</RESE_FIELD_3>\n" +
" <RESE_FIELD_4>string..............</RESE_FIELD_4>\n" +
" <RESE_FIELD_5>string..............</RESE_FIELD_5>\n" +
" </item>\n" +
" <item>\n" +
" <ZOAPZ>clbx000003</ZOAPZ>\n" +
" <ZOAXM>2</ZOAXM>\n" +
" <SGTXT>item2</SGTXT>\n" +
" <LIFNR/>\n" +
" <HKONT>90010601</HKONT>\n" +
" <KOSTL>1200180001</KOSTL>\n" +
" <PSWBT>100.23</PSWBT>\n" +
" <PSWSL>CNY</PSWSL>\n" +
" <SHKZG>S</SHKZG>\n" +
" <BOAPZ>string..............</BOAPZ>\n" +
" <RESE_FIELD_1>string..............</RESE_FIELD_1>\n" +
" <RESE_FIELD_2>string..............</RESE_FIELD_2>\n" +
" <RESE_FIELD_3>string..............</RESE_FIELD_3>\n" +
" <RESE_FIELD_4>string..............</RESE_FIELD_4>\n" +
" <RESE_FIELD_5>string..............</RESE_FIELD_5>\n" +
" </item>\n" +
" <item>\n" +
" <ZOAPZ>clbx000003</ZOAPZ>\n" +
" <ZOAXM>3</ZOAXM>\n" +
" <SGTXT>item3</SGTXT>\n" +
" <LIFNR/>\n" +
" <HKONT>90010602</HKONT>\n" +
" <KOSTL>1200180001</KOSTL>\n" +
" <PSWBT>23.0</PSWBT>\n" +
" <PSWSL>CNY</PSWSL>\n" +
" <SHKZG>S</SHKZG>\n" +
" <BOAPZ>string..............</BOAPZ>\n" +
" <RESE_FIELD_1>string..............</RESE_FIELD_1>\n" +
" <RESE_FIELD_2>string..............</RESE_FIELD_2>\n" +
" <RESE_FIELD_3>string..............</RESE_FIELD_3>\n" +
" <RESE_FIELD_4>string..............</RESE_FIELD_4>\n" +
" <RESE_FIELD_5>string..............</RESE_FIELD_5>\n" +
" </item>\n" +
" </IT_OA_ITEMS>\n" +
" </n0:ZFI_OA_DOC_POSTINGResponse>\n" +
" </soap-env:Body>\n" +
"</soap-env:Envelope>";
response = service.parseResponse(response, successField, successVal, messageField);
}catch (Exception e){
log.error("流程数据推送SAP error : " + e.getMessage());
error = e.getMessage();
success = false;
}
try {
service.logToOA(modelId, url, requestId, xml, response, error);
}catch (Exception e){
log.error("日志数据写入建模失败! " + e.getMessage());
}
if(!success){
throw new CustomerException("WorkflowToSap Action execute error : " + error);
}
}
@Test
@ -49,4 +162,149 @@ public class SAPTest extends BaseTest {
List<String> strings = CusData2OA.batchWriteToModel(modelId, sql, list);
System.out.println("data => " + strings);
}
@Test
public void testResponse() throws JSONException {
String response = "<soap-env:Envelope\n" +
" xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
" <soap-env:Header/>\n" +
" <soap-env:Body>\n" +
" <n0:ZFI_OA_DOC_POSTINGResponse\n" +
" xmlns:n0=\"urn:sap-com:document:sap:rfc:functions\">\n" +
" <ES_OA_OUTPUT>\n" +
" <ZOAPZ>clbx000003</ZOAPZ>\n" +
" <BELNR/>\n" +
" <BUKRS>1200</BUKRS>\n" +
" <BUDAT>2023-05-01</BUDAT>\n" +
" <BKTXT>t?·???????é??è????¨</BKTXT>\n" +
" <TYPE>E</TYPE>\n" +
" <MESSAGE> 1000 上不存在成本中心 1200180001/2023/05/01 。</MESSAGE>\n" +
" <ERDAT>2023-05-15</ERDAT>\n" +
" <ERZET>13:46:11</ERZET>\n" +
" </ES_OA_OUTPUT>\n" +
" <IT_OA_ITEMS>\n" +
" <item>\n" +
" <ZOAPZ>clbx000002</ZOAPZ>\n" +
" <ZOAXM>1</ZOAXM>\n" +
" <SGTXT>item1</SGTXT>\n" +
" <LIFNR>CN07010001</LIFNR>\n" +
" <HKONT/>\n" +
" <KOSTL/>\n" +
" <PSWBT>123.23</PSWBT>\n" +
" <PSWSL>CNY</PSWSL>\n" +
" <SHKZG>H</SHKZG>\n" +
" <BOAPZ>string..............</BOAPZ>\n" +
" <RESE_FIELD_1>string..............</RESE_FIELD_1>\n" +
" <RESE_FIELD_2>string..............</RESE_FIELD_2>\n" +
" <RESE_FIELD_3>string..............</RESE_FIELD_3>\n" +
" <RESE_FIELD_4>string..............</RESE_FIELD_4>\n" +
" <RESE_FIELD_5>string..............</RESE_FIELD_5>\n" +
" </item>\n" +
" <item>\n" +
" <ZOAPZ>clbx000003</ZOAPZ>\n" +
" <ZOAXM>2</ZOAXM>\n" +
" <SGTXT>item2</SGTXT>\n" +
" <LIFNR/>\n" +
" <HKONT>90010601</HKONT>\n" +
" <KOSTL>1200180001</KOSTL>\n" +
" <PSWBT>100.23</PSWBT>\n" +
" <PSWSL>CNY</PSWSL>\n" +
" <SHKZG>S</SHKZG>\n" +
" <BOAPZ>string..............</BOAPZ>\n" +
" <RESE_FIELD_1>string..............</RESE_FIELD_1>\n" +
" <RESE_FIELD_2>string..............</RESE_FIELD_2>\n" +
" <RESE_FIELD_3>string..............</RESE_FIELD_3>\n" +
" <RESE_FIELD_4>string..............</RESE_FIELD_4>\n" +
" <RESE_FIELD_5>string..............</RESE_FIELD_5>\n" +
" </item>\n" +
" <item>\n" +
" <ZOAPZ>clbx000003</ZOAPZ>\n" +
" <ZOAXM>3</ZOAXM>\n" +
" <SGTXT>item3</SGTXT>\n" +
" <LIFNR/>\n" +
" <HKONT>90010602</HKONT>\n" +
" <KOSTL>1200180001</KOSTL>\n" +
" <PSWBT>23.0</PSWBT>\n" +
" <PSWSL>CNY</PSWSL>\n" +
" <SHKZG>S</SHKZG>\n" +
" <BOAPZ>string..............</BOAPZ>\n" +
" <RESE_FIELD_1>string..............</RESE_FIELD_1>\n" +
" <RESE_FIELD_2>string..............</RESE_FIELD_2>\n" +
" <RESE_FIELD_3>string..............</RESE_FIELD_3>\n" +
" <RESE_FIELD_4>string..............</RESE_FIELD_4>\n" +
" <RESE_FIELD_5>string..............</RESE_FIELD_5>\n" +
" </item>\n" +
" </IT_OA_ITEMS>\n" +
" </n0:ZFI_OA_DOC_POSTINGResponse>\n" +
" </soap-env:Body>\n" +
"</soap-env:Envelope>";
JSONObject xmlResponseObj = XML.toJSONObject(response);
log.info("接口响应 : \n" + xmlResponseObj);
Map<String, Object> responseMap = com.alibaba.fastjson.JSONObject.parseObject(xmlResponseObj.toString(), Map.class);
System.out.println("responseMap : " + com.alibaba.fastjson.JSONObject.toJSONString(responseMap));
// code = Util.null2String(parseMap(responseMap, RESPONSE_CODE));
// if(!successCode.equals(code)){
// throw new RuntimeException("推送erp接口失败! " + Util.null2String(readConfigUtil.parseMap(responseMap, RESPONSE_DESCRIPTION)));
// }
}
/**
* <h1></h1>
* @param responseMap map
* @param responseField map Response.Execution
* @return
*/
public String parseMap(Map<String, Object> responseMap, String responseField){
String[] strArr = responseField.split("\\.");
int i = 0;
while (i < strArr.length - 1){
Object o = responseMap.get(strArr[i]);
if(o instanceof Map){
responseMap = (Map<String, Object>) o;
}else if(o instanceof List){
List<Map<String, Object>> list = (List<Map<String, Object>>) o;
if(CollectionUtils.isEmpty(list)){
return "";
}
responseMap = list.get(0);
}
i++;
}
return Util.null2String(responseMap.get(strArr[strArr.length - 1]));
}
@Test
public void testB(){
String path = "sap.sap.xml";
System.out.println(parseConfigPath(path));
}
/**
* <h1>xml</h1>
* wxr.memsic.test.xml = /wxr/memsic/test.xml
* @param configFilePath
* @return
*/
public String parseConfigPath(String configFilePath){
StringBuilder filePath = new StringBuilder(GCONST.getSysFilePath());
int beginIndex = configFilePath.indexOf(".");
int endIndex = configFilePath.lastIndexOf(".");
if(beginIndex == endIndex){
filePath.append(configFilePath);
}else {
String[] pathArr = configFilePath.split("\\.");
for (int i = 0; i < pathArr.length - 2; i++) {
if(i != 0){
filePath.append(File.separator);
}
filePath.append(pathArr[i]);
}
filePath.append(File.separator)
.append(pathArr[pathArr.length - 2])
.append(".")
.append(pathArr[pathArr.length - 1]);
}
return filePath.toString();
}
}

View File

@ -0,0 +1,19 @@
package xuanran.wang.http_test.annotations;
import java.lang.annotation.*;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/5/25 14:42
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface CusJsonMappingConfig {
String configCode() default "";
String tableName() default "";
}

View File

@ -15,5 +15,5 @@ import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
public @interface CusReqAfterHandleRegister {
Class<?> afterHandle();
Class<?>[] afterHandle();
}

View File

@ -23,4 +23,6 @@ public @interface CusRequestPost {
@AliasFor(annotation = CusRequestType.class, attribute = "requestType")
int requestType() default CusRequestClientConstant.POST;
String configCode() default "";
}

View File

@ -7,7 +7,9 @@ import lombok.Setter;
import xuanran.wang.http_test.annotations.handle.CusResponseSuccessHandle;
import xuanran.wang.http_test.handle.CusRequestAfterHandle;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
@ -31,8 +33,8 @@ public class CusRequestEntity{
private boolean async = false;
private String host = "";
private int port;
private Class<?> returnType;
private CusRequestAfterHandle cusRequestAfter;
private Type returnType;
private List<CusRequestAfterHandle> cusRequestAfter;
private CusResponseSuccessHandle responseSuccessHandle;
private Map<String, Object> responseMap;
}

View File

@ -7,6 +7,7 @@ import aiyh.utils.tool.cn.hutool.core.annotation.AnnotationUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import xuanran.wang.http_test.annotations.handle.CusReqAfterHandleRegister;
import xuanran.wang.http_test.annotations.handle.CusResponseSuccessHandle;
@ -85,16 +86,17 @@ public class CusHandleCenter{
}
public Object requestAfterHandle(Method method, CusRequestEntity cusRequest, ResponeVo responseVo){
if(cusRequest.getCusRequestAfter() == null){
CusReqAfterHandleRegister cusReqAfterHandleRegister = method.getDeclaredAnnotation(CusReqAfterHandleRegister.class);
if(cusReqAfterHandleRegister != null){
RequestUtil.setCusRequestAfter(cusReqAfterHandleRegister, cusRequest);
}else {
List<CusRequestAfterHandle> tempList = new ArrayList<>();
tempList.add(new CusDefaultRequestAfterHandle());
cusRequest.setCusRequestAfter(tempList);
}
}
// Type genericReturnType = method.getGenericReturnType();
cusRequest.setReturnType(method.getReturnType());
cusRequest.setReturnType(method.getGenericReturnType());
CusResponseSuccessHandle cusResponseSuccessHandle = method.getDeclaredAnnotation(CusResponseSuccessHandle.class);
if(cusResponseSuccessHandle != null && cusRequest.getResponseSuccessHandle() == null){
if(cusResponseSuccessHandle != null && cusRequest.getResponseSuccessHandle() != null){
cusRequest.setResponseSuccessHandle(cusResponseSuccessHandle);
}
return requestAfterHandle(cusRequest, responseVo);
@ -113,11 +115,19 @@ public class CusHandleCenter{
responseVo.getEntityString()));
throw new CustomerException(Util.logStr("can not fetch [{}]", url)); //
}
CusRequestAfterHandle handle = cusRequest.getCusRequestAfter() == null ? new CusDefaultRequestAfterHandle() : cusRequest.getCusRequestAfter();
cusRequest.setCusRequestAfter(handle);
cusRequest.setResponseMap(responseVo.getResponseMap());
List<CusRequestAfterHandle> cusRequestAfter = cusRequest.getCusRequestAfter();
Object res = null;
log.info(Util.logStr("cusRequest: {}", JSONObject.toJSONString(cusRequest)));
Object res = handle.parseResponse(cusRequest, responseVo);
for (CusRequestAfterHandle handle : cusRequestAfter) {
if(RequestUtil.isMethodOverridden(handle.getClass(), CusDefaultRequestAfterHandle.class, "parseResponse")){
res = handle.parseResponse(cusRequest, responseVo);
}else {
CusDefaultRequestAfterHandle defaultRequestAfterHandle = new CusDefaultRequestAfterHandle();
res = defaultRequestAfterHandle.parseResponse(cusRequest, responseVo);
}
handle.service(cusRequest, responseVo);
}
return res;
}

View File

@ -25,11 +25,10 @@ public abstract class CusRequestHandle {
realRequestUrl.append(url);
}else {
realRequestUrl.append(host);
if(!host.endsWith(":")){
realRequestUrl.append(":");
if(port > 0 && !host.endsWith(":")){
realRequestUrl.append(":").append(port);
}
realRequestUrl.append(port);
if(!url.endsWith("/")){
if(!host.endsWith("/") && !url.startsWith("/")){
realRequestUrl.append("/");
}
realRequestUrl.append(url);

View File

@ -72,6 +72,9 @@ public class RequestHeaderHandle implements CusRequestBeforeHandle {
Parameter parameter = parameters[i];
CusRequestHeader requestHeader = parameter.getAnnotation(CusRequestHeader.class);
if(requestHeader != null){
if(Map.class.isAssignableFrom(parameter.getType())){
headers.putAll((Map<? extends String, ? extends String>) args[i]);
}else {
String val = Util.null2DefaultStr(args[i], "").trim();
String key = requestHeader.value().trim();
if(StringUtils.isNotBlank(key) && StringUtils.isNotBlank(val)){
@ -79,6 +82,7 @@ public class RequestHeaderHandle implements CusRequestBeforeHandle {
}
}
}
}
cusRequest.getHeaders().putAll(headers);
}
}

View File

@ -10,6 +10,7 @@ import xuanran.wang.http_test.constant.CusRequestClientConstant;
import xuanran.wang.http_test.entity.CusRequestEntity;
import xuanran.wang.http_test.handle.CusRequestAfterHandle;
import java.lang.reflect.Type;
import java.util.Map;
/**
@ -22,12 +23,11 @@ public class CusDefaultRequestAfterHandle implements CusRequestAfterHandle {
@Override
public Object parseResponse(CusRequestEntity cusRequest, ResponeVo responseVo) {
Class<?> returnType = cusRequest.getReturnType();
if(ResponeVo.class.isAssignableFrom(returnType)) {
Type returnType = cusRequest.getReturnType();
if(ResponeVo.class.isAssignableFrom(returnType.getClass())) {
return responseVo;
}
String json = responseVo.getEntityString();
cusRequest.setResponseMap(responseVo.getResponseMap());
CusResponseSuccessHandle responseSuccessHandle = cusRequest.getResponseSuccessHandle();
if(responseSuccessHandle != null){
String successCondition = responseSuccessHandle.successCondition();

View File

@ -8,6 +8,8 @@ import xuanran.wang.http_test.entity.CusRequestEntity;
import xuanran.wang.http_test.handle.CusRequestBeforeHandle;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* <h1></h1>
@ -23,7 +25,6 @@ public class CusUrlHandle implements CusRequestBeforeHandle {
throw new CustomerException("method not found CusRequestUrl!");
}
cusRequest.setUrl(requestUrl.url());
Class<?> returnType = method.getReturnType();
cusRequest.setReturnType(returnType);
cusRequest.setReturnType(method.getGenericReturnType());
}
}

View File

@ -17,6 +17,8 @@ import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
/**
@ -29,12 +31,13 @@ public class RequestUtil implements InvocationHandler {
private CusRequestAddress cusRequestAddress = null;
private final Logger log = Util.getLogger();
private final CusHandleCenter handleCenter = new CusHandleCenter();
private final CusRequestEntity cusRequest = new CusRequestEntity();
private CusRequestEntity cusRequest;
public <T> T getRequestClient(Class<?> clazz){
Annotation annotation = clazz.getDeclaredAnnotation(CusRequestClient.class);
if(annotation == null){
throw new CustomerException(Util.logStr(clazz.getName() + " not found CusRequestClient annotation!"));
}
cusRequest = new CusRequestEntity();
// 请求后处理
CusReqAfterHandleRegister cusReqAfterHandleRegister = clazz.getDeclaredAnnotation(CusReqAfterHandleRegister.class);
if(cusReqAfterHandleRegister != null){
@ -62,7 +65,6 @@ public class RequestUtil implements InvocationHandler {
cusRequest.setPort(port);
}
handleCenter.requestBeforeHandle(cusRequest, method, args);
log.info("requestHandle : \n" + JSONObject.toJSONString(cusRequest));
ResponeVo responeVo = handleCenter.requestHandle(cusRequest, method);
return handleCenter.requestAfterHandle(method, cusRequest, responeVo);
}
@ -70,16 +72,33 @@ public class RequestUtil implements InvocationHandler {
public static void setCusRequestAfter(CusReqAfterHandleRegister cusReqAfterHandleRegister,
CusRequestEntity cusRequest){
if(cusReqAfterHandleRegister != null){
Class<?> clazz = cusReqAfterHandleRegister.afterHandle();
if (CusRequestAfterHandle.class.isAssignableFrom(clazz)) {
Class<?>[] clazz = cusReqAfterHandleRegister.afterHandle();
List<CusRequestAfterHandle> requestAfter = cusRequest.getCusRequestAfter();
if(requestAfter == null){
requestAfter = new ArrayList<>();
}
cusRequest.setCusRequestAfter(requestAfter);
for (Class<?> aClass : clazz) {
if (CusRequestAfterHandle.class.isAssignableFrom(aClass)) {
try {
Object cusRequestAfter = clazz.newInstance();
cusRequest.setCusRequestAfter((CusRequestAfterHandle) cusRequestAfter);
CusRequestAfterHandle cusRequestAfter = (CusRequestAfterHandle) aClass.newInstance();
requestAfter.add(cusRequestAfter);
}catch (Exception e){
throw new CustomerException(Util.logStr("class : {}, newInstance error!", e.getMessage()));
}
}
}
}
}
public static boolean isMethodOverridden(Class<?> subclass, Class<?> superclass, String methodName) {
try {
Method method = subclass.getDeclaredMethod(methodName);
Method superMethod = superclass.getDeclaredMethod(methodName);
return !method.equals(superMethod);
} catch (NoSuchMethodException e) {
return false;
}
}
}

View File

@ -0,0 +1,27 @@
package xuanran.wang.http_test.service;
import xuanran.wang.http_test.annotations.CusRequestClient;
import xuanran.wang.http_test.annotations.header.CusRequestHeader;
import xuanran.wang.http_test.annotations.request_type.CusRequestPost;
import javax.ws.rs.core.MediaType;
import java.util.Map;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/5/24 14:53
*/
@CusRequestClient(host = "https://ecology.yeyaguitu.cn")
public interface EcTestService {
@CusRequestPost(url = "/api/ec/dev/auth/regist")
@CusRequestHeader(cusHeaders = {"appid:JYZ", "loginid:sysadmin","Content-type:"+ MediaType.APPLICATION_JSON})
Map<String, Object> register();
@CusRequestPost(url = "/api/ec/dev/auth/regist")
@CusRequestHeader(cusHeaders = {"Content-type:"+ MediaType.APPLICATION_JSON})
Map<String, Object> register(@CusRequestHeader("appid") String appId,
@CusRequestHeader Map<String, String> headers);
}

View File

@ -2,12 +2,15 @@ package xuanran.wang.http_test.service;
import xuanran.wang.http_test.annotations.*;
import xuanran.wang.http_test.annotations.body.CusRequestBody;
import xuanran.wang.http_test.annotations.handle.CusReqAfterHandleRegister;
import xuanran.wang.http_test.annotations.handle.CusResponseSuccessHandle;
import xuanran.wang.http_test.annotations.header.CusRequestHeader;
import xuanran.wang.http_test.annotations.request_path.CusPathQuery;
import xuanran.wang.http_test.annotations.request_type.CusRequestGet;
import xuanran.wang.http_test.annotations.request_type.CusRequestPost;
import xuanran.wang.http_test.constant.CusRequestClientConstant;
import xuanran.wang.http_test.test.Student;
import xuanran.wang.http_test.test.TestRequestAfterHandle;
import java.util.List;
import java.util.Map;
@ -19,7 +22,6 @@ import java.util.Map;
* @date 2023/3/10 12:39
*/
@CusRequestClient(host = "http://114.115.168.220", port = 8191)
//@CusReqAfterHandleRegister(afterHandle = TestRequestAfterHandle.class)
public interface TestService {
@CusRequestGet(url = "educate-plat/api/v1/class/getClassList")
@ -30,7 +32,8 @@ public interface TestService {
errorMsg = "msg",
data = "data"
)
Map<String, Object> getStu(Map<String, Object> path,
@CusReqAfterHandleRegister(afterHandle = {TestRequestAfterHandle.class})
List<Student> getStu(Map<String, Object> path,
@CusRequestBody Map<String, Object> body,
@CusRequestHeader("hsjhdsad") String test,
@CusPathQuery("test") String test1);

View File

@ -2,6 +2,7 @@ package xuanran.wang.http_test.test;
import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.api.doc.migrate.util.FtpUtil;
import com.jcraft.jsch.ChannelSftp;
import org.junit.Test;
@ -9,6 +10,7 @@ import weaver.backup.utils.ZipUtil;
import xuanran.wang.http_test.entity.CusHandleEntity;
import xuanran.wang.http_test.handle.util.HandleUtil;
import xuanran.wang.http_test.proxy.CusUtil;
import xuanran.wang.http_test.service.EcTestService;
import xuanran.wang.http_test.service.TestService;
import java.util.*;
@ -23,6 +25,7 @@ import java.util.stream.Collectors;
public class RequestTest extends BaseTest {
private TestService requestClient = CusUtil.getRequestClient(TestService.class);
private EcTestService ecTestService = CusUtil.getRequestClient(EcTestService.class);
@Test
public void test(){
HashMap<String, Object> map = new HashMap<>();
@ -36,9 +39,11 @@ public class RequestTest extends BaseTest {
path.put("e","5");
path.put("f","6");
Map<String, Object> stu = requestClient.getStu(map, body, "a", "test1111");
log.info("stu : \n" + JSONObject.toJSONString(stu));
// List<Student> stu = requestClient.getStu(map, body, "a", "test1111");
List<Student> stu = requestClient.getStu(map, body, "a", "test1111");
for (Student student : stu) {
System.out.println("stu => " + student);
}
// String json = "{\"xuanran.wang.http_test.requestBeforeHandle.path_handle\":[{\"handleClass\":\"xuanran.wang.http_test.requestBeforeHandle.path_handle.CusPathParseHandle\",\"order\":0,\"packageName\":\"xuanran.wang.http_test.requestBeforeHandle.path_handle\"},{\"handleClass\":\"xuanran.wang.http_test.requestBeforeHandle.path_handle.TestHandle\",\"order\":99,\"packageName\":\"xuanran.wang.http_test.requestBeforeHandle.path_handle\"}],\"xuanran.wang.http_test.requestBeforeHandle.header_handle\":[{\"handleClass\":\"xuanran.wang.http_test.requestBeforeHandle.header_handle.RequestHeaderHandle\",\"order\":0,\"packageName\":\"xuanran.wang.http_test.requestBeforeHandle.header_handle\"}]}";
// System.out.println(JSONObject.parseObject(JSONObject.toJSONString(json), Map.class));
// String stu1 = requestClient.getStu(body);
@ -61,4 +66,16 @@ public class RequestTest extends BaseTest {
}
}
@Test
public void testB(){
Map<String, Object> register = ecTestService.register();
System.out.printf("register : " + JSONObject.toJSONString(register));
HashMap<String, String> header = new HashMap<>();
header.put("loginid","123");
header.put("dadsada","sasas");
Map<String, Object> register1 = ecTestService.register("JYZ1", header);
System.out.printf("register1 : " + JSONObject.toJSONString(register1));
}
}

View File

@ -0,0 +1,49 @@
package xuanran.wang.http_test.test;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/5/23 11:40
*/
public class Student {
private String teacherId;
private int belongYear;
private String classNo;
private String className;
private String id;
public void setTeacherId(String teacherId) {
this.teacherId = teacherId;
}
public String getTeacherId() {
return teacherId;
}
public void setBelongYear(int belongYear) {
this.belongYear = belongYear;
}
public int getBelongYear() {
return belongYear;
}
public void setClassNo(String classNo) {
this.classNo = classNo;
}
public String getClassNo() {
return classNo;
}
public void setClassName(String className) {
this.className = className;
}
public String getClassName() {
return className;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}