IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 重新传输的后端实现 -> 正文阅读

[Java知识库]重新传输的后端实现

重新传输的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;
    }

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-16 22:07:36  更:2022-03-16 22:09:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 9:12:50-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码