Commit 24d9e43f authored by 张森's avatar 张森

扫描漏洞修改

parent 6ed04012
package com.yeejoin.equipmanage.common.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @description: http https工具类 原生
* @author: duanwei
* @create: 2019-06-03 11:19
**/
public class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
// 连接超时时间
public static final int CONNECTION_TIMEOUT = 5000;
// 请求超时时间
public static final int CONNECTION_REQUEST_TIMEOUT = 5000;
// 数据读取等待超时
public static final int SOCKET_TIMEOUT = 10000;
// http
public static final String HTTP = "http";
// https
public static final String HTTPS = "https";
// http端口
public static final int DEFAULT_HTTP_PORT = 80;
// https端口
public static final int DEFAULT_HTTPS_PORT = 443;
// 默认编码
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)[默认编码:UTF-8]
*
* @param url (参数直接拼接到URL后面,即http://test.com?a=1&b=2的形式)
* @return
*/
public static String get(String url) throws IOException, URISyntaxException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
return get(url, null, DEFAULT_ENCODING);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)[默认编码:UTF-8]
*
* @param url (url不带参数,例:http://test.com)
* @param reqMap (参数放置到一个map中)
* @return
*/
public static String get(String url, Map<String, Object> reqMap) throws IOException, URISyntaxException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
return get(url, reqMap, DEFAULT_ENCODING);
}
/**
* 根据请求头选择相应的client
* https HttpUtil.createSSLInsecureClient
* http createDefault
* @param url (url不带参数,例:http://test.com)
* @return CloseableHttpClient
*/
public static CloseableHttpClient getHttpClient(String url){
CloseableHttpClient httpClient = null;
try {
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtil.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
}catch (Exception e){
log.error("请求client 初始化失败 请检查地址是否正确,url={}",url,e);
throw new RuntimeException(e);
}
return httpClient;
}
/**
* 获取post请求头
* @param url (url不带参数,例:http://test.com)
* @return HttpPost
*/
public static HttpPost getHttpPost(String url)
{
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @param encoding
* @return
*/
public static String get(String url, Map<String, Object> reqMap, String encoding) throws IOException, URISyntaxException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result = "";
// 处理参数
List<NameValuePair> params = buildParams(reqMap);
CloseableHttpResponse response = null;
HttpGet httpGet;
CloseableHttpClient httpClient=null;
try {
httpClient=getHttpClient(url);
if (params != null && params.size() > 0) {
URIBuilder builder = new URIBuilder(url);
builder.setParameters(params);
httpGet = new HttpGet(builder.build());
} else {
httpGet = new HttpGet(url);
}
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
//默认允许自动重定向
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
// 发送请求,并接收响应
response = httpClient.execute(httpGet);
result = handleResponse(url, encoding, response);
} finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return result;
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)[默认编码:UTF-8]
*
* @param url
* @param reqMap
* @return
*/
public static String post(String url, Map<String, Object> reqMap) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
return post(url, reqMap, DEFAULT_ENCODING);
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param reqMap 入参是个map
* @param encoding
* @return
*/
public static String post(String url, Map<String, Object> reqMap, String encoding) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result="";
// 添加参数
List<NameValuePair> params = buildParams(reqMap);
CloseableHttpClient httpClient=null;
CloseableHttpResponse response = null;
try {
httpClient=getHttpClient(url);
HttpPost httpPost = getHttpPost(url);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(params, encoding));
// 发送请求,并接收响应
response = httpClient.execute(httpPost);
result = handleResponse(url, encoding, response);
log.info("http调用完成,返回数据:{}", result);
}finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return result;
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param jsonParams 入参是个json字符串
* @return
*/
public static String post(String url, String jsonParams) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
log.info("----->调用请求 url:{} ---->json参数:{}",url,jsonParams);
return post(url, jsonParams, DEFAULT_ENCODING);
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param jsonParams 入参是个json字符串
* @param encoding
* @return
*/
public static String post(String url, String jsonParams, String encoding) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result;
CloseableHttpClient httpClient;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtil.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
try {
HttpPost httpPost = getHttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", encoding)));
// 发送请求,并接收响应
response = httpClient.execute(httpPost);
result = handleResponse(url, encoding, response);
// result= JSONObject.parseObject(result).getString("data");
} finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return result;
}
/**
* 创建一个SSL信任所有证书的httpClient对象
*
* @return
*/
public static CloseableHttpClient createSSLInsecureClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// 默认信任所有证书
HostnameVerifier hostnameVerifier = (hostname, session) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
/**
* 处理响应,获取响应报文
*
* @param url
* @param encoding
* @param response
* @return
* @throws IOException
*/
private static String handleResponse(String url, String encoding, CloseableHttpResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
if (response != null) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
br = new BufferedReader(new InputStreamReader(entity.getContent(), encoding));
String s;
while ((s = br.readLine()) != null) {
sb.append(s);
}
}
// 释放entity
EntityUtils.consume(entity);
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
log.info("-----> get请求404,未找到资源. url:" + url);
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
log.info("-----> get请求500,服务器端异常. url:" + url);
}
}
} finally {
ExtendedIOUtils.closeQuietly(br);
}
return sb.toString();
}
private static List<NameValuePair> buildParams(Map<String, Object> reqMap) {
List<NameValuePair> params = new ArrayList<>();
if (reqMap != null && reqMap.keySet().size() > 0) {
Iterator<Map.Entry<String, Object>> iter = reqMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entity = iter.next();
params.add(new BasicNameValuePair(entity.getKey(), entity.getValue().toString()));
}
}
return params;
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
// 信任所有证书
return new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
}
}
package com.yeejoin.equipmanage.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.equipmanage.common.config.GlobalCache;
import com.yeejoin.equipmanage.common.vo.ResponeVo;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @description: HTTP HTTPS 二次封装
* @author: duanwei
* @create: 2020-05-28 13:57
**/
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
// 连接超时时间
public static final int CONNECTION_TIMEOUT = 5000;
// 请求超时时间
public static final int CONNECTION_REQUEST_TIMEOUT = 5000;
// 数据读取等待超时
public static final int SOCKET_TIMEOUT = 10000;
// http
public static final String HTTP = "http";
// https
public static final String HTTPS = "https";
// http端口
public static final int DEFAULT_HTTP_PORT = 80;
// https端口
public static final int DEFAULT_HTTPS_PORT = 443;
// 默认编码
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* 根据请求头选择相应的client
* https HttpUtil.createSSLInsecureClient
* http createDefault
*
* @param url (url不带参数,例:http://test.com)
* @return CloseableHttpClient
*/
private static CloseableHttpClient getHttpClient(String url) {
CloseableHttpClient httpClient = null;
try {
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
} catch (Exception e) {
log.error("请求client 初始化失败 请检查地址是否正确,url=" + url + " error" + e);
throw new RuntimeException(e);
}
return httpClient;
}
/**
* 获取post请求头
*
* @param url (url不带参数,例:http://test.com)
* @return HttpPost
*/
public static HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
*/
public static ResponeVo get(String url) throws IOException {
log.info("----->调用请求 url:" + url);
String result = "";
// 处理参数
HttpGet httpGet;
CloseableHttpClient httpClient = null;
httpClient = getHttpClient(url);
httpGet = new HttpGet(url);
//加入请求头
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpGet.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpGet.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECTION_TIMEOUT)
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
//默认允许自动重定向
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
return baseRequest(httpClient, httpGet);
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param jsonParams 入参是个json字符串
* @return
*/
public static ResponeVo post(String url, String jsonParams) throws IOException,
NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result;
CloseableHttpClient httpClient;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPost httpPost = getHttpPost(url);
if (GlobalCache.header != null && !GlobalCache.header.isEmpty()) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPost.setHeader(key, value);
}
} else {
GlobalCache.header.put("Content-Type", "application/json;charset=UTF-8");
}
//加入全局请求令牌权限
httpPost.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
log.error("请求头为空");
}
return baseRequest(httpClient, httpPost);
}
/**
* post请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url
* @param jsonParams 入参是个json字符串
* @return
*/
public static ResponeVo post(String url, String jsonParams, Map<String, String> headerMap) throws IOException,
NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
Assert.hasText(url, "url invalid");
String result;
CloseableHttpClient httpClient;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPost httpPost = getHttpPost(url);
if (GlobalCache.header != null && !GlobalCache.header.isEmpty()) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPost.setHeader(key, value);
}
} else {
GlobalCache.header.put("Content-Type", "application/json;charset=UTF-8");
}
//加入全局请求令牌权限
if (!headerMap.isEmpty()) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
} else {
httpPost.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
}
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
log.error("请求头为空");
}
return baseRequest(httpClient, httpPost);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @return
*/
public static ResponeVo delete(String url) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
HttpDelete httpDelete = new HttpDelete(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpDelete.setHeader(key, value);
}
}
httpDelete.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
return baseRequest(httpClient, httpDelete);
}
/**
* get请求(1.处理http请求;2.处理https请求,信任所有证书)
*
* @param url (只能是http或https请求)
* @return
*/
public static ResponeVo put(String url, String jsonParams) throws IOException, NoSuchAlgorithmException,
KeyStoreException, KeyManagementException {
log.info("----->调用请求 url:" + url + " ---->json参数:" + jsonParams);
CloseableHttpClient httpClient = null;
String content;
if (url.startsWith(HTTPS)) {
// 创建一个SSL信任所有证书的httpClient对象
httpClient = HttpUtils.createSSLInsecureClient();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
if (GlobalCache.header != null) {
for (String key : GlobalCache.header.keySet()) {
String value = GlobalCache.header.get(key);
httpPut.setHeader(key, value);
}
}
//加入全局请求令牌权限
httpPut.setHeader("Http-Authorization", GlobalCache.paramMap.get("token"));
if (GlobalCache.header.get("Content-Type") != null) {
String contentType = GlobalCache.header.get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType)) {
JSONObject jsonObject = JSONObject.parseObject(jsonParams);
List<NameValuePair> params = new ArrayList<>();
//循环json key value 仅能解决正常对象 若Json对象中嵌套数组 则可能需要单独处理
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
httpPut.setEntity(new UrlEncodedFormEntity(params, DEFAULT_ENCODING));
}
}
if ("application/json;charset=UTF-8".equals(contentType)) {
httpPut.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", DEFAULT_ENCODING)));
}
} else {
log.error("请求头为空");
}
return baseRequest(httpClient, httpPut);
}
private static List<NameValuePair> buildParams(Map<String, Object> reqMap) {
List<NameValuePair> params = new ArrayList<>();
if (reqMap != null && reqMap.keySet().size() > 0) {
Iterator<Map.Entry<String, Object>> iter = reqMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entity = iter.next();
params.add(new BasicNameValuePair(entity.getKey(), entity.getValue().toString()));
}
}
return params;
}
/**
* 创建一个SSL信任所有证书的httpClient对象
*
* @return
*/
public static CloseableHttpClient createSSLInsecureClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// 默认信任所有证书
HostnameVerifier hostnameVerifier = (hostname, session) -> true;
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
/**
* 绕过验证
*
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
// 信任所有证书
return new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (arg0, arg1) -> true).build();
}
private static String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
log.error(e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
public static ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
try {
String content;
response = httpClient.execute(request);
content = inputStreamToString(response.getEntity().getContent());
responeVo.setCode(response.getStatusLine().getStatusCode());
responeVo.setContent(content);
responeVo.setResponse(response);
log.info("http调用完成,返回数据" + content);
} catch (Exception e) {
log.error(" http调用失败:" + e);
}
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
}
...@@ -231,17 +231,7 @@ public class WlCarMileageController { ...@@ -231,17 +231,7 @@ public class WlCarMileageController {
} }
/**
* 获取轨迹
*
* @return
*/
@RequestMapping(value = "/travel", method = RequestMethod.GET)
@ApiOperation(httpMethod = "GET", value = "获取轨迹", notes = "获取轨迹")
@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
public List<Coordinate> travel(long id) {
return iWlCarMileageService.getCoordinateList(id);
}
/** /**
* 获取日历 * 获取日历
......
...@@ -21,7 +21,6 @@ public interface IWlCarMileageService extends IService<WlCarMileage> { ...@@ -21,7 +21,6 @@ public interface IWlCarMileageService extends IService<WlCarMileage> {
Double totalMileage(String iotCode); Double totalMileage(String iotCode);
List<Coordinate> getCoordinateList(long id);
Map<String,Boolean> getCalender(long id,Date date); Map<String,Boolean> getCalender(long id,Date date);
......
...@@ -13,7 +13,6 @@ import com.yeejoin.equipmanage.common.entity.CarSpeedWarningRecord; ...@@ -13,7 +13,6 @@ import com.yeejoin.equipmanage.common.entity.CarSpeedWarningRecord;
import com.yeejoin.equipmanage.common.entity.WlCarMileage; import com.yeejoin.equipmanage.common.entity.WlCarMileage;
import com.yeejoin.equipmanage.common.utils.CoordinateUtil; import com.yeejoin.equipmanage.common.utils.CoordinateUtil;
import com.yeejoin.equipmanage.common.utils.DateUtils; import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.common.utils.HttpUtil;
import com.yeejoin.equipmanage.common.utils.RedisUtil; import com.yeejoin.equipmanage.common.utils.RedisUtil;
import com.yeejoin.equipmanage.controller.Coordinate; import com.yeejoin.equipmanage.controller.Coordinate;
import com.yeejoin.equipmanage.fegin.IotFeign; import com.yeejoin.equipmanage.fegin.IotFeign;
...@@ -69,7 +68,6 @@ import java.util.stream.Collectors; ...@@ -69,7 +68,6 @@ import java.util.stream.Collectors;
@EnableAsync @EnableAsync
public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlCarMileage> public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlCarMileage>
implements IWlCarMileageService { implements IWlCarMileageService {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
private final String GUIDE_KEY = "8d2ab194d72e88d3636e9d721814333a"; private final String GUIDE_KEY = "8d2ab194d72e88d3636e9d721814333a";
private final String GUIDE_URL = "https://restapi.amap.com/v4/grasproad/driving?"; private final String GUIDE_URL = "https://restapi.amap.com/v4/grasproad/driving?";
private final String GUIDE_ADDRESS_URL = "https://restapi.amap.com/v3/geocode/regeo?"; private final String GUIDE_ADDRESS_URL = "https://restapi.amap.com/v3/geocode/regeo?";
...@@ -132,137 +130,6 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC ...@@ -132,137 +130,6 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
return this.baseMapper.totalMileage(iotCode); return this.baseMapper.totalMileage(iotCode);
} }
@Override
public List<Coordinate> getCoordinateList(long id) {
double speed = 0;
WlCarMileage wlCarMileage = this.getById(id);
String iotCode = wlCarMileage.getIotCode();
String measurement = iotCode.substring(0, 8);
String deviceName = iotCode.replace(measurement, "");
// 由于iot存在毫秒故结束时间要+1秒 iot+1秒有bug还是查不到 +2秒
ResponseModel<List<Object>> result = iotFeign.getLiveData(measurement, deviceName, wlCarMileage.getStartTime(),
new Date(wlCarMileage.getEndTime().getTime()));
List<Object> list = result.getResult();
List<Coordinate> coordinateList = new ArrayList<Coordinate>();
if (list != null) {
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
for (Object object : list) {
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object));
if (jsonObject.get("FireCar_Longitude") != null && jsonObject.get("FireCar_Latitude") != null) {
Coordinate coordinate = new Coordinate();
List<Double> lnglat = new ArrayList<Double>();
lnglat.add(jsonObject.getDoubleValue("FireCar_Longitude"));
lnglat.add(jsonObject.getDoubleValue("FireCar_Latitude"));
coordinate.setLnglat(lnglat);
coordinate.setSpeed(jsonObject.getDoubleValue("fireCar_Speed"));
speed = speed + jsonObject.getDoubleValue("fireCar_Speed");
String time = jsonObject.getString("time");
if (time.length() > 20) {
try {
coordinate.setTime(format1.parse(jsonObject.getString("time")).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
} else {
try {
coordinate.setTime(format2.parse(jsonObject.getString("time")).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
}
double direction = jsonObject.getDoubleValue("direction");
if (!ObjectUtils.isEmpty(direction)) {
coordinate.setDirection(jsonObject.getDoubleValue("direction"));
} else {
coordinate.setDirection(0);
}
coordinateList.add(coordinate);
}
}
}
// 倒序坐标变为正序
Collections.reverse(coordinateList);
// 坐标轨迹纠偏
double avgSpeed = speed / coordinateList.size();
double count = Double.valueOf(coordinateList.size()) / 500;
int ceil = (int) Math.ceil(count);
ArrayList<Coordinate> resultList = new ArrayList<>();
for (int i = 1; i <= ceil; i++) {
if (i == ceil) {
List<Coordinate> coordinates = coordinateList.subList(500 * (i - 1), coordinateList.size());
List<Coordinate> check = check(coordinates, avgSpeed);
resultList.addAll(check);
} else {
List<Coordinate> coordinates = coordinateList.subList(500 * (i - 1), 500 + (i - 1) * 500);
List<Coordinate> check = check(coordinates, avgSpeed);
resultList.addAll(check);
}
}
return resultList;
}
private List<Coordinate> check(List<Coordinate> list, double avgSpeed) {
ArrayList<Coordinate> coordinates = new ArrayList<>();
JSONArray objects = new JSONArray();
int count = 0;
for (Coordinate coordinate : list) {
JSONObject jsonObject = new JSONObject();
// 经度
jsonObject.put("x", coordinate.getLnglat().get(0));
// 纬度
jsonObject.put("y", coordinate.getLnglat().get(1));
// 角度
jsonObject.put("ag", coordinate.getDirection());
// 速度
jsonObject.put("sp", coordinate.getSpeed() > 0 ? coordinate.getSpeed() : avgSpeed);
// 时间
if (count == 0) {
jsonObject.put("tm", coordinate.getTime() / 1000);
} else {
jsonObject.put("tm", 3 * count);
}
count += 1;
objects.add(jsonObject);
}
String s = objects.toJSONString();
StringBuilder api = new StringBuilder(GUIDE_URL);
api.append("key=").append(GUIDE_KEY);
String result = null;
try {
result = HttpUtil.post(api.toString(), s);
} catch (IOException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
e.printStackTrace();
}
if (result != null) {
Map<String, Object> jsonObject = (Map<String, Object>) JSONObject.parseObject(result);
//判断是否坐标不满足高德地图纠偏需求
if (jsonObject.containsKey("errcode") && jsonObject.get("errcode").toString().equals("30001")) {
return list;
}
if (jsonObject.containsKey("data")) {
JSONObject data3 = JSONObject.parseObject(jsonObject.get("data").toString());
JSONArray points1 = JSONArray.parseArray(data3.get("points").toString());
// for (int i = 0; i < points1.size(); i++) {
// JSONObject jsonObject1 = JSONObject.parseObject(points1.get(i).toString());
// List<Double> doubles = new ArrayList<>();
// Coordinate coordinate = new Coordinate();
// doubles.add(Double.valueOf(jsonObject1.get("x").toString()));
// doubles.add(Double.valueOf(jsonObject1.get("y").toString()));
// coordinate.setLnglat(doubles);
// Double speeed = getSpeedByOriginalData(objects, Double.valueOf(jsonObject1.get("x").toString()), Double.valueOf(jsonObject1.get("y").toString()));
// coordinate.setSpeed(speeed);
// coordinates.add(coordinate);
// }
coordinates = giveSpeedToCoordinate(objects, points1);
}
}
return coordinates;
}
@Override @Override
public Map<String, Boolean> getCalender(long id, Date date) { public Map<String, Boolean> getCalender(long id, Date date) {
...@@ -314,16 +181,12 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC ...@@ -314,16 +181,12 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
@Scheduled(cron = "${mileage.segmentation.cron}") @Scheduled(cron = "${mileage.segmentation.cron}")
@Async @Async
public void mileageSegmentation() { public void mileageSegmentation() {
log.info("轨迹切分定时任务开始执行时间.............{}", LocalDateTime.now());
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTime(new Date()); cal.setTime(new Date());
cal.add(Calendar.DATE, -1); cal.add(Calendar.DATE, -1);
String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
log.info("轨迹切分定时任务数据过滤时间.............{}", nowDate);
List<WlCarMileage> list = this.baseMapper.list(nowDate); List<WlCarMileage> list = this.baseMapper.list(nowDate);
log.info("需要切分数据, {}", list);
log.info("销毁所有坐标信息成功");
log.info("------------------跨天轨迹切分任开始切分里程-------------------------------");
list.forEach(item -> { list.forEach(item -> {
redisTemplate.delete(item.getIotCode()); redisTemplate.delete(item.getIotCode());
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
...@@ -393,10 +256,8 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC ...@@ -393,10 +256,8 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
item.setTravel(new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue()); item.setTravel(new BigDecimal(travel / 1000).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
item.setTakeTime(takeTime); item.setTakeTime(takeTime);
this.getBaseMapper().updateById(item); this.getBaseMapper().updateById(item);
log.info("-----------跨天轨迹切分任更新车辆坐标成功:::" + JSONObject.toJSONString(item) + "-----------------"); }
}
}); });
log.info("-------------------跨天轨迹切分任务执行完成..............");
//删除过期的告警数据 //删除过期的告警数据
Date endTime = DateUtil.offsetDay(new Date(),-15); Date endTime = DateUtil.offsetDay(new Date(),-15);
String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:00"); String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:00");
...@@ -474,12 +335,10 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC ...@@ -474,12 +335,10 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
} else { } else {
this.getBaseMapper().deleteById(item.getId()); this.getBaseMapper().deleteById(item.getId());
} }
log.info("-----------正常结束轨迹更新车辆坐标成功:::" + JSONObject.toJSONString(item) + "-----------------"); }
}
} }
}); });
log.info("轨迹切分任务执行完成..............");
//删除无效的告警数据 //删除无效的告警数据
Date endTime = DateUtil.offsetMinute(new Date(),-10); Date endTime = DateUtil.offsetMinute(new Date(),-10);
String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:00"); String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:00");
...@@ -588,12 +447,9 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC ...@@ -588,12 +447,9 @@ public class WlCarMileageServiceImpl extends ServiceImpl<WlCarMileageMapper, WlC
Double travel1 = CoordinateUtil.distance(startLatitude, startLongitude, jsonObject1.getDoubleValue("x"), jsonObject1.getDoubleValue("y")); Double travel1 = CoordinateUtil.distance(startLatitude, startLongitude, jsonObject1.getDoubleValue("x"), jsonObject1.getDoubleValue("y"));
Double travel2 = CoordinateUtil.distance(startLatitude, startLongitude, jsonObject2.getDoubleValue("x"), jsonObject2.getDoubleValue("y")); Double travel2 = CoordinateUtil.distance(startLatitude, startLongitude, jsonObject2.getDoubleValue("x"), jsonObject2.getDoubleValue("y"));
log.info("travel1:" + travel1 + "travel2:" + travel2);
if (travel2 > travel1) { if (travel2 > travel1) {
log.info("travel1:" + travel1 + "travel2:" + travel2); speed = jsonObject1.getDoubleValue("sp");
log.info("lat:" + startLatitude + "long:" + startLongitude);
log.info("lat:" + jsonObject1.getDoubleValue("x") + "long:" + jsonObject1.getDoubleValue("y"));
speed = jsonObject1.getDoubleValue("sp");
break; break;
} else { } else {
speed = jsonObject2.getDoubleValue("sp"); speed = jsonObject2.getDoubleValue("sp");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment