Browse Source

Merge branch 'dev' of http://192.168.1.220:10080/Amoy2/wlyy2.0 into dev

liubing 3 years ago
parent
commit
5b6a55a309

+ 1 - 0
svr/svr-cloud-device/src/main/java/com/yihu/jw/care/service/OnenetService.java

@ -154,6 +154,7 @@ public class OnenetService {
                    String psk = jsonObject.getJSONObject("data").getString("psk");
                    device.setDeviceId(deviceId);
                    device.setPsk(psk);
                    device.setCreateTime(new Date());
                    onenetDevices.add(device);
                }
            }catch (Exception e){

+ 2 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/SvrCloudTransforApplication.java

@ -5,12 +5,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
/**
 * Created by yeshijie on 2021/10/14.
 */
@SpringBootApplication
@ComponentScan("com.yihu")
@EnableAsync
public class SvrCloudTransforApplication extends SpringBootServletInitializer {
    public static void main(String[] args)  {

+ 42 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/config/AsyncConfig.java

@ -0,0 +1,42 @@
package com.yihu.jw.care.config;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: yeshijie
 * @Date: 2021/4/30
 * @Description: 异步线程配置
 */
@Configuration
public class AsyncConfig {
    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(20);
        // 设置队列容量
        executor.setQueueCapacity(200);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("user-transfor-");
        // 设置拒绝策略
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        // 等待所有任务结束后再关闭线程池
//        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}

+ 111 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/controller/BaseController.java

@ -0,0 +1,111 @@
package com.yihu.jw.care.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 *
 */
public class BaseController {
    private static Logger logger = LoggerFactory.getLogger("error_logger");
    /**
     * 获取request中body数据
     */
    public String getRequestBodyData(HttpServletRequest request) throws IOException {
        BufferedReader bufferReader = new BufferedReader(request.getReader());
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = bufferReader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @return
     */
    public String error(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("code", code);
            map.put("msg", msg);
            map.put("success", false);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 接口处理成功
     * @return
     */
    public String success() {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("code", 200);
            map.put("success", true);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public String write(int code, String msg) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("code", code);
            map.put("msg", msg);
            map.put("success", true);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 返回接口处理结果
     *
     * @param code  结果码,成功为200
     * @param msg   结果提示信息
     * @param value 结果数据
     * @return
     */
    public String write(int code, String msg, String key, Object value) {
        try {
            Map<Object, Object> map = new HashMap<Object, Object>();
            ObjectMapper mapper = new ObjectMapper();
            map.put("code", code);
            map.put("msg", msg);
            map.put(key, value);
            return mapper.writeValueAsString(map);
        } catch (Exception e) {
            error(e);
            return error(-1, "服务器异常,请稍候再试!");
        }
    }
    public void error(Exception e) {
        e.printStackTrace();
    }
}

+ 104 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/controller/OnenetController.java

@ -0,0 +1,104 @@
package com.yihu.jw.care.controller;
import com.yihu.jw.care.service.OnenetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * Created with IntelliJ IDEA.
 * onenet平台验证无法请求杭州服务器 只能转发
 * @Author: yeshijie
 * @Date: 2021/10/20
 * @Description:
 */
@RestController
@RequestMapping("/siterwelldevice")
@Api(value = "onenet设备相关服务", description = "onenet设备相关服务")
public class OnenetController extends BaseController{
    private static Logger logger = LoggerFactory.getLogger(OnenetController.class);
    @Autowired
    private OnenetService onenetService;
    /**
     * 功能描述:第三方平台数据接收。<p>
     *           <ul>注:
     *               <li>1.OneNet平台为了保证数据不丢失,有重发机制,如果重复数据对业务有影响,数据接收端需要对重复数据进行排除重复处理。</li>
     *               <li>2.OneNet每一次post数据请求后,等待客户端的响应都设有时限,在规定时限内没有收到响应会认为发送失败。
     *                    接收程序接收到数据时,尽量先缓存起来,再做业务逻辑处理。</li>
     *           </ul>
     * @param body 数据消息
     * @return 任意字符串。OneNet平台接收到http 200的响应,才会认为数据推送成功,否则会重发。
     */
    @RequestMapping(value = "receive",method = RequestMethod.POST)
    public String receive(@RequestBody String body) throws Exception {
        logger.info("data receive:  body String --- " +body);
        /************************************************
         *  解析数据推送请求,非加密模式。
         *  如果是明文模式使用以下代码
         **************************************************/
        /*************明文模式  start****************/
        onenetService.receive(body);
        /*************明文模式  end****************/
        /********************************************************
         *  解析数据推送请求,加密模式
         *
         *  如果是加密模式使用以下代码
         ********************************************************/
        /*************加密模式  start****************/
//        Util.BodyObj obj1 = Util.resolveBody(body, true);
//        logger.info("data receive:  body Object--- " +obj1);
//        if (obj1 != null){
//            boolean dataRight1 = Util.checkSignature(obj1, token);
//            if (dataRight1){
//                String msg = Util.decryptMsg(obj1, aeskey);
//                logger.info("data receive: content" + msg);
//            }else {
//                logger.info("data receive:  signature error " );
//            }
//        }else {
//            logger.info("data receive: body empty error" );
//        }
        /*************加密模式  end****************/
        return "ok";
    }
    /**
     * 功能说明: URL&Token验证接口。如果验证成功返回msg的值,否则返回其他值。
     * @param msg 验证消息
     * @param nonce 随机串
     * @param signature 签名
     * @return msg值
     */
    @RequestMapping(value = "receive", method = RequestMethod.GET)
    public String check(@RequestParam(value = "msg") String msg,
                        @RequestParam(value = "nonce") String nonce,
                        @RequestParam(value = "signature") String signature) throws Exception {
        logger.info("url&token check: msg:{} nonce{} signature:{}",msg,nonce,signature);
        return msg;
    }
    @ApiOperation("触发器消息通知接收--废弃")
    @RequestMapping(value = "triggerMessage",method = {RequestMethod.POST,RequestMethod.GET})
    public String triggerMessage(@RequestBody String body) {
        try {
            logger.info("======================:"+body);
            return success();
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1,"Device data incoming failure");
        }
    }
}

+ 26 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/service/OnenetService.java

@ -0,0 +1,26 @@
package com.yihu.jw.care.service;
import com.yihu.jw.care.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
 * Created by yeshijie on 2021/10/20.
 */
@Service
public class OnenetService {
    private Logger logger = LoggerFactory.getLogger(AqgService.class);
    private static final String baseUrl = "https://zhyzh.gongshu.gov.cn/device/";
//    private static final String baseUrl = "http://ehr.yihu.com/wlyy/aqg";
    @Async
    public void receive(String body){
        String url = baseUrl + "siterwelldevice/receive";
        String result = HttpClientUtil.postBodyStr(url,body);
        logger.info(url+","+result);
    }
}

+ 138 - 0
svr/svr-cloud-transfor/src/main/java/com/yihu/jw/care/util/HttpClientUtil.java

@ -0,0 +1,138 @@
package com.yihu.jw.care.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class HttpClientUtil {
	/**
	 * 发送post请求
	 * @param url 请求地址
	 * @param params 请求参数
	 * @param chatSet 编码格式
	 * @return
	 */
	public static String post(String url, List<NameValuePair> params, String chatSet) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 创建httppost
		HttpPost httppost = new HttpPost(url);
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(params, chatSet);
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 发送get请求
	 * @param url 请求地址
	 * @param chatSet 编码格式
	 * @return
	 */
	public static String get(String url, String chatSet) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url);
			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					return EntityUtils.toString(entity, chatSet);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	public static String postBodyStr(String url, String params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params, headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	public static String postBody(String url, JSONObject params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		String ret = restTemplate.postForObject(url, formEntity, String.class);
		return ret;
	}
	public static void putBody(String url,JSONObject params){
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>(params.toString(), headers);
		restTemplate.put(url, formEntity, String.class);
	}
}