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/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/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/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/WorkflowConditionsSetValueAction.java index 32b0635..51e8442 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 @@ -4,6 +4,7 @@ import aiyh.utils.Util; import aiyh.utils.action.SafeCusBaseAction; import aiyh.utils.annotation.*; import aiyh.utils.excention.CustomerException; +import com.alibaba.fastjson.JSON; import com.google.common.base.Strings; import ebu7common.youhong.ai.bean.Builder; import lombok.Getter; @@ -12,6 +13,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 +33,7 @@ public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { @RequiredMark("流程条件赋值配置表唯一标识字段值") @PrintParamMark - @ActionDefaultTestValue("test") + @ActionDefaultTestValue("getdata") private String onlyMark; @ActionOptionalParam(desc = "条件修改所在明细表,1-明细1,2-明细2", value = "") @@ -54,14 +56,15 @@ 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); @@ -71,7 +74,7 @@ public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { 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) @@ -89,6 +92,8 @@ public class WorkflowConditionsSetValueAction extends SafeCusBaseAction { .build()); } } + log.info("条件值: " + JSON.toJSONString(main)); + log.info("条件值: " + JSON.toJSONString(detail)); service.updateWorkflowDetailData(main, billTable, null); service.updateWorkflowDetailData(detail, billTable + "_dt" + detailNo, detailNo); } catch (Exception e) { @@ -101,6 +106,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/service/WorkflowConditionsSetValueService.java b/src/main/java/weaver/youhong/ai/pcn/actioin/conditionssetvalue/service/WorkflowConditionsSetValueService.java index ada3399..90218dd 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,7 @@ package weaver.youhong.ai.pcn.actioin.conditionssetvalue.service; import aiyh.utils.Util; import aiyh.utils.tool.Assert; +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 +29,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 +65,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; + } + /** *

更新明细表数据

* @@ -94,6 +101,9 @@ public class WorkflowConditionsSetValueService { StringBuilder sb = new StringBuilder("update "); sb.append(billTable).append(" set "); for (Map.Entry entry : updateBatchData.get(0).entrySet()) { + if (entry.getKey().equals("_id_")) { + continue; + } sb.append(entry.getKey()) .append(" = #{item.") .append(entry.getKey()) 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..082a0e9 --- /dev/null +++ b/src/main/java/weaver/youhong/ai/pcn/actioin/generateloginid/GenerateLoginIdAction.java @@ -0,0 +1,94 @@ +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 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(Integer.parseInt(numberFillQuantity)); + int newLoginId = Integer.parseInt(lastLoginIdNo) + 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..8051418 --- /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} 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/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..245fac3 100644 --- a/src/test/java/youhong/ai/pcn/RolesTest.java +++ b/src/test/java/youhong/ai/pcn/RolesTest.java @@ -8,6 +8,7 @@ import com.engine.hrm.service.impl.RolesMembersServiceImpl; 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.schedule.addrolebyhasundering.RegisterRoleMemberByHasUnderingCronJob; import weaver.youhong.ai.pcn.schedule.addrolemember.RegisterRoleMemberCronJob; @@ -75,6 +76,6 @@ public class RolesTest extends BaseTest { @Test public void generateFile() { - GenerateFileUtil.createActionDocument(WorkflowConditionsSetValueAction.class); + GenerateFileUtil.createActionDocument(GenerateLoginIdAction.class); } } 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,