作为上级,要支持下级的注册、保活、注销、校时的请求。
提供的url路径:
序号 |
功能 |
URI |
请求方法 |
1 |
注册 |
/VIID/System/Register |
POST |
2 |
注销 |
/VIID/System/UnRegister |
POST |
3 |
保活 |
/VIID/System/Keepalive |
POST |
4 |
校时 |
/VIID/System/Time |
GET |
application-dev.yml
server:
port: 10005
server1400:
dahua:
ip: 44.160.252.68
port: 9400
code: 35070000005031000001
username: ADMIN
password: ADMIN999
myip: 44.110.2.21
receiveAddr: http://${server1400.myip}:${server.port}
applicantName: 管理员
applicantOrg: xx公司
code: 35070000005031000155
会话管理接口 java 程序实现:
@Api(tags = "GAT/1400 会话管理接口")
@RestController
@RequestMapping("/VIID/System")
@Slf4j
public class SessionController {
@Autowired
private RestTemplate restTemplate;
@Value("${server1400.username}")
private String username;
@Value("${server1400.password}")
private String password;
@Value("${server1400.dahua.code:}")
private String dahuaCode;
String registerUrl, unRegisterUrl, keepaliveUrl, timeUrl;
public SessionController(
@Value("${server1400.dahua.ip}") String ip,
@Value("${server1400.dahua.port}") String port) {
registerUrl = "http://" + ip + ":" + port + "/VIID/System/Register";
unRegisterUrl = "http://" + ip + ":" + port + "/VIID/System/UnRegister";
keepaliveUrl = "http://" + ip + ":" + port + "/VIID/System/Keepalive";
timeUrl = "http://" + ip + ":" + port + "/VIID/System/Time";
}
@PostMapping("/Register")
@ApiOperation(value = "注册", httpMethod = "POST")
public Result register(@RequestBody String json) {
log.warn("json={}",json);
// 请求头设置
RegisterRequestObject obj = JSONObject.parseObject(json,RegisterRequestObject.class);
String deviceId = obj.getRegisterObject().getDeviceID();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
headers.set("User-Identify", deviceId);
headers.setConnection("keepalive");
// 请求参数设置
RegisterRequestObject registerRequestObject = new RegisterRequestObject();
RegisterRequestObject.RegisterObject registerObject = new RegisterRequestObject.RegisterObject();
registerObject.setDeviceID(deviceId);
registerRequestObject.setRegisterObject(registerObject);
HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(registerRequestObject), headers);
// 第一次请求
ResponseEntity<String> responseEntity = restTemplate.exchange(registerUrl, HttpMethod.POST, httpEntity, String.class);
int code = responseEntity.getStatusCode().value();
if (org.apache.http.HttpStatus.SC_UNAUTHORIZED == code) {
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 (int i = 0; i < children.length; i++) {
String item = children[i];
String[] itemEntry = item.split("=");
if (itemEntry[0].equals("Digest realm")) {
realm = itemEntry[1].replaceAll("\"", "");
} else if (itemEntry[0].equals("qop")) {
qop = itemEntry[1].replaceAll("\"", "");
} else if (itemEntry[0].equals("nonce")) {
nonce = itemEntry[1].replaceAll("\"", "");
}
}
String nc = "00000001";
String cnonce = DigestUtils.generateSalt2(8);
String response = DigestUtils.getResponse(username, realm, password, nonce, nc, cnonce, qop, method, registerUrl);
String authorization = DigestUtils.getAuthorization(username, realm, nonce, registerUrl, qop, nc, cnonce, response, opaque);
headers.set("Authorization", authorization);
// 第二次请求
httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(registerRequestObject), headers);
responseEntity = restTemplate.exchange(registerUrl, HttpMethod.POST, httpEntity, String.class);
code = responseEntity.getStatusCode().value();
if (org.apache.http.HttpStatus.SC_OK == code) {
String body = responseEntity.getBody();
return Result.success();
}
}
return Result.failed("注册失败");
}
@AuthIgnore
@PostMapping("/Keepalive")
@ApiOperation(value = "保活", httpMethod = "POST")
public Result keepalive(@RequestBody String json) {
log.warn("json={}",json);
KeepaliveRequestObject obj = JSONObject.parseObject(json,KeepaliveRequestObject.class);
String deviceId = obj.getKeepaliveObject().getDeviceID();
// 请求头设置
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
headers.set("User-Identify", deviceId);
headers.setConnection("keepalive");
// 请求参数设置
KeepaliveRequestObject keepaliveRequestObject = new KeepaliveRequestObject();
KeepaliveRequestObject.KeepaliveObject keepaliveObject = new KeepaliveRequestObject.KeepaliveObject();
keepaliveObject.setDeviceID(deviceId);
keepaliveRequestObject.setKeepaliveObject(keepaliveObject);
log.warn("保活请求 url:{} ,参数:{}", keepaliveUrl, keepaliveRequestObject);
HttpEntity<KeepaliveRequestObject> httpEntity = new HttpEntity<>(keepaliveRequestObject, headers);
// 请求执行
ResponseEntity<String> responseEntity = restTemplate.exchange(keepaliveUrl, HttpMethod.POST, httpEntity, String.class);
if (org.apache.http.HttpStatus.SC_OK == responseEntity.getStatusCode().value()) {
return Result.success();
}
return Result.failed("保活失败");
}
@AuthIgnore
@PostMapping("/UnRegister")
@ApiOperation(value = "注销", httpMethod = "POST")
public Result unregister(@RequestBody String json) {
log.warn("json={}",json);
UnRegisterRequestObject obj = JSONObject.parseObject(json,UnRegisterRequestObject.class);
String deviceId = obj.getUnRegisterObject().getDeviceID();
// 请求头设置
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
headers.set("User-Identify", deviceId);
headers.setConnection("keepalive");
// 请求参数设置
UnRegisterRequestObject unRegisterRequestObject = new UnRegisterRequestObject();
UnRegisterRequestObject.UnRegisterObject unRegisterObject = new UnRegisterRequestObject.UnRegisterObject();
unRegisterObject.setDeviceID(dahuaCode);
unRegisterRequestObject.setUnRegisterObject(unRegisterObject);
HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(unRegisterRequestObject), headers);
// 第一次请求
ResponseEntity<String> responseEntity = restTemplate.exchange(unRegisterUrl, HttpMethod.POST, httpEntity, String.class);
if (org.apache.http.HttpStatus.SC_UNAUTHORIZED == responseEntity.getStatusCode().value()) {
HttpHeaders responseEntityHeaders = responseEntity.getHeaders();
String authenticate = responseEntityHeaders.get("WWW-Authenticate").get(0);
String[] children = authenticate.split(",");
// Digest realm="myrealm",qop="auth",nonce="dmktZGlnZXN0OjQzNTQyNzI3Nzg="
String realm = null, qop = null, nonce = null, opaque = null, method = "POST";
;
for (int i = 0; i < children.length; i++) {
String item = children[i];
String[] itemEntry = item.split("=");
if (itemEntry[0].equals("Digest realm")) {
realm = itemEntry[1].replaceAll("\"", "");
} else if (itemEntry[0].equals("qop")) {
qop = itemEntry[1].replaceAll("\"", "");
} else if (itemEntry[0].equals("nonce")) {
nonce = itemEntry[1].replaceAll("\"", "");
}
}
String nc = "00000001";
String cnonce = DigestUtils.generateSalt2(8);
String response = DigestUtils.getResponse(username, realm, password, nonce, nc, cnonce, qop, method, unRegisterUrl);
String authorization = DigestUtils.getAuthorization(username, realm, nonce, unRegisterUrl, qop, nc, cnonce, response, opaque);
headers.set("Authorization", authorization);
// 第二次请求
httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(unRegisterRequestObject), headers);
responseEntity = restTemplate.exchange(unRegisterUrl, HttpMethod.POST, httpEntity, String.class);
if (org.apache.http.HttpStatus.SC_OK == responseEntity.getStatusCode().value()) {
return Result.success();
}
}
return Result.failed("注销失败");
}
@AuthIgnore
@GetMapping("/Time")
@ApiOperation(value = "校时", httpMethod = "GET")
public Result time(@RequestBody String json) {
log.warn("json={}",json);
UnRegisterRequestObject obj = JSONObject.parseObject(json,UnRegisterRequestObject.class);
String deviceId = obj.getUnRegisterObject().getDeviceID();
// 请求头设置
HttpHeaders headers = new HttpHeaders();
headers.set("User-Identify", deviceId);
headers.setConnection("keepalive");
HttpEntity<Object> httpEntity = new HttpEntity<>(null, headers);
ResponseEntity<SystemTimeObject> entity = restTemplate.getForEntity(timeUrl, SystemTimeObject.class, httpEntity);
SystemTimeObject.SystemTime systemTime = entity.getBody().getSystemTime();
String time = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
return Result.success(time);
}
}
涉及到的实体类:
RegisterObject.java
@Data
public class RegisterRequestObject {
private RegisterObject RegisterObject;
@Data
public static class RegisterObject {
private String DeviceID;
}
}
KeepaliveRequestObject.java
@Data
public class KeepaliveRequestObject {
private KeepaliveObject KeepaliveObject;
@Data
public static class KeepaliveObject {
private String DeviceID;
}
}
UnRegisterRequestObject.java
@Data
public class UnRegisterRequestObject {
private UnRegisterObject UnRegisterObject;
@Data
public static class UnRegisterObject {
private String DeviceID;
}
}
SystemTimeObject.java
@Data
public class SystemTimeObject {
private SystemTime SystemTime;
@Data
public class SystemTime{
private String VIIDServerID;
private String TimeMode;
private String LocalTime;
private String TimeZone;
}
}
Result.java
@Data
public class Result<T> implements Serializable {
private String code;
private T data;
private String msg;
@JsonInclude(JsonInclude.Include.NON_NULL)
private Long total;
public static <T> Result<T> success() {
return success(null);
}
public static <T> Result<T> success(T data) {
ResultCode rce = ResultCode.SUCCESS;
if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
rce = ResultCode.SYSTEM_EXECUTION_ERROR;
}
return result(rce, data);
}
public static <T> Result<T> failed() {
return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), ResultCode.SYSTEM_EXECUTION_ERROR.getMsg(), null);
}
public static <T> Result<T> failed(String msg) {
return result(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), msg, null);
}
public static <T> Result<T> status(boolean status) {
if (status) {
return success();
} else {
return failed();
}
}
public static <T> Result<T> failed(IResultCode resultCode) {
return result(resultCode.getCode(), resultCode.getMsg(), null);
}
private static <T> Result<T> result(IResultCode resultCode, T data) {
return result(resultCode.getCode(), resultCode.getMsg(), data);
}
private static <T> Result<T> result(String code, String msg, T data) {
Result<T> result = new Result<T>();
result.setCode(code);
result.setData(data);
result.setMsg(msg);
return result;
}
public static <T> Result<T> success(T data, Long total) {
Result<T> result = new Result();
result.setCode(ResultCode.SUCCESS.getCode());
result.setMsg(ResultCode.SUCCESS.getMsg());
result.setData(data);
result.setTotal(total);
return result;
}
}
IResultCode.java
public interface IResultCode {
String getCode();
String getMsg();
}
ResultCode.java
public enum ResultCode implements IResultCode, Serializable {
SUCCESS("00000","一切ok"),
SYSTEM_EXECUTION_ERROR("B0001","系统执行出错");
@Override
public String getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
private String code;
private String msg;
}
SubscribeReq.java
@ApiModel
@Data
public class SubscribeReq {
@ApiModelProperty(value = "设备ID", example = "13030421191190201061", required = true)
private String deviceId;
private String type;
}
订阅与接收
@Api(tags = "GAT/1400 订阅接口")
@RestController
@RequestMapping("/v1/subscribe")
@Slf4j
public class SubscribeController {
@Autowired
private RestTemplate restTemplate;
@Value("${server1400.receiveAddr:}")
private String receiveAddr;
@Value("${server1400.applicantName:}")
private String applicantName;
@Value("${server1400.applicantOrg:}")
private String applicantOrg;
@Value("${server1400.dahua.code:}")
private String dahuaCode;
//订阅后接收通知的时间间隔
@Value("${server1400.reportInterval:10}")
private int reportInterval;
private int days = 300;
String subscribeUrl;
public SubscribeController(
@Value("${server1400.dahua.ip}") String ip,
@Value("${server1400.dahua.port}") String port) {
subscribeUrl = "http://" + ip + ":" + port + "/VIID/Subscribes";
}
@PostMapping
@ApiOperation(value = "订阅", httpMethod = "POST")
@RequestMapping("/subByType")
public Result subByType(@RequestBody SubscribeReq subscribeReq) {
String title = "";
String receiveUrl = receiveAddr+"/v1/subscribe/receiveXtml";
String subscribeDetail = subscribeReq.getType();; // 订阅类别
String ResultImageDeclare = "-1";
String ResultFeatureDeclare = "-1";
switch (subscribeDetail){
case "5":
title = "订阅采集系统目录";
receiveUrl = receiveAddr+"/v1/subscribe/receiveXtml";
ResultImageDeclare = "-1";
ResultFeatureDeclare = "-1";
break;
case "3":
title = "订阅采集设备目录";
receiveUrl = receiveAddr+"/v1/subscribe/receiveSbml";
ResultImageDeclare = "-1";
ResultFeatureDeclare = "-1";
break;
case "12":
title = "订阅人脸识别消息";
receiveUrl = receiveAddr+"/v1/subscribe/receiveFace";
ResultImageDeclare = "-1";
ResultFeatureDeclare = "-1";
break;
}
// 订阅统一标识码 = *机关机构代码 + 子类型编码(03-订阅)+ 时间编码(YYYYMMDDhhmmss) + 流水序号(00001)
String time = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
Random random = new Random();
int xh = 10000+random.nextInt(1000);
String subscribeID = "350700000050" + "03" + time + xh;
// 订阅资源路径 赋值为 下级平台的国标编码
String resourceURI = dahuaCode; // 订阅资源路径
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().plusDays(days));
Integer operateType = 0;
SubscribeRequestObject subscribeRequestObject = new SubscribeRequestObject();
SubscribeRequestObject.SubscribeListObject subscribeListObject = new SubscribeRequestObject.SubscribeListObject();
subscribeRequestObject.setSubscribeListObject(subscribeListObject);
List<SubscribeRequestObject.Subscribe> subscribeList = new ArrayList<>();
SubscribeRequestObject.Subscribe subscribe = new SubscribeRequestObject.Subscribe();
subscribe.setSubscribeID(subscribeID);
subscribe.setTitle(title);
subscribe.setSubscribeDetail(subscribeDetail);
subscribe.setResourceURI(dahuaCode);
subscribe.setApplicantName(applicantName);
subscribe.setApplicantOrg(applicantOrg);
subscribe.setBeginTime(beginTime);
subscribe.setEndTime(endTime);
subscribe.setReceiveAddr(receiveUrl);
subscribe.setOperateType(operateType);
subscribe.setResultFeatureDeclare(ResultFeatureDeclare);
subscribe.setResultImageDeclare(ResultImageDeclare);
subscribe.setReportInterval(reportInterval);
subscribeList.add(subscribe);
subscribeListObject.setSubscribeObject(subscribeList);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
headers.set("User-Identify", dahuaCode);
String bodyStr = JSONUtil.toJsonStr(subscribeRequestObject);
HttpEntity<String> httpEntity = new HttpEntity<>(bodyStr, headers);
// 请求执行
try{
ResponseEntity<String> responseEntity = restTemplate.exchange(subscribeUrl, HttpMethod.POST, httpEntity, String.class);
int code = responseEntity.getStatusCode().value();
if (org.apache.http.HttpStatus.SC_OK == code) {
String body = responseEntity.getBody();
return Result.success();
}
}catch(Exception e){
log.error("有异常:{}",e.getMessage());
}finally {
}
return Result.failed("订阅失败");
}
@PostMapping("/receiveFace")
public Result receiveFace(@RequestBody String json) {
log.warn("receiveFace...");
//初始json
JSONObject obj1 = JSONObject.parseObject(json);
//第一层JSONObject
JSONObject obj2 = obj1.getJSONObject("SubscribeNotificationListObject");
//第一层JSONObject中的JSONArray
JSONArray arr1 = obj2.getJSONArray("SubscribeNotificationObject");
for (int i = 0; i < arr1.size(); i++) {
JSONObject obj3 = arr1.getJSONObject(i);
JSONObject obj4 = obj3.getJSONObject("FaceObjectList");
JSONArray arr2 = obj4.getJSONArray("FaceObject");
int len = arr2.size();
for (int j = 0; j < len; j++) {
//obj5,就是对应的人脸数据结构
JSONObject obj5 = arr2.getJSONObject(i);
String DeviceID = obj5.getString("DeviceID");
String FaceID = obj5.getString("FaceID");
String SourceID = obj5.getString("SourceID");
String ShotTime = obj5.getString("ShotTime");
//图片
JSONObject obj6 = obj5.getJSONObject("SubImageList");
//arr3就是图片的结构
JSONArray arr3 = obj6.getJSONArray("SubImageInfoObject");
//...
}
}
return Result.success();
}
@PostMapping("/receiveXtml")
public Result receiveXtml(@RequestBody String json) {
log.warn("receiveXtml...");
return Result.success();
}
@PostMapping("/receiveSbml")
public Result receiveSbml(@RequestBody String json) {
log.warn("receiveSbml...");
return Result.success();
}
@PostMapping
@ApiOperation(value = "取消订阅", httpMethod = "POST")
@RequestMapping("/cancelSubV2")
public Result cancelSubV2(@RequestBody String json){
JSONObject obj = JSONObject.parseObject(json);
String id = obj.getString("id");
SubscribeRequestObject.Subscribe rec = new SubscribeRequestObject.Subscribe();
rec.setSubscribeID(id);
rec.setOperateType(1);
rec.setSubscribeCancelOrg(applicantOrg);
rec.setSubscribeCancelPerson(applicantName);
rec.setCancelTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
rec.setCancelReason("取消订阅");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
headers.set("User-Identify", dahuaCode);
Map<String,Object> map = new HashMap<>();
map.put("SubscribeObject",rec);
String bodyStr = JSON.toJSONString(map);
HttpEntity<String> httpEntity = new HttpEntity<>(bodyStr, headers);
// 请求执行
String url = subscribeUrl+"/"+id;
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class);
int code = responseEntity.getStatusCode().value();
if (org.apache.http.HttpStatus.SC_OK == code) {
String body = responseEntity.getBody();
// log.warn("取消订阅OK");
return Result.success();
}
return Result.failed("取消订阅失败");
}
}