首页 > 其他分享 >149-gat1400对接(作为上级,与下级对接)

149-gat1400对接(作为上级,与下级对接)

时间:2022-12-19 18:35:45浏览次数:45  
标签:gat1400 String 对接 private 149 headers Result new public

作为上级,要支持下级的注册、保活、注销、校时的请求。

提供的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("取消订阅失败");
    }
	
	
}

标签:gat1400,String,对接,private,149,headers,Result,new,public
From: https://blog.51cto.com/u_14816966/5953484

相关文章

  • 「Editorial」Codeforces Contest 1149
    C.TreeGenerator™容易发现树上一条路径一定形如))...)((...(。也就是对于任意子段,去掉匹配了的括号后还剩下的部分。而这个东西还是不太好表示,我们有如下引理:这个值......
  • 物流行业对接BMW EDI项目案例分析
    宝马集团的悠久历史始于1916年,总部位于德国慕尼黑。是德国最成功的汽车和摩托车制造商之一,也是德国规模最大的制造工业公司之一。项目背景物流行业C公司作为BMW的承运商,......
  • 浙里办H5对接单点登录
    准备工作vue.config中设置 publicPath:'./',    outputDir:'build',路由改为Hash模式       准备好key值  ,问申请组件的人要   a......
  • 招商银行企银直连 招行云直连 国密SM2 SM4 PHP实现对接
    研究了好久好久,终于搞定了,参考了网上很多代码,网上所有的代码多多少少都有问题,要么是各种报错,要么是能签字不能验签,要么是有时候成功有时候失败。就截止2022.12.13日此时,网......
  • 微信公众号服务号配置对接在线客服系统教程
    如果只需要实现微信公众号的关注自动回复,关键词自动回复功能,普通订阅号就可以当需要对接实现公众号的模板消息提醒,模板消息与客服端H5的对接,访客在微信点击或扫码时获取到......
  • 8100视频中台如何对接报警信息
    1.配置视频中台信息推送地址  2.在对应业务系统中开发接受信息接口//接口地址自定义@RequestMapping(value=“/notifyVideoOnlineStatus”)publicResultEntityn......
  • W公司对接奥迪Audi EDI项目案例
    项目背景奥迪(Audi)是德国大众汽车集团子公司奥迪汽车公司旗下的豪华汽车品牌,作为高技术水平、质量标准、创新能力、以及经典车型款式的代表,奥迪是汽车品牌之一。公司总部设......
  • springboot集成kettle实现对接oracle数据
    简单记录一下springboot引用kettle对接数据第一步(这一步讲述了下载kettle、创建数据库连接、转换等,如果这一步会的可以略过,直接看第二步)先从kettle官网下载kettle,官网地......
  • 对接苹果 https://appleid.apple.com/auth/token
    c# 对接苹果 https://appleid.apple.com/auth/tokenusingMicrosoft.IdentityModel.Tokens;usingMobaFlyx.Utils;usingSystem;usingSystem.Collections.Generic......
  • Peppol网络对接流程
    Peppol代表泛欧在线公共采购,现在连接到Peppol的组织可以通过高度安全的国际网络交换商业文件。知行软件通过了PEPPOL的AS2及AS4测试,被OpenPEPPOLAISBL正式认证......