重新传输的Controller实现
@RequestMapping(value = "/retransmissionByPlanId",method = RequestMethod.GET)
@ApiOperation("通过计划id重新传输")
public ServiceResult retransmissionByPlanId(String planId){
// 确认下流程
return planService.retransmissionByPlanId(planId);
}
批量重新传输的Controller实现
@RequestMapping(value = "/retransmissionByPlanIdBatch",method = RequestMethod.POST)
@ApiOperation("批量通过计划id重新传输")
public ServiceResult retransmissionByPlanIdBatch(@RequestBody String [] planIdArray){
return planService.retransmissionByPlanIdBatch(planIdArray);
}
重新传输的 ServiceImpl 实现
@Override
public ServiceResult retransmissionByPlanId(String planId) {
ServiceResult result = new ServiceResult(false);
Map<String,Object> param = new HashMap<>();
param.put("planID",planId);
List<Map<String,Object>> list = mapper.select(param);
if (null!=list && list.size()>0){
Map <String,Object> messageMap = new HashMap<>();
String messageBody= getDataNotifyParam(list.get(0));
messageMap.put("appKey","");
messageMap.put("bizCode","");
messageMap.put("message",messageBody);
String mqUrl = config.getMqApi()+"send";
clientConfiguration.sendPost(mqUrl,JSON.toJSONString(messageMap, SerializerFeature.WriteMapNullValue));
result.setSuccess(true);
}else {
result.setMessage("重新传输失败");
}
return null;
}
public String getDataNotifyParam(Map<String,Object> data ) {
Map<String,Object> conditionMap = new HashMap<>();
Map<String,Object> dataNotifyParam = new HashMap<>();
JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data));
conditionMap.put("planID",data.get("planID").toString());
List<Map<String,Object>> result = taskMapper.queryTaskDetailConditionList(conditionMap);
if(null!=result&& result.size()>0){
JSONObject taskJsonObject = JSONObject.parseObject(JSON.toJSONString(result.get(0)));
dataNotifyParam.put("requireTaskID",taskJsonObject.getString("requireTaskID"));
dataNotifyParam.put("taskID",taskJsonObject.getString("taskID"));
}else {
dataNotifyParam.put("requireTaskID","");
dataNotifyParam.put("taskID","");
}
dataNotifyParam.put("planID",jsonObject.getInteger("planID"));
dataNotifyParam.put("antenna",jsonObject.getString("antenna"));
dataNotifyParam.put("satellite",jsonObject.getString("satellite"));
dataNotifyParam.put("fileList",jsonObject.getString("fileList"));
dataNotifyParam.put("receiveResult","FALSE");
return JSON.toJSONString(dataNotifyParam, SerializerFeature.WriteMapNullValue);
}
Config工具类
package cn.piesat.sar.base;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Data
@Component
public class Config {
// @Value("${account.url}")
// private String authUrl;
@Value("${mq.api}")
private String mqApi;
}
clientConfiguration工具类
package cn.piesat.sar.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.http.*;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.*;
import org.apache.http.conn.HttpConnectionFactory;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.HttpMessageParserFactory;
import org.apache.http.io.HttpMessageWriterFactory;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.LineParser;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
@Component
public class ClientConfiguration {
private final Logger logger = LoggerFactory.getLogger(ClientConfiguration.class);
CloseableHttpClient httpclient;
PoolingHttpClientConnectionManager connManager;
RequestConfig defaultRequestConfig;
public ClientConfiguration() {
HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
@Override
public HttpMessageParser<HttpResponse> create(
SessionInputBuffer buffer, MessageConstraints constraints) {
LineParser lineParser = new BasicLineParser() {
@Override
public Header parseHeader(final CharArrayBuffer buffer) {
try {
return super.parseHeader(buffer);
} catch (ParseException ex) {
return new BasicHeader(buffer.toString(), null);
}
}
};
return new DefaultHttpResponseParser(
buffer, lineParser, DefaultHttpResponseFactory.INSTANCE, constraints) {
@Override
protected boolean reject(final CharArrayBuffer line, int count) {
return false;
}
};
}
};
HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
requestWriterFactory, responseParserFactory);
try {
SSLContext sslcontext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslConnectionSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry, connFactory);
SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.build();
connManager.setDefaultSocketConfig(socketConfig);
connManager.setValidateAfterInactivity(1000);
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
this.defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(20000)
.setConnectTimeout(20000)
.setConnectionRequestTimeout(20000)
.setCookieSpec(CookieSpecs.DEFAULT)
.setExpectContinueEnabled(true)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Collections.singletonList(AuthSchemes.BASIC))
.build();
this.httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
public JSONObject get(String url, Map<String, Object> paramMap) {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpget = new HttpGet(url);
httpget.setConfig(this.defaultRequestConfig);
if (!StringUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httpget.addHeader(key, paramMap.get(key).toString());
}
}
response = httpclient.execute(httpget, HttpClientContext.create());
JSONObject jsonObject = null;
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
if (httpget != null) {
try {
httpget.clone();
} catch (Exception e) {
logger.error("catch Exception:", e);
}
}
}
}
public Integer getResultCode(String url) {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpget = new HttpGet(url);
httpget.setConfig(this.defaultRequestConfig);
response = httpclient.execute(httpget, HttpClientContext.create());
return response.getStatusLine().getStatusCode();
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
if (httpget != null) {
try {
httpget.clone();
} catch (Exception e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSONObject sendGet(String url, Map<String, Object> paramMap) {
HttpGet httpget = null;
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
List<NameValuePair> paramList = new LinkedList<>();
for (String key : paramMap.keySet()) {
Object value = paramMap.get(key);
if (value != null) {
paramList.add(new BasicNameValuePair(key, value.toString()));
}
}
uriBuilder.setParameters(paramList);
CloseableHttpClient httpclient = this.httpclient;
httpget = new HttpGet(uriBuilder.build());
httpget.setConfig(this.defaultRequestConfig);
response = httpclient.execute(httpget, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
logger.info("http请求" + url + "结果状态码为:" + statusCode);
JSONObject jsonObject = null;
if (statusCode == 200) {
String contentType = response.getEntity().getContentType().getValue();
if (contentType.contains("image")) {
int imageSize = (int) response.getEntity().getContentLength();
if (imageSize > 0) {
byte imageData[] = new byte[imageSize];
response.getEntity().getContent().read(imageData);
Map<String, byte[]> tmp = new HashMap<>();
tmp.put("image", imageData);
jsonObject = JSON.parseObject(JSON.toJSONString(tmp));
}
} else {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
}
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSONObject sendPost(String url, String body) {
HttpPost httppost = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httppost = new HttpPost(url);
httppost.setConfig(this.defaultRequestConfig);
httppost.addHeader("Content-Type", "application/json");
httppost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
response = httpclient.execute(httppost, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
logger.info("http请求" + url + "结果状态码为:" + statusCode);
JSONObject jsonObject;
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
logger.error("http请求" + url + "结果状态码为:", statusCode);
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSONObject sendPost(String url, Map<String, Object> paramMap, String body) {
HttpPost httppost = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httppost = new HttpPost(url);
httppost.setConfig(this.defaultRequestConfig);
httppost.addHeader("Content-Type", "application/json");
if (!CollectionUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httppost.addHeader(key, paramMap.get(key).toString());
}
}
httppost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
response = httpclient.execute(httppost, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
JSONObject jsonObject;
logger.info("http请求" + url + "结果状态码为:" + statusCode);
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSONObject sendPut(String url, Map<String, Object> paramMap, String body) {
HttpPut httpPut = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpPut = new HttpPut(url);
httpPut.setConfig(this.defaultRequestConfig);
httpPut.addHeader("Content-Type", "application/json");
if (!CollectionUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httpPut.addHeader(key, paramMap.get(key).toString());
}
}
if (!StringUtils.isEmpty(body)) {
httpPut.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
}
response = httpclient.execute(httpPut, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
JSONObject jsonObject;
logger.info("http请求" + url + "结果状态码为:" + statusCode);
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
public JSONObject sendDelete(String url, Map<String, Object> paramMap) {
HttpDelete httpDelete = null;
CloseableHttpResponse response = null;
try {
CloseableHttpClient httpclient = this.httpclient;
httpDelete = new HttpDelete(url);
httpDelete.setConfig(this.defaultRequestConfig);
httpDelete.addHeader("Content-Type", "application/json");
if (!CollectionUtils.isEmpty(paramMap)) {
for (String key : paramMap.keySet()) {
httpDelete.addHeader(key, paramMap.get(key).toString());
}
}
response = httpclient.execute(httpDelete, HttpClientContext.create());
int statusCode = response.getStatusLine().getStatusCode();
JSONObject jsonObject;
logger.info("http请求" + url + "结果状态码为:" + statusCode);
if (statusCode == 200) {
jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()), Feature.OrderedField);
} else {
jsonObject = null;
}
return jsonObject;
} catch (Exception e) {
logger.error("catch Exception:", e);
return null;
} finally {
if (response != null) {
try {
response.getEntity().getContent().close();
} catch (IOException e) {
logger.error("catch Exception:", e);
}
}
}
}
}
批量重新传输的ServiceImpl实现
@Override
public ServiceResult retransmissionByPlanIdBatch(String[] planIdArray) {
ServiceResult result = new ServiceResult(false);
if(planIdArray.length==0 || null==planIdArray){
result.setMessage("参数缺失");
return result;
}
for(int i=0;i<planIdArray.length;i++){
String planId = planIdArray[i] ;
result = retransmissionByPlanId(planId);
}
return result;
}
|