重新传输的后端实现

重新传输的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());
    //通过planid获取 任务数据
    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() {
        // Use custom message parser / writer to customize the way HTTP
        // messages are parsed from and written out to the data stream.
        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) {
                        // try to ignore all garbage preceding a status line infinitely
                        return false;
                    }

                };
            }

        };
        HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

        // Use a custom connection factory to customize the process of
        // initialization of outgoing HTTP connections. Beside standard connection
        // configuration parameters HTTP connection factory can define message
        // parser / writer routines to be employed by individual connections.
        HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
                requestWriterFactory, responseParserFactory);

        // Client HTTP connection objects when fully initialized can be bound to
        // an arbitrary network socket. The process of network socket initialization,
        // its connection to a remote address and binding to a local one is controlled
        // by a connection socket factory.

        // SSL context for secure connections can be created either based on
        // system or application specific properties.

        try {
            SSLContext sslcontext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();

            // Create a registry of custom connection socket factories for supported
            // protocol schemes.
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, hostnameVerifier);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", sslConnectionSocketFactory)
                    .build();
            // Create a connection manager with custom configuration.
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry, connFactory);

            // Create socket configuration
            SocketConfig socketConfig = SocketConfig.custom()
                    .setTcpNoDelay(true)
                    .build();
            // Configure the connection manager to use socket configuration either
            // by default or for a specific host.
            connManager.setDefaultSocketConfig(socketConfig);
            // Validate connections after 1 sec of inactivity
            connManager.setValidateAfterInactivity(1000);

            // Create message constraints
            MessageConstraints messageConstraints = MessageConstraints.custom()
                    .setMaxHeaderCount(200)
                    .setMaxLineLength(2000)
                    .build();
            // Create connection configuration
            ConnectionConfig connectionConfig = ConnectionConfig.custom()
                    .setMalformedInputAction(CodingErrorAction.IGNORE)
                    .setUnmappableInputAction(CodingErrorAction.IGNORE)
                    .setCharset(Consts.UTF_8)
                    .setMessageConstraints(messageConstraints)
                    .build();
            // Configure the connection manager to use connection configuration either
            connManager.setDefaultConnectionConfig(connectionConfig);

            // Configure total max or per route limits for persistent connections
            // that can be kept in the pool or leased by the connection manager.
            connManager.setMaxTotal(100);
            connManager.setDefaultMaxPerRoute(10);

            // Create global request configuration
            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);
                }
            }
        }
    }


    /**
     * 获取get请求的返回码
     *
     * @param url
     * @return
     */
    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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值