diff --git a/pom.xml b/pom.xml index 73b1973..f0d96a3 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.objecteye viid-collector - 1.0-SNAPSHOT + 1.0 8 @@ -49,14 +49,6 @@ spring-boot-starter-web - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-discovery - - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-config - - org.projectlombok lombok @@ -72,5 +64,41 @@ org.apache.commons commons-pool2 + + org.apache.commons + commons-lang3 + + + commons-codec + commons-codec + + + org.springframework.boot + spring-boot-starter-validation + + + org.apache.httpcomponents + httpclient + + + + + + org.springframework.boot + spring-boot-maven-plugin + + viid-collector + com.objecteye.VIIDCollectorApplication + + + + + repackage + + + + + + \ No newline at end of file diff --git a/src/main/java/com/objecteye/config/ApplicationConfigurationProperties.java b/src/main/java/com/objecteye/config/Gat1400Properties.java index 57913b9..80a9c8e 100644 --- a/src/main/java/com/objecteye/config/ApplicationConfigurationProperties.java +++ b/src/main/java/com/objecteye/config/Gat1400Properties.java @@ -2,16 +2,22 @@ package com.objecteye.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; +import org.springframework.context.annotation.Configuration; /** * @author: liuhaoyu - * @date: 2023/6/28 + * @date: 2023/7/5 */ @Data -@Component -@ConfigurationProperties(prefix = "config.application") -public class ApplicationConfigurationProperties { +@Configuration +@ConfigurationProperties(prefix = "gat1400") +public class Gat1400Properties { - private String platformCode; + private String serverAddress; + + private Integer port; + + private String accessKey; + + private String securityKey; } diff --git a/src/main/java/com/objecteye/config/ObjectMapperConfigure.java b/src/main/java/com/objecteye/config/ObjectMapperConfigure.java deleted file mode 100644 index 0bd64ac..0000000 --- a/src/main/java/com/objecteye/config/ObjectMapperConfigure.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.objecteye.config; - -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.Data; -import org.springframework.context.annotation.Bean; - -/** - * @author: liuhaoyu - * @date: 2023/6/28 - */ -@Data -public class ObjectMapperConfigure { - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } -} diff --git a/src/main/java/com/objecteye/content/VIIDApi.java b/src/main/java/com/objecteye/content/VIIDApi.java index 8242342..a704ca2 100644 --- a/src/main/java/com/objecteye/content/VIIDApi.java +++ b/src/main/java/com/objecteye/content/VIIDApi.java @@ -6,7 +6,8 @@ package com.objecteye.content; */ public class VIIDApi { - public static final String SYSTEM_PREFIX = "/VIID/System"; + private static final String VIID = "/VIID"; + public static final String SYSTEM_PREFIX = VIID + "/System"; /** * 注册 */ @@ -19,6 +20,12 @@ public class VIIDApi { * 保活 */ public static final String KEEPALIVE = SYSTEM_PREFIX + "/Keepalive"; + /** + * 校时 + */ + public static final String TIME = SYSTEM_PREFIX + "/Time"; + + public static final String SUBSCRIBES = VIID + "/Subscribes"; private VIIDApi() { } diff --git a/src/main/java/com/objecteye/content/VIIDContent.java b/src/main/java/com/objecteye/content/VIIDContent.java new file mode 100644 index 0000000..4928292 --- /dev/null +++ b/src/main/java/com/objecteye/content/VIIDContent.java @@ -0,0 +1,13 @@ +package com.objecteye.content; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +public class VIIDContent { + + public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + + private VIIDContent() { + } +} diff --git a/src/main/java/com/objecteye/content/ViidCollectorRedisKey.java b/src/main/java/com/objecteye/content/ViidCollectorRedisKey.java index 50ff7f5..bc00f0d 100644 --- a/src/main/java/com/objecteye/content/ViidCollectorRedisKey.java +++ b/src/main/java/com/objecteye/content/ViidCollectorRedisKey.java @@ -6,7 +6,7 @@ package com.objecteye.content; */ public class ViidCollectorRedisKey { /** - * 设备连接信息缓存 + * 设备订阅信息 */ public static final String DEVICE_CACHE = "vc:dc"; diff --git a/src/main/java/com/objecteye/controller/SubscribeController.java b/src/main/java/com/objecteye/controller/SubscribeController.java new file mode 100644 index 0000000..93e7a90 --- /dev/null +++ b/src/main/java/com/objecteye/controller/SubscribeController.java @@ -0,0 +1,35 @@ +package com.objecteye.controller; + +import com.objecteye.handle.viid.SubscribeHandle; +import com.objecteye.pojo.DeviceIdParams; +import com.objecteye.pojo.Result; +import com.objecteye.pojo.viid.subscribe.SubscribeNotificationRequestObject; +import com.objecteye.utils.JSONUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Slf4j +@RestController +@RequiredArgsConstructor +public class SubscribeController { + private final SubscribeHandle subscribeHandle; + + @PostMapping("subscribe") + public Result subscribe(@RequestBody @Validated DeviceIdParams params) { + return Result.success(subscribeHandle.subscribe(params.getDeviceId())); + } + + @PostMapping("receiver") + public Result receiver(@RequestBody SubscribeNotificationRequestObject subscribeNotificationRequestObject) { + log.info("notification: \n{}", JSONUtils.toPrettyJsonString(subscribeNotificationRequestObject)); + return Result.success(); + } +} diff --git a/src/main/java/com/objecteye/controller/SystemController.java b/src/main/java/com/objecteye/controller/SystemController.java new file mode 100644 index 0000000..c8ccbea --- /dev/null +++ b/src/main/java/com/objecteye/controller/SystemController.java @@ -0,0 +1,38 @@ +package com.objecteye.controller; + +import com.objecteye.handle.viid.CommonHandle; +import com.objecteye.pojo.DeviceIdParams; +import com.objecteye.pojo.Result; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@RestController +@RequestMapping("system") +@RequiredArgsConstructor +public class SystemController { + + private final CommonHandle commonHandle; + + @PostMapping("register") + public Result register(@RequestBody @Validated DeviceIdParams params) { + return Result.success(commonHandle.register(params.getDeviceId())); + } + + @PostMapping("unregister") + public Result unregister(@RequestBody @Validated DeviceIdParams params) { + return Result.success(commonHandle.unregister(params.getDeviceId())); + } + + @PostMapping("keepalive") + public Result keepalive(@RequestBody @Validated DeviceIdParams params) { + return Result.success(commonHandle.keepalive(params.getDeviceId())); + } +} diff --git a/src/main/java/com/objecteye/handle/StartUpAndShutdown.java b/src/main/java/com/objecteye/handle/StartUpAndShutdown.java index 846ecc4..82f33ea 100644 --- a/src/main/java/com/objecteye/handle/StartUpAndShutdown.java +++ b/src/main/java/com/objecteye/handle/StartUpAndShutdown.java @@ -1,13 +1,8 @@ package com.objecteye.handle; -import com.alibaba.nacos.common.utils.ExceptionUtil; -import com.fasterxml.jackson.databind.ObjectMapper; import com.objecteye.content.ViidCollectorRedisKey; -import com.objecteye.handle.viid.VIIDCommonHandle; -import com.objecteye.pojo.platform.DeviceRequestParams; +import com.objecteye.handle.viid.CommonHandle; import lombok.RequiredArgsConstructor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -26,32 +21,25 @@ import java.util.function.Consumer; @Component @RequiredArgsConstructor public class StartUpAndShutdown implements DisposableBean, ApplicationRunner { - private final VIIDCommonHandle viidCommonHandle; + private final CommonHandle commonHandle; private final StringRedisTemplate stringRedisTemplate; - private final ObjectMapper objectMapper; - - private final Logger logger = LoggerFactory.getLogger(StartUpAndShutdown.class); @Override public void destroy() throws Exception { - allCacheHandle(viidCommonHandle::unregister); + allCacheHandle(commonHandle::unregister); } @Override public void run(ApplicationArguments args) throws Exception { - allCacheHandle(viidCommonHandle::register); + allCacheHandle(commonHandle::register); } - private void allCacheHandle(Consumer func) { + private void allCacheHandle(Consumer func) { try (Cursor> cursor = stringRedisTemplate.boundHashOps(ViidCollectorRedisKey.DEVICE_CACHE) .scan(ScanOptions.scanOptions().build())) { while (cursor.hasNext()) { Map.Entry entry = cursor.next(); - try { - func.accept(objectMapper.readValue(entry.getValue().toString(), DeviceRequestParams.class)); - } catch (Exception e) { - logger.error(ExceptionUtil.getAllExceptionMsg(e)); - } + func.accept(entry.getKey().toString()); } } } diff --git a/src/main/java/com/objecteye/handle/viid/CommonHandle.java b/src/main/java/com/objecteye/handle/viid/CommonHandle.java new file mode 100644 index 0000000..3e56503 --- /dev/null +++ b/src/main/java/com/objecteye/handle/viid/CommonHandle.java @@ -0,0 +1,140 @@ +package com.objecteye.handle.viid; + +import com.objecteye.config.Gat1400Properties; +import com.objecteye.content.VIIDApi; +import com.objecteye.pojo.viid.common.KeepaliveRequestObject; +import com.objecteye.pojo.viid.common.RegisterObject; +import com.objecteye.pojo.viid.common.RegisterRequestObject; +import com.objecteye.pojo.viid.common.UnRegisterRequestObject; +import com.objecteye.utils.DigestUtils; +import com.objecteye.utils.JSONUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +/** + * @author: liuhaoyu + * @date: 2023/6/28 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class CommonHandle { + private final RestTemplate restTemplate; + private final Gat1400Properties gat1400Properties; + private static final String HTTP = "http://"; + + /** + * 注册 + * + * @param deviceId 注册目标设备 + * @return 注册结果 + */ + public boolean register(String deviceId) { + // 请求参数设置 + RegisterRequestObject registerRequestObject = new RegisterRequestObject(); + RegisterObject registerObject = new RegisterObject(); + registerObject.setDeviceId(deviceId); + registerRequestObject.setRegisterObject(registerObject); + return twoStepCheck(VIIDApi.REGISTER, deviceId, JSONUtils.toJsonString(registerRequestObject)); + } + + /** + * 保活 + * + * @param deviceId 心跳目标设备 + * @return 发送结果 + */ + public boolean keepalive(String deviceId) { + String keepaliveUrl = getAddress() + VIIDApi.KEEPALIVE; + // 请求参数设置 + KeepaliveRequestObject keepaliveRequestObject = new KeepaliveRequestObject(); + RegisterObject keepaliveObject = new RegisterObject(); + keepaliveObject.setDeviceId(deviceId); + keepaliveRequestObject.setKeepaliveObject(keepaliveObject); + if (log.isDebugEnabled()) { + log.debug("保活请求 url:{} ,参数:{}", keepaliveUrl, keepaliveRequestObject); + } + + HttpEntity httpEntity = new HttpEntity<>(JSONUtils.toJsonString(keepaliveRequestObject), + buildRequestHttpHeader(deviceId)); + // 请求执行 + ResponseEntity responseEntity = postForEntity(keepaliveUrl, httpEntity); + return org.apache.http.HttpStatus.SC_OK == responseEntity.getStatusCode().value(); + } + + /** + * 注销 + * + * @param deviceId 注销目标设备 + * @return 注销结果 + */ + public boolean unregister(String deviceId) { + // 请求参数设置 + UnRegisterRequestObject unRegisterRequestObject = new UnRegisterRequestObject(); + RegisterObject unRegisterObject = new RegisterObject(); + unRegisterObject.setDeviceId(deviceId); + unRegisterRequestObject.setUnRegisterObject(unRegisterObject); + return twoStepCheck(VIIDApi.UNREGISTER, deviceId, JSONUtils.toJsonString(unRegisterRequestObject)); + } + + private String getAddress() { + return HTTP + gat1400Properties.getServerAddress() + ":" + gat1400Properties.getPort(); + } + + private HttpHeaders buildRequestHttpHeader(String deviceId) { + // 请求头设置 + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-Type", "application/json;charset=UTF-8"); + headers.set("User-Identify", deviceId); + headers.setConnection("keepalive"); + return headers; + } + + private ResponseEntity postForEntity(String url, HttpEntity httpEntity) { + return restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); + } + + private boolean twoStepCheck(String uri, String deviceId, String requestJson) { + String url = getAddress() + uri; + // 请求头设置 + HttpHeaders headers = buildRequestHttpHeader(deviceId); + // 第一次请求 + ResponseEntity responseEntity = postForEntity(url, new HttpEntity<>(requestJson, headers)); + if (org.apache.http.HttpStatus.SC_UNAUTHORIZED == responseEntity.getStatusCode().value()) { + headers.set("Authorization", getAuthorization(responseEntity, url)); + // 第二次请求 + responseEntity = postForEntity(url, new HttpEntity<>(requestJson, headers)); + return org.apache.http.HttpStatus.SC_OK == responseEntity.getStatusCode().value(); + } + return false; + } + + private String getAuthorization(ResponseEntity responseEntity, String url) { + HttpHeaders responseEntityHeaders = responseEntity.getHeaders(); + String authenticate = responseEntityHeaders.get("WWW-Authenticate").get(0); + String[] children = authenticate.split(","); + String realm = null, qop = null, nonce = null, opaque = null, method = "POST"; + for (String item : children) { + String[] itemEntry = item.split("="); + if ("Digest realm".equals(itemEntry[0])) { + realm = itemEntry[1].replaceAll("\"", ""); + } else if ("qop".equals(itemEntry[0])) { + qop = itemEntry[1].replaceAll("\"", ""); + } else if ("nonce".equals(itemEntry[0])) { + nonce = itemEntry[1].replaceAll("\"", ""); + } + } + String nc = "00000001"; + String cnonce = DigestUtils.generateSalt2(8); + String response = DigestUtils.getResponse(gat1400Properties.getAccessKey(), realm, gat1400Properties.getSecurityKey(), + nonce, nc, cnonce, qop, method, url); + return DigestUtils.getAuthorization(gat1400Properties.getAccessKey(), realm, nonce, + url, qop, nc, cnonce, response, opaque); + } +} diff --git a/src/main/java/com/objecteye/handle/viid/SubscribeHandle.java b/src/main/java/com/objecteye/handle/viid/SubscribeHandle.java new file mode 100644 index 0000000..86507fe --- /dev/null +++ b/src/main/java/com/objecteye/handle/viid/SubscribeHandle.java @@ -0,0 +1,127 @@ +package com.objecteye.handle.viid; + +import com.objecteye.config.Gat1400Properties; +import com.objecteye.content.VIIDApi; +import com.objecteye.content.ViidCollectorRedisKey; +import com.objecteye.pojo.viid.subscribe.Subscribe; +import com.objecteye.pojo.viid.subscribe.SubscribeRequestObject; +import com.objecteye.utils.JSONUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class SubscribeHandle { + private final StringRedisTemplate stringRedisTemplate; + private final Gat1400Properties gat1400Properties; + private final RestTemplate restTemplate; + @Value("${receiver}") + private String receiver; + + public boolean subscribe(String deviceId) { + // 订阅统一标识码 = 公安机关机构代码 + 子类型编码(03-订阅)+ 时间编码(YYYYMMDDhhmmss) + 流水序号(00001) + String time = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").format(LocalDateTime.now()); + String toSecond = time.substring(0, 14); + String toMill = time.substring(14); + String subscribeId = "123456789012" + "03" + toSecond + StringUtils.leftPad(toMill, 5, "0"); + String title = "订阅人脸识别、车牌识别消息"; + // 订阅类别: 12-人脸信息 13-车辆信息 + String subscribeDetail = "12,13"; + + String beginTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()); + + String endTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now().plusMinutes(10L)); + + Integer operateType = 0; + + SubscribeRequestObject subscribeRequestObject = new SubscribeRequestObject(); + SubscribeRequestObject.SubscribeListObject subscribeListObject = new SubscribeRequestObject.SubscribeListObject(); + subscribeRequestObject.setSubscribeListObject(subscribeListObject); + + List subscribeList = new ArrayList<>(); + + Subscribe subscribe = new Subscribe(); + subscribe.setSubscribeId(subscribeId); + subscribe.setTitle(title); + subscribe.setSubscribeDetail(subscribeDetail); + subscribe.setResourceUri(deviceId); + subscribe.setBeginTime(beginTime); + subscribe.setEndTime(endTime); + subscribe.setReceiveAddr(receiver); + subscribe.setOperateType(operateType); + subscribeList.add(subscribe); + subscribeListObject.setSubscribeObject(subscribeList); + + HttpEntity httpEntity = new HttpEntity<>(JSONUtils.toJsonString(subscribeRequestObject), + buildHttpHeaders(deviceId)); + if (log.isDebugEnabled()) { + log.debug("上传人脸消息体:{}", JSONUtils.toJsonString(subscribeRequestObject)); + } + // 请求执行 + ResponseEntity responseEntity = restTemplate.exchange(getUrl(VIIDApi.SUBSCRIBES), HttpMethod.POST, + httpEntity, String.class); + if (org.apache.http.HttpStatus.SC_OK == responseEntity.getStatusCode().value()) { + stringRedisTemplate.opsForHash().put(ViidCollectorRedisKey.DEVICE_CACHE, deviceId, subscribeId); + return true; + } + return false; + } + + public boolean unsubscribe(String deviceId) { + Object subscribeIdObj = stringRedisTemplate.opsForHash().get(ViidCollectorRedisKey.DEVICE_CACHE, deviceId); + if (null == subscribeIdObj) { + return false; + } + SubscribeRequestObject subscribeRequestObject = new SubscribeRequestObject(); + SubscribeRequestObject.SubscribeListObject subscribeListObject = new SubscribeRequestObject.SubscribeListObject(); + subscribeRequestObject.setSubscribeListObject(subscribeListObject); + + List subscribeList = new ArrayList<>(); + + Subscribe subscribe = new Subscribe(); + subscribe.setSubscribeId(subscribeIdObj.toString()); + subscribe.setOperateType(1); + subscribeList.add(subscribe); + subscribeListObject.setSubscribeObject(subscribeList); + + HttpEntity httpEntity = new HttpEntity<>(JSONUtils.toJsonString(subscribeRequestObject), + buildHttpHeaders(deviceId)); + ResponseEntity responseEntity = restTemplate.exchange(getUrl(VIIDApi.SUBSCRIBES), + HttpMethod.POST, httpEntity, String.class); + if (org.apache.http.HttpStatus.SC_OK == responseEntity.getStatusCode().value()) { + stringRedisTemplate.opsForHash().delete(ViidCollectorRedisKey.DEVICE_CACHE, deviceId); + return true; + } + return false; + } + + private String getUrl(String uri) { + return "http://" + gat1400Properties.getServerAddress() + ":" + gat1400Properties.getPort() + uri; + } + + private HttpHeaders buildHttpHeaders(String deviceId) { + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-Type", "application/json;charset=utf-8"); + headers.set("User-Identify", deviceId); + return headers; + } +} diff --git a/src/main/java/com/objecteye/handle/viid/VIIDCommonHandle.java b/src/main/java/com/objecteye/handle/viid/VIIDCommonHandle.java deleted file mode 100644 index 10887b4..0000000 --- a/src/main/java/com/objecteye/handle/viid/VIIDCommonHandle.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.objecteye.handle.viid; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.objecteye.config.ApplicationConfigurationProperties; -import com.objecteye.content.VIIDApi; -import com.objecteye.content.enums.VIIDConfirmStatusTypeEnum; -import com.objecteye.pojo.platform.DeviceRequestParams; -import com.objecteye.pojo.viid.common.CommonDeviceIdRequestParams; -import com.objecteye.pojo.viid.common.ResponseStatusResponse; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; -import org.springframework.web.client.RestTemplate; - -/** - * @author: liuhaoyu - * @date: 2023/6/28 - */ -@Slf4j -@Component -@RequiredArgsConstructor -public class VIIDCommonHandle { - private final ObjectMapper objectMapper; - private final RestTemplate restTemplate; - private final ApplicationConfigurationProperties applicationConfigurationProperties; - private static final String CONTENT_TYPE = "application/*+JSON"; - private static final String HTTP = "http://"; - - /** - * 注册 - * - * @param deviceRequestParams 注册目标设备 - * @return 注册结果 - */ - public boolean register(DeviceRequestParams deviceRequestParams) { - return commonDeviceIdPost(deviceRequestParams, VIIDApi.REGISTER); - } - - /** - * 保活 - * - * @param deviceRequestParams 心跳目标设备 - * @return 发送结果 - */ - public boolean keepalive(DeviceRequestParams deviceRequestParams) { - return commonDeviceIdPost(deviceRequestParams, VIIDApi.KEEPALIVE); - } - - /** - * 注销 - * - * @param deviceRequestParams 注销目标设备 - * @return 注销结果 - */ - public boolean unregister(DeviceRequestParams deviceRequestParams) { - return commonDeviceIdPost(deviceRequestParams, VIIDApi.UNREGISTER); - } - - private boolean commonDeviceIdPost(DeviceRequestParams deviceRequestParams, String uri) { - return checkResponse(restTemplate.postForEntity(getAddress(deviceRequestParams) + uri, - buildHttpEntity(buildCommonDeviceIdRequestParam(deviceRequestParams)), String.class)); - } - - private CommonDeviceIdRequestParams buildCommonDeviceIdRequestParam(DeviceRequestParams deviceRequestParams) { - CommonDeviceIdRequestParams commonDeviceIdRequestParams = new CommonDeviceIdRequestParams(); - commonDeviceIdRequestParams.setDeviceId(applicationConfigurationProperties.getPlatformCode()); - return commonDeviceIdRequestParams; - } - - private String getAddress(DeviceRequestParams deviceRequestParams) { - return HTTP + deviceRequestParams.getHost() + ":" + deviceRequestParams.getPort(); - } - - private boolean checkResponse(ResponseEntity responseEntity) { - String body = responseEntity.getBody(); - if (StringUtils.hasText(body)) { - try { - ResponseStatusResponse responseStatusResponse = objectMapper.readValue(body, ResponseStatusResponse.class); - if (null == responseStatusResponse || null == responseStatusResponse.getStatusCode() || - !responseStatusResponse.getStatusCode().equals(VIIDConfirmStatusTypeEnum.OK.ordinal())) { - if (log.isDebugEnabled()) { - log.debug("register failed, {}", body); - } - return false; - } - return true; - } catch (JsonProcessingException e) { - if (log.isDebugEnabled()) { - log.debug("convert failed, {}", body); - } - return false; - } - } - return false; - } - - private HttpEntity buildHttpEntity(T t) { - HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE); - - return new HttpEntity<>(t, httpHeaders); - } -} diff --git a/src/main/java/com/objecteye/pojo/platform/DeviceRequestParams.java b/src/main/java/com/objecteye/pojo/DeviceIdParams.java index 036c7ef..abdce9c 100644 --- a/src/main/java/com/objecteye/pojo/platform/DeviceRequestParams.java +++ b/src/main/java/com/objecteye/pojo/DeviceIdParams.java @@ -1,25 +1,18 @@ -package com.objecteye.pojo.platform; +package com.objecteye.pojo; import lombok.Data; +import javax.validation.constraints.NotEmpty; import java.io.Serializable; /** * @author: liuhaoyu - * @date: 2023/6/28 + * @date: 2023/7/6 */ @Data -public class DeviceRequestParams implements Serializable { - private static final long serialVersionUID = -7801549061937667804L; +public class DeviceIdParams implements Serializable { + private static final long serialVersionUID = 2371999237808825162L; + @NotEmpty(message = "设备信息为空") private String deviceId; - - private String host; - - private String port; - - private String accessKey; - - private String securityKey; - } diff --git a/src/main/java/com/objecteye/pojo/Result.java b/src/main/java/com/objecteye/pojo/Result.java new file mode 100644 index 0000000..febfd33 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/Result.java @@ -0,0 +1,45 @@ +package com.objecteye.pojo; + +import lombok.Data; + +import java.io.Serializable; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class Result implements Serializable { + + private static final long serialVersionUID = -3498710365399499894L; + + private Integer code; + + private String message; + + private T data; + + public static Result success(T t) { + Result result = new Result<>(); + result.setCode(200); + result.setMessage("Success"); + result.setData(t); + return result; + } + + public static Result success() { + return success(null); + } + + public static Result failed(String message) { + return failed(message, null); + } + + public static Result failed(String message, T t) { + Result result = new Result<>(); + result.setCode(201); + result.setMessage(message); + result.setData(t); + return result; + } +} diff --git a/src/main/java/com/objecteye/pojo/viid/common/KeepaliveRequestObject.java b/src/main/java/com/objecteye/pojo/viid/common/KeepaliveRequestObject.java new file mode 100644 index 0000000..14e6223 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/common/KeepaliveRequestObject.java @@ -0,0 +1,15 @@ +package com.objecteye.pojo.viid.common; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class KeepaliveRequestObject { + + @JsonProperty("KeepaliveObject") + private RegisterObject keepaliveObject; +} diff --git a/src/main/java/com/objecteye/pojo/viid/common/CommonDeviceIdRequestParams.java b/src/main/java/com/objecteye/pojo/viid/common/RegisterObject.java index 61dba35..9b9d355 100644 --- a/src/main/java/com/objecteye/pojo/viid/common/CommonDeviceIdRequestParams.java +++ b/src/main/java/com/objecteye/pojo/viid/common/RegisterObject.java @@ -3,15 +3,12 @@ package com.objecteye.pojo.viid.common; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; -import java.io.Serializable; - /** * @author: liuhaoyu - * @date: 2023/6/28 + * @date: 2023/7/5 */ @Data -public class CommonDeviceIdRequestParams implements Serializable { - private static final long serialVersionUID = 1L; +public class RegisterObject { @JsonProperty("DeviceID") private String deviceId; diff --git a/src/main/java/com/objecteye/pojo/viid/common/RegisterRequestObject.java b/src/main/java/com/objecteye/pojo/viid/common/RegisterRequestObject.java new file mode 100644 index 0000000..5fbf823 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/common/RegisterRequestObject.java @@ -0,0 +1,15 @@ +package com.objecteye.pojo.viid.common; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class RegisterRequestObject { + + @JsonProperty("RegisterObject") + private RegisterObject registerObject; +} diff --git a/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusResponse.java b/src/main/java/com/objecteye/pojo/viid/common/ResponseStatus.java index ecc9f4a..529f480 100644 --- a/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusResponse.java +++ b/src/main/java/com/objecteye/pojo/viid/common/ResponseStatus.java @@ -10,7 +10,7 @@ import java.io.Serializable; * @date: 2023/6/28 */ @Data -public class ResponseStatusResponse implements Serializable { +public class ResponseStatus implements Serializable { private static final long serialVersionUID = 1L; diff --git a/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusListObject.java b/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusListObject.java new file mode 100644 index 0000000..6471f3d --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusListObject.java @@ -0,0 +1,23 @@ +package com.objecteye.pojo.viid.common; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class ResponseStatusListObject { + + @JsonProperty("ResponseStatusList") + private ResponseStatusList responseStatusList; + + @Data + public static class ResponseStatusList{ + @JsonProperty("ResponseStatusObject") + private List responseStatusObject; + } +} diff --git a/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusObjectWrapper.java b/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusObjectWrapper.java new file mode 100644 index 0000000..d7a18f2 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/common/ResponseStatusObjectWrapper.java @@ -0,0 +1,15 @@ +package com.objecteye.pojo.viid.common; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class ResponseStatusObjectWrapper { + + @JsonProperty("ResponseStatusObject") + private ResponseStatus responseStatusObject; +} diff --git a/src/main/java/com/objecteye/pojo/viid/common/SystemTimeObject.java b/src/main/java/com/objecteye/pojo/viid/common/SystemTimeObject.java new file mode 100644 index 0000000..7adb285 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/common/SystemTimeObject.java @@ -0,0 +1,27 @@ +package com.objecteye.pojo.viid.common; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class SystemTimeObject { + + @JsonProperty("SystemTime") + private SystemTime systemTime; + + @Data + public static class SystemTime { + @JsonProperty("VIIDServerID") + private String serverId; + @JsonProperty("TimeMode") + private String timeMode; + @JsonProperty("LocalTime") + private String localTime; + @JsonProperty("TimeZone") + private String timeZone; + } +} diff --git a/src/main/java/com/objecteye/pojo/viid/common/UnRegisterRequestObject.java b/src/main/java/com/objecteye/pojo/viid/common/UnRegisterRequestObject.java new file mode 100644 index 0000000..43969ee --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/common/UnRegisterRequestObject.java @@ -0,0 +1,15 @@ +package com.objecteye.pojo.viid.common; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class UnRegisterRequestObject { + + @JsonProperty("UnRegisterObject") + private RegisterObject unRegisterObject; +} diff --git a/src/main/java/com/objecteye/pojo/viid/detail/Face.java b/src/main/java/com/objecteye/pojo/viid/detail/Face.java new file mode 100644 index 0000000..4a15be2 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/detail/Face.java @@ -0,0 +1,46 @@ +package com.objecteye.pojo.viid.detail; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class Face { + + @JsonProperty("FaceID") + private String faceId; + @JsonProperty("InfoKind") + private Integer infoKind; + @JsonProperty("SourceID") + private String sourceId; + @JsonProperty("DeviceID") + private String deviceId; + @JsonProperty("LeftTopX") + private Integer leftTopX; + @JsonProperty("LeftTopY") + private Integer leftTopY; + @JsonProperty("RightBtmX") + private Integer rightBtmX; + @JsonProperty("RightBtmY") + private Integer rightBtmY; + @JsonProperty("IsDriver") + private Integer isDriver; + @JsonProperty("IsForeigner") + private Integer isForeigner; + @JsonProperty("IsSuspectedTerrorist") + private Integer isSuspectedTerrorist; + @JsonProperty("IsCriminalInvolved") + private Integer isCriminalInvolved; + @JsonProperty("IsDetainees") + private Integer isDetainees; + @JsonProperty("IsVictim") + private Integer isVictim; + @JsonProperty("IsSuspiciousPerson") + private Integer isSuspiciousPerson; + @JsonProperty("SubImageList") + private SubImageList subImageList; + +} diff --git a/src/main/java/com/objecteye/pojo/viid/detail/FaceRequestObject.java b/src/main/java/com/objecteye/pojo/viid/detail/FaceRequestObject.java new file mode 100644 index 0000000..e9bd4f8 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/detail/FaceRequestObject.java @@ -0,0 +1,24 @@ +package com.objecteye.pojo.viid.detail; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class FaceRequestObject { + + @JsonProperty("FaceListObject") + private FaceListObject faceListObject; + + @Data + public static class FaceListObject { + @JsonProperty("FaceObject") + private List faceObject; + } + +} diff --git a/src/main/java/com/objecteye/pojo/viid/detail/MotorVehicle.java b/src/main/java/com/objecteye/pojo/viid/detail/MotorVehicle.java new file mode 100644 index 0000000..596a31e --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/detail/MotorVehicle.java @@ -0,0 +1,43 @@ +package com.objecteye.pojo.viid.detail; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class MotorVehicle { + + @JsonProperty("MotorVehicleID") + private String motorVehicleId; + @JsonProperty("InfoKind") + private Integer infoKind; + @JsonProperty("SourceID") + private String sourceId; + @JsonProperty("DeviceID") + private String deviceId; + @JsonProperty("StorageUrl1") + private String storageUrl1; + @JsonProperty("LeftTopX") + private Integer leftTopX; + @JsonProperty("LeftTopY") + private Integer leftTopY; + @JsonProperty("RightBtmX") + private Integer rightBtmX; + @JsonProperty("RightBtmY") + private Integer rightBtmY; + @JsonProperty("HasPlate") + private Boolean hasPlate; + @JsonProperty("PlateClass") + private String plateClass; + @JsonProperty("PlateColor") + private String plateColor; + @JsonProperty("PlateNo") + private String plateNo; + @JsonProperty("VehicleColor") + private String vehicleColor; + @JsonProperty("SubImageList") + private SubImageList subImageList; +} diff --git a/src/main/java/com/objecteye/pojo/viid/detail/MotorVehicleRequestObject.java b/src/main/java/com/objecteye/pojo/viid/detail/MotorVehicleRequestObject.java new file mode 100644 index 0000000..81e2190 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/detail/MotorVehicleRequestObject.java @@ -0,0 +1,24 @@ +package com.objecteye.pojo.viid.detail; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class MotorVehicleRequestObject { + + @JsonProperty("MotorVehicleListObject") + private MotorVehicleListObject motorVehicleListObject; + + @Data + public static class MotorVehicleListObject { + + @JsonProperty("MotorVehicleObject") + private List motorVehicleObject; + } +} diff --git a/src/main/java/com/objecteye/pojo/viid/detail/SubImageInfo.java b/src/main/java/com/objecteye/pojo/viid/detail/SubImageInfo.java new file mode 100644 index 0000000..9c0c455 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/detail/SubImageInfo.java @@ -0,0 +1,67 @@ +package com.objecteye.pojo.viid.detail; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class SubImageInfo { + /** + * 图片ID【String(41)】 + */ + @JsonProperty("ImageID") + private String imageId; + /** + * 视频图像分析处理事件类型 + */ + @JsonProperty("EventSort") + private Integer eventSort; + /** + * 设备编码【String(20)】 + */ + @JsonProperty("DeviceID") + private String deviceId; + /** + * 存储路径 + */ + @JsonProperty("StoragePath") + private String storagePath; + /** + * 图像类型 + */ + @JsonProperty("ImageType") + private String imageType; + /** + * 图片格式 + */ + @JsonProperty("FileFormat") + private String fileFormat; + /** + * 拍摄时间【格式(yyyyMMddHHmmss)】 + */ + @JsonProperty("ShotTime") + private String shotTime; + /** + * 水平像素值 + */ + @JsonProperty("Width") + private Integer width; + /** + * 垂直像素值 + */ + @JsonProperty("Height") + private Integer height; + /** + * 图片(base64) + */ + @JsonProperty("Data") + private String data; + /** + * 图像类型(02-车牌彩色小图,11-人脸图) + */ + @JsonProperty("Type") + private String type; +} diff --git a/src/main/java/com/objecteye/pojo/viid/detail/SubImageList.java b/src/main/java/com/objecteye/pojo/viid/detail/SubImageList.java new file mode 100644 index 0000000..2178126 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/detail/SubImageList.java @@ -0,0 +1,17 @@ +package com.objecteye.pojo.viid.detail; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class SubImageList { + + @JsonProperty("SubImageInfoObject") + private List subImageInfoObject; +} diff --git a/src/main/java/com/objecteye/pojo/viid/subscribe/Subscribe.java b/src/main/java/com/objecteye/pojo/viid/subscribe/Subscribe.java index 47ed368..8f6c6bd 100644 --- a/src/main/java/com/objecteye/pojo/viid/subscribe/Subscribe.java +++ b/src/main/java/com/objecteye/pojo/viid/subscribe/Subscribe.java @@ -95,4 +95,29 @@ public class Subscribe implements Serializable { */ @JsonProperty("SubscribeStatus") private Integer subscribeStatus; + /** + * 订阅原因 + */ + @JsonProperty("Reason") + private String reason; + /** + * 取消订阅机构 + */ + @JsonProperty("SubscribeCancelOrg") + private String subscribeCancelOrg; + /** + * 取消订阅人员 + */ + @JsonProperty("SubscribeCancelPerson") + private String subscribeCancelPerson; + /** + * 取消时间 + */ + @JsonProperty("CancelTime") + private String cancelTime; + /** + * 取消原因 + */ + @JsonProperty("CancelReason") + private String cancelReason; } diff --git a/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeNotification.java b/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeNotification.java new file mode 100644 index 0000000..312cd6e --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeNotification.java @@ -0,0 +1,29 @@ +package com.objecteye.pojo.viid.subscribe; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.objecteye.pojo.viid.detail.FaceRequestObject; +import com.objecteye.pojo.viid.detail.MotorVehicleRequestObject; +import lombok.Data; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class SubscribeNotification { + + @JsonProperty("NotificationID") + private String notificationId; + @JsonProperty("SubscribeID") + private String subscribeId; + @JsonProperty("Title") + private String title; + @JsonProperty("TriggerTime") + private String triggerTime; + @JsonProperty("InfoIDs") + private String infoIds; + @JsonProperty("FaceListObject") + private FaceRequestObject.FaceListObject faceListObject; + @JsonProperty("MotorVehicleListObject") + private MotorVehicleRequestObject.MotorVehicleListObject motorVehicleListObject; +} diff --git a/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeNotificationRequestObject.java b/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeNotificationRequestObject.java new file mode 100644 index 0000000..65ab262 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeNotificationRequestObject.java @@ -0,0 +1,23 @@ +package com.objecteye.pojo.viid.subscribe; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/6 + */ +@Data +public class SubscribeNotificationRequestObject { + + @JsonProperty("SubscribeNotificationListObject") + private SubscribeNotificationListObject subscribeNotificationListObject; + + @Data + public static class SubscribeNotificationListObject { + @JsonProperty("SubscribeNotificationObject") + private List subscribeNotificationObject; + } +} diff --git a/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeRequestObject.java b/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeRequestObject.java new file mode 100644 index 0000000..2f590c6 --- /dev/null +++ b/src/main/java/com/objecteye/pojo/viid/subscribe/SubscribeRequestObject.java @@ -0,0 +1,23 @@ +package com.objecteye.pojo.viid.subscribe; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * @author: liuhaoyu + * @date: 2023/7/5 + */ +@Data +public class SubscribeRequestObject { + + @JsonProperty("SubscribeListObject") + private SubscribeListObject subscribeListObject; + + @Data + public static class SubscribeListObject { + @JsonProperty("SubscribeObject") + private List subscribeObject; + } +} diff --git a/src/main/java/com/objecteye/utils/DigestUtils.java b/src/main/java/com/objecteye/utils/DigestUtils.java new file mode 100644 index 0000000..0cbd931 --- /dev/null +++ b/src/main/java/com/objecteye/utils/DigestUtils.java @@ -0,0 +1,100 @@ +package com.objecteye.utils; + +import org.apache.commons.codec.binary.Hex; + +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.Random; + +public class DigestUtils { + + + /** + * 加密遵循RFC2671规范 将相关参数加密生成一个MD5字符串,并返回 + */ + public static String getResponse( + String username, + String realm, + String password, + String nonce, + String nc, + String cnonce, + String qop, + String method, + String uri + ) { + String A1 = username + ":" + realm + ":" + password; + byte[] md5ByteA1 = md5(A1.getBytes()); + String HA1 = new String(Hex.encodeHex(md5ByteA1)); + + String A2 = method + ":" + uri; + byte[] md5ByteA2 = md5(A2.getBytes()); + String HA2 = new String(Hex.encodeHex(md5ByteA2)); + + + String original = HA1 + ":" + (nonce + ":" + nc + ":" + cnonce + ":" + qop) + ":" + HA2; + byte[] md5ByteOriginal = md5(original.getBytes()); + return new String(Hex.encodeHex(md5ByteOriginal)); + } + + public static String getAuthorization(String username, String realm, String nonce, String uri, String qop, String nc, String cnonce, String response, String opaque) { + return "Digest username=\"" + username + "\"" + + ",realm=\"" + realm + "\"" + + ",nonce=\"" + nonce + "\"" + + ",uri=\"" + uri + "\"" + + ",qop=\"" + qop + "\"" + + ",nc=\"" + nc + "\"" + + ",cnonce=\"" + cnonce + "\"" + + ",response=\"" + response + "\"" + + ",opaque=\"" + opaque; + } + + + /** + * 对输入字符串进行md5散列. + */ + public static byte[] md5(byte[] input) { + return digest(input, "MD5", null, 1); + } + + /** + * 对字符串进行散列, 支持md5与sha1算法. + */ + private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) { + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + + if (salt != null) { + digest.update(salt); + } + + byte[] result = digest.digest(input); + + for (int i = 1; i < iterations; i++) { + digest.reset(); + result = digest.digest(result); + } + return result; + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + public static String generateSalt2(int length) { + StringBuilder val = new StringBuilder(); + Random random = new Random(); + //参数length,表示生成几位随机数 + for (int i = 0; i < length; i++) { + //输出字母还是数字 + if (random.nextInt(2) % 2 == 0) { + //输出是大写字母还是小写字母 + val.append((char) (random.nextInt(26) + random.nextInt(2) % 2 == 0 ? 65 : 97)); + } else { + val.append(random.nextInt(10)); + } + } + return val.toString().toLowerCase(); + } + + +} diff --git a/src/main/java/com/objecteye/utils/JSONUtils.java b/src/main/java/com/objecteye/utils/JSONUtils.java new file mode 100644 index 0000000..74b8d7c --- /dev/null +++ b/src/main/java/com/objecteye/utils/JSONUtils.java @@ -0,0 +1,404 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.objecteye.utils; + +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.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.fasterxml.jackson.databind.type.CollectionType; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.lang.Nullable; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; + +import static com.fasterxml.jackson.databind.DeserializationFeature.*; +import static com.fasterxml.jackson.databind.MapperFeature.REQUIRE_SETTERS_FOR_GETTERS; +import static com.objecteye.content.VIIDContent.YYYY_MM_DD_HH_MM_SS; +import static java.nio.charset.StandardCharsets.UTF_8; + +/** + * json utils + */ +@Slf4j +public class JSONUtils { + + static { + log.info("init timezone: {}", TimeZone.getDefault()); + } + + private static final ObjectMapper objectMapper = JsonMapper.builder() + .configure(FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true) + .configure(READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) + .configure(REQUIRE_SETTERS_FOR_GETTERS, true) + .addModule(new SimpleModule() + .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer()) + .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer())) + .defaultTimeZone(TimeZone.getDefault()) + .defaultDateFormat(new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS)) + .build(); + + private JSONUtils() { + throw new UnsupportedOperationException("Construct JSONUtils"); + } + + public static synchronized void setTimeZone(TimeZone timeZone) { + objectMapper.setTimeZone(timeZone); + } + + public static ArrayNode createArrayNode() { + return objectMapper.createArrayNode(); + } + + public static ObjectNode createObjectNode() { + return objectMapper.createObjectNode(); + } + + public static JsonNode toJsonNode(Object obj) { + return objectMapper.valueToTree(obj); + } + + /** + * json representation of object + * + * @param object object + * @param feature feature + * @return object to json string + */ + public static String toJsonString(Object object, SerializationFeature feature) { + try { + ObjectWriter writer = objectMapper.writer(feature); + return writer.writeValueAsString(object); + } catch (Exception e) { + log.error("object to json exception!", e); + } + + return null; + } + + /** + * This method deserializes the specified Json into an object of the specified class. It is not + * suitable to use if the specified class is a generic type since it will not have the generic + * type information because of the Type Erasure feature of Java. Therefore, this method should not + * be used if the desired type is a generic type. Note that this method works fine if the any of + * the fields of the specified object are generics, just the object itself should not be a + * generic type. + * + * @param json the string from which the object is to be deserialized + * @param clazz the class of T + * @param T + * @return an object of type T from the string + * classOfT + */ + public static @Nullable T parseObject(String json, Class clazz) { + if (StringUtils.isBlank(json)) { + return null; + } + + try { + return objectMapper.readValue(json, clazz); + } catch (Exception e) { + log.error("Parse object exception, jsonStr: {}, class: {}", json, clazz, e); + } + return null; + } + + /** + * deserialize + * + * @param src byte array + * @param clazz class + * @param deserialize type + * @return deserialize type + */ + public static T parseObject(byte[] src, Class clazz) { + if (src == null) { + return null; + } + String json = new String(src, UTF_8); + return parseObject(json, clazz); + } + + /** + * json to list + * + * @param json json string + * @param clazz class + * @param T + * @return list + */ + public static List toList(String json, Class clazz) { + if (StringUtils.isBlank(json)) { + return Collections.emptyList(); + } + + try { + CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, clazz); + return objectMapper.readValue(json, listType); + } catch (Exception e) { + log.error("parse list exception!", e); + } + + return Collections.emptyList(); + } + + /** + * check json object valid + * + * @param json json + * @return true if valid + */ + public static boolean checkJsonValid(String json) { + + if (StringUtils.isBlank(json)) { + return false; + } + + try { + objectMapper.readTree(json); + return true; + } catch (IOException e) { + log.error("check json object valid exception!", e); + } + + return false; + } + + /** + * Method for finding a JSON Object field with specified name in this + * node or its child nodes, and returning value it has. + * If no matching field is found in this node or its descendants, returns null. + * + * @param jsonNode json node + * @param fieldName Name of field to look for + * @return Value of first matching node found, if any; null if none + */ + public static String findValue(JsonNode jsonNode, String fieldName) { + JsonNode node = jsonNode.findValue(fieldName); + + if (node == null) { + return null; + } + + return node.asText(); + } + + /** + * json to map + * {@link #toMap(String, Class, Class)} + * + * @param json json + * @return json to map + */ + public static Map toMap(String json) { + return parseObject(json, new TypeReference>() { + }); + } + + /** + * json to map + * + * @param json json + * @param classK classK + * @param classV classV + * @param K + * @param V + * @return to map + */ + public static Map toMap(String json, Class classK, Class classV) { + if (StringUtils.isBlank(json)) { + return Collections.emptyMap(); + } + + try { + return objectMapper.readValue(json, new TypeReference>() { + }); + } catch (Exception e) { + log.error("json to map exception!", e); + } + + return Collections.emptyMap(); + } + + /** + * from the key-value generated json to get the str value no matter the real type of value + * @param json the json str + * @param nodeName key + * @return the str value of key + */ + public static String getNodeString(String json, String nodeName) { + try { + JsonNode rootNode = objectMapper.readTree(json); + JsonNode jsonNode = rootNode.findValue(nodeName); + if (Objects.isNull(jsonNode)) { + return ""; + } + return jsonNode.isTextual() ? jsonNode.asText() : jsonNode.toString(); + } catch (JsonProcessingException e) { + return ""; + } + } + + /** + * json to object + * + * @param json json string + * @param type type reference + * @param + * @return return parse object + */ + public static T parseObject(String json, TypeReference type) { + if (StringUtils.isBlank(json)) { + return null; + } + + try { + return objectMapper.readValue(json, type); + } catch (Exception e) { + log.error("json to map exception!", e); + } + + return null; + } + + /** + * object to json string + * + * @param object object + * @return json string + */ + public static String toJsonString(Object object) { + try { + return objectMapper.writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException("Object json deserialization exception.", e); + } + } + + public static String toPrettyJsonString(Object object) { + try { + return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException("Object json deserialization exception.", e); + } + } + + /** + * serialize to json byte + * + * @param obj object + * @param object type + * @return byte array + */ + public static byte[] toJsonByteArray(T obj) { + if (obj == null) { + return null; + } + String json = ""; + try { + json = toJsonString(obj); + } catch (Exception e) { + log.error("json serialize exception.", e); + } + + return json.getBytes(UTF_8); + } + + public static ObjectNode parseObject(String text) { + try { + if (StringUtils.isEmpty(text)) { + return parseObject(text, ObjectNode.class); + } else { + return (ObjectNode) objectMapper.readTree(text); + } + } catch (Exception e) { + throw new RuntimeException("String json deserialization exception.", e); + } + } + + public static ArrayNode parseArray(String text) { + try { + return (ArrayNode) objectMapper.readTree(text); + } catch (Exception e) { + throw new RuntimeException("Json deserialization exception.", e); + } + } + + /** + * json serializer + */ + public static class JsonDataSerializer extends JsonSerializer { + + @Override + public void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.writeRawValue(value); + } + + } + + /** + * json data deserializer + */ + public static class JsonDataDeserializer extends JsonDeserializer { + + @Override + public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + JsonNode node = p.getCodec().readTree(p); + if (node instanceof TextNode) { + return node.asText(); + } else { + return node.toString(); + } + } + + } + + public static class LocalDateTimeSerializer extends JsonSerializer { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS); + + @Override + public void serialize(LocalDateTime value, + JsonGenerator gen, + SerializerProvider serializers) throws IOException { + gen.writeString(value.format(formatter)); + } + } + + public static class LocalDateTimeDeserializer extends JsonDeserializer { + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS); + + @Override + public LocalDateTime deserialize(JsonParser p, DeserializationContext context) throws IOException { + return LocalDateTime.parse(p.getValueAsString(), formatter); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index e69de29..5bf1366 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -0,0 +1,23 @@ +gat1400: + server-address: 127.0.0.1 + port: 9000 + access-key: admin + security-key: 123456 +receiver: http://localhost:8888/receiver +spring: + application: + name: viid-collector + redis: + host: 192.168.60.126 + port: 6379 + timeout: 10000ms + lettuce: + pool: + max-active: 8 + max-wait: -1ms + min-idle: 0 + max-idle: 8 +logging: + level: + root: error + com.objecteye: debug \ No newline at end of file