搭建智慧城乡项目,并实现mq消息订阅,websocket推送报警信息等功能
This commit is contained in:
20
src/main/java/com/xkrs/SmartUrbanRuralApplication.java
Normal file
20
src/main/java/com/xkrs/SmartUrbanRuralApplication.java
Normal file
@ -0,0 +1,20 @@
|
||||
package com.xkrs;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.jms.annotation.EnableJms;
|
||||
|
||||
/**
|
||||
* 启动类
|
||||
* @author XinYi Song
|
||||
**/
|
||||
@SpringBootApplication
|
||||
//启动消息队列
|
||||
@EnableJms
|
||||
public class SmartUrbanRuralApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SmartUrbanRuralApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
70
src/main/java/com/xkrs/common/config/BeanConfig.java
Normal file
70
src/main/java/com/xkrs/common/config/BeanConfig.java
Normal file
@ -0,0 +1,70 @@
|
||||
package com.xkrs.common.config;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 14:16
|
||||
*/
|
||||
import org.apache.activemq.ActiveMQConnectionFactory;
|
||||
import org.apache.activemq.command.ActiveMQQueue;
|
||||
import org.apache.activemq.command.ActiveMQTopic;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jms.config.JmsListenerContainerFactory;
|
||||
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
|
||||
import org.springframework.jms.core.JmsMessagingTemplate;
|
||||
import javax.jms.ConnectionFactory;
|
||||
import javax.jms.Queue;
|
||||
import javax.jms.Topic;
|
||||
|
||||
@Configuration
|
||||
public class BeanConfig {
|
||||
|
||||
@Value("${spring.activemq.broker-url}")
|
||||
private String brokerUrl;
|
||||
|
||||
@Value("${spring.activemq.user}")
|
||||
private String username;
|
||||
|
||||
@Value("${spring.activemq.topic-name}")
|
||||
private String password;
|
||||
|
||||
@Value("${spring.activemq.topic-name}")
|
||||
private String topicName;
|
||||
|
||||
@Value("${spring.activemq.topic-name1}")
|
||||
private String topicName1;
|
||||
|
||||
@Bean(name = "topic")
|
||||
public Topic topic() {
|
||||
return new ActiveMQTopic(topicName);
|
||||
}
|
||||
|
||||
@Bean(name = "topic1")
|
||||
public Topic topic1() {
|
||||
return new ActiveMQTopic(topicName1);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConnectionFactory connectionFactory(){
|
||||
return new ActiveMQConnectionFactory(username, password, brokerUrl);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public JmsMessagingTemplate jmsMessageTemplate(){
|
||||
return new JmsMessagingTemplate(connectionFactory());
|
||||
}
|
||||
|
||||
/**
|
||||
* 在Topic模式中,对消息的监听需要对containerFactory进行配置
|
||||
* @param connectionFactory
|
||||
* @return
|
||||
*/
|
||||
@Bean("topicListener")
|
||||
public JmsListenerContainerFactory<?> topicJmsListenerContainerFactory(ConnectionFactory connectionFactory){
|
||||
SimpleJmsListenerContainerFactory factory = new SimpleJmsListenerContainerFactory();
|
||||
factory.setConnectionFactory(connectionFactory);
|
||||
factory.setPubSubDomain(true);
|
||||
return factory;
|
||||
}
|
||||
}
|
23
src/main/java/com/xkrs/common/config/CorsConfig.java
Normal file
23
src/main/java/com/xkrs/common/config/CorsConfig.java
Normal file
@ -0,0 +1,23 @@
|
||||
package com.xkrs.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 系统跨域配置
|
||||
* @author tajochen
|
||||
*/
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
|
||||
@Resource
|
||||
private CorsInterceptor corsInterceptor;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(corsInterceptor);
|
||||
}
|
||||
}
|
29
src/main/java/com/xkrs/common/config/CorsInterceptor.java
Normal file
29
src/main/java/com/xkrs/common/config/CorsInterceptor.java
Normal file
@ -0,0 +1,29 @@
|
||||
package com.xkrs.common.config;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* 跨域处理
|
||||
* @author tajochen
|
||||
*/
|
||||
@Component
|
||||
public class CorsInterceptor implements HandlerInterceptor {
|
||||
|
||||
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
|
||||
//添加跨域CORS
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Credentials", "false");
|
||||
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
|
||||
response.setHeader("Access-Control-Allow-Headers", "Content-Type , Authorization," +
|
||||
"Accept,Origin,X-Requested-With");
|
||||
response.setHeader("Access-Control-Max-Age", "216000");
|
||||
response.setHeader("Content-Type","application/json;charset=UTF-8");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
37
src/main/java/com/xkrs/common/config/MvcConfig.java
Normal file
37
src/main/java/com/xkrs/common/config/MvcConfig.java
Normal file
@ -0,0 +1,37 @@
|
||||
package com.xkrs.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* WebMVC配置
|
||||
* @author Tajochen
|
||||
*/
|
||||
@Configuration
|
||||
public class MvcConfig implements WebMvcConfigurer {
|
||||
|
||||
/**
|
||||
* 放行跨域请求
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOrigins("*")
|
||||
.allowedMethods("*")
|
||||
.allowedHeaders("*");
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时任务线程池更改,防止多个任务并行
|
||||
*/
|
||||
@Bean
|
||||
public TaskScheduler taskScheduler() {
|
||||
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(5);
|
||||
return scheduler;
|
||||
}
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
package com.xkrs.common.encapsulation;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 输出信息对象
|
||||
* @author tajochen
|
||||
* @param <T>
|
||||
*/
|
||||
public class EncapsulationObejct<T> implements Serializable {
|
||||
|
||||
/**
|
||||
* 状态码
|
||||
*/
|
||||
int status;
|
||||
|
||||
/**
|
||||
* 提示信息
|
||||
*/
|
||||
String msg;
|
||||
|
||||
/**
|
||||
* 数据
|
||||
*/
|
||||
T data;
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "EncapsulationObejct{" +
|
||||
"status=" + status +
|
||||
", msg='" + msg + '\'' +
|
||||
", data=" + data +
|
||||
'}';
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package com.xkrs.common.encapsulation;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.validation.FieldError;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* 输出信息封装
|
||||
* @author tajochen
|
||||
*/
|
||||
@Component
|
||||
public class OutputEncapsulation {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(OutputEncapsulation.class);
|
||||
|
||||
/**
|
||||
* 读取多国语言文件
|
||||
* @return
|
||||
*/
|
||||
public static MessageSource messageSource() {
|
||||
Properties properties = new Properties();
|
||||
// 使用ClassLoader加载properties配置文件生成对应的输入流
|
||||
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
|
||||
// 使用properties对象加载输入流
|
||||
try {
|
||||
properties.load(in);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
|
||||
messageSource.setBasename("i18n/messages");
|
||||
messageSource.setDefaultEncoding("UTF-8");
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* 封装输出数据
|
||||
* @param promptMessageEnum
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static String outputEncapsulationObject(PromptMessageEnum promptMessageEnum, Object obj, Locale locale) {
|
||||
|
||||
EncapsulationObejct encapsulationObejct = new EncapsulationObejct();
|
||||
encapsulationObejct.setStatus(promptMessageEnum.getCode());
|
||||
encapsulationObejct.setMsg(messageSource().getMessage(promptMessageEnum.getText(),null,locale));
|
||||
encapsulationObejct.setData(obj);
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
// 忽略无法转换的对象
|
||||
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
|
||||
// 忽略json字符串中不识别的属性
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
|
||||
JavaTimeModule javaTimeModule = new JavaTimeModule();
|
||||
objectMapper.registerModule(javaTimeModule);
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
String strByEo = "";
|
||||
try {
|
||||
strByEo = objectMapper.writeValueAsString(encapsulationObejct);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
logger.warn(e.toString());
|
||||
}
|
||||
return strByEo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出请求值检验错误信息
|
||||
* @param fieldErrors
|
||||
* @return
|
||||
*/
|
||||
public static String outputEncapsulationErrorList(List<FieldError> fieldErrors, Locale locale){
|
||||
List<String> errorMsg = new ArrayList<>();
|
||||
for (FieldError fieldError : fieldErrors) {
|
||||
String errMessage = fieldError.getDefaultMessage().subSequence(1,fieldError.getDefaultMessage().length()-1).toString();
|
||||
errorMsg.add(messageSource().getMessage(errMessage,null,locale));
|
||||
}
|
||||
return outputEncapsulationObject(PromptMessageEnum.PARAM_ILLEGAL,errorMsg,locale);
|
||||
}
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package com.xkrs.common.encapsulation;
|
||||
|
||||
/**
|
||||
* 提示信息枚举
|
||||
* @author tajochen
|
||||
*/
|
||||
public enum PromptMessageEnum{
|
||||
|
||||
// 执行成功
|
||||
SUCCESS(0, "sys.message.success"),
|
||||
|
||||
|
||||
// 用户权限错误或非法操作: 1001-1999
|
||||
USER_NOT_LOGGED(1001, "sys.message.user.not_logged_in"),
|
||||
USER_LOGIN_ERROR(1002, "sys.message.user.login_error"),
|
||||
USER_ACCOUNT_FORBIDDEN(1003, "sys.message.user.account_forbidden"),
|
||||
USER_ACCOUNT_NOT_ACTIVATED(1004, "sys.message.user.account_not_activated"),
|
||||
USER_HAS_OVERTIME(1005, "sys.message.user.overtime"),
|
||||
USER_NO_PERMISSION(1006,"sys.message.user.no_permission"),
|
||||
USER_ALREADY_LOGGED(1007, "sys.message.user.already_logged"),
|
||||
|
||||
// 请求参数错误或非法:2001-2999
|
||||
PARAM_NULL(2001, "sys.message.param.null"),
|
||||
PARAM_ILLEGAL(2002, "sys.message.param.illegal"),
|
||||
|
||||
// 数据返回错误:3001-3999
|
||||
DATA_NONE(3001, "sys.message.data.none"),
|
||||
|
||||
DATA_WRONG(3002, "sys.message.data.wrong"),
|
||||
DATA_EXIT(3003,"sys.message.exit"),
|
||||
|
||||
// 操作失败:4001-4999
|
||||
PROCESS_FAIL(4001,"sys.message.process.fail"),
|
||||
PROCESS_OVERTIME(4002,"sys.message.process.overtime"),
|
||||
FILE_EXISTS(4003,"sys.message.file.exists"),
|
||||
FILE_WRITE_ERROR(4004,"sys.message.file.write.error"),
|
||||
FILE_READ_ERROR(4005,"sys.message.file.read.error"),
|
||||
|
||||
// 系统内部错误或异常:5001-5999
|
||||
SYSTEM_INNER_ERROR(5001,"sys.message.system.inner_error"),
|
||||
SYSTEM_ABNORMAL(5002,"sys.message.system.abnormal"),
|
||||
SYSTEM_BUSY(5003,"sys.message.system.busy"),
|
||||
SYSTEM_MAINTAIN(5004,"sys.message.system.maintain"),
|
||||
|
||||
// 数据库错误:6001-6999
|
||||
DATABASE_ERROR(6001,"sys.message.database.error");
|
||||
|
||||
private int code;
|
||||
|
||||
private String text;
|
||||
|
||||
private PromptMessageEnum(int code,String text) {
|
||||
this.code = code;
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return this.text;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
}
|
48
src/main/java/com/xkrs/common/tools/GetTokenTool.java
Normal file
48
src/main/java/com/xkrs/common/tools/GetTokenTool.java
Normal file
@ -0,0 +1,48 @@
|
||||
package com.xkrs.common.tools;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.xkrs.util.Md5Util;
|
||||
import com.xkrs.util.RequestUtil;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 8:41
|
||||
*/
|
||||
public class GetTokenTool {
|
||||
public static String getToken(){
|
||||
String url1 = "https://111.26.161.203:443/admin/API/accounts/authorize";
|
||||
String json1 = "{\n" +
|
||||
" \"userName\": system,\n" +
|
||||
" \"ipAddress\": \"\",\n" +
|
||||
" \"clientType\": \"WINPC\"\n" +
|
||||
"}";
|
||||
// 第一次鉴权
|
||||
String doPostJson = RequestUtil.doPostJson(url1, json1);
|
||||
Map map = JackSonTool.json2map(doPostJson);
|
||||
String randomKey = (String) map.get("randomKey");
|
||||
|
||||
String admin123 = Md5Util.stringToMd5("admin123");
|
||||
String stringToMd5 = Md5Util.stringToMd5("system" + admin123);
|
||||
String toMd5 = Md5Util.stringToMd5(stringToMd5);
|
||||
String md5 = Md5Util.stringToMd5("system:" + "DSS:" + toMd5);
|
||||
String signature = Md5Util.stringToMd5(md5 + ":" + randomKey);
|
||||
|
||||
String url2 = "https://111.26.161.203:443/admin/API/accounts/authorize";
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("userName","system");
|
||||
jsonObject.put("randomKey",randomKey);
|
||||
jsonObject.put("mac","");
|
||||
jsonObject.put("encryptType","MD5");
|
||||
jsonObject.put("ipAddress","");
|
||||
jsonObject.put("signature",signature);
|
||||
jsonObject.put("clientType","WINPC");
|
||||
// 第二次鉴权
|
||||
String postJson = RequestUtil.doPostJson(url2, jsonObject.toString());
|
||||
Map map1 = JackSonTool.json2map(postJson);
|
||||
String token = (String) map1.get("token");
|
||||
return token;
|
||||
}
|
||||
}
|
58
src/main/java/com/xkrs/common/tools/GetVideoTool.java
Normal file
58
src/main/java/com/xkrs/common/tools/GetVideoTool.java
Normal file
@ -0,0 +1,58 @@
|
||||
package com.xkrs.common.tools;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xkrs.util.RequestUtil;
|
||||
|
||||
/**
|
||||
* 获取视频连接
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/9 16:25
|
||||
*/
|
||||
public class GetVideoTool {
|
||||
|
||||
public static String getVideo() throws JsonProcessingException {
|
||||
String token = GetTokenTool.getToken();
|
||||
String url = "https://111.26.161.203:443/admin/API/SS/Record/GetAlarmRecords?token=" + token;
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("clientType","WINPC_V1");
|
||||
jsonObject.put("clientMac","30:9c:23:79:40:08");
|
||||
jsonObject.put("clientPushId","");
|
||||
jsonObject.put("project","PSDK");
|
||||
jsonObject.put("method","SS.Record.GetAlarmRecords");
|
||||
JSONObject jsonObject1 = new JSONObject();
|
||||
jsonObject1.put("alarmCode","{8348AB45-93EF-E14B-BD85-F8FCB737C655}");
|
||||
jsonObject1.put("optional","/admin/API/SS/Record/GetAlarmRecords");
|
||||
jsonObject.put("data",jsonObject1);
|
||||
String s = RequestUtil.doPostJson(url, jsonObject.toString());
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readTree(s);
|
||||
JsonNode data = jsonNode.get("data");
|
||||
JsonNode records = data.get("records").get(0);
|
||||
|
||||
String urlVideo = "/admin/API/SS/Playback/StartPlaybackByFile?token=" + token;
|
||||
JSONObject jsonObject2 = new JSONObject();
|
||||
jsonObject2.put("ssId",records.get("ssId").asText());
|
||||
jsonObject2.put("optional",urlVideo);
|
||||
jsonObject2.put("fileName",records.get("recordName").asText());
|
||||
jsonObject2.put("startTime",records.get("startTime").asText());
|
||||
jsonObject2.put("endTime",records.get("endTime").asText());
|
||||
jsonObject2.put("recordType",records.get("recordType").asText());
|
||||
jsonObject2.put("diskId",records.get("diskId").asText());
|
||||
jsonObject2.put("recordSource",records.get("recordSource").asText());
|
||||
jsonObject2.put("channelId",records.get("channelId").asText());
|
||||
jsonObject2.put("streamId",records.get("streamId").asText());
|
||||
jsonObject2.put("enableRtsps","0");
|
||||
jsonObject2.put("nvrId","");
|
||||
JSONObject jsonObject3 = new JSONObject();
|
||||
jsonObject3.put("data",jsonObject2);
|
||||
String s1 = RequestUtil.doPostJson("https://111.26.161.203:443"+urlVideo, jsonObject3.toString());
|
||||
ObjectMapper objectMapper1 = new ObjectMapper();
|
||||
JsonNode jsonNode1 = objectMapper1.readTree(s1);
|
||||
JsonNode data1 = jsonNode1.get("data");
|
||||
String url1 = data1.get("url").asText();
|
||||
return url1;
|
||||
}
|
||||
}
|
174
src/main/java/com/xkrs/common/tools/JackSonTool.java
Normal file
174
src/main/java/com/xkrs/common/tools/JackSonTool.java
Normal file
@ -0,0 +1,174 @@
|
||||
package com.xkrs.common.tools;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 序列化工具
|
||||
* @author tajochen
|
||||
*/
|
||||
public class JackSonTool {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(JackSonTool.class);
|
||||
|
||||
private JackSonTool() {
|
||||
}
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
static {
|
||||
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
|
||||
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
|
||||
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
|
||||
OBJECT_MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<>() {
|
||||
@Override
|
||||
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
|
||||
jsonGenerator.writeString("");
|
||||
}
|
||||
});
|
||||
// 解决jackson无法反序列化LocalDateTime的问题,引入jsr310标准
|
||||
JavaTimeModule javaTimeModule = new JavaTimeModule();
|
||||
OBJECT_MAPPER.registerModule(javaTimeModule);
|
||||
OBJECT_MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化
|
||||
* @param obj
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> String encode(T obj) {
|
||||
if (Objects.isNull(obj)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return OBJECT_MAPPER.writeValueAsString(obj);
|
||||
} catch (Exception e) {
|
||||
logger.error("json encode error, obj={}", obj, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化
|
||||
* @param json
|
||||
* @param valueType
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> T decode(String json, Class<T> valueType) {
|
||||
if (!json.isEmpty() && !Objects.isNull(valueType)) {
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(json, valueType);
|
||||
} catch (Exception e) {
|
||||
logger.error("json decode fail,jsonString={}, type={}", json, valueType.getName(), e);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化成list
|
||||
* @param <T>
|
||||
* @param json
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static <T> List decode2List(String json, Class<T> clazz) {
|
||||
if (!json.isEmpty() && !Objects.isNull(clazz)) {
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
|
||||
} catch (Exception var3) {
|
||||
logger.error("json decode2list fail,json={},classType={}", json, clazz.getName(), var3);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转换为 Map<String, Object>
|
||||
*
|
||||
* @param jsonString
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static <T> Map json2map(String jsonString) {
|
||||
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(jsonString, Map.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转换为 Map<String, T>
|
||||
*/
|
||||
public static <T> Map<String, T> json2map(String jsonString, Class<T> clazz) {
|
||||
Map<String, T> map = null;
|
||||
try {
|
||||
map = OBJECT_MAPPER.readValue(jsonString, new TypeReference<Map<String, T>>() {
|
||||
});
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
Map<String, T> result = new HashMap<String, T>(128);
|
||||
for (Map.Entry<String, T> entry : map.entrySet()) {
|
||||
result.put(entry.getKey(), OBJECT_MAPPER.convertValue(entry.getValue(), clazz));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将一个JSON字符串转换为T对象
|
||||
* @param json
|
||||
* @param typeReference
|
||||
* @return
|
||||
*/
|
||||
public static <T> T toObject(String json, TypeReference<T> typeReference) {
|
||||
try {
|
||||
return OBJECT_MAPPER.readValue(json, typeReference);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("failed to convert string to object", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* map转clazz对象
|
||||
* @param map
|
||||
* @param clazz
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> T mapToObject(Map map, Class<T> clazz) {
|
||||
String json = null;
|
||||
try {
|
||||
json = OBJECT_MAPPER.writeValueAsString(map);
|
||||
return OBJECT_MAPPER.readValue(json, clazz);
|
||||
} catch (Exception e) {
|
||||
logger.error("json map2object fail,map={},ClassName={}", json, clazz.getName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
94
src/main/java/com/xkrs/controller/EquipmentController.java
Normal file
94
src/main/java/com/xkrs/controller/EquipmentController.java
Normal file
@ -0,0 +1,94 @@
|
||||
package com.xkrs.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.xkrs.common.encapsulation.PromptMessageEnum;
|
||||
import com.xkrs.common.tools.GetTokenTool;
|
||||
import com.xkrs.common.tools.JackSonTool;
|
||||
import com.xkrs.dao.EquipmentDao;
|
||||
import com.xkrs.model.entity.Equipment;
|
||||
import com.xkrs.util.DateTimeUtil;
|
||||
import com.xkrs.util.RequestUtil;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import static com.xkrs.common.encapsulation.OutputEncapsulation.outputEncapsulationObject;
|
||||
|
||||
@RestController
|
||||
public class EquipmentController {
|
||||
|
||||
@Resource
|
||||
private EquipmentDao equipmentDao;
|
||||
|
||||
@GetMapping("/getEquipment")
|
||||
public String getEquipment(){
|
||||
Locale locale = LocaleContextHolder.getLocale();
|
||||
|
||||
// 鉴权拿到token
|
||||
String token = GetTokenTool.getToken();
|
||||
|
||||
String urlGet = "https://111.26.161.203:443/admin/API/tree/devices";
|
||||
JSONObject jsonObject2 = new JSONObject();
|
||||
jsonObject2.put("orgCode","");
|
||||
List list = new ArrayList();
|
||||
jsonObject2.put("deviceCodes",list);
|
||||
jsonObject2.put("categories",list);
|
||||
String s = jsonObject2.toString();
|
||||
|
||||
String doPostJsonGetData = RequestUtil.doPostJsonGetData(urlGet, s, token);
|
||||
Map json2map = JackSonTool.json2map(doPostJsonGetData);
|
||||
LinkedHashMap data1 = (LinkedHashMap ) json2map.get("data");
|
||||
String json = JSON.toJSONString(data1);
|
||||
Map map4 = JackSonTool.json2map(json);
|
||||
List<Map> devices = (List<Map>) map4.get("devices");
|
||||
for(Map obj : devices){
|
||||
Equipment equipment = new Equipment();
|
||||
equipment.setEquipmentCode(obj.get("code").toString());
|
||||
equipment.setEquipmentName(obj.get("name").toString());
|
||||
String type = obj.get("type").toString();
|
||||
if("1".equals(type)){
|
||||
equipment.setEquipmentType("DVR");
|
||||
}else if("2".equals(type)){
|
||||
equipment.setEquipmentType("IPC");
|
||||
}else if("3".equals(type)){
|
||||
equipment.setEquipmentType("NVS");
|
||||
}else if("5".equals(type)){
|
||||
equipment.setEquipmentType("MDVR");
|
||||
}else if("6".equals(type)){
|
||||
equipment.setEquipmentType("NVR");
|
||||
}else if("9".equals(type)){
|
||||
equipment.setEquipmentType("PVR");
|
||||
}else if("10".equals(type)){
|
||||
equipment.setEquipmentType("EVS");
|
||||
}else if("12".equals(type)){
|
||||
equipment.setEquipmentType("SMART_IPC");
|
||||
}else if("14".equals(type)){
|
||||
equipment.setEquipmentType("SMART_NVR");
|
||||
}else if("21".equals(type)){
|
||||
equipment.setEquipmentType("VTT");
|
||||
}else if("26".equals(type)){
|
||||
equipment.setEquipmentType("TC");
|
||||
}else if("28".equals(type)){
|
||||
equipment.setEquipmentType("DSJ");
|
||||
}else if("29".equals(type)){
|
||||
equipment.setEquipmentType("MPT");
|
||||
}else if("34".equals(type)){
|
||||
equipment.setEquipmentType("WATCHER");
|
||||
}else if("35".equals(type)){
|
||||
equipment.setEquipmentType("MCS");
|
||||
}else {
|
||||
equipment.setEquipmentType("IVSS");
|
||||
}
|
||||
equipment.setEquipmentStatus(obj.get("status").toString());
|
||||
String modifyTime = DateTimeUtil.timeMillisToString(Long.parseLong(obj.get("modifyTime").toString()));
|
||||
equipment.setInstallationTime(modifyTime);
|
||||
equipmentDao.save(equipment);
|
||||
}
|
||||
return outputEncapsulationObject(PromptMessageEnum.SUCCESS, "设备入库成功!", locale);
|
||||
}
|
||||
}
|
119
src/main/java/com/xkrs/controller/TestController.java
Normal file
119
src/main/java/com/xkrs/controller/TestController.java
Normal file
@ -0,0 +1,119 @@
|
||||
package com.xkrs.controller;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xkrs.common.tools.GetTokenTool;
|
||||
import com.xkrs.common.tools.JackSonTool;
|
||||
import com.xkrs.util.Md5Util;
|
||||
import com.xkrs.util.RequestUtil;
|
||||
import com.xkrs.util.WeatherUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 14:32
|
||||
*/
|
||||
@RestController
|
||||
public class TestController {
|
||||
|
||||
@GetMapping("/getTT")
|
||||
public Map getTT(){
|
||||
String url1 = "https://111.26.161.203:443/admin/API/accounts/authorize";
|
||||
String json1 = "{\n" +
|
||||
" \"userName\": system,\n" +
|
||||
" \"ipAddress\": \"\",\n" +
|
||||
" \"clientType\": \"WINPC\"\n" +
|
||||
"}";
|
||||
// 第一次鉴权
|
||||
String doPostJson = RequestUtil.doPostJson(url1, json1);
|
||||
Map map = JackSonTool.json2map(doPostJson);
|
||||
String randomKey = (String) map.get("randomKey");
|
||||
|
||||
String admin123 = Md5Util.stringToMd5("admin123");
|
||||
String stringToMd5 = Md5Util.stringToMd5("system" + admin123);
|
||||
String toMd5 = Md5Util.stringToMd5(stringToMd5);
|
||||
String md5 = Md5Util.stringToMd5("system:" + "DSS:" + toMd5);
|
||||
String signature = Md5Util.stringToMd5(md5 + ":" + randomKey);
|
||||
|
||||
String url2 = "https://111.26.161.203:443/admin/API/accounts/authorize";
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("userName","system");
|
||||
jsonObject.put("randomKey",randomKey);
|
||||
jsonObject.put("mac","");
|
||||
jsonObject.put("encryptType","MD5");
|
||||
jsonObject.put("ipAddress","");
|
||||
jsonObject.put("signature",signature);
|
||||
jsonObject.put("clientType","WINPC");
|
||||
// 第二次鉴权
|
||||
String postJson = RequestUtil.doPostJson(url2, jsonObject.toString());
|
||||
Map map1 = JackSonTool.json2map(postJson);
|
||||
String token = (String) map1.get("token");
|
||||
return map1;
|
||||
}
|
||||
|
||||
@PostMapping("/getVideo")
|
||||
public String getVideo(@RequestParam("alarmCode") String alarmCode) throws JsonProcessingException {
|
||||
String token = GetTokenTool.getToken();
|
||||
String url = "https://111.26.161.203:443/admin/API/SS/Record/GetAlarmRecords?token=" + token;
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("clientType","WINPC_V1");
|
||||
jsonObject.put("clientMac","30:9c:23:79:40:08");
|
||||
jsonObject.put("clientPushId","");
|
||||
jsonObject.put("project","PSDK");
|
||||
jsonObject.put("method","SS.Record.GetAlarmRecords");
|
||||
JSONObject jsonObject1 = new JSONObject();
|
||||
jsonObject1.put("alarmCode",alarmCode);
|
||||
jsonObject1.put("optional","/admin/API/SS/Record/GetAlarmRecords");
|
||||
jsonObject.put("data",jsonObject1);
|
||||
String s = RequestUtil.doPostJson(url, jsonObject.toString());
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readTree(s);
|
||||
JsonNode data = jsonNode.get("data");
|
||||
JsonNode records = data.get("records").get(0);
|
||||
|
||||
String urlVideo = "/admin/API/SS/Playback/StartPlaybackByFile?token=" + token;
|
||||
JSONObject jsonObject2 = new JSONObject();
|
||||
jsonObject2.put("ssId",records.get("ssId").asText());
|
||||
jsonObject2.put("optional",urlVideo);
|
||||
jsonObject2.put("fileName",records.get("recordName").asText());
|
||||
jsonObject2.put("startTime",records.get("startTime").asText());
|
||||
jsonObject2.put("endTime",records.get("endTime").asText());
|
||||
jsonObject2.put("recordType",records.get("recordType").asText());
|
||||
jsonObject2.put("diskId",records.get("diskId").asText());
|
||||
jsonObject2.put("recordSource",records.get("recordSource").asText());
|
||||
jsonObject2.put("channelId",records.get("channelId").asText());
|
||||
jsonObject2.put("streamId",records.get("streamId").asText());
|
||||
jsonObject2.put("enableRtsps","0");
|
||||
jsonObject2.put("nvrId","");
|
||||
JSONObject jsonObject3 = new JSONObject();
|
||||
jsonObject3.put("data",jsonObject2);
|
||||
String s1 = RequestUtil.doPostJson("https://111.26.161.203:443"+urlVideo, jsonObject3.toString());
|
||||
ObjectMapper objectMapper1 = new ObjectMapper();
|
||||
JsonNode jsonNode1 = objectMapper1.readTree(s1);
|
||||
JsonNode data1 = jsonNode1.get("data");
|
||||
String url1 = data1.get("url").asText();
|
||||
return url1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取天气信息的接口
|
||||
* @return
|
||||
*/
|
||||
@GetMapping("/getWeather")
|
||||
public JsonNode getWeather(){
|
||||
JsonNode forecastWeather = WeatherUtils.getForecastWeather();
|
||||
JsonNode results = forecastWeather.path("results");
|
||||
JsonNode jsonNode = results.get(0);
|
||||
JsonNode daily = jsonNode.path("daily");
|
||||
JsonNode jsonNode1 = daily.get(0);
|
||||
return jsonNode1;
|
||||
}
|
||||
}
|
11
src/main/java/com/xkrs/dao/EquipmentDao.java
Normal file
11
src/main/java/com/xkrs/dao/EquipmentDao.java
Normal file
@ -0,0 +1,11 @@
|
||||
package com.xkrs.dao;
|
||||
|
||||
import com.xkrs.model.entity.Equipment;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 9:26
|
||||
*/
|
||||
public interface EquipmentDao extends JpaRepository<Equipment,Long> {
|
||||
}
|
31
src/main/java/com/xkrs/dao/FireDao.java
Normal file
31
src/main/java/com/xkrs/dao/FireDao.java
Normal file
@ -0,0 +1,31 @@
|
||||
package com.xkrs.dao;
|
||||
|
||||
import com.xkrs.model.entity.Fire;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 17:12
|
||||
*/
|
||||
@Component
|
||||
public interface FireDao extends JpaRepository<Fire,Long> {
|
||||
|
||||
/**
|
||||
* 根据报警编码查询火情信息
|
||||
* @param code
|
||||
* @return
|
||||
*/
|
||||
Fire findByAlarmCode(String code);
|
||||
|
||||
/**
|
||||
* 根据报警编码修改图片信息
|
||||
* @param code
|
||||
* @param picturePath
|
||||
*/
|
||||
@Modifying(clearAutomatically=true)
|
||||
@Query(value = "update fire set picture_path = ?2 where alarm_code = ?1",nativeQuery = true)
|
||||
void updatePicturePath(String code, String picturePath);
|
||||
}
|
153
src/main/java/com/xkrs/model/entity/Equipment.java
Normal file
153
src/main/java/com/xkrs/model/entity/Equipment.java
Normal file
@ -0,0 +1,153 @@
|
||||
package com.xkrs.model.entity;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 9:01
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "equipment")
|
||||
public class Equipment {
|
||||
/**
|
||||
* 主键id
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "equipment_seq_gen")
|
||||
@SequenceGenerator(name = "equipment_seq_gen", sequenceName = "equipment_id_seq",allocationSize = 1)
|
||||
private Integer id;
|
||||
|
||||
/**
|
||||
* 设备编码
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String equipmentCode;
|
||||
|
||||
/**
|
||||
* 设备名称
|
||||
*/
|
||||
@Column(length = 65, columnDefinition = "varchar(65)")
|
||||
private String equipmentName;
|
||||
|
||||
/**
|
||||
* 设备类别
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String equipmentType;
|
||||
|
||||
/**
|
||||
* 设备状态
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String equipmentStatus;
|
||||
|
||||
/**
|
||||
* 设备经度
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String equipmentLongitude;
|
||||
|
||||
/**
|
||||
* 设备纬度
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String equipmentLatitude;
|
||||
|
||||
/**
|
||||
* 安装时间
|
||||
*/
|
||||
@Column(length = 65, columnDefinition = "varchar(65)")
|
||||
private String installationTime;
|
||||
|
||||
public Equipment() {
|
||||
}
|
||||
|
||||
public Equipment(Integer id, String equipmentCode, String equipmentName, String equipmentType, String equipmentStatus, String equipmentLongitude, String equipmentLatitude, String installationTime) {
|
||||
this.id = id;
|
||||
this.equipmentCode = equipmentCode;
|
||||
this.equipmentName = equipmentName;
|
||||
this.equipmentType = equipmentType;
|
||||
this.equipmentStatus = equipmentStatus;
|
||||
this.equipmentLongitude = equipmentLongitude;
|
||||
this.equipmentLatitude = equipmentLatitude;
|
||||
this.installationTime = installationTime;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEquipmentCode() {
|
||||
return equipmentCode;
|
||||
}
|
||||
|
||||
public void setEquipmentCode(String equipmentCode) {
|
||||
this.equipmentCode = equipmentCode;
|
||||
}
|
||||
|
||||
public String getEquipmentName() {
|
||||
return equipmentName;
|
||||
}
|
||||
|
||||
public void setEquipmentName(String equipmentName) {
|
||||
this.equipmentName = equipmentName;
|
||||
}
|
||||
|
||||
public String getEquipmentType() {
|
||||
return equipmentType;
|
||||
}
|
||||
|
||||
public void setEquipmentType(String equipmentType) {
|
||||
this.equipmentType = equipmentType;
|
||||
}
|
||||
|
||||
public String getEquipmentStatus() {
|
||||
return equipmentStatus;
|
||||
}
|
||||
|
||||
public void setEquipmentStatus(String equipmentStatus) {
|
||||
this.equipmentStatus = equipmentStatus;
|
||||
}
|
||||
|
||||
public String getEquipmentLongitude() {
|
||||
return equipmentLongitude;
|
||||
}
|
||||
|
||||
public void setEquipmentLongitude(String equipmentLongitude) {
|
||||
this.equipmentLongitude = equipmentLongitude;
|
||||
}
|
||||
|
||||
public String getEquipmentLatitude() {
|
||||
return equipmentLatitude;
|
||||
}
|
||||
|
||||
public void setEquipmentLatitude(String equipmentLatitude) {
|
||||
this.equipmentLatitude = equipmentLatitude;
|
||||
}
|
||||
|
||||
public String getInstallationTime() {
|
||||
return installationTime;
|
||||
}
|
||||
|
||||
public void setInstallationTime(String installationTime) {
|
||||
this.installationTime = installationTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Equipment{" +
|
||||
"id=" + id +
|
||||
", equipmentCode='" + equipmentCode + '\'' +
|
||||
", equipmentName='" + equipmentName + '\'' +
|
||||
", equipmentType='" + equipmentType + '\'' +
|
||||
", equipmentStatus='" + equipmentStatus + '\'' +
|
||||
", equipmentLongitude='" + equipmentLongitude + '\'' +
|
||||
", equipmentLatitude='" + equipmentLatitude + '\'' +
|
||||
", installationTime='" + installationTime + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
329
src/main/java/com/xkrs/model/entity/Fire.java
Normal file
329
src/main/java/com/xkrs/model/entity/Fire.java
Normal file
@ -0,0 +1,329 @@
|
||||
package com.xkrs.model.entity;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 15:09
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "fire")
|
||||
public class Fire {
|
||||
|
||||
/**
|
||||
* 主键id
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "fire_seq_gen")
|
||||
@SequenceGenerator(name = "fire_seq_gen", sequenceName = "fire_id_seq",allocationSize = 1)
|
||||
private Integer id;
|
||||
|
||||
/**
|
||||
* 设备编号
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String deviceCode;
|
||||
|
||||
/**
|
||||
* 通道号
|
||||
*/
|
||||
@Column(length = 11, columnDefinition = "varchar(11)")
|
||||
private String channelSeq;
|
||||
|
||||
/**
|
||||
* 单元类型
|
||||
*/
|
||||
@Column(length = 11, columnDefinition = "varchar(11)")
|
||||
private String unitType;
|
||||
|
||||
/**
|
||||
* 节点类型
|
||||
*/
|
||||
@Column(length = 11, columnDefinition = "varchar(11)")
|
||||
private String nodeType;
|
||||
|
||||
/**
|
||||
* 通道编码
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String nodeCode;
|
||||
|
||||
/**
|
||||
* 报警编码
|
||||
*/
|
||||
@Column(length = 65, columnDefinition = "varchar(65)")
|
||||
private String alarmCode;
|
||||
|
||||
/**
|
||||
* 报警状态
|
||||
*/
|
||||
@Column(length = 11, columnDefinition = "varchar(11)")
|
||||
private String alarmStat;
|
||||
|
||||
/**
|
||||
* 报警类型
|
||||
*/
|
||||
@Column(length = 15, columnDefinition = "varchar(15)")
|
||||
private String alarmType;
|
||||
|
||||
/**
|
||||
* 报警等级
|
||||
*/
|
||||
@Column(length = 11, columnDefinition = "varchar(11)")
|
||||
private String alarmGrade;
|
||||
|
||||
/**
|
||||
* 报警图片
|
||||
*/
|
||||
@Column(length = 85, columnDefinition = "varchar(85)")
|
||||
private String alarmPicture;
|
||||
|
||||
/**
|
||||
* 报警时间
|
||||
*/
|
||||
@Column(length = 65, columnDefinition = "varchar(65)")
|
||||
private String alarmDate;
|
||||
|
||||
/**
|
||||
* 报警源名称
|
||||
*/
|
||||
@Column(length = 95, columnDefinition = "varchar(95)")
|
||||
private String alarmSourceName;
|
||||
|
||||
/**
|
||||
* 报警经度
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String alarmLongitude;
|
||||
|
||||
/**
|
||||
* 报警纬度
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String alarmLatitude;
|
||||
|
||||
/**
|
||||
* 海拔
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String altitude;
|
||||
|
||||
/**
|
||||
* 距离
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String fireDistance;
|
||||
|
||||
/**
|
||||
* 火点编号
|
||||
*/
|
||||
@Column(length = 32, columnDefinition = "varchar(32)")
|
||||
private String fireId;
|
||||
|
||||
/**
|
||||
* 图片地址
|
||||
*/
|
||||
private String picturePath;
|
||||
|
||||
public Fire() {
|
||||
}
|
||||
|
||||
public Fire(Integer id, String deviceCode, String channelSeq, String unitType, String nodeType, String nodeCode, String alarmCode, String alarmStat, String alarmType, String alarmGrade, String alarmPicture, String alarmDate, String alarmSourceName, String alarmLongitude, String alarmLatitude, String altitude, String fireDistance, String fireId, String picturePath) {
|
||||
this.id = id;
|
||||
this.deviceCode = deviceCode;
|
||||
this.channelSeq = channelSeq;
|
||||
this.unitType = unitType;
|
||||
this.nodeType = nodeType;
|
||||
this.nodeCode = nodeCode;
|
||||
this.alarmCode = alarmCode;
|
||||
this.alarmStat = alarmStat;
|
||||
this.alarmType = alarmType;
|
||||
this.alarmGrade = alarmGrade;
|
||||
this.alarmPicture = alarmPicture;
|
||||
this.alarmDate = alarmDate;
|
||||
this.alarmSourceName = alarmSourceName;
|
||||
this.alarmLongitude = alarmLongitude;
|
||||
this.alarmLatitude = alarmLatitude;
|
||||
this.altitude = altitude;
|
||||
this.fireDistance = fireDistance;
|
||||
this.fireId = fireId;
|
||||
this.picturePath = picturePath;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDeviceCode() {
|
||||
return deviceCode;
|
||||
}
|
||||
|
||||
public void setDeviceCode(String deviceCode) {
|
||||
this.deviceCode = deviceCode;
|
||||
}
|
||||
|
||||
public String getChannelSeq() {
|
||||
return channelSeq;
|
||||
}
|
||||
|
||||
public void setChannelSeq(String channelSeq) {
|
||||
this.channelSeq = channelSeq;
|
||||
}
|
||||
|
||||
public String getUnitType() {
|
||||
return unitType;
|
||||
}
|
||||
|
||||
public void setUnitType(String unitType) {
|
||||
this.unitType = unitType;
|
||||
}
|
||||
|
||||
public String getNodeType() {
|
||||
return nodeType;
|
||||
}
|
||||
|
||||
public void setNodeType(String nodeType) {
|
||||
this.nodeType = nodeType;
|
||||
}
|
||||
|
||||
public String getNodeCode() {
|
||||
return nodeCode;
|
||||
}
|
||||
|
||||
public void setNodeCode(String nodeCode) {
|
||||
this.nodeCode = nodeCode;
|
||||
}
|
||||
|
||||
public String getAlarmCode() {
|
||||
return alarmCode;
|
||||
}
|
||||
|
||||
public void setAlarmCode(String alarmCode) {
|
||||
this.alarmCode = alarmCode;
|
||||
}
|
||||
|
||||
public String getAlarmStat() {
|
||||
return alarmStat;
|
||||
}
|
||||
|
||||
public void setAlarmStat(String alarmStat) {
|
||||
this.alarmStat = alarmStat;
|
||||
}
|
||||
|
||||
public String getAlarmType() {
|
||||
return alarmType;
|
||||
}
|
||||
|
||||
public void setAlarmType(String alarmType) {
|
||||
this.alarmType = alarmType;
|
||||
}
|
||||
|
||||
public String getAlarmGrade() {
|
||||
return alarmGrade;
|
||||
}
|
||||
|
||||
public void setAlarmGrade(String alarmGrade) {
|
||||
this.alarmGrade = alarmGrade;
|
||||
}
|
||||
|
||||
public String getAlarmPicture() {
|
||||
return alarmPicture;
|
||||
}
|
||||
|
||||
public void setAlarmPicture(String alarmPicture) {
|
||||
this.alarmPicture = alarmPicture;
|
||||
}
|
||||
|
||||
public String getAlarmDate() {
|
||||
return alarmDate;
|
||||
}
|
||||
|
||||
public void setAlarmDate(String alarmDate) {
|
||||
this.alarmDate = alarmDate;
|
||||
}
|
||||
|
||||
public String getAlarmSourceName() {
|
||||
return alarmSourceName;
|
||||
}
|
||||
|
||||
public void setAlarmSourceName(String alarmSourceName) {
|
||||
this.alarmSourceName = alarmSourceName;
|
||||
}
|
||||
|
||||
public String getAlarmLongitude() {
|
||||
return alarmLongitude;
|
||||
}
|
||||
|
||||
public void setAlarmLongitude(String alarmLongitude) {
|
||||
this.alarmLongitude = alarmLongitude;
|
||||
}
|
||||
|
||||
public String getAlarmLatitude() {
|
||||
return alarmLatitude;
|
||||
}
|
||||
|
||||
public void setAlarmLatitude(String alarmLatitude) {
|
||||
this.alarmLatitude = alarmLatitude;
|
||||
}
|
||||
|
||||
public String getAltitude() {
|
||||
return altitude;
|
||||
}
|
||||
|
||||
public void setAltitude(String altitude) {
|
||||
this.altitude = altitude;
|
||||
}
|
||||
|
||||
public String getFireDistance() {
|
||||
return fireDistance;
|
||||
}
|
||||
|
||||
public void setFireDistance(String fireDistance) {
|
||||
this.fireDistance = fireDistance;
|
||||
}
|
||||
|
||||
public String getFireId() {
|
||||
return fireId;
|
||||
}
|
||||
|
||||
public void setFireId(String fireId) {
|
||||
this.fireId = fireId;
|
||||
}
|
||||
|
||||
public String getPicturePath() {
|
||||
return picturePath;
|
||||
}
|
||||
|
||||
public void setPicturePath(String picturePath) {
|
||||
this.picturePath = picturePath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Fire{" +
|
||||
"id=" + id +
|
||||
", deviceCode='" + deviceCode + '\'' +
|
||||
", channelSeq='" + channelSeq + '\'' +
|
||||
", unitType='" + unitType + '\'' +
|
||||
", nodeType='" + nodeType + '\'' +
|
||||
", nodeCode='" + nodeCode + '\'' +
|
||||
", alarmCode='" + alarmCode + '\'' +
|
||||
", alarmStat='" + alarmStat + '\'' +
|
||||
", alarmType='" + alarmType + '\'' +
|
||||
", alarmGrade='" + alarmGrade + '\'' +
|
||||
", alarmPicture='" + alarmPicture + '\'' +
|
||||
", alarmDate='" + alarmDate + '\'' +
|
||||
", alarmSourceName='" + alarmSourceName + '\'' +
|
||||
", alarmLongitude='" + alarmLongitude + '\'' +
|
||||
", alarmLatitude='" + alarmLatitude + '\'' +
|
||||
", altitude='" + altitude + '\'' +
|
||||
", fireDistance='" + fireDistance + '\'' +
|
||||
", fireId='" + fireId + '\'' +
|
||||
", picturePath='" + picturePath + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
230
src/main/java/com/xkrs/util/DateTimeUtil.java
Normal file
230
src/main/java/com/xkrs/util/DateTimeUtil.java
Normal file
@ -0,0 +1,230 @@
|
||||
package com.xkrs.util;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 日期时间工具
|
||||
* @author tajochen
|
||||
*/
|
||||
public class DateTimeUtil {
|
||||
|
||||
private final static String COMMON_PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
|
||||
private final static String COMMON_PATTERN_DATE = "yyyy-MM-dd";
|
||||
private final static DateTimeFormatter COMMON_FORMATTER_DATETIME = DateTimeFormatter.ofPattern(COMMON_PATTERN_DATETIME);
|
||||
private final static DateTimeFormatter COMMON_FORMATTER_DATE = DateTimeFormatter.ofPattern(COMMON_PATTERN_DATE);
|
||||
private final static ZoneOffset DEFAULT_ZONE_OFFSET = ZoneOffset.of("+8");
|
||||
|
||||
/**
|
||||
* 字符串转LocalDate
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static LocalDate stringToDate(String date) {
|
||||
assert date != null;
|
||||
return LocalDate.parse(date, COMMON_FORMATTER_DATE);
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalDate转字符串
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static String dateToString(LocalDate date) {
|
||||
assert date != null;
|
||||
return COMMON_FORMATTER_DATE.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalDateTime转字符串
|
||||
* @param dateTime
|
||||
* @return
|
||||
*/
|
||||
public static String dateTimeToString(LocalDateTime dateTime) {
|
||||
assert dateTime != null;
|
||||
return COMMON_FORMATTER_DATETIME.format(dateTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转LocalDateTime
|
||||
* @param dateStr
|
||||
* @return
|
||||
*/
|
||||
public static LocalDateTime stringToDateTime(String dateStr) {
|
||||
assert dateStr != null;
|
||||
return LocalDateTime.parse(dateStr, COMMON_FORMATTER_DATETIME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转Instant时间戳
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static Instant stringToInstant(String str) {
|
||||
assert str != null;
|
||||
return stringToDateTime(str).toInstant(DEFAULT_ZONE_OFFSET);
|
||||
}
|
||||
|
||||
/**
|
||||
* LocalDateTime转字符串(格式化)
|
||||
* @param dateTime
|
||||
* @param formatter
|
||||
* @return
|
||||
*/
|
||||
public static String dateToStringFormatter(LocalDateTime dateTime, DateTimeFormatter formatter) {
|
||||
assert dateTime != null;
|
||||
return formatter.format(dateTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转LocalDateTime(格式化)
|
||||
* @param dateStr
|
||||
* @param formatter
|
||||
* @return
|
||||
*/
|
||||
public static LocalDateTime stringToDateTimeFormatter(String dateStr, DateTimeFormatter formatter) {
|
||||
assert dateStr != null;
|
||||
return LocalDateTime.parse(dateStr, formatter);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转 local date
|
||||
* @param dateStr
|
||||
* @return
|
||||
*/
|
||||
public static LocalDate stringToDateFormatter(String dateStr){
|
||||
LocalDate date = LocalDate.parse(dateStr, COMMON_FORMATTER_DATE);
|
||||
return date;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 日期转时间戳
|
||||
* @param dateTime
|
||||
* @return
|
||||
*/
|
||||
public static long dateToTimeMillis(LocalDateTime dateTime) {
|
||||
assert dateTime != null;
|
||||
return dateTime.toInstant(DEFAULT_ZONE_OFFSET).toEpochMilli();
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间戳转日期
|
||||
* @param timeMillis
|
||||
* @return
|
||||
*/
|
||||
public static LocalDateTime timeMillisToDate(long timeMillis) {
|
||||
Instant instant = Instant.ofEpochMilli(timeMillis);
|
||||
return LocalDateTime.ofInstant(instant, DEFAULT_ZONE_OFFSET);
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间戳转时间
|
||||
* @param timeMillis
|
||||
* @return
|
||||
*/
|
||||
public static LocalDateTime timeMillisToTime(long timeMillis) {
|
||||
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(timeMillis, 0, ZoneOffset.ofHours(8));
|
||||
return localDateTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 时间戳转时间再转字符串
|
||||
* @param timeMillis
|
||||
* @return
|
||||
*/
|
||||
public static String timeMillisToString(long timeMillis){
|
||||
LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(timeMillis, 0, ZoneOffset.ofHours(8));
|
||||
return COMMON_FORMATTER_DATETIME.format(localDateTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间 hh:mm:ss:nnn
|
||||
* @return
|
||||
*/
|
||||
public static LocalDateTime getNowTime() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
return now;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期 yyyy-MM-dd
|
||||
* @return
|
||||
*/
|
||||
public static LocalDate getToday() {
|
||||
LocalDate now = LocalDate.now();
|
||||
return now;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前 Instant 时间戳
|
||||
* @return
|
||||
*/
|
||||
public static Instant getInstant() {
|
||||
Instant timeStamp = Instant.now();
|
||||
return timeStamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间 yyyy-MM-ss hh:mm:ss
|
||||
* @return
|
||||
*/
|
||||
public static String getNowTimeStr(){
|
||||
return COMMON_FORMATTER_DATETIME.format(getNowTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断日期格式是否合法 "yyyy-MM-dd"
|
||||
* @param strDate
|
||||
* @return
|
||||
*/
|
||||
public static boolean isValidDate(String strDate) {
|
||||
final int minLen = 10;
|
||||
if(strDate == null || strDate.length() < minLen) {
|
||||
return false;
|
||||
}
|
||||
//正则表达式校验日期格式 yyyy-MM-dd
|
||||
String eL = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-" +
|
||||
"(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})" +
|
||||
"(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)(([0-9]{3}[1-9]|[0-9]{2}[1-9]" +
|
||||
"[0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-" +
|
||||
"(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|" +
|
||||
"((0[48]|[2468][048]|[3579][26])00))-02-29)";
|
||||
Pattern pat = Pattern.compile(eL);
|
||||
Matcher matcher = pat.matcher(strDate);
|
||||
return matcher.matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断时间格式 格式必须为 "YYYY-MM-DD HH:mm:ss"
|
||||
* @param sDateTime
|
||||
* @return
|
||||
*/
|
||||
public static boolean isValidDateTime(String sDateTime) {
|
||||
final int minLen = 19;
|
||||
if ((sDateTime == null) || (sDateTime.length() < minLen)) {
|
||||
return false;
|
||||
}
|
||||
String eL = "(((01[0-9]{2}|0[2-9][0-9]{2}|[1-9][0-9]{3})-(0?[13578]|1[02])-" +
|
||||
"(0?[1-9]|[12]\\\\d|3[01]))|((01[0-9]{2}|0[2-9][0-9]{2}|[1-9][0-9]{3})-" +
|
||||
"(0?[13456789]|1[012])-(0?[1-9]|[12]\\\\d|30))|((01[0-9]{2}|0[2-9][0-9]{2}|[1-9][0-9]{3})-0?2-" +
|
||||
"(0?[1-9]|1\\\\d|2[0-8]))|(((1[6-9]|[2-9]\\\\d)(0[48]|[2468][048]|[13579][26])|((04|08|12|16|[2468][048]|" +
|
||||
"[3579][26])00))-0?2-29)) (20|21|22|23|[0-1]?\\\\d):[0-5]?\\\\d:[0-5]?\\\\d";
|
||||
Pattern pat = Pattern.compile(eL);
|
||||
Matcher matcher = pat.matcher(sDateTime);
|
||||
return matcher.matches();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String mm = "1626340246";
|
||||
long l = Long.parseLong(mm);
|
||||
String timeMillisToString = timeMillisToString(l);
|
||||
System.out.println(timeMillisToString);
|
||||
}
|
||||
|
||||
}
|
33
src/main/java/com/xkrs/util/Md5Util.java
Normal file
33
src/main/java/com/xkrs/util/Md5Util.java
Normal file
@ -0,0 +1,33 @@
|
||||
package com.xkrs.util;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* @author xkrs
|
||||
*/
|
||||
public class Md5Util {
|
||||
|
||||
public static String stringToMd5(String content){
|
||||
byte[] secretBytes = null;
|
||||
try {
|
||||
secretBytes = MessageDigest.getInstance("md5").digest(
|
||||
content.getBytes());
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException("没有md5这个算法!");
|
||||
}
|
||||
// 16进制数字
|
||||
String md5code = new BigInteger(1, secretBytes).toString(16);
|
||||
// 如果生成数字未满32位,需要前面补0
|
||||
for (int i = 0; i < 32 - md5code.length(); i++) {
|
||||
md5code = "0" + md5code;
|
||||
}
|
||||
return md5code;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String s = stringToMd5("12345");
|
||||
System.out.println(s);
|
||||
}
|
||||
}
|
372
src/main/java/com/xkrs/util/RequestUtil.java
Normal file
372
src/main/java/com/xkrs/util/RequestUtil.java
Normal file
@ -0,0 +1,372 @@
|
||||
package com.xkrs.util;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.http.Consts;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.NameValuePair;
|
||||
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.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.entity.mime.HttpMultipartMode;
|
||||
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.http.entity.mime.content.StringBody;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 上传工具
|
||||
* @author XinYi Song
|
||||
**/
|
||||
public class RequestUtil {
|
||||
|
||||
private static final String FIREFOX_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0";
|
||||
private static final String CHROME_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
|
||||
"(KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36";
|
||||
/**
|
||||
* 模拟 get请求
|
||||
* @param url 链接
|
||||
* @param map 参数列表
|
||||
*/
|
||||
public static String getStandard(String url, Map<String,String> map) {
|
||||
String body = "";
|
||||
// 1.拿到一个httpclient的对象
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
// 2.1 提交请求体
|
||||
ArrayList<NameValuePair> parameters = new ArrayList<>();
|
||||
URIBuilder builder = null;
|
||||
// 装填参数
|
||||
if(map!=null){
|
||||
for (Map.Entry<String, String> entry : map.entrySet()) {
|
||||
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
builder = new URIBuilder(url);
|
||||
builder.setParameters(parameters);
|
||||
// 2.设置请求方式和请求信息
|
||||
HttpGet httpGet = new HttpGet(builder.build());
|
||||
// 2.1 提交header头信息
|
||||
httpGet.addHeader("user-agent", FIREFOX_UA);
|
||||
// 3.执行请求
|
||||
response = httpClient.execute(httpGet);
|
||||
// 4.获取返回值
|
||||
assert response != null;
|
||||
// 按指定编码转换结果实体为String类型
|
||||
body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
|
||||
// 5.关闭连接
|
||||
response.close();
|
||||
httpClient.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟get请求(加请求头)
|
||||
* @param url
|
||||
* @param param
|
||||
* @param token
|
||||
* @return
|
||||
*/
|
||||
public static String doGet(String url, Map<String, String> param,String token) {
|
||||
|
||||
final int okResNum = 200;
|
||||
|
||||
String result = null;
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
URIBuilder builder = new URIBuilder(url);
|
||||
if (param != null) {
|
||||
for (String key : param.keySet()) {
|
||||
builder.addParameter(key, param.get(key));
|
||||
}
|
||||
}
|
||||
URI uri = builder.build();
|
||||
HttpGet httpGet = new HttpGet(uri);
|
||||
httpGet.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
|
||||
httpGet.addHeader("Authorization",token);
|
||||
response = httpclient.execute(httpGet);
|
||||
if (response.getStatusLine().getStatusCode() == okResNum) {
|
||||
result = EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (response != null) {
|
||||
response.close();
|
||||
}
|
||||
httpclient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 带参数的get请求
|
||||
* @param url
|
||||
* @param param
|
||||
* @return String
|
||||
*/
|
||||
public static JsonNode doGetJsonNode(String url, Map<String, String> param) {
|
||||
// 创建Httpclient对象
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
|
||||
String resultString = "";
|
||||
JsonNode node = null;
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
// 创建uri
|
||||
URIBuilder builder = new URIBuilder(url);
|
||||
if (param != null) {
|
||||
for (String key : param.keySet()) {
|
||||
builder.addParameter(key, param.get(key));
|
||||
}
|
||||
}
|
||||
URI uri = builder.build();
|
||||
// 创建http GET请求
|
||||
HttpGet httpGet = new HttpGet(uri);
|
||||
// 执行请求
|
||||
response = httpclient.execute(httpGet);
|
||||
// 判断返回状态是否为200
|
||||
if (response.getStatusLine().getStatusCode() == 200) {
|
||||
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
//使用ObjectMapper对象对 User对象进行转换
|
||||
node = objectMapper.readTree(resultString);
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
if (response != null) {
|
||||
response.close();
|
||||
}
|
||||
httpclient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟Post请求 application/x-www-form-urlencoded
|
||||
* @param url 资源地址
|
||||
* @param map 参数列表
|
||||
* @return
|
||||
*/
|
||||
public static String postStandard(String url, Map<String,String> map) {
|
||||
String body = "";
|
||||
// 创建httpclient对象
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
// 创建post方式请求对象
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
// 装填参数
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
if(map!=null){
|
||||
for (Map.Entry<String, String> entry : map.entrySet()) {
|
||||
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
}
|
||||
try {
|
||||
// 设置参数到请求对象中
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
|
||||
// 设置header报文头信息
|
||||
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
|
||||
httpPost.setHeader("User-Agent", FIREFOX_UA);
|
||||
httpPost.setHeader("Accept", "application");
|
||||
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
|
||||
// 执行请求操作,并拿到结果(同步阻塞)
|
||||
CloseableHttpResponse response = client.execute(httpPost);
|
||||
// 获取结果实体
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity != null) {
|
||||
// 按指定编码转换结果实体为String类型
|
||||
body = EntityUtils.toString(entity, "UTF-8");
|
||||
}
|
||||
EntityUtils.consume(entity);
|
||||
// 释放链接
|
||||
response.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
client.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* 传送json类型的post请求
|
||||
* @param url
|
||||
* @param json
|
||||
* @return String
|
||||
*/
|
||||
public static String doPostJson(String url, String json) {
|
||||
// 创建Httpclient对象
|
||||
// CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpClient httpClient = SeeSSLCloseableHttpClient.getCloseableHttpClient();
|
||||
CloseableHttpResponse response = null;
|
||||
String resultString = "";
|
||||
try {
|
||||
// 创建Http Post请求
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
// 创建请求内容
|
||||
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
|
||||
httpPost.setEntity(entity);
|
||||
httpPost.setHeader("Content-Type","application/json");
|
||||
httpPost.setHeader("User-Agent", FIREFOX_UA);
|
||||
// 执行http请求
|
||||
response = httpClient.execute(httpPost);
|
||||
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return resultString;
|
||||
}
|
||||
|
||||
|
||||
public static String doPostJsonGetData(String url, String json, String token) {
|
||||
// 创建Httpclient对象
|
||||
// CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
CloseableHttpClient httpClient = SeeSSLCloseableHttpClient.getCloseableHttpClient();
|
||||
CloseableHttpResponse response = null;
|
||||
String resultString = "";
|
||||
try {
|
||||
// 创建Http Post请求
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
// 创建请求内容
|
||||
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
|
||||
httpPost.setEntity(entity);
|
||||
httpPost.setHeader("Content-Type","application/json");
|
||||
httpPost.setHeader("User-Agent", FIREFOX_UA);
|
||||
httpPost.setHeader("X-Subject-Token", token);
|
||||
// 执行http请求
|
||||
response = httpClient.execute(httpPost);
|
||||
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return resultString;
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟Post请求 multipart/form-data
|
||||
* @param postFile 请求文件
|
||||
* @param postUrl 请求链接
|
||||
* @param postParam 请求参数
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,Object> postFile(File postFile, String postUrl, Map<String,String> postParam) {
|
||||
|
||||
Logger log = LoggerFactory.getLogger(RequestUtil.class);
|
||||
Map<String,Object> resultMap = new HashMap<>(16);
|
||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||
try{
|
||||
// 把一个普通参数和文件上传给下面这个地址
|
||||
HttpPost httpPost = new HttpPost(postUrl);
|
||||
|
||||
// 设置传输参数
|
||||
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
|
||||
// 解决乱码问题
|
||||
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
|
||||
multipartEntity.setCharset(StandardCharsets.UTF_8);
|
||||
|
||||
// 设置文件参数 ,获取文件名postFile.getName()
|
||||
// 把文件转换成流对象FileBody
|
||||
multipartEntity.addBinaryBody("file",postFile,ContentType.create("multipart/form-data",
|
||||
Consts.UTF_8),postFile.getName());
|
||||
// 设计文件以外的参数
|
||||
Set<String> keySet = postParam.keySet();
|
||||
for (String key : keySet) {
|
||||
// 相当于<input type="text" name="name" value=name>
|
||||
multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create(
|
||||
"multipart/form-data", Consts.UTF_8)));
|
||||
}
|
||||
HttpEntity reqEntity = multipartEntity.build();
|
||||
httpPost.setEntity(reqEntity);
|
||||
// 设置header报文头信息
|
||||
httpPost.setHeader("User-Agent", FIREFOX_UA);
|
||||
httpPost.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
|
||||
httpPost.setHeader("Accept-Encoding","gzip, deflate");
|
||||
|
||||
// 发起请求,返回请求的响应
|
||||
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
|
||||
resultMap.put("statusCode", response.getStatusLine().getStatusCode());
|
||||
// 获取响应对象
|
||||
HttpEntity resEntity = response.getEntity();
|
||||
if (resEntity != null) {
|
||||
// 打印响应内容
|
||||
resultMap.put("data", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
|
||||
resultMap.put("message", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
|
||||
resultMap.put("status", EntityUtils.toString(resEntity, StandardCharsets.UTF_8));
|
||||
}
|
||||
// 销毁
|
||||
EntityUtils.consume(resEntity);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
httpClient.close();
|
||||
} catch (IOException e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
log.info("上传结果:" + resultMap);
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String url1 = "https://111.26.161.203:443/admin/API/accounts/authorize";
|
||||
String json1 = "{\n" +
|
||||
" \"userName\": system,\n" +
|
||||
" \"ipAddress\": \"\",\n" +
|
||||
" \"clientType\": \"WINPC\"\n" +
|
||||
"}";
|
||||
String doPostJson = doPostJson(url1, json1);
|
||||
/*JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("userName","system");
|
||||
jsonObject.put("ipAddress","");
|
||||
jsonObject.put("clientType","WINPC");*/
|
||||
|
||||
System.out.println(doPostJson);
|
||||
}
|
||||
}
|
64
src/main/java/com/xkrs/util/SeeSSLCloseableHttpClient.java
Normal file
64
src/main/java/com/xkrs/util/SeeSSLCloseableHttpClient.java
Normal file
@ -0,0 +1,64 @@
|
||||
package com.xkrs.util;
|
||||
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.HttpClientConnectionManager;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
|
||||
public class SeeSSLCloseableHttpClient {
|
||||
|
||||
private static X509TrustManager tm = new X509TrustManager() {
|
||||
@Override
|
||||
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
public static CloseableHttpClient getCloseableHttpClient() {
|
||||
SSLContext ctx = null;
|
||||
try {
|
||||
ctx = SSLContext.getInstance("TLS");
|
||||
ctx.init(null, new TrustManager[] { tm }, null);
|
||||
} catch (KeyManagementException e) {
|
||||
e.printStackTrace();
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
HttpClientBuilder builder = HttpClientBuilder.create();
|
||||
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(ctx,
|
||||
NoopHostnameVerifier.INSTANCE);
|
||||
builder.setSSLSocketFactory(sslConnectionFactory);
|
||||
|
||||
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
|
||||
.register("https", sslConnectionFactory).build();
|
||||
|
||||
HttpClientConnectionManager ccm1 = new BasicHttpClientConnectionManager(registry);
|
||||
|
||||
builder.setConnectionManager(ccm1);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
}
|
113
src/main/java/com/xkrs/util/TopicConsumerListener.java
Normal file
113
src/main/java/com/xkrs/util/TopicConsumerListener.java
Normal file
@ -0,0 +1,113 @@
|
||||
package com.xkrs.util;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/8 14:42
|
||||
*/
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xkrs.dao.FireDao;
|
||||
import com.xkrs.model.entity.Fire;
|
||||
import com.xkrs.websocket.server.WebSocketServer;
|
||||
import org.springframework.jms.annotation.JmsListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.transaction.Transactional;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
public class TopicConsumerListener {
|
||||
|
||||
@Resource
|
||||
private FireDao fireDao;
|
||||
|
||||
/**
|
||||
* topic模式的消费者
|
||||
* 订阅火情报警信息
|
||||
* @param message
|
||||
*/
|
||||
@JmsListener(destination="${spring.activemq.topic-name}", containerFactory="topicListener")
|
||||
public void readActiveQueue(String message) throws IOException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readTree(message);
|
||||
String method = jsonNode.get("method").asText();
|
||||
if("vms.alarm.msg".equals(method)){
|
||||
JsonNode info = jsonNode.get("info");
|
||||
Fire fire = new Fire();
|
||||
fire.setDeviceCode(info.get("deviceCode").asText());
|
||||
fire.setChannelSeq(info.get("channelSeq").asText());
|
||||
fire.setUnitType(info.get("unitType").asText());
|
||||
fire.setNodeType(info.get("nodeType").asText());
|
||||
fire.setNodeCode(info.get("nodeCode").asText());
|
||||
String alarmCode = info.get("alarmCode").asText();
|
||||
fire.setAlarmCode(alarmCode);
|
||||
fire.setAlarmStat(info.get("alarmStat").asText());
|
||||
fire.setAlarmType(info.get("alarmType").asText());
|
||||
fire.setAlarmGrade(info.get("alarmGrade").asText());
|
||||
fire.setAlarmPicture(info.get("alarmPicture").asText());
|
||||
String modifyTime = DateTimeUtil.timeMillisToString(Long.parseLong(info.get("alarmDate").asText()));
|
||||
fire.setAlarmDate(modifyTime);
|
||||
fire.setAlarmSourceName(info.get("alarmSourceName").asText());
|
||||
fire.setAlarmLongitude(info.get("gpsX").asText());
|
||||
fire.setAlarmLatitude(info.get("gpsY").asText());
|
||||
fire.setAltitude(info.get("altitude").asText());
|
||||
fire.setFireDistance(info.get("fireDistance").asText());
|
||||
fire.setFireId(info.get("fsid").asText());
|
||||
Map<String,String> map = new HashMap<String,String>();
|
||||
map.put("deviceCode",info.get("deviceCode").asText());
|
||||
map.put("channelSeq",info.get("channelSeq").asText());
|
||||
map.put("unitType",info.get("unitType").asText());
|
||||
map.put("nodeType",info.get("nodeType").asText());
|
||||
map.put("nodeCode",info.get("nodeCode").asText());
|
||||
map.put("alarmCode",alarmCode);
|
||||
map.put("alarmStat",info.get("alarmStat").asText());
|
||||
map.put("alarmType",info.get("alarmType").asText());
|
||||
map.put("alarmGrade",info.get("alarmGrade").asText());
|
||||
map.put("alarmPicture",info.get("alarmPicture").asText());
|
||||
map.put("alarmDate",modifyTime);
|
||||
map.put("alarmSourceName",info.get("alarmSourceName").asText());
|
||||
map.put("alarmLongitude",info.get("gpsX").asText());
|
||||
map.put("alarmLatitude",info.get("gpsY").asText());
|
||||
map.put("altitude",info.get("altitude").asText());
|
||||
map.put("fireDistance",info.get("fireDistance").asText());
|
||||
map.put("fsid",info.get("fsid").asText());
|
||||
String jsonString = JSON.toJSONString(map);
|
||||
WebSocketServer.BroadCastInfo(jsonString);
|
||||
|
||||
fireDao.save(fire);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅火情图片
|
||||
* @param message
|
||||
*/
|
||||
@Transactional(rollbackOn = Exception.class)
|
||||
@JmsListener(destination="${spring.activemq.topic-name1}", containerFactory="topicListener")
|
||||
public void readActivePicture(String message) throws JsonProcessingException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
JsonNode jsonNode = objectMapper.readTree(message);
|
||||
String method = jsonNode.get("method").asText();
|
||||
if("vms.notifyAlarmPicture".equals(method)){
|
||||
JsonNode info = jsonNode.get("info");
|
||||
String alarmCode = info.get("alarmCode").asText();
|
||||
Fire byAlarmCode = fireDao.findByAlarmCode(alarmCode);
|
||||
if("".equals(byAlarmCode.getPicturePath()) || byAlarmCode.getPicturePath() == null){
|
||||
String picture = info.get("picture").asText();
|
||||
fireDao.updatePicturePath(alarmCode,picture);
|
||||
}else {
|
||||
String picture1 = byAlarmCode.getPicturePath() + "," + info.get("picture").asText();
|
||||
fireDao.updatePicturePath(alarmCode,picture1);
|
||||
}
|
||||
|
||||
System.out.println("topic接受到的图片:" + message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
26
src/main/java/com/xkrs/util/WeatherUtils.java
Normal file
26
src/main/java/com/xkrs/util/WeatherUtils.java
Normal file
@ -0,0 +1,26 @@
|
||||
package com.xkrs.util;
|
||||
|
||||
/**
|
||||
* @Author: XinYi Song
|
||||
* @Date: 2022/2/7 16:22
|
||||
*/
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @description:获取地区天气工具类
|
||||
*/
|
||||
public class WeatherUtils {
|
||||
|
||||
public static JsonNode getForecastWeather() {
|
||||
String url = "http://portalweather.comsys.net.cn/weather03/api/weatherService/getDailyWeather?cityName=大同";
|
||||
Map<String, String> map = new HashMap<>(3);
|
||||
JsonNode jsonNode = RequestUtil.doGetJsonNode(url, map);
|
||||
return jsonNode;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.xkrs.websocket.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
|
||||
/**
|
||||
* websocket广播配置
|
||||
* @author xkrs
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketBrokerConfig implements WebSocketMessageBrokerConfigurer {
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
registry.addEndpoint("/endPointClientServer").withSockJS();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry registry) {
|
||||
registry.enableSimpleBroker("/ws");
|
||||
}
|
||||
}
|
16
src/main/java/com/xkrs/websocket/config/WebSocketConfig.java
Normal file
16
src/main/java/com/xkrs/websocket/config/WebSocketConfig.java
Normal file
@ -0,0 +1,16 @@
|
||||
package com.xkrs.websocket.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
|
||||
|
||||
/**
|
||||
* @author xkrs
|
||||
*/
|
||||
@Configuration
|
||||
public class WebSocketConfig {
|
||||
@Bean
|
||||
public ServerEndpointExporter serverEndpointExporter(){
|
||||
return new ServerEndpointExporter();
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.xkrs.websocket.controller;
|
||||
|
||||
import com.xkrs.websocket.server.WebSocketServer;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author XinYi Song
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ws")
|
||||
public class WebSocketController {
|
||||
|
||||
|
||||
/**
|
||||
* 群发消息内容
|
||||
* @param message
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value="/sendAll", method= RequestMethod.GET)
|
||||
public String sendAllMessage(@RequestParam(required=true) String message){
|
||||
try {
|
||||
WebSocketServer.BroadCastInfo(message);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定会话ID发消息
|
||||
* @param message 消息内容
|
||||
* @param id 连接会话ID
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value="/sendOne", method=RequestMethod.GET)
|
||||
public String sendOneMessage(@RequestParam(required=true) String message,@RequestParam(required=true) String id){
|
||||
try {
|
||||
WebSocketServer.SendMessage(message,id);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
}
|
129
src/main/java/com/xkrs/websocket/server/WebSocketServer.java
Normal file
129
src/main/java/com/xkrs/websocket/server/WebSocketServer.java
Normal file
@ -0,0 +1,129 @@
|
||||
package com.xkrs.websocket.server;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.websocket.*;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* @author XinYi Song
|
||||
*/
|
||||
@ServerEndpoint(value = "/ws/asset")
|
||||
@Component
|
||||
public class WebSocketServer {
|
||||
|
||||
public static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
System.out.println("websocket 加载");
|
||||
}
|
||||
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
|
||||
/**
|
||||
* concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
|
||||
*/
|
||||
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
|
||||
|
||||
|
||||
/**
|
||||
* 连接建立成功调用的方法
|
||||
*/
|
||||
@OnOpen
|
||||
public void onOpen(Session session) {
|
||||
SessionSet.add(session);
|
||||
// 在线数加1
|
||||
int cnt = OnlineCount.incrementAndGet();
|
||||
log.info("有连接加入,当前连接数为:{}", cnt);
|
||||
SendMessage(session, "连接成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接关闭调用的方法
|
||||
*/
|
||||
@OnClose
|
||||
public void onClose(Session session) {
|
||||
SessionSet.remove(session);
|
||||
int cnt = OnlineCount.decrementAndGet();
|
||||
log.info("有连接关闭,当前连接数为:{}", cnt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到客户端消息后调用的方法
|
||||
*
|
||||
* @param message
|
||||
* 客户端发送过来的消息
|
||||
*/
|
||||
@OnMessage
|
||||
public void onMessage(String message, Session session) {
|
||||
log.info("来自客户端的消息:{}",message);
|
||||
SendMessage(session, "收到消息,消息内容:"+message);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 出现错误
|
||||
* @param session
|
||||
* @param error
|
||||
*/
|
||||
@OnError
|
||||
public void onError(Session session, Throwable error) {
|
||||
log.error("发生错误:{},Session ID: {}",error.getMessage(),session.getId());
|
||||
error.printStackTrace();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息,实践表明,每次浏览器刷新,session会发生变化。
|
||||
* @param session
|
||||
* @param message
|
||||
*/
|
||||
public static void SendMessage(Session session, String message) {
|
||||
try {
|
||||
session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
|
||||
} catch (IOException e) {
|
||||
log.error("发送消息出错:{}", e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 群发消息
|
||||
* @param message
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void BroadCastInfo(String message) throws IOException {
|
||||
for (Session session : SessionSet) {
|
||||
if(session.isOpen()){
|
||||
SendMessage(session, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定Session发送消息
|
||||
* @param sessionId
|
||||
* @param message
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void SendMessage(String message,String sessionId) throws IOException {
|
||||
Session session = null;
|
||||
for (Session s : SessionSet) {
|
||||
if(s.getId().equals(sessionId)){
|
||||
session = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(session!=null){
|
||||
SendMessage(session, message);
|
||||
}
|
||||
else{
|
||||
log.warn("没有找到你指定ID的会话:{}",sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user