diff --git a/src/main/java/com/seeyon/utils/form/ClauseFactor.java b/src/main/java/com/seeyon/utils/form/ClauseFactor.java index d2dd6b1..b4d2207 100644 --- a/src/main/java/com/seeyon/utils/form/ClauseFactor.java +++ b/src/main/java/com/seeyon/utils/form/ClauseFactor.java @@ -1,6 +1,7 @@ package com.seeyon.utils.form; public enum ClauseFactor { + NEQ,//不相等 EQ, //相等 GT, //大于 GE, //大于等于 @@ -10,10 +11,16 @@ public enum ClauseFactor { NOT_NULL, //非空 LIKE, //模糊 AND, - OR + OR, + IN, + NOT_IN ; + public boolean isNullType() { return this == NULL || this == NOT_NULL; } + public boolean isInType() { + return this == IN || this == NOT_IN; + } } diff --git a/src/main/java/com/seeyon/utils/form/EnumMapUtils.java b/src/main/java/com/seeyon/utils/form/EnumMapUtils.java index 1c4e6c0..6866267 100644 --- a/src/main/java/com/seeyon/utils/form/EnumMapUtils.java +++ b/src/main/java/com/seeyon/utils/form/EnumMapUtils.java @@ -1,6 +1,5 @@ package com.seeyon.utils.form; -import com.seeyon.cap4.form.api.FormApi4Cap4; import com.seeyon.cap4.form.bean.FormBean; import com.seeyon.cap4.form.bean.FormFieldBean; import com.seeyon.cap4.form.bean.FormTableBean; @@ -12,34 +11,30 @@ import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem; import com.seeyon.ctp.util.JDBCAgent; import org.apache.commons.lang3.StringUtils; -import java.util.Arrays; -import java.util.List; -import java.util.Map; +import java.util.*; public class EnumMapUtils { - public static String getMasterTableEnumItemValue(String formNo,String fieldDisplay, String targetValue) { + public static String getEnumItemValueByDisplayValue(FormBean cap4FormBean,String fieldDisplay, String targetValue) { if(targetValue == null || "null".equals(targetValue) || "".equals(targetValue)){ - return ""; + return null; } try { - FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4"); - FormBean cap4FormBean = formApi4Cap4.getFormByFormCode(formNo); FormTableBean masterTableBean = cap4FormBean.getMasterTableBean(); FormFieldBean beanByDisplay = masterTableBean.getFieldBeanByDisplay(fieldDisplay); if(beanByDisplay == null || beanByDisplay.getEnumId() == 0l) { - return ""; + return null; } return getEnumItemValueByEnumId(targetValue, beanByDisplay.getEnumId()); } catch (Exception e) { - return ""; + return null; } } public static String getEnumItemIdByGroupNameAndItemShowValue(String enumGroupName, String targetValue) { String sql = "SELECT * FROM ctp_enum ce let join ctp_enum_item cei on ce.`ID` = cei.REF_ENUMID where ce.`ENUMNAME` = ? and CEI.`SHOWVALUE` = ?"; if(StringUtils.isAnyBlank(enumGroupName, targetValue)){ - return ""; + return null; } Long enumId = null; JDBCAgent agent = new JDBCAgent(); @@ -47,7 +42,7 @@ public class EnumMapUtils { agent.execute(sql, Arrays.asList(enumGroupName,targetValue)); List> list = (List>) agent.resultSetToList(); if(list == null || list.size() == 0) { - return ""; + return null; } Map map = list.get(0); enumId = (Long)map.get("ID"); @@ -57,13 +52,13 @@ public class EnumMapUtils { }finally { agent.close(); } - return ""; + return null; } - public static String getEnumItemValue(String rootPCode, String groupValue, String targetValue) { + public static String getEnumItemValueByRootPCode(String rootPCode, String groupValue, String targetValue) { if(targetValue == null || "null".equals(targetValue) || "".equals(targetValue)){ - return ""; + return null; } String queryIdSql = "SELECT ce.ID FROM ctp_enum ce inner join ctp_enum cei on ce.`PARENT_ID` = cei.ID where CEI.`PROGRAM_CODE` = ? and ce.`ENUMNAME` = ?"; Long enumId = null; @@ -72,62 +67,89 @@ public class EnumMapUtils { agent.execute(queryIdSql, Arrays.asList(rootPCode,groupValue)); List> list = (List>) agent.resultSetToList(); if(list == null || list.size() == 0) { - return ""; + return null; } Map map = list.get(0); enumId = (Long)map.get("ID"); } catch (Exception e) { - return ""; + return null; }finally { agent.close(); } EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew"); CtpEnumBean ctpEnumBean = enumManagerNew.getEnum(enumId); if(ctpEnumBean == null) { - return ""; + return null; } List ctpEnumItems = ctpEnumBean.getItems(); if(ctpEnumBean.getItems() == null) { - return ""; + return null; } for (CtpEnumItem enumItem : ctpEnumItems) { if(enumItem.getShowvalue().equals(targetValue)) { return enumItem.getId() + ""; } } - return ""; + return null; + } + + public static Set getEnumItemValues(FormBean cap4FormBean, String fieldDisplay) { + Set set = new HashSet<>(); + try { + FormTableBean masterTableBean = cap4FormBean.getMasterTableBean(); + FormFieldBean beanByDisplay = masterTableBean.getFieldBeanByDisplay(fieldDisplay); + if(beanByDisplay == null || beanByDisplay.getEnumId() == 0l) { + return set; + } + EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew"); + CtpEnumBean ctpEnumBean = enumManagerNew.getEnum(beanByDisplay.getEnumId()); + + if(ctpEnumBean == null) { + return set; + } + List ctpEnumItems = ctpEnumBean.getItems(); + if(ctpEnumBean.getItems() == null) { + return set; + } + for (CtpEnumItem enumItem : ctpEnumItems) { + set.add(enumItem.getShowvalue()); + } + } catch (Exception e) { + + } + return set; } public static String getEnumItemValueByEnumId(String showValue,long enumId) { EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew"); CtpEnumBean ctpEnumBean = enumManagerNew.getEnum(enumId); if(ctpEnumBean == null) { - return ""; + return null; } List ctpEnumItems = ctpEnumBean.getItems(); if(ctpEnumBean.getItems() == null) { - return ""; + return null; } for (CtpEnumItem enumItem : ctpEnumItems) { if(enumItem.getShowvalue().equals(showValue)) { return enumItem.getId() + ""; } } - return ""; + return null; } public static String getEnumShowValue(Object enumItemId) throws BusinessException { if(enumItemId == null) { - return ""; + return null; } Long temp = enumItemId instanceof Long ? (Long)enumItemId : (enumItemId instanceof String ? Long.parseLong((String)enumItemId) : null); if(temp == null) { - return ""; + return null; } EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew"); CtpEnumItem ctpEnumItem = enumManagerNew.getCtpEnumItem(temp); if(ctpEnumItem == null) { - return ""; + return null; } return ctpEnumItem.getShowvalue(); } diff --git a/src/main/java/com/seeyon/utils/form/FormExportUtil.java b/src/main/java/com/seeyon/utils/form/FormSaveUtil.java similarity index 70% rename from src/main/java/com/seeyon/utils/form/FormExportUtil.java rename to src/main/java/com/seeyon/utils/form/FormSaveUtil.java index 11587c0..4dceff8 100644 --- a/src/main/java/com/seeyon/utils/form/FormExportUtil.java +++ b/src/main/java/com/seeyon/utils/form/FormSaveUtil.java @@ -1,5 +1,8 @@ package com.seeyon.utils.form; +import com.seeyon.ctp.services.ServiceException; +import com.seeyon.v3x.services.form.FormFactory; +import com.seeyon.v3x.services.form.bean.FormExport; import com.seeyon.v3x.services.form.bean.RecordExport; import com.seeyon.v3x.services.form.bean.SubordinateFormExport; import com.seeyon.v3x.services.form.bean.ValueExport; @@ -10,14 +13,14 @@ import java.util.Map; import java.util.Set; //创建无流程表单数据处理工具类 -public class FormExportUtil { +public class FormSaveUtil { /** * 设置主表信息 * @param map 设置主表字段。Map<主表显示名称,主表数据> * @return */ - public List setFormValue(Map map ){ + public static List setFormValue(Map map ){ // 创建返回值对象 List valueExports = new ArrayList(); ValueExport valueExport ; @@ -32,7 +35,6 @@ public class FormExportUtil { valueExport.setValue(map.get(key).toString()); valueExports.add(valueExport); } - System.out.println(key+":"+map.get(key)); } } return valueExports; @@ -42,7 +44,7 @@ public class FormExportUtil { * 设置从表信息 * @param lists 设置主表字段。List> */ - public List setSubordinateFormValue(List> lists){ + public static List setSubordinateFormValue(List> lists){ List subordinateFormExports = new ArrayList(); SubordinateFormExport subordinateFormExport = new SubordinateFormExport(); List recordExports = new ArrayList(); @@ -60,7 +62,7 @@ public class FormExportUtil { return subordinateFormExports; } - public List setAllSubordinateFormValue(List> lists){ + public static List setAllSubordinateFormValue(List> lists){ List subordinateFormExports = new ArrayList(); for (Map list : lists) { SubordinateFormExport subordinateFormExport = new SubordinateFormExport(); @@ -80,5 +82,15 @@ public class FormExportUtil { return subordinateFormExports; } - + public static void formSave(String loginName, String formNo, FormFactory formFactory, Map mainFormData, List> subFormDatas) throws ServiceException { + FormExport formExport = new FormExport(); + FormExportUtil formExportUtil = new FormExportUtil(); + List valueExport = formExportUtil.setFormValue(mainFormData); + formExport.setValues(valueExport); + if(subFormDatas != null) { + formExport.setSubordinateForms(formExportUtil.setAllSubordinateFormValue(subFormDatas)); + } + formFactory.importBusinessFormData(loginName, formNo, + formExport, new String[] {}); + } } diff --git a/src/main/java/com/seeyon/utils/form/FormTableExecutor.java b/src/main/java/com/seeyon/utils/form/FormTableExecutor.java index ba1d0f1..f8e8a1b 100644 --- a/src/main/java/com/seeyon/utils/form/FormTableExecutor.java +++ b/src/main/java/com/seeyon/utils/form/FormTableExecutor.java @@ -4,7 +4,6 @@ import com.seeyon.aicloud.common.JsonUtils; import com.seeyon.cap4.form.api.FormApi4Cap4; import com.seeyon.cap4.form.bean.FormBean; import com.seeyon.cap4.form.bean.FormFieldBean; -import com.seeyon.cap4.form.bean.FormTableBean; import com.seeyon.ctp.common.AppContext; import com.seeyon.ctp.common.exceptions.BusinessException; import com.seeyon.ctp.util.JDBCAgent; @@ -16,18 +15,16 @@ import java.util.stream.Collectors; public class FormTableExecutor { - /* ========== 表定位 ========== */ - private static final Log log = LogFactory.getLog(FormTableExecutor.class); - /* ========== 表定位 ========== */ - - public TableContext master(String formNo) throws BusinessException { + /*获取主表定义bean对象*/ + public static TableContext master(String formNo) throws BusinessException { FormBean form = getForm(formNo); return new TableContext(form.getMasterTableBean()); } - public TableContext sub(String formNo, String subTable) throws BusinessException { + /*获取从表定义bean对象*/ + public static TableContext sub(String formNo, String subTable) throws BusinessException { FormBean form = getForm(formNo); return form.getSubTableBean().stream() .filter(t -> t.getTableName().equals(subTable) || t.getDisplay().equals(subTable)) @@ -36,12 +33,13 @@ public class FormTableExecutor { .orElseThrow(() -> new BusinessException("未找到子表:" + subTable)); } - private FormBean getForm(String formNo) throws BusinessException { + private static FormBean getForm(String formNo) throws BusinessException { FormApi4Cap4 api = (FormApi4Cap4) AppContext.getBean("formApi4Cap4"); return api.getFormByFormCode(formNo); } - private void fillUpdateFields(TableContext ctx, List updateFields) { + /*填充update字段fieldName*/ + private static void fillUpdateFields(TableContext ctx, List updateFields) { if (updateFields == null) return; for (FormUpdateField c : updateFields) { @@ -52,7 +50,8 @@ public class FormTableExecutor { } } - private void fillConditionFields(TableContext ctx, List conditions) { + /*填充condition字段fieldName*/ + private static void fillConditionFields(TableContext ctx, List conditions) { if (conditions == null) return; for (FormWhereCondition c : conditions) { @@ -67,7 +66,8 @@ public class FormTableExecutor { } } - private List resolveQueryColumns(TableContext ctx, List displays) { + /*将查询列display转换为fieldName*/ + private static List resolveQueryColumns(TableContext ctx, List displays) { if (displays == null) return Collections.emptyList(); return displays.stream() .map(ctx.getTableBean()::getFieldBeanByDisplay) @@ -78,7 +78,7 @@ public class FormTableExecutor { /* ========== 查询方法 ========== */ - public List query(TableContext ctx, + public static List query(TableContext ctx, List queryDisplays, List conditions, boolean changeEnum) { @@ -110,7 +110,8 @@ public class FormTableExecutor { return new ArrayList<>(); } - public FormColumn queryOne(TableContext ctx, + /*查询单条记录*/ + public static FormColumn queryOne(TableContext ctx, List conditions, boolean changeEnum) { @@ -138,7 +139,8 @@ public class FormTableExecutor { return null; } - public List pageQuery(TableContext ctx, + /*分页查询*/ + public static List pageQuery(TableContext ctx, List displays, List conditions, int pageNo, @@ -174,7 +176,8 @@ public class FormTableExecutor { return new ArrayList<>(); } - public long count(TableContext ctx,List countField,List conditions) { + /*统计数量*/ + public static long count(TableContext ctx,List countField,List conditions) { fillConditionFields(ctx, conditions); List countColumn = resolveQueryColumns(ctx,countField); SqlBuildParam param = new SqlBuildParam(); @@ -199,8 +202,8 @@ public class FormTableExecutor { } - - public int update(TableContext ctx, List fields, List conditions) { + /*更新操作*/ + public static int update(TableContext ctx, List fields, List conditions) { if (fields == null || fields.isEmpty()) throw new IllegalArgumentException("更新字段不能为空"); if (conditions == null || conditions.isEmpty()) throw new IllegalArgumentException("UPDATE必须带条件"); fillConditionFields(ctx, conditions); @@ -224,7 +227,8 @@ public class FormTableExecutor { return 0; } - public int delete(TableContext ctx, List conditions) { + /*删除操作*/ + public static int delete(TableContext ctx, List conditions) { if (conditions == null || conditions.isEmpty()) throw new IllegalArgumentException("DELETE必须带条件"); fillConditionFields(ctx, conditions); SqlBuildParam param = new SqlBuildParam(); @@ -247,7 +251,8 @@ public class FormTableExecutor { } /* ========== 构建 FormColumn ========== */ - private FormColumn buildFormColumn(Map row, + /*填充结果字段*/ + private static FormColumn buildFormColumn(Map row, TableContext ctx, boolean changeEnum) { FormColumn column = new FormColumn(); @@ -262,10 +267,8 @@ public class FormTableExecutor { if (changeEnum && field.isEnumField()) { value = EnumMapUtils.getEnumShowValue(value); } - // 枚举、部门、成员等特殊字段处理 - value = handleFieldSpecialType(field, value); - + // value = handleFieldSpecialType(field, value); FormFieldVo vo = new FormFieldVo(); vo.setDisplayName(field.getDisplay()); vo.setValue(value); @@ -284,13 +287,13 @@ public class FormTableExecutor { return column; } - private Object handleFieldSpecialType(FormFieldBean field, Object value) throws BusinessException { + private static Object handleFieldSpecialType(FormFieldBean field, Object value) throws BusinessException { if (value == null) return null; switch (field.getInputType()) { case "select": - if (field.getEnumId() != 0L) { - return EnumMapUtils.getEnumItemValueByEnumId(String.valueOf(value), field.getEnumId()); + if (field.isEnumField()) { + return EnumMapUtils.getEnumShowValue(value); } break; case "department": @@ -308,22 +311,7 @@ public class FormTableExecutor { return value; } - public boolean isMasterTableFile(String displayName, String formNo) { - FormApi4Cap4 formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4"); - try { - FormBean cap4FormBean = formApi4Cap4.getFormByFormCode(formNo); - FormTableBean masterTableBean = cap4FormBean.getMasterTableBean(); - FormFieldBean fieldBeanByDisplay = masterTableBean.getFieldBeanByDisplay(displayName); - return fieldBeanByDisplay != null && - ("image".equals(fieldBeanByDisplay.getInputType()) || - "attachment".equals(fieldBeanByDisplay.getInputType())); - } catch (BusinessException e) { - - } - return false; - } - - private Map buildCountSql( + private static Map buildCountSql( String countField, String tableName, List conditions) { @@ -337,7 +325,7 @@ public class FormTableExecutor { return buildResult(sql, params); } - private Map buildSelectSql( + private static Map buildSelectSql( String tableName, List queryColumns, List conditions, @@ -374,7 +362,7 @@ public class FormTableExecutor { return buildResult(sql, params); } - private Map buildUpdateSql( + private static Map buildUpdateSql( String tableName, List fields, List conditions) { @@ -417,7 +405,7 @@ public class FormTableExecutor { return buildResult(sql, params); } - private Map buildDeleteSql( + private static Map buildDeleteSql( String tableName, List conditions) { @@ -435,7 +423,7 @@ public class FormTableExecutor { return buildResult(sql, params); } - private Map buildInsertSql( + private static Map buildInsertSql( String tableName, Map data) { @@ -474,63 +462,82 @@ public class FormTableExecutor { * @param params 参数列表(引用传递) * @return 拼接后的 WHERE 子句(包含 WHERE 关键字) */ - private String buildWhereClause(List conditions, List params) { + private static String buildWhereClause(List conditions, List params) { if (conditions == null || conditions.isEmpty()) { return ""; } - - StringBuilder whereClause = new StringBuilder(" WHERE "); - int conditionIndex = 0; - - for (FormWhereCondition condition : conditions) { - // 处理括号起始 - if (condition.isStartWithBracket()) { - whereClause.append("("); + StringBuilder whereCause = new StringBuilder(" WHERE "); + for (int i = 0; i < conditions.size(); i++) { + FormWhereCondition c = conditions.get(i); + // 左括号 + if (c.isStartWithBracket()) { + whereCause.append("("); } - - // 字段名校验 - String fieldName = condition.getFieldName(); - ClauseFactor factor = condition.getClauseFactor(); + String field = c.getFieldName(); + ClauseFactor factor = c.getClauseFactor(); String operator = parseOperator(factor); - - // 构建条件表达式 - String conditionExpr; - if (factor != null && factor.isNullType()) { - // 处理 NULL/NOT NULL 条件(无需参数) - conditionExpr = String.format("%s %s", fieldName, operator); + // NULL / NOT NULL + if (factor.isNullType()) { + whereCause.append(field).append(" ").append(operator); + } else if (factor.isInType()) { + appendInClause(whereCause, field, operator, c.getValue(), params); } else { - // 处理普通条件(带占位符) - conditionExpr = String.format("%s %s ?", fieldName, operator); - // 处理函数模板(如 TO_DATE) - if (condition.getIndex() != null) { - conditionExpr = conditionExpr.replace("?", condition.getIndex()); + String placeholder = "?"; + // 函数模板(如 TO_DATE(?)) + if (c.getIndex() != null) { + placeholder = c.getIndex(); + } + whereCause.append(field).append(" ").append(operator).append(" ").append(placeholder); + if (ClauseFactor.LIKE.equals(factor)) { + params.add("%" + c.getValue() + "%"); + } else { + params.add(c.getValue()); } - // 添加参数值 - params.add(condition.getValue()); } - - whereClause.append(conditionExpr); - - // 处理括号闭合 - if (condition.isEndWithBracket()) { - whereClause.append(")"); + // 右括号 + if (c.isEndWithBracket()) { + whereCause.append(")"); } - - // 添加连接符(AND/OR) - if (conditionIndex < conditions.size() - 1) { - whereClause.append(" ").append(condition.getConcatFactor()).append(" "); + // AND / OR + if (i < conditions.size() - 1) { + whereCause.append(" ").append(c.getConcatFactor()).append(" "); } - conditionIndex++; } - - return whereClause.toString(); + return whereCause.toString(); } + private static void appendInClause( + StringBuilder sql, + String field, + String operator, + Object value, + List params) { + if (!(value instanceof Collection)) { + throw new IllegalArgumentException("IN 条件的值必须是 Collection"); + } + Collection values = (Collection) value; + if (values.isEmpty()) { + // 防止 SQL 语法错误 + sql.append("1 = 0"); + return; + } + sql.append(field).append(" ").append(operator).append(" ("); + int index = 0; + for (Object v : values) { + if (index > 0) { + sql.append(", "); + } + sql.append("?"); + params.add(v); + index++; + } + sql.append(")"); + } /** * 解析运算符映射(eq -> =, lt -> < 等) */ - private String parseOperator(ClauseFactor factor) { + private static String parseOperator(ClauseFactor factor) { if(factor == null) { return "="; } @@ -547,14 +554,14 @@ public class FormTableExecutor { } } - private Map buildResult(StringBuilder sql, List params) { + private static Map buildResult(StringBuilder sql, List params) { Map result = new HashMap<>(); result.put("sql", sql.toString()); result.put("params", params); return result; } - private Map generateSql(SqlBuildParam param) { + private static Map generateSql(SqlBuildParam param) { if (param == null || param.getSqlType() == null) { throw new IllegalArgumentException("SqlBuildParam or SqlType cannot be null"); diff --git a/src/main/java/com/seeyon/utils/form/FormWhereCondition.java b/src/main/java/com/seeyon/utils/form/FormWhereCondition.java index b318a12..30029ba 100644 --- a/src/main/java/com/seeyon/utils/form/FormWhereCondition.java +++ b/src/main/java/com/seeyon/utils/form/FormWhereCondition.java @@ -1,9 +1,13 @@ package com.seeyon.utils.form; +import java.util.ArrayList; +import java.util.List; + public class FormWhereCondition { private String display; private String fieldName; //字段名 private Object value; //值 + private List values; //值 private ClauseFactor clauseFactor; //条件因子 eq lt gt not_null null private ClauseFactor concatFactor = ClauseFactor.AND; //拼接因子 private boolean startWithBracket = false; //是否以括号开头生成子条件 @@ -11,6 +15,7 @@ public class FormWhereCondition { private String index; public FormWhereCondition() { + this.values = new ArrayList<>(); } public String getDisplay() { @@ -118,4 +123,15 @@ public class FormWhereCondition { public void setEndWithBracket(boolean endWithBracket) { this.endWithBracket = endWithBracket; } + + public List getValues() { + return values; + } + public FormWhereCondition addValue(Object value) { + this.values.add(value); + return this; + } + public void setValues(List values) { + this.values = values; + } } diff --git a/src/main/java/com/seeyon/utils/http/HttpClient.java b/src/main/java/com/seeyon/utils/http/HttpClient.java index 35d716f..e0bb645 100644 --- a/src/main/java/com/seeyon/utils/http/HttpClient.java +++ b/src/main/java/com/seeyon/utils/http/HttpClient.java @@ -246,18 +246,18 @@ public class HttpClient { HttpEntity entity = httpResponse.getEntity(); content = EntityUtils.toString(entity, encode); } catch (Exception e) { - e.printStackTrace(); + }finally{ try { httpResponse.close(); } catch (IOException e) { - e.printStackTrace(); + } } try { //关闭连接、释放资源 closeableHttpClient.close(); } catch (IOException e) { - e.printStackTrace(); + } return content; } diff --git a/src/main/java/com/seeyon/utils/http/OaResp.java b/src/main/java/com/seeyon/utils/http/OaResp.java new file mode 100644 index 0000000..9afda60 --- /dev/null +++ b/src/main/java/com/seeyon/utils/http/OaResp.java @@ -0,0 +1,32 @@ +package com.seeyon.utils.http; + +public class OaResp { + + private Integer code; + private String message; + private Object data; + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } +} \ No newline at end of file diff --git a/src/main/java/com/seeyon/utils/http/OaRestClient.java b/src/main/java/com/seeyon/utils/http/OaRestClient.java new file mode 100644 index 0000000..b4c4a0c --- /dev/null +++ b/src/main/java/com/seeyon/utils/http/OaRestClient.java @@ -0,0 +1,114 @@ +package com.seeyon.utils.http; + +import com.alibaba.fastjson.JSONObject; +import com.seeyon.aicloud.common.JsonUtils; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicHeader; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class OaRestClient { + + private static final Logger log = LoggerFactory.getLogger(OaRestClient.class); + private String oaHost; + private String restName; + private String restPwd; + private Boolean cacheToken = false; + private ConcurrentHashMap tokenCache = new ConcurrentHashMap<>(); + + public OaRestClient(String oaHost, String restName, String restPwd, Boolean cacheToken) { + this.oaHost = oaHost; + this.restName = restName; + this.restPwd = restPwd; + this.cacheToken = cacheToken; + } + + public OaResp sendGet(String bizName, String url) throws Exception { + Map headers = new HashMap<>(); + headers.put("token",getToken()); + log.info(bizName + "请求链接为:" + url); + String respStr = HttpClient.httpGet(oaHost + "/seeyon/rest" + url,headers,null); + log.info(bizName + "响应结果为:" + respStr); + return resovleResp(respStr); + } + + public OaResp sendPost(String bizName,String url,Map params) throws Exception { + Map headers = new HashMap<>(); + headers.put("token",getToken()); + String paramStr = JsonUtils.toJSONString(params); + log.info(bizName + "请求参数为:" + paramStr); + String respStr = HttpClient.httpPostRaw(oaHost + "/seeyon/rest" + url,paramStr,headers,null); + log.info(bizName + "响应结果为:" + respStr); + return resovleResp(respStr); + } + + OaResp resovleResp(String respStr){ + return JsonUtils.parseObject(respStr,OaResp.class); + } + + private String applyToken() { + String url = oaHost +"/seeyon/rest/token/" + restName + "/" + restPwd + "?loginName=" + restName; + DefaultHttpClient client = new DefaultHttpClient(); + String result = ""; + HttpGet get = new HttpGet(url); + // 添加 Headers 信息 + get.addHeader(new BasicHeader("Accept", "application/json")); + try { + HttpResponse res = client.execute(get); + if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + result = EntityUtils.toString(res.getEntity()); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + String token = null; + if(result.contains("{")) { + JSONObject jsObj = JSONObject.parseObject(result); + token = jsObj.get("id").toString(); + }else { + token = result; + } + return token; + } + + private String getToken(){ + if(cacheToken) { + String token = tokenCache.get(restName); + if(token != null && !checkExpire(token)) { + return token; + }else { + String tokenStr = applyToken(); + tokenCache.put(restName, tokenStr); + return tokenStr; + } + } + return applyToken(); + } + + private boolean checkExpire(String token) { + String url = oaHost + "/seeyon/rest/cap4/batch/refresh"; + try{ + Map headers = new HashMap<>(); + headers.put("token",token); + headers.put("loginName",restName); + String respStr = HttpClient.httpPostRaw(url, null, headers,null); + Map map = JsonUtils.parseObject(respStr, Map.class); + if("0".equals(map.get("code"))) { + return false; + }else { + return true; + } + } catch (Exception e){ + return true; + } + } + +} \ No newline at end of file diff --git a/src/test/OaRestClientTest.java b/src/test/OaRestClientTest.java new file mode 100644 index 0000000..0f5c707 --- /dev/null +++ b/src/test/OaRestClientTest.java @@ -0,0 +1,5 @@ +public class OaRestClientTest { + public static void main(String[] args) { + OaRestClientTest oaRestClientTest = new OaRestClientTest(); + } +}