diff --git a/javascript/youhong.ai/pcn/workflow_code_block.js b/javascript/youhong.ai/pcn/workflow_code_block.js index 9618e72..a6bb3d9 100644 --- a/javascript/youhong.ai/pcn/workflow_code_block.js +++ b/javascript/youhong.ai/pcn/workflow_code_block.js @@ -483,4 +483,56 @@ $(() => { } }) }) -/* ******************* 当明细数据未加载完成时 控制流程提交 end ******************* */ \ No newline at end of file +/* ******************* 当明细数据未加载完成时 控制流程提交 end ******************* */ + + +/* ******************* 流程明细字段包含某个字符串时给某个字段赋值为某个东西start ******************* */ +$(() => { + let config = [{ + table: 'detail_1', + mapping: [{ + sourceField: '', + targetField: '', + sourceIncludes: '', + targetSet: '' + }] + }] + + + function runJs() { + config.forEach(item => { + let tableName = item.table + let mapping = item.mapping + if (tableName === "main") { + mapping.forEach(row => { + let sourceValue = WfForm.getFieldValue(WfForm.convertFieldNameToId(row.sourceField, tableName)); + if (sourceValue.indexOf(row.sourceIncludes) !== -1) { + WfForm.changeFieldValue(WfForm.convertFieldNameToId(row.targetField, tableName, { + value: row.targetSet + })) + } + }) + } else { + let rowIndexArr = WfForm.getDetailAllRowIndexStr(tableName).split(","); + rowIndexArr.forEach(rowIndex => { + mapping.forEach(row => { + let sourceValue = WfForm.getFieldValue(WfForm.convertFieldNameToId(row.sourceField, tableName)); + if (sourceValue.indexOf(row.sourceIncludes) !== -1) { + WfForm.changeFieldValue(WfForm.convertFieldNameToId(row.targetField, tableName) + "_" + rowIndex, { + value: row.targetSet + }) + } + }) + }) + } + + }) + } + + + WfForm.registerCheckEvent(WfForm.OPER_SUBMIT, callback => { + runJs() + callback() + }) +}) +/* ******************* 流程明细字段包含某个字符串时给某个字段赋值为某个东西end ******************* */ diff --git a/pom.xml b/pom.xml index 35aac38..48c519d 100644 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,18 @@ junit 4.12 + + + + + + + + com.hierynomus + smbj + 0.10.0 + @@ -80,12 +91,11 @@ - - org.apache.rocketmq - rocketmq-client - 4.4.0 - - + + org.apache.rocketmq + rocketmq-client + 4.4.0 + diff --git a/src/main/java/aiyh/utils/ThreadPoolConfig.java b/src/main/java/aiyh/utils/ThreadPoolConfig.java index 1975126..acafd24 100644 --- a/src/main/java/aiyh/utils/ThreadPoolConfig.java +++ b/src/main/java/aiyh/utils/ThreadPoolConfig.java @@ -12,23 +12,23 @@ import java.util.concurrent.*; */ public class ThreadPoolConfig { - private static volatile ExecutorService threadPool; - - public static ExecutorService createThreadPoolInstance() { - if (threadPool == null) { - synchronized (ThreadPoolConfig.class) { - if (threadPool == null) { - ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-aiyh-%d").build(); - threadPool = new ThreadPoolExecutor(25, - 50, - 60L, - TimeUnit.SECONDS, - new ArrayBlockingQueue<>(100), - threadFactory, - new ThreadPoolExecutor.AbortPolicy()); - } - } - } - return threadPool; - } + private static volatile ExecutorService threadPool; + + public static ExecutorService createThreadPoolInstance() { + if (threadPool == null) { + synchronized (ThreadPoolConfig.class) { + if (threadPool == null) { + ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-aiyh-%d").build(); + threadPool = new ThreadPoolExecutor(25, + 50, + 60L, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(100), + threadFactory, + new ThreadPoolExecutor.CallerRunsPolicy()); + } + } + } + return threadPool; + } } diff --git a/src/main/java/aiyh/utils/Util.java b/src/main/java/aiyh/utils/Util.java index 4ab3b95..7bc4337 100644 --- a/src/main/java/aiyh/utils/Util.java +++ b/src/main/java/aiyh/utils/Util.java @@ -1151,6 +1151,34 @@ public class Util extends weaver.general.Util { } + public static String getProperties(String fileName, String key) { + String propertyPath = GCONST.getPropertyPath(); + if (StringUtil.isNullOrEmpty(fileName)) { + return null; + } + if (fileName.contains(".properties")) { + fileName.replace(".properties", ""); + } + String path = propertyPath + "prop2map" + File.separator + fileName + ".properties"; + Properties prop = new Properties(); + InputStream inputStream = null; + try { + inputStream = new BufferedInputStream(new FileInputStream(path)); + prop.load(inputStream); + return prop.getProperty(key); + } catch (IOException e) { + throw new RuntimeException("找不到文件:" + path); + } finally { + try { + if (inputStream != null) { + inputStream.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + } + /** * 通过文件名获取到对应的配置文件map对象 * @@ -3687,4 +3715,8 @@ public class Util extends weaver.general.Util { } return Util.getValueByKeyStr("main." + fieldInfo.getFieldName(), workflowData); } + + public static Map createFunctionMap() { + return null; + } } diff --git a/src/main/java/aiyh/utils/annotation/recordset/SqlOracleDbFieldAnn.java b/src/main/java/aiyh/utils/annotation/recordset/SqlOracleDbFieldAnn.java new file mode 100644 index 0000000..540ba18 --- /dev/null +++ b/src/main/java/aiyh/utils/annotation/recordset/SqlOracleDbFieldAnn.java @@ -0,0 +1,19 @@ +package aiyh.utils.annotation.recordset; + +import java.lang.annotation.*; + +/** + *

sql字段映射

+ * + *

create: 2023-02-07 17:31

+ * + * @author youHong.ai + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +@Documented +public @interface SqlOracleDbFieldAnn { + + String value(); +} diff --git a/src/main/java/aiyh/utils/entity/DocImageInfo.java b/src/main/java/aiyh/utils/entity/DocImageInfo.java index 9834f9f..49753e0 100644 --- a/src/main/java/aiyh/utils/entity/DocImageInfo.java +++ b/src/main/java/aiyh/utils/entity/DocImageInfo.java @@ -10,12 +10,12 @@ import lombok.Data; */ @Data public class DocImageInfo { - - private Integer docId; - private Integer imageFileId; - private String imageFileName; - private Integer id; - private Integer detailId; - private Integer fileSize; - + + private Integer docId; + private Integer imageFileId; + private String imageFileName; + private Integer id; + private Integer detailId; + private Integer fileSize; + private Integer docFileType; } diff --git a/src/main/java/aiyh/utils/entity/FieldViewInfo.java b/src/main/java/aiyh/utils/entity/FieldViewInfo.java index e337135..c76e2bb 100644 --- a/src/main/java/aiyh/utils/entity/FieldViewInfo.java +++ b/src/main/java/aiyh/utils/entity/FieldViewInfo.java @@ -1,5 +1,6 @@ package aiyh.utils.entity; +import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -17,20 +18,32 @@ import lombok.ToString; public class FieldViewInfo { /** 字段id */ + @SqlOracleDbFieldAnn("ID") + private Integer id; /** 字段名 */ + @SqlOracleDbFieldAnn("FIELD_NAME") + private String fieldName; /** 字段表名 */ + @SqlOracleDbFieldAnn("TABLE_NAME") + private String tableName; /** 表id */ + @SqlOracleDbFieldAnn("BILL_ID") + private Integer billId; /** 字段类型 */ + @SqlOracleDbFieldAnn("FIELD_TYPE") + private Integer fieldType; /** 字段类型名称 */ + @SqlOracleDbFieldAnn("FIELD_HTML_TYPE") + private String fieldHtmlType; } diff --git a/src/main/java/aiyh/utils/httpUtil/ResponeVo.java b/src/main/java/aiyh/utils/httpUtil/ResponeVo.java index 3029b96..7605284 100644 --- a/src/main/java/aiyh/utils/httpUtil/ResponeVo.java +++ b/src/main/java/aiyh/utils/httpUtil/ResponeVo.java @@ -4,6 +4,7 @@ package aiyh.utils.httpUtil; import aiyh.utils.Util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -133,7 +134,11 @@ public class ResponeVo implements HttpResponse { ObjectMapper mapper = new ObjectMapper(); this.entityMap = mapper.readValue(this.getEntityString(), Map.class); } catch (JsonProcessingException ignored) { - this.resultList = (List) JSONArray.parseArray(this.getEntityString(), Map.class); + try { + this.resultList = (List) JSONArray.parseArray(this.getEntityString(), Map.class); + } catch (JSONException e) { + Util.getLogger().error("Unable to convert the response result to array!" + Util.getErrString(e)); + } } catch (Exception e) { Util.getLogger().error("Unable to convert the response result to map or array!" + Util.getErrString(e)); } diff --git a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java index 7d750b5..05491b2 100644 --- a/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java +++ b/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java @@ -4,13 +4,15 @@ import aiyh.utils.Util; import aiyh.utils.httpUtil.*; import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread; import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack; -import aiyh.utils.zwl.common.ToolUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.spring.PropertyPreFilters; import com.google.common.base.Strings; import com.google.common.util.concurrent.ThreadFactoryBuilder; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.CredentialsProvider; @@ -41,1256 +43,1262 @@ import java.util.function.Function; * @author EBU7-dev1-ayh * @date 2021/8/31 0031 17:16 http请求工具 与HttpStaticUtils使用相同,说明请查看HttpStaticUtils */ - +@ToString public class HttpUtils { - public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY"; - public static final ThreadLocal HTTP_UTIL_PARAM_INFO_THREAD_LOCAL = new ThreadLocal<>(); - private static final Logger log = Util.getLogger("http_util"); - private final ToolUtil toolUtil = new ToolUtil(); - private final GlobalCache globalCache = new GlobalCache(); - // 线程池 - private final ThreadPoolExecutor executorService; - private final PropertyPreFilters filters = new PropertyPreFilters(); - private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); - // 默认编码 - private String DEFAULT_ENCODING = "UTF-8"; - private String sslKeyPath = ""; - - private String password = ""; - - public void setSslKeyPath(String sslKeyPath) { - this.sslKeyPath = sslKeyPath; - } - - - public void setPassword(String password) { - this.password = password; - } - - /** - * basic 认证 - */ - private CredentialsProvider credentialsProvider = null; - - { - // private final ExecutorService executorService = Executors.newFixedThreadPool(3); - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - ThreadFactory threadFactory = threadFactoryBuilder.setNameFormat("util-http-pool").build(); - executorService = new ThreadPoolExecutor(5, 200, 0L, - TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(1024), - threadFactory, - new ThreadPoolExecutor.AbortPolicy()); - String[] excludeProperties = {"locale", "contentByteArr", "response"}; - excludefilter.addExcludes(excludeProperties); - } - - public HttpUtils() { - - } - - public HttpUtils(CredentialsProvider credentialsProvider) { - this.credentialsProvider = credentialsProvider; - } - - public HttpUtils(String DEFAULT_ENCODING) { - this.DEFAULT_ENCODING = DEFAULT_ENCODING; - } - - public static String urlHandle(String url, Map params) { - if (params == null || params.size() <= 0) { - return url; - } - String serializeParams = serializeParams(params); - String getUrl; - if (!url.contains("?")) { - if (url.endsWith("/")) { - getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams; - } else { - getUrl = url + "?" + serializeParams; - } - } else { - if (url.endsWith("?")) { - getUrl = url + serializeParams; - } else { - getUrl = url + "&" + serializeParams; - } - } - return getUrl; - } - - private static String serializeParams(Map params) { - if (params != null && params.size() > 0) { - StringBuilder builder = new StringBuilder(); - for (Map.Entry entry : params.entrySet()) { - builder.append("&"); - builder.append(entry.getKey()); - builder.append("="); - builder.append(entry.getValue()); - } - return removeSeparator(builder); - } - return ""; - } - - private static String removeSeparator(StringBuilder sqlBuilder) { - String str = sqlBuilder.toString().trim(); - String removeSeparator = "&"; - if (str.endsWith(removeSeparator)) { - // 如果以分&号结尾,则去除&号 - str = str.substring(0, str.length() - 1); - } - if (str.trim().startsWith(removeSeparator)) { - // 如果以&开头,则去除& - str = str.substring(1); - } - return str; - } - - public void setCredentialsProvider(CredentialsProvider credentialsProvider) { - this.credentialsProvider = credentialsProvider; - } - - public GlobalCache getGlobalCache() { - return globalCache; - } - - public void setDEFAULT_ENCODING() { - this.DEFAULT_ENCODING = DEFAULT_ENCODING; - } - - public HttpPost getHttpPost(String url) { - HttpPost httpPost = new HttpPost(url); - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(10000) - .setConnectionRequestTimeout(10000) - .setRedirectsEnabled(true) - .build(); - httpPost.setConfig(requestConfig); - return httpPost; - } - - public HttpGet getHttpGet(String url) { - HttpGet httpGet = new HttpGet(url); - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(10000) - .setConnectionRequestTimeout(10000) - .setRedirectsEnabled(true) - .build(); - httpGet.setConfig(requestConfig); - return httpGet; - } - - - /** - * 获取httpclient对象 - * - * @param url 请求地址 - * @return 对象 - */ - private CloseableHttpClient getHttpClient(String url) { - if (Strings.isNullOrEmpty(this.sslKeyPath)) { - return HttpManager.getHttpConnection(url, this.credentialsProvider); - } else { - return HttpManager.getHttpConnection(url, this.credentialsProvider, sslKeyPath, password); - } - } - - /** - * get请求 - * - * @param url 请求地址 - * @return 请求结果 - * @throws IOException io异常 - */ - public ResponeVo apiGet(String url) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headers); - httpUtilParamInfo.setUrl(getUrl.trim()); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setParams(params); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - return baseRequest(httpConnection, httpGet); - } - - /** - * delete请求 - * - * @param url 请求地址 - * @return 请求结果 - * @throws IOException io异常 - */ - public ResponeVo apiDelete(String url) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headers); - httpUtilParamInfo.setParams(params); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - return baseRequest(httpConnection, httpDelete); - } - - /** - * get请求 - * - * @param url 请求地址 - * @param headers 请求头 - * @return 请求结果 - * @throws IOException io异常 - */ - public ResponeVo apiGet(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setParams(params); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - return baseRequest(httpConnection, httpGet); - } - - public ResponeVo apiDelete(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setParams(params); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - return baseRequest(httpConnection, httpDelete); - } - - public ResponeVo apiGet(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - String getUrl = urlHandle(url, paramsMap); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - return baseRequest(httpConnection, httpGet); - } - - public ResponeVo apiDelete(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - return baseRequest(httpConnection, httpDelete); - } - - /** - * 回调方法 - * - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void apiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - callBackRequest(httpConnection, httpGet, consumer); - } - - /** - * 回调方法 - * - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void apiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - try { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setSendDate(new Date()); - httpUtilParamInfo.setUrl(getUrl.trim()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - } catch (Exception ignore) { - - } - callBackRequest(httpConnection, httpDelete, consumer); - } - - public ResponeVo apiPost(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPost); - } - - public ResponeVo apiPut(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPut); - } - - public ResponeVo apiPost(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPost); - } - - public ResponeVo apiPost(String url, List params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, params); - return baseRequest(httpConnection, httpPost); - } - - public ResponeVo apiPostObject(String url, Object params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPostObject(url, headerMap, params); - return baseRequest(httpConnection, httpPost); - } - - public ResponeVo apiPut(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return baseRequest(httpConnection, httpPut); - } - - /** - *

上传单文件

- * - * @param url 上传地址 - * @param inputStream 文件流 - * @param fileKey 文件key - * @param fileName 文件名称 - * @param params 其他参数 - * @param headers 请求头 - * @return 响应实体 - * @throws IOException IO异常 - */ - - public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpMultipartFile multipartFile = new HttpMultipartFile(); - multipartFile.setFileName(fileName); - multipartFile.setFileKey(fileKey); - multipartFile.setStream(inputStream); - multipartFile.setFileSize(inputStream.available() / 1024L); - HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } - - - /** - *

上传多附件

- * - * @param url 上传地址 - * @param multipartFileList 附件信息 - * @param params 其他参数 - * @param headers 请求头 - * @return 响应数 - * @throws IOException Io异常 - */ - public ResponeVo apiUploadFiles(String url, List multipartFileList, Map params, - Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } - - - /** - *

上传多附件

- * - * @param url 上传地址 - * @param multipartFileList 附件信息 - * @param params 其他参数 - * @param headers 请求头 - * @return 响应数 - * @throws IOException Io异常 - */ - public ResponeVo apiPutUploadFiles(String url, List multipartFileList, Map params, - Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap); - return baseRequest(httpConnection, httpPut); - } - - /** - *

异步上传文集爱你

- * - * @param url 上传地址 - * @param inputStream 文件流 - * @param fileKey 文件key - * @param fileName 文件名称 - * @param params 其他参数 - * @param headers 请求头 - * @return 异步响应信息 - * @throws IOException IO异常 - */ - public Future apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpMultipartFile multipartFile = new HttpMultipartFile(); - multipartFile.setFileName(fileName); - multipartFile.setFileKey(fileKey); - multipartFile.setStream(inputStream); - multipartFile.setFileSize(inputStream.available() / 1024L); - HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } - - /** - *

上传文件

- * - * @param url 上传路径 - * @param file 文件对象 - * @param fileKey 文件key - * @param fileName 文件名称 - * @param params 其他参数 - * @param headers 请求头 - * @return 响应参数 - * @throws IOException IO异常 - */ - public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } - - /** - *

通过ImageFileId上传文件

- * - * @param url 请求地址 - * @param id 附件ID - * @param fileKey 文件key - * @param fileName 文件名称 - * @param params 文件参数 - * @param headers 请求头信息 - * @return 响应信息 - * @throws IOException IO异常 - */ - - public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName, - Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - InputStream inputStream = ImageFileManager.getInputStreamById(id); - HttpMultipartFile multipartFile = new HttpMultipartFile(); - multipartFile.setFileName(fileName); - multipartFile.setFileKey(fileKey); - multipartFile.setStream(inputStream); - multipartFile.setFileSize(inputStream.available() / 1024L); - HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); - return baseRequest(httpConnection, httpPost); - } - - /** - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void apiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - callBackRequest(httpConnection, httpPost, consumer); - } - - public ResponeVo apiPost(String url, Map params, Map headers, Function consumer) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return callBackRequest(httpConnection, httpPost, consumer); - } - - public ResponeVo apiPost(String url, Map params, Map headers, BiFunction, CloseableHttpResponse, ResponeVo> consumer) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return callBackRequest(paramsMap, httpConnection, httpPost, consumer); - } - - /** - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void apiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - callBackRequest(httpConnection, httpPut, consumer); - } - - private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer) throws IOException { - CloseableHttpResponse response = null; - try { - response = httpClient.execute(request); - consumer.accept(response); - } catch (Exception e) { - toolUtil.writeErrorLog(" http调用失败:" + e); - throw e; - } finally { - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); - ExtendedIOUtils.closeQuietly(httpClient); - ExtendedIOUtils.closeQuietly(response); - } - } - - private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function consumer) throws IOException { - CloseableHttpResponse response = null; - ResponeVo apply = null; - try { - response = httpClient.execute(request); - apply = consumer.apply(response); - } catch (Exception e) { - toolUtil.writeErrorLog(" http调用失败:" + e); - throw e; - } finally { - HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get(); - if (httpUtilParamInfo == null) { - httpUtilParamInfo = new HttpUtilParamInfo(); - } - httpUtilParamInfo.setResponse(apply); - if (apply.getResponseMap() == null) { - httpUtilParamInfo.setResponseString(apply.getEntityString()); - } else { - httpUtilParamInfo.setResponseMap(apply.getResponseMap()); - } - httpUtilParamInfo.setResponseDate(new Date()); - try { - log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), - JSONObject.toJSONString(httpUtilParamInfo, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat))); - } catch (Exception ignore) { - - } - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); - ExtendedIOUtils.closeQuietly(httpClient); - ExtendedIOUtils.closeQuietly(response); - } - return apply; - } - - private ResponeVo callBackRequest(Map requestParam, CloseableHttpClient httpClient, HttpUriRequest request, BiFunction, CloseableHttpResponse, ResponeVo> consumer) throws IOException { - CloseableHttpResponse response = null; - ResponeVo apply = null; - try { - response = httpClient.execute(request); - apply = consumer.apply(requestParam, response); - } catch (Exception e) { - toolUtil.writeErrorLog(" http调用失败:" + e); - throw e; - } finally { - HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get(); - if (httpUtilParamInfo == null) { - httpUtilParamInfo = new HttpUtilParamInfo(); - } - httpUtilParamInfo.setResponse(apply); - if (apply.getResponseMap() == null) { - httpUtilParamInfo.setResponseString(apply.getEntityString()); - } else { - httpUtilParamInfo.setResponseMap(apply.getResponseMap()); - } - httpUtilParamInfo.setResponseDate(new Date()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); - try { - log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), - JSONObject.toJSONString(httpUtilParamInfo, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat))); - } catch (Exception ignore) { - - } - ExtendedIOUtils.closeQuietly(httpClient); - ExtendedIOUtils.closeQuietly(response); - } - return apply; - } - - public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException { - ResponeVo responeVo = new ResponeVo(); - CloseableHttpResponse response = null; - HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get(); - if (httpUtilParamInfo == null) { - httpUtilParamInfo = new HttpUtilParamInfo(); - } - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); - try { - response = httpClient.execute(request); - HttpEntity entity = response.getEntity(); - Locale locale = response.getLocale(); - responeVo.setLocale(locale); - responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING)); - responeVo.setCode(response.getStatusLine().getStatusCode()); - responeVo.setResponse(response); - httpUtilParamInfo.setResponse(responeVo); - if (responeVo.getResponseMap() == null) { - httpUtilParamInfo.setResponseString(responeVo.getEntityString()); - } else { - httpUtilParamInfo.setResponseMap(responeVo.getResponseMap()); - } - httpUtilParamInfo.setResponseDate(new Date()); - try { - log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), - JSONObject.toJSONString(httpUtilParamInfo, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat))); - } catch (Exception ignore) { - - } - } catch (Exception e) { - toolUtil.writeErrorLog(" http调用失败:" + Util.getErrString(e)); - try { - httpUtilParamInfo.setResponseDate(new Date()); - log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), - JSONObject.toJSONString(httpUtilParamInfo, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat))); - } catch (Exception ignore) { - - } - throw e; - } finally { - ExtendedIOUtils.closeQuietly(httpClient); - ExtendedIOUtils.closeQuietly(response); - } - return responeVo; - } - - /** - * get请求 - * - * @param url 请求地址 - * @return 请求结果 - * @throws IOException io异常 - */ - public Future asyncApiGet(String url) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); - } - - /** - * delete请求 - * - * @param url 请求地址 - * @return 异步请求结果 - * @throws IOException io异常 - */ - public Future asyncApiDelete(String url) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headers = headersHandle(null); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headers.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); - } - - /** - * get请求 - * - * @param url 请求地址 - * @param headers 请求头 - * @return 异步请求结果 - * @throws IOException io异常 - */ - public Future asyncApiGet(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); - } - - public Future asyncApiDelete(String url, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map params = paramsHandle(null); - String getUrl = urlHandle(url, params); - Map headerMap = headersHandle(headers); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); - } - - public Future asyncApiGet(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); - } - - public Future asyncApiDelete(String url, Map params, Map headers) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); - } - - /** - * 回调方法 - * - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调函数 - * @throws IOException io异常 - */ - public void asyncApiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpGet httpGet = new HttpGet(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpGet.setHeader(entry.getKey(), entry.getValue()); - } - HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setSendDate(new Date()); - command.setHttpUtilParamInfo(httpUtilParamInfo); - executorService.execute(command); - } - - /** - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void asyncApiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { - Map paramsMap = paramsHandle(params); - String getUrl = urlHandle(url, paramsMap); - Map headerMap = headersHandle(headers); - CloseableHttpClient httpConnection = getHttpClient(url); - HttpDelete httpDelete = new HttpDelete(getUrl.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpDelete.setHeader(entry.getKey(), entry.getValue()); - } - HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setSendDate(new Date()); - command.setHttpUtilParamInfo(httpUtilParamInfo); - executorService.execute(command); - } - - public Future asyncApiPost(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } - - public Future asyncApiPut(String url, Map params) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(null); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); - } - - public Future asyncApiPost(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); - } - - public Future asyncApiPut(String url, Map params, Map headers) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); - } - - /** - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void asyncApiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); - HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setSendDate(new Date()); - command.setHttpUtilParamInfo(httpUtilParamInfo); - executorService.execute(command); - } - - /** - * @param url 请求地址 - * @param params 请求参数 - * @param headers 请求头信息 - * @param consumer 回调方法 - * @throws IOException io异常 - */ - public void asyncApiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { - CloseableHttpClient httpConnection = getHttpClient(url); - Map paramsMap = paramsHandle(params); - Map headerMap = headersHandle(headers); - HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); - HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setSendDate(new Date()); - command.setHttpUtilParamInfo(httpUtilParamInfo); - executorService.execute(command); - } - - private HttpPost handleHttpPostObject(String url, Map headerMap, Object paramsMap) throws UnsupportedEncodingException { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setSendDate(new Date()); - String contentType = ""; - HttpPost httpPost = new HttpPost(url.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpPost.setHeader(entry.getKey(), entry.getValue()); - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - contentType = entry.getValue(); - } - } - httpUtilParamInfo.setContentType(contentType); - if (!Strings.isNullOrEmpty(contentType) && contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) { - StringEntity stringEntity; - stringEntity = new StringEntity(JSON.toJSONString(paramsMap), DEFAULT_ENCODING); - httpPost.setEntity(stringEntity); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - return httpPost; - } - Map params = (Map) paramsMap; - if (Strings.isNullOrEmpty(contentType)) { - List nvps = new ArrayList<>(); - for (Map.Entry entry : params.entrySet()) { - // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - - // 修复请求form表单提交时,参数值被双引号括了起来 - nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); - } - httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); - httpPost.setEntity(new UrlEncodedFormEntity(nvps)); - } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { - List nvps = new ArrayList<>(); - for (Map.Entry entry : params.entrySet()) { - // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - - // 修复请求form表单提交时,参数值被双引号括了起来 - nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); - } - httpPost.setEntity(new UrlEncodedFormEntity(nvps)); - // } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { - } else { - StringEntity stringEntity; - if (params.containsKey(JSON_PARAM_KEY)) { - stringEntity = new StringEntity(JSON.toJSONString(params.get(JSON_PARAM_KEY))); - } else { - stringEntity = new StringEntity(JSON.toJSONString(params), DEFAULT_ENCODING); - } - httpPost.setEntity(stringEntity); - } - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - return httpPost; - } - - private HttpPost handleHttpPost(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { - return handleHttpPostObject(url, headerMap, paramsMap); - } - - private HttpPost handleHttpPost(String url, Map headerMap, List params) throws UnsupportedEncodingException { - return handleHttpPostObject(url, headerMap, params); - } - - /** - *

上传文件

- * - * @param url 上传地址 - * @param multipartFileList 文件信息 - * @param params 其他参数 - * @param headers 请求头信息 - * @return 返回httpPost - */ - private HttpPost uploadFileByInputStream(String url, List multipartFileList, - Map params, Map headers) { - // log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, - // excludefilter, - // SerializerFeature.PrettyFormat, - // SerializerFeature.WriteDateUseDateFormat), - // JSONObject.toJSONString(headers, - // excludefilter, - // SerializerFeature.PrettyFormat, - // SerializerFeature.WriteDateUseDateFormat))); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(params); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headers); - httpUtilParamInfo.setSendDate(new Date()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setCharset(StandardCharsets.UTF_8); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - Long totalSize = 0L; - for (HttpMultipartFile multipartFile : multipartFileList) { - log.info(Util.logStr("add file: fileName => [{}], fileKey => [{}], fileSize => [{}]kb", - multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize())); - totalSize += multipartFile.getFileSize(); - builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName()); - } - log.info("total file size: [" + totalSize + "]kb"); - ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8); - for (Map.Entry param : params.entrySet()) { - StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); - builder.addPart(param.getKey(), stringBody); - } - HttpPost httpPost = new HttpPost(url.trim()); - - for (Map.Entry entry : headers.entrySet()) { - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - continue; - } - httpPost.setHeader(entry.getKey(), entry.getValue()); - } - HttpEntity entity = builder.build(); - httpPost.setEntity(entity); - return httpPost; - } - - - /** - *

上传文件

- * - * @param url 上传地址 - * @param multipartFileList 文件信息 - * @param params 其他参数 - * @param headers 请求头信息 - * @return 返回httpPost - */ - private HttpPut uploadFileByInputStreamPut(String url, List multipartFileList, - Map params, Map headers) { - log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat), - JSONObject.toJSONString(headers, - excludefilter, - SerializerFeature.PrettyFormat, - SerializerFeature.WriteDateUseDateFormat))); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(params); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headers); - httpUtilParamInfo.setSendDate(new Date()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setCharset(StandardCharsets.UTF_8); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - Long totalSize = 0L; - for (HttpMultipartFile multipartFile : multipartFileList) { - log.info(Util.logStr("add file: fileName => [{}], fileKey => [{}], fileSize => [{}]kb", - multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize())); - totalSize += multipartFile.getFileSize(); - builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName()); - } - log.info("total file size: [" + totalSize + "]kb"); - ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8); - for (Map.Entry param : params.entrySet()) { - StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); - builder.addPart(param.getKey(), stringBody); - } - HttpPut httpPut = new HttpPut(url.trim()); - - for (Map.Entry entry : headers.entrySet()) { - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - continue; - } - httpPut.setHeader(entry.getKey(), entry.getValue()); - } - HttpEntity entity = builder.build(); - httpPut.setEntity(entity); - return httpPut; - } - - private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, - Map params, Map headers) { - log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + - "", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(params); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headers); - httpUtilParamInfo.setSendDate(new Date()); - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName); - for (Map.Entry param : params.entrySet()) { - StringBody stringBody = new StringBody(String.valueOf(param.getValue()), ContentType.MULTIPART_FORM_DATA); - builder.addPart(param.getKey(), stringBody); - } - HttpPost httpPost = new HttpPost(url.trim()); - - for (Map.Entry entry : headers.entrySet()) { - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - continue; - } - httpPost.setHeader(entry.getKey(), entry.getValue()); - } - HttpEntity entity = builder.build(); - httpPost.setEntity(entity); - return httpPost; - } - - private HttpPut handleHttpPut(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { - HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); - httpUtilParamInfo.setParams(paramsMap); - httpUtilParamInfo.setUrl(url); - httpUtilParamInfo.setHeard(headerMap); - httpUtilParamInfo.setSendDate(new Date()); - String contentType = ""; - HttpPut httpPut = new HttpPut(url.trim()); - for (Map.Entry entry : headerMap.entrySet()) { - httpPut.setHeader(entry.getKey(), entry.getValue()); - if ("Content-Type".equalsIgnoreCase(entry.getKey())) { - contentType = entry.getValue(); - } - } - if (Strings.isNullOrEmpty(contentType)) { - List nvps = new ArrayList<>(); - for (Map.Entry entry : paramsMap.entrySet()) { - // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - // 修复请求form表单提交时,参数值被双引号括了起来 - nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); - } - httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); - httpPut.setEntity(new UrlEncodedFormEntity(nvps)); - } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { - List nvps = new ArrayList<>(); - for (Map.Entry entry : paramsMap.entrySet()) { - // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); - // 修复请求form表单提交时,参数值被双引号括了起来 - nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); - } - httpPut.setEntity(new UrlEncodedFormEntity(nvps)); - } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { - StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap), DEFAULT_ENCODING); - httpPut.setEntity(stringEntity); - } - HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); - return httpPut; - } - - private String inputStreamToString(InputStream is) { - String line = ""; - StringBuilder total = new StringBuilder(); - BufferedReader rd = new BufferedReader(new InputStreamReader(is)); - try { - while ((line = rd.readLine()) != null) { - total.append(line); - } - } catch (IOException e) { - toolUtil.writeErrorLog(e.getLocalizedMessage() + "\n" + e); - } - return total.toString(); - } - - public Map headersHandle(Map headers) { - Map map = new HashMap<>(); - if (headers != null && headers.size() > 0) { - if (globalCache.header != null && globalCache.header.size() > 0) { - map.putAll(globalCache.header); - } - map.putAll(headers); - } else { - map.putAll(globalCache.header); - } - return map; - } - - public Map paramsHandle(Map params) { - Map map = new HashMap<>(); - if (params != null && params.size() > 0) { - if (globalCache.paramMap != null && globalCache.paramMap.size() > 0) { - map.putAll(globalCache.paramMap); - } - map.putAll(params); - } else { - map.putAll(globalCache.paramMap); - } - return map; - } + public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY"; + public static final ThreadLocal HTTP_UTIL_PARAM_INFO_THREAD_LOCAL = new ThreadLocal<>(); + private static final Logger log = Util.getLogger("http_util"); + @Getter + private final GlobalCache globalCache = new GlobalCache(); + // 线程池 + private final ThreadPoolExecutor executorService; + private final PropertyPreFilters filters = new PropertyPreFilters(); + private final PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter(); + // 默认编码 + @Setter + private String DEFAULT_ENCODING = "UTF-8"; + @Setter + private String sslKeyPath = ""; + @Setter + private String password = ""; + + + /** + * basic 认证 + */ + private CredentialsProvider credentialsProvider = null; + + { + // private final ExecutorService executorService = Executors.newFixedThreadPool(3); + ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); + ThreadFactory threadFactory = threadFactoryBuilder.setNameFormat("util-http-pool").build(); + executorService = new ThreadPoolExecutor(5, 200, 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(1024), + threadFactory, + new ThreadPoolExecutor.AbortPolicy()); + String[] excludeProperties = {"locale", "contentByteArr", "response"}; + excludefilter.addExcludes(excludeProperties); + } + + public HttpUtils() { + + } + + public HttpUtils(CredentialsProvider credentialsProvider) { + this.credentialsProvider = credentialsProvider; + } + + public HttpUtils(String DEFAULT_ENCODING) { + this.DEFAULT_ENCODING = DEFAULT_ENCODING; + } + + public static String urlHandle(String url, Map params) { + if (params == null || params.size() <= 0) { + return url; + } + String serializeParams = serializeParams(params); + String getUrl; + if (!url.contains("?")) { + if (url.endsWith("/")) { + getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams; + } else { + getUrl = url + "?" + serializeParams; + } + } else { + if (url.endsWith("?")) { + getUrl = url + serializeParams; + } else { + getUrl = url + "&" + serializeParams; + } + } + return getUrl; + } + + private static String serializeParams(Map params) { + if (params != null && params.size() > 0) { + StringBuilder builder = new StringBuilder(); + for (Map.Entry entry : params.entrySet()) { + builder.append("&"); + builder.append(entry.getKey()); + builder.append("="); + builder.append(entry.getValue()); + } + return removeSeparator(builder); + } + return ""; + } + + private static String removeSeparator(StringBuilder sqlBuilder) { + String str = sqlBuilder.toString().trim(); + String removeSeparator = "&"; + if (str.endsWith(removeSeparator)) { + // 如果以分&号结尾,则去除&号 + str = str.substring(0, str.length() - 1); + } + if (str.trim().startsWith(removeSeparator)) { + // 如果以&开头,则去除& + str = str.substring(1); + } + return str; + } + + + public HttpPost getHttpPost(String url) { + HttpPost httpPost = new HttpPost(url); + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .setRedirectsEnabled(true) + .build(); + httpPost.setConfig(requestConfig); + return httpPost; + } + + public HttpGet getHttpGet(String url) { + HttpGet httpGet = new HttpGet(url); + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .setRedirectsEnabled(true) + .build(); + httpGet.setConfig(requestConfig); + return httpGet; + } + + + /** + * 获取httpclient对象 + * + * @param url 请求地址 + * @return 对象 + */ + private CloseableHttpClient getHttpClient(String url) { + if (Strings.isNullOrEmpty(this.sslKeyPath)) { + return HttpManager.getHttpConnection(url, this.credentialsProvider); + } else { + return HttpManager.getHttpConnection(url, this.credentialsProvider, sslKeyPath, password); + } + } + + /** + * get请求 + * + * @param url 请求地址 + * @return 请求结果 + * @throws IOException io异常 + */ + public ResponeVo apiGet(String url) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headers.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setUrl(getUrl.trim()); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setParams(params); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + return baseRequest(httpConnection, httpGet); + } + + /** + * delete请求 + * + * @param url 请求地址 + * @return 请求结果 + * @throws IOException io异常 + */ + public ResponeVo apiDelete(String url) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headers.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + return baseRequest(httpConnection, httpDelete); + } + + /** + * get请求 + * + * @param url 请求地址 + * @param headers 请求头 + * @return 请求结果 + * @throws IOException io异常 + */ + public ResponeVo apiGet(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + return baseRequest(httpConnection, httpGet); + } + + public ResponeVo apiDelete(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + return baseRequest(httpConnection, httpDelete); + } + + public ResponeVo apiGet(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + String getUrl = urlHandle(url, paramsMap); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + return baseRequest(httpConnection, httpGet); + } + + public ResponeVo apiDelete(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + return baseRequest(httpConnection, httpDelete); + } + + /** + * 回调方法 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void apiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + callBackRequest(httpConnection, httpGet, consumer); + } + + /** + * 回调方法 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void apiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + try { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setSendDate(new Date()); + httpUtilParamInfo.setUrl(getUrl.trim()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + } catch (Exception ignore) { + + } + callBackRequest(httpConnection, httpDelete, consumer); + } + + public ResponeVo apiPost(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return baseRequest(httpConnection, httpPost); + } + + public ResponeVo apiPut(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + return baseRequest(httpConnection, httpPut); + } + + public ResponeVo apiPost(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return baseRequest(httpConnection, httpPost); + } + + public ResponeVo apiPost(String url, List params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, params); + return baseRequest(httpConnection, httpPost); + } + + public ResponeVo apiPostObject(String url, Object params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPostObject(url, headerMap, params); + return baseRequest(httpConnection, httpPost); + } + + public ResponeVo apiPut(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + return baseRequest(httpConnection, httpPut); + } + + /** + *

上传单文件

+ * + * @param url 上传地址 + * @param inputStream 文件流 + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应实体 + * @throws IOException IO异常 + */ + + public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpMultipartFile multipartFile = new HttpMultipartFile(); + multipartFile.setFileName(fileName); + multipartFile.setFileKey(fileKey); + multipartFile.setStream(inputStream); + multipartFile.setFileSize(inputStream.available() / 1024L); + HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); + return baseRequest(httpConnection, httpPost); + } + + + /** + *

上传多附件

+ * + * @param url 上传地址 + * @param multipartFileList 附件信息 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应数 + * @throws IOException Io异常 + */ + public ResponeVo apiUploadFiles(String url, List multipartFileList, Map params, + Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap); + return baseRequest(httpConnection, httpPost); + } + + + /** + *

上传多附件

+ * + * @param url 上传地址 + * @param multipartFileList 附件信息 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应数 + * @throws IOException Io异常 + */ + public ResponeVo apiPutUploadFiles(String url, List multipartFileList, Map params, + Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap); + return baseRequest(httpConnection, httpPut); + } + + /** + *

异步上传文集爱你

+ * + * @param url 上传地址 + * @param inputStream 文件流 + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 其他参数 + * @param headers 请求头 + * @return 异步响应信息 + * @throws IOException IO异常 + */ + public Future apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpMultipartFile multipartFile = new HttpMultipartFile(); + multipartFile.setFileName(fileName); + multipartFile.setFileKey(fileKey); + multipartFile.setStream(inputStream); + multipartFile.setFileSize(inputStream.available() / 1024L); + HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } + + /** + *

上传文件

+ * + * @param url 上传路径 + * @param file 文件对象 + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 其他参数 + * @param headers 请求头 + * @return 响应参数 + * @throws IOException IO异常 + */ + public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap); + return baseRequest(httpConnection, httpPost); + } + + /** + *

通过ImageFileId上传文件

+ * + * @param url 请求地址 + * @param id 附件ID + * @param fileKey 文件key + * @param fileName 文件名称 + * @param params 文件参数 + * @param headers 请求头信息 + * @return 响应信息 + * @throws IOException IO异常 + */ + + public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName, + Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + InputStream inputStream = ImageFileManager.getInputStreamById(id); + HttpMultipartFile multipartFile = new HttpMultipartFile(); + multipartFile.setFileName(fileName); + multipartFile.setFileKey(fileKey); + multipartFile.setStream(inputStream); + multipartFile.setFileSize(inputStream.available() / 1024L); + HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap); + return baseRequest(httpConnection, httpPost); + } + + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void apiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + callBackRequest(httpConnection, httpPost, consumer); + } + + public ResponeVo apiPost(String url, Map params, Map headers, Function consumer) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return callBackRequest(httpConnection, httpPost, consumer); + } + + public ResponeVo apiPost(String url, Map params, Map headers, BiFunction, CloseableHttpResponse, ResponeVo> consumer) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return callBackRequest(paramsMap, httpConnection, httpPost, consumer); + } + + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void apiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + callBackRequest(httpConnection, httpPut, consumer); + } + + private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer consumer) throws IOException { + CloseableHttpResponse response = null; + try { + response = httpClient.execute(request); + } catch (Exception e) { + log.error(" http调用失败:" + Util.getErrString(e)); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + ExtendedIOUtils.closeQuietly(httpClient); + throw e; + } + try { + consumer.accept(response); + } catch (Exception e) { + throw e; + } finally { + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + ExtendedIOUtils.closeQuietly(httpClient); + ExtendedIOUtils.closeQuietly(response); + } + } + + private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function consumer) throws IOException { + CloseableHttpResponse response = null; + ResponeVo apply = null; + try { + response = httpClient.execute(request); + } catch (Exception e) { + log.error(" http调用失败:" + Util.getErrString(e)); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + ExtendedIOUtils.closeQuietly(httpClient); + throw e; + } + try { + apply = consumer.apply(response); + } catch (Exception e) { + throw e; + } finally { + HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get(); + if (httpUtilParamInfo == null) { + httpUtilParamInfo = new HttpUtilParamInfo(); + } + httpUtilParamInfo.setResponse(apply); + if (apply != null) { + if (apply.getResponseMap() == null) { + httpUtilParamInfo.setResponseString(apply.getEntityString()); + } else { + httpUtilParamInfo.setResponseMap(apply.getResponseMap()); + } + } + httpUtilParamInfo.setResponseDate(new Date()); + try { + log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), + JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + } catch (Exception ignore) { + + } + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + ExtendedIOUtils.closeQuietly(httpClient); + ExtendedIOUtils.closeQuietly(response); + } + return apply; + } + + private ResponeVo callBackRequest(Map requestParam, CloseableHttpClient httpClient, HttpUriRequest request, BiFunction, CloseableHttpResponse, ResponeVo> consumer) throws IOException { + CloseableHttpResponse response = null; + ResponeVo apply = null; + try { + response = httpClient.execute(request); + + } catch (Exception e) { + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + log.error(" http调用失败:" + Util.getErrString(e)); + ExtendedIOUtils.closeQuietly(httpClient); + throw e; + } + try { + apply = consumer.apply(requestParam, response); + } catch (Exception e) { + throw e; + } finally { + HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get(); + if (httpUtilParamInfo == null) { + httpUtilParamInfo = new HttpUtilParamInfo(); + } + httpUtilParamInfo.setResponse(apply); + if (apply != null) { + if (apply.getResponseMap() == null) { + httpUtilParamInfo.setResponseString(apply.getEntityString()); + } else { + httpUtilParamInfo.setResponseMap(apply.getResponseMap()); + } + } + httpUtilParamInfo.setResponseDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + try { + log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), + JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + } catch (Exception ignore) { + + } + ExtendedIOUtils.closeQuietly(httpClient); + ExtendedIOUtils.closeQuietly(response); + } + return apply; + } + + public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException { + ResponeVo responeVo = new ResponeVo(); + CloseableHttpResponse response = null; + HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get(); + if (httpUtilParamInfo == null) { + httpUtilParamInfo = new HttpUtilParamInfo(); + } + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove(); + try { + response = httpClient.execute(request); + HttpEntity entity = response.getEntity(); + Locale locale = response.getLocale(); + responeVo.setLocale(locale); + responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING)); + responeVo.setCode(response.getStatusLine().getStatusCode()); + responeVo.setResponse(response); + httpUtilParamInfo.setResponse(responeVo); + if (responeVo.getResponseMap() == null) { + httpUtilParamInfo.setResponseString(responeVo.getEntityString()); + } else { + httpUtilParamInfo.setResponseMap(responeVo.getResponseMap()); + } + httpUtilParamInfo.setResponseDate(new Date()); + try { + log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), + JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + } catch (Exception ignore) { + + } + } catch (Exception e) { + log.error(" http调用失败:" + Util.getErrString(e)); + try { + httpUtilParamInfo.setResponseDate(new Date()); + log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(), + JSONObject.toJSONString(httpUtilParamInfo, + excludefilter, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + } catch (Exception ignore) { + + } + throw e; + } finally { + ExtendedIOUtils.closeQuietly(httpClient); + ExtendedIOUtils.closeQuietly(response); + } + return responeVo; + } + + /** + * get请求 + * + * @param url 请求地址 + * @return 请求结果 + * @throws IOException io异常 + */ + public Future asyncApiGet(String url) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headers.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); + } + + /** + * delete请求 + * + * @param url 请求地址 + * @return 异步请求结果 + * @throws IOException io异常 + */ + public Future asyncApiDelete(String url) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headers = headersHandle(null); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headers.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); + } + + /** + * get请求 + * + * @param url 请求地址 + * @param headers 请求头 + * @return 异步请求结果 + * @throws IOException io异常 + */ + public Future asyncApiGet(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); + } + + public Future asyncApiDelete(String url, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map params = paramsHandle(null); + String getUrl = urlHandle(url, params); + Map headerMap = headersHandle(headers); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); + } + + public Future asyncApiGet(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING)); + } + + public Future asyncApiDelete(String url, Map params, Map headers) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING)); + } + + /** + * 回调方法 + * + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调函数 + * @throws IOException io异常 + */ + public void asyncApiGet(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpGet httpGet = new HttpGet(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); + } + + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void asyncApiDelete(String url, Map params, Map headers, Consumer consumer) throws IOException { + Map paramsMap = paramsHandle(params); + String getUrl = urlHandle(url, paramsMap); + Map headerMap = headersHandle(headers); + CloseableHttpClient httpConnection = getHttpClient(url); + HttpDelete httpDelete = new HttpDelete(getUrl.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpDelete.setHeader(entry.getKey(), entry.getValue()); + } + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); + } + + public Future asyncApiPost(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } + + public Future asyncApiPut(String url, Map params) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(null); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); + } + + public Future asyncApiPost(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING)); + } + + public Future asyncApiPut(String url, Map params, Map headers) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING)); + } + + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void asyncApiPost(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap); + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); + } + + /** + * @param url 请求地址 + * @param params 请求参数 + * @param headers 请求头信息 + * @param consumer 回调方法 + * @throws IOException io异常 + */ + public void asyncApiPut(String url, Map params, Map headers, Consumer consumer) throws IOException { + CloseableHttpClient httpConnection = getHttpClient(url); + Map paramsMap = paramsHandle(params); + Map headerMap = headersHandle(headers); + HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap); + HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + command.setHttpUtilParamInfo(httpUtilParamInfo); + executorService.execute(command); + } + + private HttpPost handleHttpPostObject(String url, Map headerMap, Object paramsMap) throws UnsupportedEncodingException { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + String contentType = ""; + HttpPost httpPost = new HttpPost(url.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpPost.setHeader(entry.getKey(), entry.getValue()); + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + contentType = entry.getValue(); + } + } + httpUtilParamInfo.setContentType(contentType); + if (!Strings.isNullOrEmpty(contentType) && contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) { + StringEntity stringEntity; + stringEntity = new StringEntity(JSON.toJSONString(paramsMap), DEFAULT_ENCODING); + httpPost.setEntity(stringEntity); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + return httpPost; + } + Map params = (Map) paramsMap; + if (Strings.isNullOrEmpty(contentType)) { + List nvps = new ArrayList<>(); + for (Map.Entry entry : params.entrySet()) { + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + + // 修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); + } + httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); + httpPost.setEntity(new UrlEncodedFormEntity(nvps)); + } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { + List nvps = new ArrayList<>(); + for (Map.Entry entry : params.entrySet()) { + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + + // 修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); + } + httpPost.setEntity(new UrlEncodedFormEntity(nvps)); + // } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { + } else { + StringEntity stringEntity; + if (params.containsKey(JSON_PARAM_KEY)) { + stringEntity = new StringEntity(JSON.toJSONString(params.get(JSON_PARAM_KEY))); + } else { + stringEntity = new StringEntity(JSON.toJSONString(params), DEFAULT_ENCODING); + } + httpPost.setEntity(stringEntity); + } + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + return httpPost; + } + + private HttpPost handleHttpPost(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { + return handleHttpPostObject(url, headerMap, paramsMap); + } + + private HttpPost handleHttpPost(String url, Map headerMap, List params) throws UnsupportedEncodingException { + return handleHttpPostObject(url, headerMap, params); + } + + /** + *

上传文件

+ * + * @param url 上传地址 + * @param multipartFileList 文件信息 + * @param params 其他参数 + * @param headers 请求头信息 + * @return 返回httpPost + */ + private HttpPost uploadFileByInputStream(String url, List multipartFileList, + Map params, Map headers) { + // log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + // excludefilter, + // SerializerFeature.PrettyFormat, + // SerializerFeature.WriteDateUseDateFormat), + // JSONObject.toJSONString(headers, + // excludefilter, + // SerializerFeature.PrettyFormat, + // SerializerFeature.WriteDateUseDateFormat))); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setSendDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setCharset(StandardCharsets.UTF_8); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + Long totalSize = 0L; + for (HttpMultipartFile multipartFile : multipartFileList) { + log.info(Util.logStr("add file: fileName => [{}], fileKey => [{}], fileSize => [{}]kb", + multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize())); + totalSize += multipartFile.getFileSize(); + builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName()); + } + log.info("total file size: [" + totalSize + "]kb"); + ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8); + for (Map.Entry param : params.entrySet()) { + StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); + builder.addPart(param.getKey(), stringBody); + } + HttpPost httpPost = new HttpPost(url.trim()); + + for (Map.Entry entry : headers.entrySet()) { + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + continue; + } + httpPost.setHeader(entry.getKey(), entry.getValue()); + } + HttpEntity entity = builder.build(); + httpPost.setEntity(entity); + return httpPost; + } + + + /** + *

上传文件

+ * + * @param url 上传地址 + * @param multipartFileList 文件信息 + * @param params 其他参数 + * @param headers 请求头信息 + * @return 返回httpPost + */ + private HttpPut uploadFileByInputStreamPut(String url, List multipartFileList, + Map params, Map headers) { + log.info(Util.logStr("start request : url is [{}],other param [\n{}\n],heard [\n{}\n]", url, JSONObject.toJSONString(params, + excludefilter, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat), + JSONObject.toJSONString(headers, + excludefilter, + SerializerFeature.PrettyFormat, + SerializerFeature.WriteDateUseDateFormat))); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setSendDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setCharset(StandardCharsets.UTF_8); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + Long totalSize = 0L; + for (HttpMultipartFile multipartFile : multipartFileList) { + log.info(Util.logStr("add file: fileName => [{}], fileKey => [{}], fileSize => [{}]kb", + multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize())); + totalSize += multipartFile.getFileSize(); + builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName()); + } + log.info("total file size: [" + totalSize + "]kb"); + ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8); + for (Map.Entry param : params.entrySet()) { + StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType); + builder.addPart(param.getKey(), stringBody); + } + HttpPut httpPut = new HttpPut(url.trim()); + + for (Map.Entry entry : headers.entrySet()) { + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + continue; + } + httpPut.setHeader(entry.getKey(), entry.getValue()); + } + HttpEntity entity = builder.build(); + httpPut.setEntity(entity); + return httpPut; + } + + private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName, + Map params, Map headers) { + log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" + + "", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName)); + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(params); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headers); + httpUtilParamInfo.setSendDate(new Date()); + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName); + for (Map.Entry param : params.entrySet()) { + StringBody stringBody = new StringBody(String.valueOf(param.getValue()), ContentType.MULTIPART_FORM_DATA); + builder.addPart(param.getKey(), stringBody); + } + HttpPost httpPost = new HttpPost(url.trim()); + + for (Map.Entry entry : headers.entrySet()) { + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + continue; + } + httpPost.setHeader(entry.getKey(), entry.getValue()); + } + HttpEntity entity = builder.build(); + httpPost.setEntity(entity); + return httpPost; + } + + private HttpPut handleHttpPut(String url, Map headerMap, Map paramsMap) throws UnsupportedEncodingException { + HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo(); + httpUtilParamInfo.setParams(paramsMap); + httpUtilParamInfo.setUrl(url); + httpUtilParamInfo.setHeard(headerMap); + httpUtilParamInfo.setSendDate(new Date()); + String contentType = ""; + HttpPut httpPut = new HttpPut(url.trim()); + for (Map.Entry entry : headerMap.entrySet()) { + httpPut.setHeader(entry.getKey(), entry.getValue()); + if ("Content-Type".equalsIgnoreCase(entry.getKey())) { + contentType = entry.getValue(); + } + } + if (Strings.isNullOrEmpty(contentType)) { + List nvps = new ArrayList<>(); + for (Map.Entry entry : paramsMap.entrySet()) { + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + // 修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); + } + httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE); + httpPut.setEntity(new UrlEncodedFormEntity(nvps)); + } else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) { + List nvps = new ArrayList<>(); + for (Map.Entry entry : paramsMap.entrySet()) { + // nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue()))); + // 修复请求form表单提交时,参数值被双引号括了起来 + nvps.add(new BasicNameValuePair(entry.getKey(), Util.null2String(entry.getValue()))); + } + httpPut.setEntity(new UrlEncodedFormEntity(nvps)); + } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) { + StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap), DEFAULT_ENCODING); + httpPut.setEntity(stringEntity); + } + HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo); + return httpPut; + } + + private String inputStreamToString(InputStream is) { + String line = ""; + StringBuilder total = new StringBuilder(); + BufferedReader rd = new BufferedReader(new InputStreamReader(is)); + try { + while ((line = rd.readLine()) != null) { + total.append(line); + } + } catch (IOException e) { + log.error(e.getLocalizedMessage() + "\n" + e); + } + return total.toString(); + } + + public Map headersHandle(Map headers) { + Map map = new HashMap<>(); + if (headers != null && headers.size() > 0) { + if (globalCache.header != null && globalCache.header.size() > 0) { + map.putAll(globalCache.header); + } + map.putAll(headers); + } else { + map.putAll(globalCache.header); + } + return map; + } + + public Map paramsHandle(Map params) { + Map map = new HashMap<>(); + if (params != null && params.size() > 0) { + if (globalCache.paramMap != null && globalCache.paramMap.size() > 0) { + map.putAll(globalCache.paramMap); + } + map.putAll(params); + } else { + map.putAll(globalCache.paramMap); + } + return map; + } } diff --git a/src/main/java/aiyh/utils/mapper/UtilMapper.java b/src/main/java/aiyh/utils/mapper/UtilMapper.java index 07170c3..51648ff 100644 --- a/src/main/java/aiyh/utils/mapper/UtilMapper.java +++ b/src/main/java/aiyh/utils/mapper/UtilMapper.java @@ -61,10 +61,14 @@ public interface UtilMapper { @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid = #{docId}") DocImageInfo selectDocImageInfo(@ParamMapper("docId") String docId); - @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid in ($t{docIds})") + @Select("select id,docid doc_id," + + "imagefileid image_file_id, docfiletype doc_file_type," + + "imagefilename image_file_name from docimagefile where docid in ($t{docIds})") List selectDocImageInfos(@ParamMapper("docIds") String docIds); - @Select("select id,docid doc_id,imagefileid image_file_id,imagefilename image_file_name from docimagefile where docid in (${docIds})") + @Select("select id,docid doc_id,imagefileid image_file_id," + + "docfiletype doc_file_type," + + "imagefilename image_file_name from docimagefile where docid in (${docIds})") List selectDocImageInfos(@ParamMapper("docIds") String[] docIds); diff --git a/src/main/java/aiyh/utils/recordset/GetRsValueUtil.java b/src/main/java/aiyh/utils/recordset/GetRsValueUtil.java index c71e065..74c84bb 100644 --- a/src/main/java/aiyh/utils/recordset/GetRsValueUtil.java +++ b/src/main/java/aiyh/utils/recordset/GetRsValueUtil.java @@ -1,10 +1,12 @@ package aiyh.utils.recordset; import aiyh.utils.annotation.recordset.SqlDbFieldAnn; +import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn; import org.h2.util.StringUtils; import org.jetbrains.annotations.Nullable; import weaver.conn.RecordSet; import weaver.conn.RecordSetTrans; +import weaver.conn.constant.DBConstant; import java.lang.reflect.Field; @@ -17,28 +19,58 @@ import java.lang.reflect.Field; */ public class GetRsValueUtil { - - @Nullable - public static String getRsValue(RecordSet rs, String fieldName, Field declaredField) { - String value = rs.getString(fieldName); - if(StringUtils.isNullOrEmpty(value) && declaredField != null){ - SqlDbFieldAnn annotation = declaredField.getAnnotation(SqlDbFieldAnn.class); - if (annotation != null){ - value = rs.getString(annotation.value()); - } - } - return value; - } - - @Nullable - public static String getRsValue(RecordSetTrans rs, String fieldName, Field declaredField) { - String value = rs.getString(fieldName); - if(StringUtils.isNullOrEmpty(value) && declaredField != null){ - SqlDbFieldAnn annotation = declaredField.getAnnotation(SqlDbFieldAnn.class); - if (annotation != null){ - value = rs.getString(annotation.value()); - } - } - return value; - } + + @Nullable + public static String getRsValue(RecordSet rs, String fieldName, Field declaredField) { + String value = rs.getString(fieldName); + if (StringUtils.isNullOrEmpty(value) && declaredField != null) { + if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { + SqlOracleDbFieldAnn oracleDbFieldAnn = declaredField.getAnnotation(SqlOracleDbFieldAnn.class); + if (oracleDbFieldAnn != null) { + value = rs.getString(oracleDbFieldAnn.value()); + } + return value; + } else { + SqlDbFieldAnn annotation = declaredField.getAnnotation(SqlDbFieldAnn.class); + if (annotation != null) { + value = rs.getString(annotation.value()); + return value; + } + SqlOracleDbFieldAnn oracleDbFieldAnn = declaredField.getAnnotation(SqlOracleDbFieldAnn.class); + if (oracleDbFieldAnn != null) { + value = rs.getString(oracleDbFieldAnn.value()); + } + + } + + } + return value; + } + + @Nullable + public static String getRsValue(RecordSetTrans rs, String fieldName, Field declaredField) { + String value = rs.getString(fieldName); + if (StringUtils.isNullOrEmpty(value) && declaredField != null) { + if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { + SqlOracleDbFieldAnn oracleDbFieldAnn = declaredField.getAnnotation(SqlOracleDbFieldAnn.class); + if (oracleDbFieldAnn != null) { + value = rs.getString(oracleDbFieldAnn.value()); + } + return value; + } else { + SqlDbFieldAnn annotation = declaredField.getAnnotation(SqlDbFieldAnn.class); + if (annotation != null) { + value = rs.getString(annotation.value()); + return value; + } + SqlOracleDbFieldAnn oracleDbFieldAnn = declaredField.getAnnotation(SqlOracleDbFieldAnn.class); + if (oracleDbFieldAnn != null) { + value = rs.getString(oracleDbFieldAnn.value()); + } + + } + + } + return value; + } } diff --git a/src/main/java/aiyh/utils/recordset/ResultMapper.java b/src/main/java/aiyh/utils/recordset/ResultMapper.java index a4e89f8..6c998e4 100644 --- a/src/main/java/aiyh/utils/recordset/ResultMapper.java +++ b/src/main/java/aiyh/utils/recordset/ResultMapper.java @@ -7,6 +7,7 @@ import aiyh.utils.excention.TypeNonsupportException; import com.google.common.base.Strings; import weaver.conn.RecordSet; import weaver.conn.RecordSetTrans; +import weaver.conn.constant.DBConstant; import java.beans.BeanInfo; import java.beans.Introspector; @@ -272,7 +273,20 @@ public class ResultMapper { public Object getObjectTrans(RecordSetTrans rs, Object o, Method method) { CaseConversion annotation = method.getAnnotation(CaseConversion.class); - boolean enable = annotation == null || annotation.value(); + boolean enable = false; + if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { + if (annotation == null) { + enable = false; + } else { + enable = annotation.value(); + } + } else { + if (annotation == null) { + enable = true; + } else { + enable = annotation.value(); + } + } String[] columnName = rs.getColumnName(); String[] columnTypeName = rs.getColumnTypeName(); int[] columnTypes = rs.getColumnType(); @@ -353,7 +367,6 @@ public class ResultMapper { return o; } - // Util.getLogger().info("获取对象:" + o.toString()); BeanInfo beanInfo = Introspector.getBeanInfo(o.getClass(), Object.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { @@ -382,7 +395,20 @@ public class ResultMapper { public Object getObject(RecordSet rs, Object o, Method method) { CaseConversion annotation = method.getAnnotation(CaseConversion.class); - boolean enable = annotation == null || annotation.value(); + boolean enable = false; + if (DBConstant.DB_TYPE_ORACLE.equals(rs.getDBType())) { + if (annotation == null) { + enable = false; + } else { + enable = annotation.value(); + } + } else { + if (annotation == null) { + enable = true; + } else { + enable = annotation.value(); + } + } String[] columnName = rs.getColumnName(); String[] columnTypeName = rs.getColumnTypeName(); int[] columnTypes = rs.getColumnType(); diff --git a/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/controller/SsoYunZhaoController.java b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/controller/SsoYunZhaoController.java new file mode 100644 index 0000000..e948471 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/controller/SsoYunZhaoController.java @@ -0,0 +1,43 @@ +package com.api.youhong.ai.pcn.ssoyunzhao.controller; + +import aiyh.utils.Util; +import com.api.youhong.ai.pcn.ssoyunzhao.service.SsoYunZhaoService; +import com.sun.jersey.api.view.Viewable; +import org.apache.log4j.Logger; +import weaver.hrm.HrmUserVarify; +import weaver.hrm.User; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.Context; + +/** + *

