esb文件上传

This commit is contained in:
lvleigang 2024-12-09 15:45:16 +08:00
parent f73d39fe1c
commit ffb86f43fa
4 changed files with 417 additions and 2 deletions

View File

@ -309,6 +309,7 @@ public interface ISysApplicationService extends IBaseService<SysApplicationEntit
JsonResultEntity enableOrDisableAppDatasource(JSONObject jsonObject);
JsonResultEntity externalCallInterface(ServletRequest servletRequest, ServletResponse servletResponse);
JsonResultEntity externalCallInterfacefileUpload(ServletRequest servletRequest, ServletResponse servletResponse);
JsonResultEntity externalCallInterfaceResend(SysMessageManageLogEntity resendLogEntity);

View File

@ -55,23 +55,31 @@ import com.hzya.frame.web.action.ApplicationContextUtil;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
@ -1687,7 +1695,6 @@ public class SysApplicationServiceImpl extends BaseService<SysApplicationEntity,
@Override
@DSTransactional()
public JsonResultEntity externalCallInterface(ServletRequest servletRequest, ServletResponse servletResponse) {
//例如A应用发送数据到中台中台转发到B应用
HttpServletRequest request = (HttpServletRequest) servletRequest;
String oldbodys = ServletUtil.getBody(servletRequest);
@ -2071,6 +2078,392 @@ public class SysApplicationServiceImpl extends BaseService<SysApplicationEntity,
}
}
/**
* @param servletRequest
* @param servletResponse
* @return com.hzya.frame.web.entity.JsonResultEntity
* @Author lvleigang
* @Description 外部系统调用接口
* @Date 4:21 下午 2023/10/19
**/
@Override
@DSTransactional()
public JsonResultEntity externalCallInterfacefileUpload(ServletRequest servletRequest, ServletResponse servletResponse) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) servletRequest;
// 获取普通表单参数
HttpServletRequest request = (HttpServletRequest) servletRequest;
Map<String, String> oldheaderMap = ServletUtil.getHeaderMap(request);
//应用key
String publicKey = request.getHeader("publicKey");
//应用密钥
String secretKey = request.getHeader("secretKey");
//appId
String appId = request.getHeader("appId");
//apiCode
String apiCode = request.getHeader("apiCode");
Enumeration<String> bodyname = multipartRequest.getParameterNames();
JSONObject bodysss = new JSONObject();
if (bodyname.hasMoreElements()) {
while (bodyname.hasMoreElements()) {
String headerName = bodyname.nextElement();
String headerValue = multipartRequest.getParameter(headerName);
bodysss.put( headerName,headerValue);
}
}
String oldquerys = multipartRequest.getQueryString();
String oldbodys = bodysss.toJSONString();
Iterator<String> filenemes = multipartRequest.getFileNames();
Map<String, List<MultipartFile>> files = new HashMap<>();
if (filenemes.hasNext()) {
filenemes.forEachRemaining(element -> files.put(element,multipartRequest.getFiles(element)));
}
String ip = IPHelper.getIpAddr(multipartRequest);
if (publicKey == null || "".equals(publicKey)) {
return BaseResult.getFailureMessageEntity("请先传递公钥");
}
if (secretKey == null || "".equals(secretKey)) {
return BaseResult.getFailureMessageEntity("请先传递密钥");
}
if (appId == null || "".equals(appId)) {
return BaseResult.getFailureMessageEntity("请先传递接收方应用");
}
if (apiCode == null || "".equals(apiCode)) {
return BaseResult.getFailureMessageEntity("请先传递发送接口");
}
logger.info("请求参数publicKey" + publicKey + "】secretKey" + secretKey + "】appId" + appId + "】apiCode" + apiCode);
//根据请求a应用的公钥密钥是否能查找到一条数据
SysApplicationEntity sendApp = getAppByPublicKeySecretKey(publicKey, secretKey);
if (sendApp == null) {
return BaseResult.getFailureMessageEntity("公钥、密钥错误,请联系管理员");
}
//判断应用是否启用
if (sendApp.getAppStatus() == null || !"1".equals(sendApp.getAppStatus())) {
saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,sendApp.getName() + "应用未启用");
return BaseResult.getFailureMessageEntity(sendApp.getName() + "应用未启用,请联系管理员");
}
SysApplicationEntity receiveApp = getAppByAppId(appId);
if (receiveApp == null) {
saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"根据appId:" + appId + "未匹配到应用");
return BaseResult.getFailureMessageEntity("根据appId:" + appId + "未匹配到应用,请联系管理员");
}
//判断应用是否启用
if (receiveApp.getAppStatus() == null || !"1".equals(receiveApp.getAppStatus())) {
saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用未启用" );
return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用未启用,请联系管理员");
}
//判断应用接口是否启用
if (receiveApp.getInterfaceStatus() == null || !"1".equals(receiveApp.getInterfaceStatus())) {
saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用接口环境未启用" );
return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用接口环境未启用,请联系管理员");
}
SysApplicationApiEntity receiveApi = getApiByAppIdApiCode(receiveApp.getId(), apiCode);
if (receiveApi == null) {
saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + ":" + apiCode + "未启用或者未创建" );
return BaseResult.getFailureMessageEntity(receiveApp.getName() + ":" + apiCode + "未启用或者未创建");
}
SysApplicationApiAuthEntity sysApplicationApiAuthEntity = getApiAuthByNameAppId(sendApp.getId(), receiveApp.getId());
if (sysApplicationApiAuthEntity == null) {
saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用权限配置错误" );
return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用权限配置错误");
}
if (sysApplicationApiAuthEntity.getSystemAddress() != null && !"".equals(sysApplicationApiAuthEntity.getSystemAddress())
&& !sysApplicationApiAuthEntity.getSystemAddress().contains(ip)) {
saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误" );
return BaseResult.getFailureMessageEntity(receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误");
}
SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = getApiAuthDetailByAppIdApiIdTripartiteSystemId(receiveApp.getId(), receiveApi.getId(), sysApplicationApiAuthEntity.getId());
if (sysApplicationApiAuthDetailEntity == null) {
saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApi.getApiName() + "未授权给" + sendApp.getName() );
return BaseResult.getFailureMessageEntity(receiveApi.getApiName() + "未授权给" + sendApp.getName() + ",请联系管理员");
}
SysExtensionApiEntity sysExtensionApiEntity = new SysExtensionApiEntity();
List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
Map<String, String> headers = new HashMap<>();
if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
if (jsonArray != null && jsonArray.size() > 0) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject object1 = jsonArray.getJSONObject(i);
headers.put(object1.getString("parameterName"), object1.getString("example"));
}
}
}
if (oldheaderMap != null && oldheaderMap.size() > 0) {
for (Map.Entry<String, String> entry : oldheaderMap.entrySet()) {
if (!a.contains(entry.getKey())) {
headers.put(entry.getKey(), entry.getValue());
}
}
}
sysExtensionApiEntity.setSendApp(sendApp);
sysExtensionApiEntity.setReceiveApp(receiveApp);
sysExtensionApiEntity.setReceiveApi(receiveApi);
sysExtensionApiEntity.setHeaders(headers);
sysExtensionApiEntity.setQuerys(oldquerys);
sysExtensionApiEntity.setBodys(oldbodys);
Method[] methods = null;
Object object = null;
// 判断是否有内部api 是否扩展api 1启用 2停用
if (receiveApi.getExtensionApi() != null && "1".equals(receiveApi.getExtensionApi())
&& receiveApi.getBeanName() != null && !"".equals(receiveApi.getBeanName())
&& receiveApi.getFunName() != null && !"".equals(receiveApi.getFunName())
) {
//获取类
try {
object = ApplicationContextUtil.getBeanByName(receiveApi.getBeanName());
} catch (SecurityException e) {
}
//获取类下面的方法
methods = object.getClass().getMethods();
if (methods == null || methods.length == 0) {
return BaseResult.getFailureMessageEntity("未找到内部方法,请联系管理员");
}
for (Method m : methods) {
if (null != m) {
if (m.getName().equals(receiveApi.getFunName().trim())) {
try {
logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
sysExtensionApiEntity = (SysExtensionApiEntity) m.invoke(object, sysExtensionApiEntity);
logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
break;
} catch (Exception e) {
logger.error("invokeException{}", e.getMessage());
return BaseResult.getFailureMessageEntity("内部方法执行错误,请联系管理员");
}
}
}
}
}
headers = sysExtensionApiEntity.getHeaders();
String querys = sysExtensionApiEntity.getQuerys();
String bodys = sysExtensionApiEntity.getBodys();
//设置参数获取参数
StringBuffer url = new StringBuffer();
if(!receiveApi.getDestinationAddress().toLowerCase().startsWith("http")){
url.append(receiveApp.getInterfaceAddress());
}
url.append(receiveApi.getDestinationAddress());
if (querys != null) {
url.append("?");
url.append(querys);
}
Integer outTime = 6000;
if (receiveApi.getTimeoutPeriod() != null && !"".equals(receiveApi.getTimeoutPeriod())) {
outTime = Integer.valueOf(receiveApi.getTimeoutPeriod());
}
//1POST 2GET
String method = "POST";
if ("2".equals(receiveApi.getRequestMethod())) {
method = "GET";
}
if ("POST".equals(method)) {
StringBuilder body = new StringBuilder();
boolean flag = true;
try {
HttpPost httpPost = new HttpPost(url.toString());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if(!files.isEmpty()){
for (Map.Entry<String, List<MultipartFile>> entry : files.entrySet()) {
String key = entry.getKey();
List<MultipartFile> multipartFile = entry.getValue();
if(multipartFile != null && multipartFile.size() > 0){
for (int i = 0; i < multipartFile.size(); i++) {
File file = new File(multipartFile.get(i).getOriginalFilename());
Files.write(Paths.get(file.getAbsolutePath()), multipartFile.get(i).getBytes());
builder.addBinaryBody(key, file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
}
}
}
}
if (headers != null && headers.size() > 0) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
//if (bodys != null && !"".equals(bodys)) {
// builder.addTextBody("fileFlag", "true", ContentType.TEXT_PLAIN);
// builder.addTextBody("businessType", "application", ContentType.TEXT_PLAIN);
//}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = null;
response = HttpClientBuilder.create().build().execute(httpPost);
HttpEntity entity1 = response.getEntity();
synchronized (lock) {
body.append(EntityUtils.toString(entity1,"UTF-8"));
}
flag = true;
logger.info("返回结果:" + body);
} catch (Exception e) {
logger.error("请求错误:" + e.getMessage());
body.append(e.getMessage());
flag = false;
}
logger.info("保存日志开始");
SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(),true,null);
if (methods != null && methods.length > 0) {
for (Method m : methods) {
if (null != m) {
if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
try {
logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
m.invoke(object, sysMessageManageLogEntity);
logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
} catch (Exception e) {
logger.error("invokeException{}", e.getMessage());
}
}
}
}
}
logger.info("保存日志结束");
if (flag) {
if (JSONUtil.isTypeJSON(body.toString())) {
JSONObject jsonObject = JSONObject.parseObject(body.toString());
if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
}else {
if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
return BaseResult.getFailureMessageEntity("转发失败:"+sysMessageManageLogEntity.getReturnMsg(), jsonObject);
}else {
return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
}
}
} else {
if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
return BaseResult.getSuccessMessageEntity("转发成功", body);
}else {
if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
return BaseResult.getFailureMessageEntity("转发失败:"+sysMessageManageLogEntity.getReturnMsg(), body);
}else {
return BaseResult.getFailureMessageEntity("转发失败", body);
}
}
}
} else {
if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
return BaseResult.getFailureMessageEntity("转发失败:"+sysMessageManageLogEntity.getReturnMsg(), body);
}else {
return BaseResult.getFailureMessageEntity("转发失败", body);
}
}
} else {//GET
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
HttpGet get = new HttpGet(url.toString());
CloseableHttpResponse response = null;
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).build();
get.setConfig(requestConfig);//设置请求参数超时时间
if (headers != null && headers.size() > 0) {
for (String key : headers.keySet()) {
get.setHeader(key, headers.get(key));
}
}
StringBuilder body = new StringBuilder();
boolean flag = true;
try {
response = closeableHttpClient.execute(get);
HttpEntity entity = response.getEntity();
synchronized (lock) {
body.append(EntityUtils.toString(entity,"UTF-8"));
}
flag = true;
logger.info("返回结果:" + body);
} catch (Exception e) {
logger.error("请求错误:" + e.getMessage());
body.append(e.getMessage());
flag = false;
} finally {
try {
// 关闭响应对象
if (response != null) {
response.close();
}
// 关闭响应对象
if (closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("保存日志开始");
SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(), true,null);
if (methods != null && methods.length > 0) {
for (Method m : methods) {
if (null != m) {
if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
try {
logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
m.invoke(object, sysMessageManageLogEntity);
logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
} catch (Exception e) {
logger.error("invokeException{}", e.getMessage());
}
}
}
}
}
logger.info("保存日志结束");
if (flag) {
if (JSONUtil.isTypeJSON(body.toString())) {
JSONObject jsonObject = JSONObject.parseObject(body.toString());
if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
}else {
if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
return BaseResult.getFailureMessageEntity("转发失败:"+sysMessageManageLogEntity.getReturnMsg(), jsonObject);
}else {
return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
}
}
} else {
if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
return BaseResult.getSuccessMessageEntity("转发成功", body);
}else {
if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
return BaseResult.getFailureMessageEntity("转发失败:"+sysMessageManageLogEntity.getReturnMsg(), body);
}else {
return BaseResult.getFailureMessageEntity("转发失败", body);
}
}
}
} else {
return BaseResult.getFailureMessageEntity("转发失败", body);
}
}
}
@Override
@DSTransactional()
public JsonResultEntity externalCallInterfaceResend(SysMessageManageLogEntity resendLogEntity) {

View File

@ -102,7 +102,17 @@ public class EntranceController {
logger.info("-------------------结束调用上传文件upload接口-------------------");
return jsonResultEntity;
}
/***
* 文件上传接口
* @param
* @return@@
*/
@RequestMapping(value = "/fileUploadlist", method = RequestMethod.POST)
@ResponseBody
public JsonResultEntity fileUploadlist(MultipartFile[] file, FileUploadDto entity, ServletRequest servletRequest, ServletResponse servletResponse) {
entity.getBusinessType();
return BaseResult.getSuccessMessageEntity("gc");
}
@RequestMapping(value = "/pluginfileUpload", method = RequestMethod.POST)
@ResponseBody
public JsonResultEntity pluginfileUpload(MultipartFile file, FileUploadDto entity,String pluginPackageName, ServletRequest servletRequest, ServletResponse servletResponse) {
@ -195,6 +205,12 @@ public class EntranceController {
return sysApplicationService.externalCallInterface(servletRequest,servletResponse);
}
@RequestMapping(value = "/externalCallInterfacefileUpload")
@ResponseBody
public JsonResultEntity externalCallInterfacefileUpload(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
return sysApplicationService.externalCallInterfacefileUpload(servletRequest,servletResponse);
}
@RequestMapping(value = "/externalCallInterfaceResend")
@ResponseBody
public JsonResultEntity externalCallInterfaceResend(SysMessageManageLogEntity resendLogEntity) throws Exception {

View File

@ -114,6 +114,11 @@
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>