单点登录云召系统

+ * + *

create: 2023/2/22 23:17

+ * + * @author youHong.ai + */ +@Path("/aiyh/sso/yunzhao/") +public class SsoYunZhaoController { + + private final SsoYunZhaoService service = new SsoYunZhaoService(); + + private final Logger logger = Util.getLogger(); + + @Path("/send-redirect") + @GET + public Viewable ssoSendRedirect(@Context HttpServletRequest request, @Context HttpServletResponse response) { + try { + User user = HrmUserVarify.getUser(request, response); + String redirectPath = service.getRedirectPath(user); + response.sendRedirect(redirectPath); + } catch (Exception e) { + logger.error("单点登录跳转失败!错误信息:" + Util.getErrString(e)); + } + return null; + + } +} diff --git a/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoConstant.java b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoConstant.java new file mode 100644 index 0000000..3c4f2cf --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoConstant.java @@ -0,0 +1,78 @@ +package com.api.youhong.ai.pcn.ssoyunzhao.service; + +/** + *

常量

+ * + *

create: 2023/2/22 23:24

+ * + * @author youHong.ai + */ +public class SsoYunZhaoConstant { + protected final static String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC8R8OPv/yVtzuz\n" + + "G/kKbhC9wr+z9I7Hfk9rFsTlJ/iHis94Wmy6HxYimUF+03Awqpap4CimwPUoKIiz\n" + + "UOkPVrlj0sOrDIWEbcJGBysveYeocACV1lLfAS4WpnH2xRrz5N7BpNey67aCeUsD\n" + + "UKtgv/1zxV8G0VM0xOmx7VxDnY+KBbPYptVC++IxaKfCn1K00T+d2Q3OZ47Tkaa1\n" + + "T8tP2hZt3nrQVTpmSlk+LRDKRYorilxALTtLhdXLv7TfkWdk81YKPkt5CGtB0IhS\n" + + "KCMOuxr3Hs1Q3QGafetrA5wugfDzsDy7WQuVdaVu22nUr1xK002NW9wzjgy+sEOG\n" + + "fX03Qq6lAgMBAAECggEAMLT3+GYYN7rxLMKdyH70wcJxyWII1b7tWKzJPub6OkZE\n" + + "qcPqwLNuDIFNGjwkl9Jpq4Sbv5fHVB44Tvstb5Rl3VcW21cf60Rhr7AHEf8EgySG\n" + + "YjzRr3MksyNX9BjFgjbBEaNNUbH8wwAR0ce6rgq8zIhQrvjT56DRPABFkBBgo7mn\n" + + "bBQlspm/x70xF5TEZdIb+YuLZakWu9TfYW8rilONkLde4LcSdp9yMDQP3nfA0USc\n" + + "+cVWURm/29+LazyJL9xlzHPP0ttbnX1jiHsZhtzqskyomxlPGwSpv+QbIqEjX8Yn\n" + + "JqIpf3Xv2QX0OkzqvtUT5/LB/gzoUI14mn1ZAAy3AQKBgQD5Uj/paaUNCZLkz1AR\n" + + "ajf/kW73nWdQuMk5mTSZK+9pqyX8UKlktxk/VqG+f8zxwh/BNowLMqwF5DV85rYQ\n" + + "tNJI8s4kRbnM2VRElCXelFDMpmxxWpY72M8xit9BHCkAPbC5fOBOq22YuS4YB104\n" + + "FbvE62FLUU2MaZcaM86JXYeaYQKBgQDBUusq7JWkPYieq1i86zDx1l1jg4dJxyL5\n" + + "zdI4MBIOc5WPQhC2hfDa2n6LyFFJXVhkR8Zz25sDXq93E7RnvqGN+DfESZOOimoR\n" + + "tC879mg6k6DUdg0ear33FM/XqcNNaMFZMdQWyw4wyI374YmC4tyahoR8wkHa0V80\n" + + "3BdcBGgixQKBgQDEWL30eDp/lfaVM57+2APZxRL69n8S1zPBpKIDrtIRCbQUjQGa\n" + + "S4galYMznzorepG/e9G2T+WhjiOBhcAEUCL7SByH/FFivhTbHUDllTA8uyPT8V83\n" + + "KnuhrJg9kovHoM24hluwGNlq2Qsv6TzEmnkRj71Dr3e/CLjy7bHOBFZygQKBgH/X\n" + + "H2AxNvt3HYMfd/zl4mXqBbOq5KnrH7vlWWCCmU4pLPuhCoBIrm9rEUfKXcaQDcWy\n" + + "mQ9AZ4+g65No2mHIc/j37ZjFtugJq/6tEpcqaN5jhXU54477s0dS4eaRgm8MGN+s\n" + + "zb2M5YNo/EtWZ6K/9nXRAoelxfq3fafs6x2UZHCpAoGAaHUTShY2Hkf7V7xWRVYb\n" + + "4DnA1MOrBLXIfn/CTT9LpvewB0GFwm/1ZZbzasHz4blQNr8no2lIgPnkSukpTA5f\n" + + "JPuvPZlq7XzgqX3Q4QC3Qm4JEBouNy61sX7uLFBWTot5DcPvlWQtFC09qejYXl8V\n" + + "isFFLZd/OdlX0bHGjuOfcoo="; + protected final static String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvEfDj7/8lbc7sxv5Cm4Q\n" + + "vcK/s/SOx35PaxbE5Sf4h4rPeFpsuh8WIplBftNwMKqWqeAopsD1KCiIs1DpD1a5\n" + + "Y9LDqwyFhG3CRgcrL3mHqHAAldZS3wEuFqZx9sUa8+TewaTXsuu2gnlLA1CrYL/9\n" + + "c8VfBtFTNMTpse1cQ52PigWz2KbVQvviMWinwp9StNE/ndkNzmeO05GmtU/LT9oW\n" + + "bd560FU6ZkpZPi0QykWKK4pcQC07S4XVy7+035FnZPNWCj5LeQhrQdCIUigjDrsa\n" + + "9x7NUN0Bmn3rawOcLoHw87A8u1kLlXWlbttp1K9cStNNjVvcM44MvrBDhn19N0Ku\n" + + "pQIDAQAB"; + + protected final static String PRO_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDQJMdNMq9yXD4X\n" + + "hV8Pn9G9QPoWSQvVrdz6MSaBMt8vaBqIcHUr1Escs/VcU9MTFRycmCH9FQxAm0k9\n" + + "E1DmGEwj37CaGWVFpCgVncpD04oQg34rF9DibvW3FANYsl2DmYLkHPQ5c4IUhX1w\n" + + "Z+4B1fSC2zTzog4KkLbqowXL7jz4/o9SSZoZm+2Q0ldF+2soXw1Se7s5urM988is\n" + + "IKQN08tKgGxHs2T1XFwGQKVMDC6Z6W2sYHPCf7yk3YDhG/XqVRfR2L/JozmOl1CH\n" + + "z1igrMYJUF601IJugPVmbDjWXS5BLq45xAt70/3yYyH+i1dguqcf9HGLDqUa7T3v\n" + + "FBpKkNKJAgMBAAECggEACbI86pa635v2dIgNBqBOV/+n5tPeTkT8L1eM0KX7Ca1S\n" + + "1xpOCw2nth2YB4YMJi5sl8rqgmyxlmzle4fj0+Q738vy4Srfsd/U0jT4kDJRkzVc\n" + + "8kr4uyOqJK40/bPJcXD8TP4gTnDYFXamgk8FImbCLjph/BuHhex56PJROc/OXVcA\n" + + "7T1NQ9+ohZRHiKWvFMjgYcbsSW7psK4fBBt8vl+tnLM+ssJAi6dpbQaYodCYrOVb\n" + + "B0PE73Gr2fdw4oPJ+r6yRs71irNa37/x/oNzzFcjQlZaJgW1s+fTyBS8GWYHi582\n" + + "ldmLuKckMxitqYmd0QnLYZeKZ1jPJiTvk8KQPwBrgQKBgQD3Ykmxw5OobaxvPHQr\n" + + "Wff6MUXSkfDWEpgnhMqUEtJ7fVyi/KYBfx6hpyQ1T1Mq0B5hxlt4MdW/GMKjTWXq\n" + + "26rAdrnj4jQ/oXOgAcJmazRHrbExqSuUbl5pA6k6XtdsSNWKWqYDmSBTPc3UIFZt\n" + + "T/cOyBxBo+9TkAjqsULBk+EyuQKBgQDXZJ5YbnCMebMv/QQgqGvXHuvHQKJGhYO8\n" + + "eGD5xXjiwxbsbUSfFqdKefEdW8qqnMMWPoAPgQRGMYUzx89+JCie1t3CsXEGPmg3\n" + + "0nxxbf4E+/qzmLXzJdLqTsL6mThd9sZ3NxEnUDlW1WErIptEkhirbdH7gTlwUfMF\n" + + "yavHxSL2UQKBgGVhqGXritXZrHMhyVIC2vdzvfOfz51LnYOEjijE1fG53H8HH1k5\n" + + "qWoCP3qBecnv5KOZUN8fPUPFd+7Ix13KjF23ylKz30m8dtA6KFsk0BYX/qgldjCs\n" + + "UpCi6XV8bLh52NmMcMDEvlSe3X1zizfdL5ilNb9I2cnbG2xjHMKMQhwxAoGAGtdw\n" + + "ICcLIYZc/SLzq7oxTiqNSVRVpKIoy4jY1Od17BRRu/7V6VliWZaepID23ZIRgaki\n" + + "Pkxeovyy08QXqGmLIlg2ZHfGVPfb9vDlDyGc4TQhhtYF/pn9EbPk+mOzsYn6K4sS\n" + + "OSr3KkoHBOAYJ1BpgJt76nKtHMEpntQF8ywu8jECgYEAj2FTge7fbD5j7x5QRH6F\n" + + "5UG3P1RB6NM2wJ6Y/oDui2SawHaF4uWce5c7uJKnhELIQ5bNlDxJNfewQLKugFht\n" + + "Pbsp7Ld1j29jqqebnmC+2hOUsfGdtj8jxaEA7FwqaNWenvdiV7LktpUhCuiR/HD/\n" + + "F4oFFAlOJPm3xV9gAigsvU0=\n"; + protected final static String PRO_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0CTHTTKvclw+F4VfD5/R\n" + + "vUD6FkkL1a3c+jEmgTLfL2gaiHB1K9RLHLP1XFPTExUcnJgh/RUMQJtJPRNQ5hhM\n" + + "I9+wmhllRaQoFZ3KQ9OKEIN+KxfQ4m71txQDWLJdg5mC5Bz0OXOCFIV9cGfuAdX0\n" + + "gts086IOCpC26qMFy+48+P6PUkmaGZvtkNJXRftrKF8NUnu7ObqzPfPIrCCkDdPL\n" + + "SoBsR7Nk9VxcBkClTAwumeltrGBzwn+8pN2A4Rv16lUX0di/yaM5jpdQh89YoKzG\n" + + "CVBetNSCboD1Zmw41l0uQS6uOcQLe9P98mMh/otXYLqnH/Rxiw6lGu097xQaSpDS\n" + + "iQIDAQAB"; +} diff --git a/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java new file mode 100644 index 0000000..1505673 --- /dev/null +++ b/src/main/java/com/api/youhong/ai/pcn/ssoyunzhao/service/SsoYunZhaoService.java @@ -0,0 +1,104 @@ +package com.api.youhong.ai.pcn.ssoyunzhao.service; + +import aiyh.utils.Util; +import aiyh.utils.excention.CustomerException; +import aiyh.utils.tool.Assert; +import weaver.hrm.User; + +import javax.crypto.Cipher; +import java.lang.reflect.Method; +import java.net.URLEncoder; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +/** + *

+ * + *

create: 2023/2/22 23:19

+ * + * @author youHong.ai + */ +public class SsoYunZhaoService { + + /** + *

获取重定向路径地址

+ * + * @param user 用户 + * @return 重定向地址 + * @throws Exception 异常 + */ + + private final String environment = Util.getProperties("PcnYunZhaoSsoRsaKey", "yunzhao.environment"); + + public String getRedirectPath(User user) throws Exception { + String userCodeMethod = Util.getCusConfigValueNullOrEmpty("YunZhaoSSOUserCodeMethod", "getEmail"); + Method method = User.class.getMethod(userCodeMethod); + String value = Util.null2String(method.invoke(user)); + long currentTime = System.currentTimeMillis(); + String token = this.rsaEncryptedUserInfo(value + "\"" + String.valueOf(currentTime).substring(0, 10)); + String yunZhaoSsoPathUrl = Util.getCusConfigValue("YunZhaoSSOPathURL"); + Assert.notEmpty(yunZhaoSsoPathUrl, "can not find [YunZhaoSSOPathURL] from table [uf_cus_dev_config]"); + return yunZhaoSsoPathUrl + URLEncoder.encode(token, "UTF-8"); + } + + + /** + *

加密数据

+ * + * @param str 字符串 + * @return 加密后 + * @throws Exception 异常 + */ + public String rsaEncryptedUserInfo(String str) throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + String privateKey = ""; + if ("test".equals(environment)) { + privateKey = SsoYunZhaoConstant.PRIVATE_KEY; + } + if ("pro".equals(environment)) { + privateKey = SsoYunZhaoConstant.PRO_PRIVATE_KEY; + } + byte[] privBuffer = Base64.getDecoder().decode(privateKey.replace("\n", "")); + PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privBuffer); + PrivateKey privKey = keyFactory.generatePrivate(privSpec); + cipher.init(Cipher.ENCRYPT_MODE, privKey); + byte[] encrypted = cipher.doFinal(str.getBytes()); + String result = Base64.getEncoder().encodeToString(encrypted); + String checkSource = this.rsaDecryptUserInfo(result); + if (!checkSource.equals(str)) { + throw new CustomerException("加解密用户信息失败!"); + } + return result; + + } + + /** + *

解密数据

+ * + * @param str 加密字符串 + * @return 解密后 + * @throws Exception 异常 + */ + public String rsaDecryptUserInfo(String str) throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + String publicKey = ""; + if ("test".equals(environment)) { + publicKey = SsoYunZhaoConstant.PUBLIC_KEY; + } + if ("pro".equals(environment)) { + publicKey = SsoYunZhaoConstant.PRO_PUBLIC_KEY; + } + byte[] pubBuffer = Base64.getDecoder().decode(publicKey.replace("\n", "")); + X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubBuffer); + PublicKey pubKey = keyFactory.generatePublic(pubSpec); + cipher.init(Cipher.DECRYPT_MODE, pubKey); + byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(str.getBytes())); + return new String(decrypted); + } +} diff --git a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java index 1cdfa7c..323fd7f 100644 --- a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java +++ b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/ReceiptAndPaymentAction.java @@ -71,6 +71,11 @@ public class ReceiptAndPaymentAction extends SafeCusBaseAction { @RequiredMark("ip") private String ip; + + @PrintParamMark + @ActionOptionalParam(desc = "是否删除生成的临时本地文件,true - 删除 false - 不删除", value = "false") + private String deleteTemp = "false"; + @Override public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { try { @@ -86,7 +91,9 @@ public class ReceiptAndPaymentAction extends SafeCusBaseAction { log.info("远程连接地址:" + "smb://" + ip + receiptPath); log.info("本地文件地址: " + filePath); smbjUtil.smbPut("smb://" + ip + receiptPath, filePath, userName, password, fileName); - Files.delete(Paths.get(filePath)); + if (Boolean.parseBoolean(deleteTemp)) { + Files.delete(Paths.get(filePath)); + } } } else if (Integer.parseInt(voucherType) == 2) { String tempFilePath = server.sendReceiptVoucher(onlyMark, requestId, billTable); @@ -95,7 +102,9 @@ public class ReceiptAndPaymentAction extends SafeCusBaseAction { log.info("远程连接地址:" + "smb://" + ip + paymentPath); log.info("本地文件地址: " + tempFilePath); smbjUtil.smbPut("smb://" + ip + paymentPath, tempFilePath, userName, password, fileName); - Files.delete(Paths.get(tempFilePath)); + if (Boolean.parseBoolean(deleteTemp)) { + Files.delete(Paths.get(tempFilePath)); + } } /* ******************* 是否提交流程 ******************* */ if (Boolean.parseBoolean(submitAction)) { diff --git a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java index 56fac0c..8ed33c8 100644 --- a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java +++ b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/VoucherPayableAction.java @@ -72,6 +72,10 @@ public class VoucherPayableAction extends SafeCusBaseAction { @RequiredMark("ip") private String ip; + @PrintParamMark + @ActionOptionalParam(desc = "是否删除生成的临时本地文件,true - 删除 false - 不删除", value = "false") + private String deleteTemp = "false"; + @Override public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { @@ -91,7 +95,9 @@ public class VoucherPayableAction extends SafeCusBaseAction { log.info("远程连接地址:" + "smb://" + ip + remotePath); log.info("本地文件地址: " + tempFilePath); smbjUtil.smbPut("smb://" + ip + remotePath, tempFilePath, userName, password, fileName); - Files.delete(Paths.get(tempFilePath)); + if (Boolean.parseBoolean(deleteTemp)) { + Files.delete(Paths.get(tempFilePath)); + } /* ******************* 是否提交流程 ******************* */ if (Boolean.parseBoolean(submitAction)) { this.submitWorkflow(requestId, user.getUID()); diff --git a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/service/VoucherPayableService.java b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/service/VoucherPayableService.java index 7da6dd4..7dfc1d4 100644 --- a/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/service/VoucherPayableService.java +++ b/src/main/java/weaver/youhong/ai/haripijiu/action/sapdocking/service/VoucherPayableService.java @@ -28,176 +28,176 @@ import java.util.UUID; */ public class VoucherPayableService { - - - private final SapConfigService configService = new SapConfigService(); - - @NotNull - private static String getFilePath() { - String sysFilePath = GCONST.getSysFilePath(); - String filePath = ""; - if (sysFilePath.endsWith(File.separator)) { - filePath = sysFilePath + "temp" + File.separator + "voucher" + File.separator + - System.currentTimeMillis() + "-voucher-" + UUID.randomUUID() + ".txt"; - } else { - filePath = sysFilePath + File.separator + "temp" + File.separator + "voucher" + File.separator + - System.currentTimeMillis() + "-voucher-" + UUID.randomUUID() + ".txt"; - } - Path path = Paths.get(filePath); - if (!Files.exists(path)) { - Path parent = path.getParent(); - try { - Files.createDirectories(parent); - } catch (IOException e) { - throw new CustomerException(Util.logStr("can not create file [{}]", filePath)); - } - } - return filePath; - } - - /** - *

sendSapVoucher 获取凭证文件位置

- * 2023/2/3 11:34 - * ************************************************************ - * - * @param onlyMark 唯一标识 - * @param requestId 流程请求id - * @param billTable 流程表 - * @return String 凭证文件位置 - * @author youHong.ai ****************************************** - */ - public String sendSapVoucher(String onlyMark, String requestId, String billTable) { - - SapVoucher voucherData = configService.getVoucherData(onlyMark, requestId, billTable); - /* ******************* 整理数据 ******************* */ - StringBuilder voucherHeadBuilder = new StringBuilder(); - List voucherHead = voucherData.getVoucherHead(); - for (VoucherItem voucherItem : voucherHead) { - voucherHeadBuilder.append(voucherItem.getValue()) - .append("\t"); - } - String voucherHeadStr = voucherHeadBuilder.substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"; - StringBuilder voucherDetailBuilder = new StringBuilder(); - List> voucherDetail = voucherData.getVoucherDetail(); - for (List voucherItems : voucherDetail) { - voucherDetailBuilder.append(appendVoucherItems(voucherItems)) - .append("\r\n"); - } - String voucherDetailStr = voucherDetailBuilder.substring(0, voucherDetailBuilder.lastIndexOf("\r\n")); - String filePath = getFilePath(); - try { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( - Files.newOutputStream(Paths.get(filePath)) - )); - writer.write(voucherHeadStr); - writer.write(voucherDetailStr); - writer.flush(); - writer.close(); - } catch (IOException e) { - throw new CustomerException(Util.logStr("can not writer file [{}]", filePath)); - } - - return filePath; - } - - public String sendReceiptVoucher(String onlyMark, String requestId, String billTable) { - SapVoucher voucherData = configService.getReceiptPaymentData(onlyMark, requestId, billTable); - /* ******************* 整理数据 ******************* */ - StringBuilder voucherHeadBuilder = new StringBuilder(); - List> voucherDetail = voucherData.getVoucherDetail(); - for (int i = 0; i < voucherDetail.size(); i++) { - List voucherItems = voucherDetail.get(i); - if (i == 0) { - for (VoucherItem voucherItem : voucherItems) { - voucherHeadBuilder.append(voucherItem.getName()) - .append("\t"); - } - voucherHeadBuilder = new StringBuilder(voucherHeadBuilder - .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"); - - } - for (VoucherItem voucherItem : voucherItems) { - voucherHeadBuilder.append(voucherItem.getValue()) - .append("\t"); - } - if (i < voucherDetail.size() - 1) { - voucherHeadBuilder = new StringBuilder(voucherHeadBuilder - .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"); - } else { - voucherHeadBuilder = new StringBuilder(voucherHeadBuilder - .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + ""); - } - } - String filePath = getFilePath(); - try { - - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( - Files.newOutputStream(Paths.get(filePath)) - )); - writer.write(voucherHeadBuilder.toString()); - writer.flush(); - writer.close(); - } catch (IOException e) { - throw new CustomerException(Util.logStr("can not writer receipt voucher file [{}]", filePath)); - } - - return filePath; - } - - - public List sendPaymentVoucher(String onlyMark, String requestId, String billTable) { - SapVoucher voucherData = configService.getReceiptPaymentData(onlyMark, requestId, billTable); - List filePathList = new ArrayList<>(); - /* ******************* 整理数据 ******************* */ - StringBuilder voucherHeadBuilder = new StringBuilder(); - List> voucherDetail = voucherData.getVoucherDetail(); - for (List voucherItems : voucherDetail) { - for (VoucherItem voucherItem : voucherItems) { - voucherHeadBuilder.append(voucherItem.getName()) - .append("\t"); - } - voucherHeadBuilder = new StringBuilder(voucherHeadBuilder - .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"); - - for (VoucherItem voucherItem : voucherItems) { - voucherHeadBuilder.append(voucherItem.getValue()) - .append("\t"); - } - voucherHeadBuilder = new StringBuilder(voucherHeadBuilder - .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + ""); - - String filePath = getFilePath(); - try { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( - Files.newOutputStream(Paths.get(filePath)) - )); - writer.write(voucherHeadBuilder.toString()); - writer.flush(); - writer.close(); - } catch (IOException e) { - throw new CustomerException(Util.logStr("can not writer payment voucher file [{}]", filePath)); - } - filePathList.add(filePath); - } - return filePathList; - } - - - /** - *

appendVoucherItems 拼接凭证明细

- * 2023/2/3 11:36 - * ************************************************************ - * - * @param voucherItems 凭证明细数据 - * @return String 拼接后字符串 - * @author youHong.ai ****************************************** - */ - private String appendVoucherItems(List voucherItems) { - StringBuilder result = new StringBuilder(); - for (VoucherItem voucherItem : voucherItems) { - result.append(voucherItem.getValue()) - .append("\t"); - } - return result.toString(); - } + + + private final SapConfigService configService = new SapConfigService(); + + @NotNull + private static String getFilePath() { + String sysFilePath = GCONST.getSysFilePath(); + String filePath = ""; + if (sysFilePath.endsWith(File.separator)) { + filePath = sysFilePath + "cus_temp" + File.separator + "voucher" + File.separator + + System.currentTimeMillis() + "-voucher-" + UUID.randomUUID() + ".txt"; + } else { + filePath = sysFilePath + File.separator + "cus_temp" + File.separator + "voucher" + File.separator + + System.currentTimeMillis() + "-voucher-" + UUID.randomUUID() + ".txt"; + } + Path path = Paths.get(filePath); + if (!Files.exists(path)) { + Path parent = path.getParent(); + try { + Files.createDirectories(parent); + } catch (IOException e) { + throw new CustomerException(Util.logStr("can not create file [{}]", filePath)); + } + } + return filePath; + } + + /** + *

sendSapVoucher 获取凭证文件位置

+ * 2023/2/3 11:34 + * ************************************************************ + * + * @param onlyMark 唯一标识 + * @param requestId 流程请求id + * @param billTable 流程表 + * @return String 凭证文件位置 + * @author youHong.ai ****************************************** + */ + public String sendSapVoucher(String onlyMark, String requestId, String billTable) { + + SapVoucher voucherData = configService.getVoucherData(onlyMark, requestId, billTable); + /* ******************* 整理数据 ******************* */ + StringBuilder voucherHeadBuilder = new StringBuilder(); + List voucherHead = voucherData.getVoucherHead(); + for (VoucherItem voucherItem : voucherHead) { + voucherHeadBuilder.append(voucherItem.getValue()) + .append("\t"); + } + String voucherHeadStr = voucherHeadBuilder.substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"; + StringBuilder voucherDetailBuilder = new StringBuilder(); + List> voucherDetail = voucherData.getVoucherDetail(); + for (List voucherItems : voucherDetail) { + voucherDetailBuilder.append(appendVoucherItems(voucherItems)) + .append("\r\n"); + } + String voucherDetailStr = voucherDetailBuilder.substring(0, voucherDetailBuilder.lastIndexOf("\r\n")); + String filePath = getFilePath(); + try { + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( + Files.newOutputStream(Paths.get(filePath)) + )); + writer.write(voucherHeadStr); + writer.write(voucherDetailStr); + writer.flush(); + writer.close(); + } catch (IOException e) { + throw new CustomerException(Util.logStr("can not writer file [{}]", filePath)); + } + + return filePath; + } + + public String sendReceiptVoucher(String onlyMark, String requestId, String billTable) { + SapVoucher voucherData = configService.getReceiptPaymentData(onlyMark, requestId, billTable); + /* ******************* 整理数据 ******************* */ + StringBuilder voucherHeadBuilder = new StringBuilder(); + List> voucherDetail = voucherData.getVoucherDetail(); + for (int i = 0; i < voucherDetail.size(); i++) { + List voucherItems = voucherDetail.get(i); + if (i == 0) { + for (VoucherItem voucherItem : voucherItems) { + voucherHeadBuilder.append(voucherItem.getName()) + .append("\t"); + } + voucherHeadBuilder = new StringBuilder(voucherHeadBuilder + .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"); + + } + for (VoucherItem voucherItem : voucherItems) { + voucherHeadBuilder.append(voucherItem.getValue()) + .append("\t"); + } + if (i < voucherDetail.size() - 1) { + voucherHeadBuilder = new StringBuilder(voucherHeadBuilder + .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"); + } else { + voucherHeadBuilder = new StringBuilder(voucherHeadBuilder + .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + ""); + } + } + String filePath = getFilePath(); + try { + + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( + Files.newOutputStream(Paths.get(filePath)) + )); + writer.write(voucherHeadBuilder.toString()); + writer.flush(); + writer.close(); + } catch (IOException e) { + throw new CustomerException(Util.logStr("can not writer receipt voucher file [{}]", filePath)); + } + + return filePath; + } + + + public List sendPaymentVoucher(String onlyMark, String requestId, String billTable) { + SapVoucher voucherData = configService.getReceiptPaymentData(onlyMark, requestId, billTable); + List filePathList = new ArrayList<>(); + /* ******************* 整理数据 ******************* */ + StringBuilder voucherHeadBuilder = new StringBuilder(); + List> voucherDetail = voucherData.getVoucherDetail(); + for (List voucherItems : voucherDetail) { + for (VoucherItem voucherItem : voucherItems) { + voucherHeadBuilder.append(voucherItem.getName()) + .append("\t"); + } + voucherHeadBuilder = new StringBuilder(voucherHeadBuilder + .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + "\r\n"); + + for (VoucherItem voucherItem : voucherItems) { + voucherHeadBuilder.append(voucherItem.getValue()) + .append("\t"); + } + voucherHeadBuilder = new StringBuilder(voucherHeadBuilder + .substring(0, voucherHeadBuilder.lastIndexOf("\t")) + ""); + + String filePath = getFilePath(); + try { + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( + Files.newOutputStream(Paths.get(filePath)) + )); + writer.write(voucherHeadBuilder.toString()); + writer.flush(); + writer.close(); + } catch (IOException e) { + throw new CustomerException(Util.logStr("can not writer payment voucher file [{}]", filePath)); + } + filePathList.add(filePath); + } + return filePathList; + } + + + /** + *

appendVoucherItems 拼接凭证明细

+ * 2023/2/3 11:36 + * ************************************************************ + * + * @param voucherItems 凭证明细数据 + * @return String 拼接后字符串 + * @author youHong.ai ****************************************** + */ + private String appendVoucherItems(List voucherItems) { + StringBuilder result = new StringBuilder(); + for (VoucherItem voucherItem : voucherItems) { + result.append(voucherItem.getValue()) + .append("\t"); + } + return result.toString(); + } } diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java index 32b0635..1d32a2d 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java @@ -12,6 +12,7 @@ import lombok.ToString; import weaver.hrm.User; import weaver.soa.workflow.request.RequestInfo; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.UpdateDetailRowDto; +import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionsSetValueConfigMain; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.service.WorkflowConditionsSetValueService; import java.util.*; @@ -31,7 +32,7 @@ public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { @RequiredMark("流程条件赋值配置表唯一标识字段值") @PrintParamMark - @ActionDefaultTestValue("test") + @ActionDefaultTestValue("getdata") private String onlyMark; @ActionOptionalParam(desc = "条件修改所在明细表,1-明细1,2-明细2", value = "") @@ -54,24 +55,26 @@ public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { try { Map workflowData = new HashMap<>(16); Map workflowMainData = super.getObjMainTableValue(requestInfo); + ConditionsSetValueConfigMain conditionsSetValueConfigMain = service.getConditionConfigMain(onlyMark); if (Strings.isNullOrEmpty(detailNo)) { /* ******************* 数据修改主表 ******************* */ - Map conditionsValue = service.getConditionsValue(onlyMark, workflowData).get(billTable); + Map conditionsValue = service.getConditionsValue(conditionsSetValueConfigMain, workflowData).get(billTable); service.updateWorkflowData(conditionsValue, billTable, requestId); return; } /* ******************* 明细表 ******************* */ - List> detailData = super.getDetailTableObjValueByDetailNo(Integer.parseInt(detailNo), requestInfo); + List> detailData = super.getDetailTableObjValueByDetailNo(Integer.parseInt(detailNo) - 1, requestInfo); workflowData.put("main", workflowMainData); workflowData.put("_user_", user); workflowData.put("_workflowId_", workflowId); workflowData.put("_requestId_", requestId); workflowData.put("_billTable_", billTable); + workflowData.put("_detailTable_", billTable + "_dt" + detailNo); List main = new ArrayList<>(); List detail = new ArrayList<>(); for (Map detailDatum : detailData) { workflowData.put("detail_" + detailNo, detailDatum); - Map> conditionsValues = service.getConditionsValue(onlyMark, workflowData); + Map> conditionsValues = service.getConditionsValue(conditionsSetValueConfigMain, workflowData); Map mainConditions = conditionsValues.get(billTable); if (!Objects.isNull(mainConditions) && !mainConditions.isEmpty()) { main.add(Builder.builder(UpdateDetailRowDto::new) @@ -101,6 +104,8 @@ public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { } public void submitWorkflow(String requestId, Integer userId) { - Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "邮件发送附件提交流程!"); + if (Boolean.parseBoolean(submitAction)) { + Util.submitWorkflowThread(Integer.parseInt(requestId), userId, "流程条件赋值提交流程!"); + } } } diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java index f09f595..58d5954 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionItem.java @@ -1,5 +1,6 @@ package weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity; +import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn; import aiyh.utils.entity.FieldViewInfo; import lombok.Getter; import lombok.Setter; @@ -16,23 +17,30 @@ import lombok.ToString; @Getter @ToString public class ConditionItem { + @SqlOracleDbFieldAnn("ID") private Integer id; /** 赋值字段 */ + @SqlOracleDbFieldAnn("ID") private FieldViewInfo targetField; /** 条件取值字段 */ private FieldViewInfo conditionsField; /** 条件 */ + @SqlOracleDbFieldAnn("CONDITIONS") private Integer conditions; /** 条件对比方式 */ + @SqlOracleDbFieldAnn("CONDITIONS_TYPE") private Integer conditionsType; /** 条件对比字段 */ private FieldViewInfo conditionsContrastField; /** 条件自定义值 */ + @SqlOracleDbFieldAnn("CUSTOMER_CONDITIONS_VALUE") private String customerConditionsValue; /** 赋值规则 */ + @SqlOracleDbFieldAnn("VALUE_SET_RULES") private Integer valueSetRules; /** 自定义赋值 */ + @SqlOracleDbFieldAnn("CUSTOMER_SET_VALUE") private String customerSetValue; /** 取值字段 */ diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java index 60b02fc..4b8eb6e 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/entity/ConditionsSetValueConfigMain.java @@ -1,5 +1,6 @@ package weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity; +import aiyh.utils.annotation.recordset.SqlOracleDbFieldAnn; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -19,12 +20,15 @@ import java.util.List; public class ConditionsSetValueConfigMain { /** id */ + @SqlOracleDbFieldAnn("ID") private Integer id; /** 唯一标识 */ + @SqlOracleDbFieldAnn("ONLY_MARK") private String onlyMark; /** 流程类型 */ + @SqlOracleDbFieldAnn("WORKFLOW_TYPE") private Integer workflowType; /** 明细配置表,条件配置 */ diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java index c1cc5a7..998da81 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/mapper/WorkflowConditionsSetValueMapper.java @@ -85,9 +85,9 @@ public interface WorkflowConditionsSetValueMapper { *

批量更新数据

* * @param sql sql - * @param updateBatchData 批量参数 + * @param updateBatchData 参数 * @return */ - @BatchUpdate(custom = true) - boolean batchUpdateWorkflowData(@SqlString String sql, @BatchSqlArgs List> updateBatchData); + @Update(custom = true) + boolean batchUpdateWorkflowData(@SqlString String sql, Map updateBatchData); } diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java index ada3399..cb64531 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java @@ -2,6 +2,8 @@ package weaver.youhong.ai.pcn.actioin.conditionssetvalue.service; import aiyh.utils.Util; import aiyh.utils.tool.Assert; +import com.alibaba.fastjson.JSON; +import org.jetbrains.annotations.NotNull; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.ConditionValueDto; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.UpdateDetailRowDto; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; @@ -28,17 +30,13 @@ public class WorkflowConditionsSetValueService { /** *

获取条件赋值映射规则处理后的字段值

* - * @param onlyMark 配置表唯一标识 - * @param workflowData 流程表数据 + * @param conditionsSetValueConfigMain 配置表信息 + * @param workflowData 流程表数据 * @return 映射结果 */ - public Map> getConditionsValue(String onlyMark, Map workflowData) { - - /* ******************* 查询配置表 ******************* */ - ConditionsSetValueConfigMain conditionsSetValueConfigMain = mapper.selectConfigByOnlyMark(onlyMark); - Assert.notNull(conditionsSetValueConfigMain, "can not query configuration by onlyMark [{}]", onlyMark); + public Map> getConditionsValue(ConditionsSetValueConfigMain conditionsSetValueConfigMain, Map workflowData) { List conditionItemList = conditionsSetValueConfigMain.getConditionItemList(); - Assert.notEmpty(conditionItemList, "can not query conditionItemList by onlyMark [{}]", onlyMark); + /* ******************* 映射规则处理 ,责任链初始化 ******************* */ ConditionsTypeTreatment conditionsTypeTreatment = new ConditionsTypeTreatment( new ConditionsTreatment( @@ -68,6 +66,16 @@ public class WorkflowConditionsSetValueService { return result; } + @NotNull + public ConditionsSetValueConfigMain getConditionConfigMain(String onlyMark) { + /* ******************* 查询配置表 ******************* */ + ConditionsSetValueConfigMain conditionsSetValueConfigMain = mapper.selectConfigByOnlyMark(onlyMark); + Assert.notNull(conditionsSetValueConfigMain, "can not query configuration by onlyMark [{}]", onlyMark); + List conditionItemList = conditionsSetValueConfigMain.getConditionItemList(); + Assert.notEmpty(conditionItemList, "can not query conditionItemList by onlyMark [{}]", onlyMark); + return conditionsSetValueConfigMain; + } + /** *

更新明细表数据

* @@ -86,32 +94,42 @@ public class WorkflowConditionsSetValueService { return; } List> updateBatchData = new ArrayList<>(updateDetailRowDtoList.size()); - for (UpdateDetailRowDto updateDetailRowDto : updateDetailRowDtoList) { + for (int i = 0; i < updateDetailRowDtoList.size(); i++) { + UpdateDetailRowDto updateDetailRowDto = updateDetailRowDtoList.get(i); + updateDetailRow = updateDetailRowDtoList.get(i); Map updateData = updateDetailRowDto.getUpdateData(); - updateData.put("_id_", updateDetailRow.getWhereValue()); + updateData.put("_" + updateDetailRow.getWhereField() + "_", updateDetailRow.getWhereValue()); updateBatchData.add(updateData); } - StringBuilder sb = new StringBuilder("update "); - sb.append(billTable).append(" set "); - for (Map.Entry entry : updateBatchData.get(0).entrySet()) { - sb.append(entry.getKey()) - .append(" = #{item.") - .append(entry.getKey()) - .append("},"); - } - sb.deleteCharAt(sb.length() - 1); - sb.append(" where ") - .append(updateDetailRow.getWhereField()) - .append(" = #{item._id_}"); - String sql = sb.toString(); - boolean flag = mapper.batchUpdateWorkflowData(sql, updateBatchData); - if (!flag) { - try { - Thread.sleep(500); - } catch (InterruptedException ignore) { + for (int i = 0; i < updateBatchData.size(); i++) { + Map datum = updateBatchData.get(i); + updateDetailRow = updateDetailRowDtoList.get(i); + StringBuilder sb = new StringBuilder("update "); + sb.append(billTable).append(" set "); + for (Map.Entry entry : datum.entrySet()) { + if (("_" + updateDetailRow.getWhereField() + "_").equals(entry.getKey())) { + continue; + } + sb.append(entry.getKey()) + .append(" = #{") + .append(entry.getKey()) + .append("},"); + } + sb.deleteCharAt(sb.length() - 1); + sb.append(" where ") + .append(updateDetailRow.getWhereField()) + .append(" = #{" + "_") + .append(updateDetailRow.getWhereField()) + .append("_") + .append("}"); + String sql = sb.toString(); + boolean flag = mapper.batchUpdateWorkflowData(sql, datum); + + if (!flag) { + Util.getLogger().info("更新条件字段值失败!" + sql + " : " + JSON.toJSONString(datum)); } - mapper.batchUpdateWorkflowData(sql, updateBatchData); } + } diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java index 3355570..ba14fb8 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ConditionsTreatment.java @@ -2,6 +2,7 @@ package weaver.youhong.ai.pcn.actioin.conditionssetvalue.util; import aiyh.utils.Util; import aiyh.utils.annotation.MethodRuleNo; +import aiyh.utils.entity.FieldViewInfo; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.dto.ConditionValueDto; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.entity.ConditionItem; @@ -48,12 +49,21 @@ public class ConditionsTreatment { public ConditionValueDto executeTreatment(ConditionItem conditionItem, Object value) { Map workflowData = ConditionsTypeTreatment.WORKFLOW_DATA.get(); - Object sourceValue = workflowData.get(conditionItem.getConditionsField().getFieldName()); + FieldViewInfo conditionsField = conditionItem.getConditionsField(); + Object sourceValue = Util.getValueByFieldViwInfo(conditionsField, workflowData); Boolean apply = METHOD_MAP.get(conditionItem.getConditions()).apply( Util.null2String(sourceValue), Util.null2String(value) ); if (apply) { + FieldViewInfo targetField = conditionItem.getTargetField(); + String tableName = targetField.getTableName(); + if (tableName.contains("_dt")) { + String[] dts = tableName.split("_dt"); + ((Map) workflowData.get("detail_" + dts[1])).put(targetField.getFieldName(), value); + } else { + ((Map) workflowData.get("main")).put(targetField.getFieldName(), value); + } return this.valueSetRulesTreatment.createConditionValue(conditionItem); } return null; diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java index 8999875..ccbcf06 100644 --- a/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/util/ValueSetRulesTreatment.java @@ -51,6 +51,7 @@ public class ValueSetRulesTreatment { return Builder.builder(ConditionValueDto::new) .with(ConditionValueDto::setFieldName, conditionItem.getTargetField().getFieldName()) .with(ConditionValueDto::setValue, value) + .with(ConditionValueDto::setTableName, conditionItem.getTargetField().getTableName()) .build(); } diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/docfieltoattachment/CopyDocFileToAttachmentAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/docfieltoattachment/CopyDocFileToAttachmentAction.java new file mode 100644 index 0000000..c2beddb --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/docfieltoattachment/CopyDocFileToAttachmentAction.java @@ -0,0 +1,100 @@ +package weaver.youhong.ai.pcn.actioin.docfieltoattachment; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.ActionDesc; +import aiyh.utils.annotation.ActionOptionalParam; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import aiyh.utils.entity.DocImageInfo; +import aiyh.utils.excention.CustomerException; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import weaver.file.ImageFileManager; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.youhong.ai.pcn.actioin.docfieltoattachment.mapper.CopyDocFileToAttachmentMapper; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *

文档字段中附件复制到附件字段中

+ * + *

create: 2023/2/21 18:40

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +@ActionDesc(value = "文档字段中附件复制到附件字段中", author = "youhong.ai") +public class CopyDocFileToAttachmentAction extends SafeCusBaseAction { + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") + private String block = "true"; + + @PrintParamMark + @RequiredMark("字段映射配置字段: 文档字段:附件字段;文档字段:附件字段") + private String fieldMappings; + + private final CopyDocFileToAttachmentMapper mapper = Util.getMapper(CopyDocFileToAttachmentMapper.class); + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + String[] fieldMappingArr = fieldMappings.split(";"); + Map mainTableValue = super.getMainTableValue(requestInfo); + Map sqlValue = new HashMap<>(); + for (String fieldMapping : fieldMappingArr) { + copyFile(fieldMapping, mainTableValue, sqlValue, String.valueOf(workflowId), billTable, user.getUID()); + } + StringBuilder sb = new StringBuilder("update "); + sb.append(billTable).append(" set "); + for (Map.Entry entry : sqlValue.entrySet()) { + sb.append(entry.getKey()).append(" = ").append("#{").append(entry.getKey()).append("},"); + } + sb.deleteCharAt(sb.length() - 1); + sb.append(" where requestid = ").append(requestId); + if (mapper.updateDocIds(sb.toString(), sqlValue)) { + Thread.sleep(500); + mapper.updateDocIds(sb.toString(), sqlValue); + } + } catch (Exception e) { + if (Boolean.parseBoolean(block)) { + throw new CustomerException(e.getMessage(), e); + } + } + } + + private void copyFile(String fieldMapping, Map mainTableValue, + Map sqlValue, String workflowId, + String billTable, int userId) { + List docIds = new ArrayList<>(); + String[] split = fieldMapping.split(":"); + String docField = split[0]; + String fileField = split[1]; + String docId = mainTableValue.get(docField); + List docImageInfos = Util.selectImageInfoByDocIds(docId); + for (DocImageInfo docImageInfo : docImageInfos) { + if (docImageInfo.getDocFileType() != 2) { + continue; + } + InputStream inputStreamById = ImageFileManager.getInputStreamById(docImageInfo.getImageFileId()); + String docCategorysByTable = Util.getDocCategorysByTable(workflowId, fileField, billTable); + String[] categoryArr = docCategorysByTable.split(","); + String category = categoryArr[categoryArr.length - 1]; + try { + int doc = Util.createDoc(docImageInfo.getImageFileName(), Integer.parseInt(category), inputStreamById, userId); + docIds.add(doc); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + sqlValue.put(fileField, Util.intJoin(docIds, ",")); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/docfieltoattachment/mapper/CopyDocFileToAttachmentMapper.java b/src/main/java/weaver/youhong/ai/pcn/actioin/docfieltoattachment/mapper/CopyDocFileToAttachmentMapper.java new file mode 100644 index 0000000..916dd82 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/docfieltoattachment/mapper/CopyDocFileToAttachmentMapper.java @@ -0,0 +1,22 @@ +package weaver.youhong.ai.pcn.actioin.docfieltoattachment.mapper; + +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.SqlString; +import aiyh.utils.annotation.recordset.Update; + +import java.util.Map; + +/** + *

+ * + *

create: 2023/2/21 19:13

+ * + * @author youHong.ai + */ +@SqlMapper +public interface CopyDocFileToAttachmentMapper { + + @Update(custom = true) + boolean updateDocIds(@SqlString String sql, + Map map); +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/GenerateLoginIdAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/GenerateLoginIdAction.java new file mode 100644 index 0000000..5732d89 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/GenerateLoginIdAction.java @@ -0,0 +1,102 @@ +package weaver.youhong.ai.pcn.actioin.generateloginid; + +import aiyh.utils.Util; +import aiyh.utils.action.SafeCusBaseAction; +import aiyh.utils.annotation.ActionDesc; +import aiyh.utils.annotation.ActionOptionalParam; +import aiyh.utils.annotation.PrintParamMark; +import aiyh.utils.annotation.RequiredMark; +import com.google.common.base.Strings; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import weaver.hrm.User; +import weaver.soa.workflow.request.RequestInfo; +import weaver.youhong.ai.pcn.actioin.generateloginid.mapper.GenerateLoginIdMapper; + +import java.text.NumberFormat; +import java.util.Map; + +/** + *

生成loginid

+ * + *

create: 2023/2/21 19:46

+ * + * @author youHong.ai + */ +@Getter +@Setter +@ToString +@ActionDesc(value = "根据分部生成对应的登录名", author = "youhong.ai") +public class GenerateLoginIdAction extends SafeCusBaseAction { + + @PrintParamMark + @RequiredMark("流程回写登录名字段名") + private String loginIdField; + + + @PrintParamMark + @RequiredMark("分部简称流程字段名") + private String subCompanyTextField; + + + @PrintParamMark + @ActionOptionalParam(value = "4", desc = "登录名序列数字位长度,序列不足时前缀补0,如0001,默认长度4位") + private String numberFillQuantity = "4"; + + + @PrintParamMark + @ActionOptionalParam(value = "true", desc = "是否失败后阻断流程") + private String block = "true"; + + private final GenerateLoginIdMapper mapper = Util.getMapper(GenerateLoginIdMapper.class); + + @Override + public void doSubmit(String requestId, String billTable, int workflowId, User user, RequestInfo requestInfo) { + try { + Map mainTableValue = super.getMainTableValue(requestInfo); + String subCompanyName = mainTableValue.get(subCompanyTextField); + String subCompanyId = mapper.selectSubCompanyIdBySubCompanyName(subCompanyName); + Map lastLoginIdInfo = mapper.selectLastLoginId(subCompanyName, subCompanyId, subCompanyName + "%"); + String loginIdNo = lastLoginIdInfo.get("loginIdNo"); + String loginId = prefixFill(loginIdNo, subCompanyName); + if (mapper.updateLoginId(billTable, requestId, loginId, loginIdField)) { + try { + Thread.sleep(500); + } catch (Exception ignore) { + } + mapper.updateLoginId(billTable, requestId, loginId, loginIdField); + } + } catch (Exception e) { + if (Boolean.parseBoolean(block)) { + throw e; + } + } + } + + /** + *

前缀补齐

+ * + * @param lastLoginIdNo 最后登录名编号 + * @param prefix 前缀 + * @return 登录名 + */ + private String prefixFill(String lastLoginIdNo, String prefix) { + NumberFormat numberFormat = NumberFormat.getInstance(); + // 禁用数字格式化分组。 + numberFormat.setGroupingUsed(false); + // 保留最小位数 + numberFormat.setMinimumIntegerDigits(Integer.parseInt(numberFillQuantity)); + // 保留最大位数 + numberFormat.setMaximumIntegerDigits(10); + long i = 0L; + try { + if (!Strings.isNullOrEmpty(lastLoginIdNo)) { + i = Long.parseLong(lastLoginIdNo); + } + } catch (NumberFormatException ignore) { + } + long newLoginId = i + 1; + return prefix + numberFormat.format(newLoginId); + } +} diff --git a/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/mapper/GenerateLoginIdMapper.java b/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/mapper/GenerateLoginIdMapper.java new file mode 100644 index 0000000..a12019d --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/mapper/GenerateLoginIdMapper.java @@ -0,0 +1,64 @@ +package weaver.youhong.ai.pcn.actioin.generateloginid.mapper; + +import aiyh.utils.annotation.recordset.ParamMapper; +import aiyh.utils.annotation.recordset.Select; +import aiyh.utils.annotation.recordset.SqlMapper; +import aiyh.utils.annotation.recordset.Update; + +import java.util.Map; + +/** + *

+ * + *

create: 2023/2/21 20:31

+ * + * @author youHong.ai + */ +@SqlMapper +public interface GenerateLoginIdMapper { + + + /** + *

通过分部简称查询分部id

+ * + * @param subCompanyName 分部简称 + * @return 分部id + */ + @Select("select id from hrmsubcompany where SUBCOMPANYNAME = #{subCompanyName}") + String selectSubCompanyIdBySubCompanyName(String subCompanyName); + + /** + *

查询当前分部的人员的登录名的最后一个编号

+ * + * @param loginIdPrefix 登录名前缀 + * @param subCompanyId 分部id + * @param loginLike 登录名前缀+% + * @return 当前分部人员id和登录名编号 + */ + @Select("select id,substring(LOGINID,length(#{loginIdPrefix}) + 1) login_id_no \n" + + "from hrmresource \n" + + "where SUBCOMPANYID1 = #{subCompanyId} and LOGINID like #{loginLike} \n" + + " order by cast(substring(LOGINID,length(#{loginIdPrefix}) + 1) as decimal) \n" + + " desc limit 1") + Map selectLastLoginId( + @ParamMapper("loginIdPrefix") String loginIdPrefix, + @ParamMapper("subCompanyId") String subCompanyId, + @ParamMapper("loginLike") String loginLike + ); + + + /** + *

更新流程中的loginId字段

+ * + * @param billTable 流程表 + * @param requestId 请求id + * @param loginId 登录id + * @param loginIdField 登录id所属字段 + * @return 是否更新成功 + */ + @Update("update $t{billTable} set $t{loginIdField} = #{loginId} where requestid = #{requestId}") + boolean updateLoginId(@ParamMapper("billTable") String billTable, + @ParamMapper("requestId") String requestId, + @ParamMapper("loginId") String loginId, + @ParamMapper("loginIdField") String loginIdField); +} diff --git a/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties b/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties new file mode 100644 index 0000000..d693e16 --- /dev/null +++ b/src/main/resources/WEB-INF/prop/prop2map/PcnYunZhaoSsoRsaKey.properties @@ -0,0 +1 @@ +yunzhao.environment=test \ No newline at end of file diff --git a/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java b/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java index ceca37a..50f1450 100644 --- a/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java +++ b/src/test/java/youhong/ai/haripijiu/TestHaRiPiJiu.java @@ -20,4 +20,10 @@ public class TestHaRiPiJiu extends BaseTest { GenerateFileUtil.createActionDocument(VoucherPayableAction.class); GenerateFileUtil.createActionDocument(ReceiptAndPaymentAction.class); } + + + @Test + public void test1() { + + } } diff --git a/src/test/java/youhong/ai/pcn/RolesTest.java b/src/test/java/youhong/ai/pcn/RolesTest.java index 7dc7d3c..b063412 100644 --- a/src/test/java/youhong/ai/pcn/RolesTest.java +++ b/src/test/java/youhong/ai/pcn/RolesTest.java @@ -3,14 +3,20 @@ package youhong.ai.pcn; import aiyh.utils.GenerateFileUtil; import aiyh.utils.Util; import basetest.BaseTest; +import com.alibaba.fastjson.JSON; +import com.api.youhong.ai.pcn.ssoyunzhao.service.SsoYunZhaoService; import com.engine.common.util.ServiceUtil; import com.engine.hrm.service.impl.RolesMembersServiceImpl; +import com.google.common.base.Strings; import org.junit.Test; import weaver.hrm.User; import weaver.youhong.ai.pcn.actioin.conditionssetvalue.WorkflowConditionsSetValueAction; +import weaver.youhong.ai.pcn.actioin.generateloginid.GenerateLoginIdAction; +import weaver.youhong.ai.pcn.actioin.generateloginid.mapper.GenerateLoginIdMapper; import weaver.youhong.ai.pcn.schedule.addrolebyhasundering.RegisterRoleMemberByHasUnderingCronJob; import weaver.youhong.ai.pcn.schedule.addrolemember.RegisterRoleMemberCronJob; +import java.text.NumberFormat; import java.util.HashMap; import java.util.Map; @@ -62,10 +68,53 @@ public class RolesTest extends BaseTest { @Test public void test3() { - String value = "1"; - System.out.println(Double.parseDouble(value)); + // String value = "1"; + // System.out.println(Double.parseDouble(value)); + GenerateLoginIdMapper mapper = Util.getMapper(GenerateLoginIdMapper.class); + Map wld = mapper.selectLastLoginId("wld", "3", "wld%"); + System.out.println(JSON.toJSONString(wld)); + System.out.println(this.prefixFill(wld.get("loginIdNo"), "PCN")); } + private String prefixFill(String lastLoginIdNo, String prefix) { + NumberFormat numberFormat = NumberFormat.getInstance(); + // 禁用数字格式化分组。 + numberFormat.setGroupingUsed(false); + // 保留最小位数 + numberFormat.setMinimumIntegerDigits(Integer.parseInt("4")); + // 保留最大位数 + numberFormat.setMaximumIntegerDigits(10); + long i = 0L; + try { + if (!Strings.isNullOrEmpty(lastLoginIdNo)) { + i = Long.parseLong(lastLoginIdNo); + } + } catch (NumberFormatException ignore) { + } + long newLoginId = i + 1; + return prefix + numberFormat.format(newLoginId); + } + + + @Test + public void testsso() throws Exception { + User user = new User(22); + SsoYunZhaoService service = new SsoYunZhaoService(); + System.out.println(service.getRedirectPath(user)); + String s = service.rsaEncryptedUserInfo("test_public_decrypt@email.test.com\"1234567891011"); + System.out.println(s); + System.out.println("1234567891011".substring(0, 10)); + System.out.println(service.rsaDecryptUserInfo(s)); + + } + + + @Test + public void testToken() throws Exception { + SsoYunZhaoService service = new SsoYunZhaoService(); + String s = service.rsaDecryptUserInfo("rO76Ung4eKvIXUK5+r9s26SQ1jyBfKjjOSUaV3Wmw6ZLE/kMHD07HOraAGdKdl9B4gwbbpYinBXT/S9O/6Jj3dDL2R81PkOYG/q+dYWkTFdAn5KsItdF6mKY/4wzPd0+5axPa5KjD7LUUwxb+G+jD3x4nTRU3HYJaCxNyjeXc5ndY/zrQKUsyLPlmgTWG1LrS2enoPg+9rZKiix/81N16O9F1om/X8LmS/N5Byh9bzYXbJrBK2AeDuF83ricyLNeKW/Wh5ZUnqfKWjeeER2uDgw9hq6njkIYYw7JLXsMeyUbNKA1R1Ng2XzxuoaBo/WRix7+5phX/4wbspMb6d/nOg=="); + System.out.println(s); + } @Test public void testWorkflowConditionSetValue() { @@ -75,6 +124,6 @@ public class RolesTest extends BaseTest { @Test public void generateFile() { - GenerateFileUtil.createActionDocument(WorkflowConditionsSetValueAction.class); + GenerateFileUtil.createActionDocument(GenerateLoginIdAction.class); } } diff --git a/src/test/java/youhong/ai/pcn/Rsa.java b/src/test/java/youhong/ai/pcn/Rsa.java new file mode 100644 index 0000000..c245b66 --- /dev/null +++ b/src/test/java/youhong/ai/pcn/Rsa.java @@ -0,0 +1,73 @@ +package youhong.ai.pcn; + +import org.apache.commons.codec.binary.Base64; + +import javax.crypto.Cipher; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +public class Rsa { + + public static void main(String[] args) throws Exception { + String privateKey = + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTWNWQiLBU7v5g" + "\n" + + "HdwWodocMRH8Hz2z3ZAMOsA0ObTD3oGkfczAG+XbNY/wK6zeeosmlMR/NraOSQmf" + "\n" + + "Vzr2hdzErEHS04RDEtcCV9clWIO7lS9lVDx0ob5IR+vMjk+HdobdEimQ06gJqYzI" + "\n" + + "PprUprrv5ZwuLwlyRHwAJJwyKE/MJLWBLw2641xLAjJ4v09UM5K74uBjXszDk1Ci" + "\n" + + "MSOsEtuGYJv60KGIO50MUDK5tj8cjUfK3VzGj2ILmf7c/WISMltcnW+8O/JJqpmX" + "\n" + + "Z+mltTKqJbdHQj2ig8/BxECIS1GyWkD3q0yB8FHkA1axdJZ+fxtt6q9AIws+Fil2" + "\n" + + "pvE5GLIvAgMBAAECggEAVBhza1ZYLWFp1Tm1j0U40rY+6YJ7GNjvictOP4Bf5xpr" + "\n" + + "K5KQ9WP2wDHFwPFsbF3MZWyq6WA0uOh+kW6bvG+SHL2jo8wMxKtQA4pWxH3MUZdH" + "\n" + + "wbFd/8MAcwh5T/o48bt4JVxkVMA4O6uFKhRxEcVHE/wcM0+tOIZVr081xnqzcHL1" + "\n" + + "YSgM1aSvDQnE3ds9j0jnd0LR0W+tidpHL/J8D+yZMIGyw7wQzZ4Xo4OmSOvb1NPY" + "\n" + + "TThPyRy1m8D5vP6etiI/tKlLMkvJvr1G5EPzTb/ECkqcTerOZwSfRkUnpOgD11sa" + "\n" + + "XRzJeR3ByzFweuFipUNEToCXsrSP7gdcSfcFliDjYQKBgQDDcRT8xcJt7gWX6LFV" + "\n" + + "m8ggRBoqRgwDcr2PwW3NpcQKDKH4XhQrESFOBwEVn3vwv6NJ9NLLnOKuYbLAF1jR" + "\n" + + "4BHZJmerrUeMFTvkdoyb07tFDfZah+yx8NKlJzNaGTJr5FwqLuPXADCQtIqz4/Ql" + "\n" + + "jQWymB0BXwvyVWjU99AKorqh1QKBgQDBAMLUjYZNbk+D0LC79/G9GIZQvJdRQhuH" + "\n" + + "lzC0wlOvBy47UwvE/2RMp8R+LS9nroa+O4zRmRE160nmmvzF7mPszAI+aG3Jl64L" + "\n" + + "0ej3ynQ8ONgRRB4UBJFyzcj0Yctjk+gC9kj89DdtBdYhOfSlIfIFTv6BGH+9lvZa" + "\n" + + "+YT3FnJB8wKBgQCtjLkqTSH+JCLrZkIy1wa7QD5L06/PUBBsm0M6Hj0a/2TE/CXE" + "\n" + + "qI1+kFGyNdEFU+dYQQL+s+3HFBJ66UCB/gtbXPMqS9EA38ozceIibb4Z7/AXLCRP" + "\n" + + "Tp5+8XR0SXOwwzPkcYb44L4/gVK5s26V+chZcyIumYwuQRG6K+SdzSsVkQKBgCSw" + "\n" + + "61kTKqQPw4gQpXimk0tanTY+FBo7khY91OGYS+ZrXAulJwilcMDt5/oAxxFT6YPC" + "\n" + + "uGukSNRSTbNMZZ+PSWncAtUwbyay8kCHAF4TG/PS7qihpYIyuB/2JSzoZo0gsivV" + "\n" + + "/FwyZVMRl/qrFOpLwMHnmZSbPrWhPGZhJzj+CGynAoGAQOtCerAPjkMX83NpC/MK" + "\n" + + "DtGyGpdE/7tSw7QCuwvNlN7lm/B67a/nXTUd7vWH+sRP9HbpT+gPOhsm9fljVi0j" + "\n" + + "W3Or5jjT5n/FuA8zSr1a39BtusucOek2ATAUh5661/zJcFO3IAeUAOMRRo8NaM2M" + "\n" + + "ssgdq0nGP23DNakgVPko8+E=" + "\n"; + + String publicKey = + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk1jVkIiwVO7+YB3cFqHa" + "\n" + + "HDER/B89s92QDDrANDm0w96BpH3MwBvl2zWP8Cus3nqLJpTEfza2jkkJn1c69oXc" + "\n" + + "xKxB0tOEQxLXAlfXJViDu5UvZVQ8dKG+SEfrzI5Ph3aG3RIpkNOoCamMyD6a1Ka6" + "\n" + + "7+WcLi8JckR8ACScMihPzCS1gS8NuuNcSwIyeL9PVDOSu+LgY17Mw5NQojEjrBLb" + "\n" + + "hmCb+tChiDudDFAyubY/HI1Hyt1cxo9iC5n+3P1iEjJbXJ1vvDvySaqZl2fppbUy" + "\n" + + "qiW3R0I9ooPPwcRAiEtRslpA96tMgfBR5ANWsXSWfn8bbeqvQCMLPhYpdqbxORiy" + "\n" + + "LwIDAQAB" + "\n"; + + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + + byte[] privBuffer = Base64.decodeBase64(privateKey); + PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privBuffer); + PrivateKey privKey = keyFactory.generatePrivate(privSpec); + cipher.init(Cipher.ENCRYPT_MODE, privKey); + byte[] encrypted = cipher.doFinal("user@example.com\"1422331953".getBytes()); + + System.out.println("Encrypted with private key:"); + System.out.println(Base64.encodeBase64String(encrypted)); + + byte[] pubBuffer = Base64.decodeBase64(publicKey); + X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubBuffer); + PublicKey pubKey = keyFactory.generatePublic(pubSpec); + cipher.init(Cipher.DECRYPT_MODE, pubKey); + byte[] decrypted = cipher.doFinal(encrypted); + + System.out.println("Decrypted with public key:"); + System.out.println(new String(decrypted)); + } +} \ No newline at end of file diff --git a/view-mysql.sql b/view-mysql.sql index a74ea14..c8d6c41 100644 --- a/view-mysql.sql +++ b/view-mysql.sql @@ -1,6 +1,6 @@ -- 流程类型视图,可用于数据集成或流览按钮 create - or replace view workflow_type_info_view as +or replace view workflow_type_info_view as select wb.id, wb.workflowname, wt.typename, @@ -11,7 +11,7 @@ from workflow_base wb -- 流程表单视图,用于流览按钮或数据集成,配置流程类型表可以用字段联动获取流程表表名 create - or replace view workflow_table_view as +or replace view workflow_table_view as select base.id, base.workflowname, base.formid, @@ -22,7 +22,7 @@ from workflow_bill bill -- 流程明细表信息,可用流程主表查询对应的明细表信息,用于流览框 create - or replace view workflow_detail_table_view as +or replace view workflow_detail_table_view as select CONCAT(bill.id, '-', base.id) id, bill.id bill_id, base.id workflow_id, @@ -34,7 +34,7 @@ from workflow_billdetailtable bill -- 流程和建模字段视图,更具流程和建模的billid可以查询流程和建模中的字段信息 create - or replace view workflow_field_table_view as +or replace view workflow_field_table_view as select wb.id, wb.fieldname, concat(ht.indexdesc, ':', wb.fieldname) indexdesc, @@ -59,13 +59,14 @@ select wb.id, when wb.FIELDHTMLTYPE = '3' then '流览框' when wb.FIELDHTMLTYPE = '4' then 'check框' when wb.FIELDHTMLTYPE = '5' then '选择框' - else '附件上传' end) fieldhtmltype + else '附件上传' end) fieldhtmltype, + wb.FIELDHTMLTYPE fieldtype from workflow_billfield wb left join htmllabelindex ht on wb.fieldlabel = ht.id; -- 建模表信息视图 create - or replace view mode_bill_info_view as +or replace view mode_bill_info_view as select bill.id, bill.tablename, hti.indexdesc from workflow_bill bill left join htmllabelindex hti on hti.id = bill.namelabel @@ -74,7 +75,7 @@ where bill.id < 0 -- 流程节点信息视图 create - or replace view workflow_node_info_view as +or replace view workflow_node_info_view as select distinct nb.id, nb.nodename, (case when wb.version is null then 1 else wb.version end) version,