repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/DeviceControlPosition.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/DeviceControlPosition.java
package io.github.lunasaw.gb28181.common.entity.control; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * * <?xml version="1.0" encoding="UTF-8"?> * <Control> * <CmdType>DeviceControl</CmdType> * <SN>840481</SN> * <DeviceID>channelId</DeviceID> * <HomePosition> * <Enabled>1</Enabled> * <ResetTime>resetTime</ResetTime> * <PresetIndex>presetIndex</PresetIndex> * </HomePosition> * </Control> * * @author luna */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @XmlRootElement(name = "Control") @XmlAccessorType(XmlAccessType.FIELD) public class DeviceControlPosition extends DeviceControlBase { @XmlElement(name = "HomePosition") public HomePosition homePosition; public DeviceControlPosition(String cmdType, String sn, String deviceId) { super(cmdType, sn, deviceId); this.setControlType("HomePosition"); } public static void main(String[] args) { DeviceControlPosition alarm = new DeviceControlPosition(); alarm.setCmdType("DeviceControl"); alarm.setSn("179173"); alarm.setDeviceId("123"); HomePosition homePosition = new HomePosition(); homePosition.setEnabled("1"); homePosition.setResetTime("222"); homePosition.setPresetIndex("2"); alarm.setHomePosition(homePosition); System.out.println(alarm); } @Getter @Setter @AllArgsConstructor @NoArgsConstructor @XmlRootElement(name = "HomePosition") @XmlAccessorType(XmlAccessType.FIELD) public static class HomePosition { @XmlElement(name = "Enabled") public String enabled; @XmlElement(name = "ResetTime") public String resetTime; @XmlElement(name = "PresetIndex") private String presetIndex; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/DeviceControlTeleBoot.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/DeviceControlTeleBoot.java
package io.github.lunasaw.gb28181.common.entity.control; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * @author luna */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @XmlRootElement(name = "Control") @XmlAccessorType(XmlAccessType.FIELD) public class DeviceControlTeleBoot extends DeviceControlBase { @XmlElement(name = "TeleBoot") private String teleBoot = "Boot"; public DeviceControlTeleBoot(String cmdType, String sn, String deviceId) { super(cmdType, sn, deviceId); this.setControlType("TeleBoot"); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionFormat.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionFormat.java
package io.github.lunasaw.gb28181.common.entity.control.instruction; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * PTZ指令格式基础类 * 根据 A.3.1 指令格式 规范实现 * <p> * 字节1: A5H (指令首字节) * 字节2: 组合码1 (高4位版本信息 + 低4位校验位) * 字节3: 地址低8位 * 字节4: 指令码 * 字节5: 数据1 * 字节6: 数据2 * 字节7: 组合码2 (高4位数据3 + 低4位地址高4位) * 字节8: 校验码 */ @Data @NoArgsConstructor @AllArgsConstructor public class PTZInstructionFormat { /** * 指令首字节 固定为A5H */ public static final byte INSTRUCTION_HEADER = (byte) 0xA5; /** * 版本信息 本标准版本1.0 */ public static final byte VERSION = 0x0; /** * 字节1: 指令首字节 A5H */ private byte header = INSTRUCTION_HEADER; /** * 字节2: 组合码1 */ private byte combinationCode1; /** * 字节3: 地址低8位 */ private byte addressLow; /** * 字节4: 指令码 */ private byte instructionCode; /** * 字节5: 数据1 */ private byte data1; /** * 字节6: 数据2 */ private byte data2; /** * 字节7: 组合码2 */ private byte combinationCode2; /** * 字节8: 校验码 */ private byte checksum; /** * 构造函数 * * @param address 设备地址 (0x000-0xFFF) * @param instructionCode 指令码 * @param data1 数据1 * @param data2 数据2 * @param data3 数据3 (组合码2高4位) */ public PTZInstructionFormat(int address, byte instructionCode, byte data1, byte data2, byte data3) { this.header = INSTRUCTION_HEADER; this.addressLow = (byte) (address & 0xFF); this.instructionCode = instructionCode; this.data1 = data1; this.data2 = data2; // 计算组合码1 this.combinationCode1 = calculateCombinationCode1(); // 计算组合码2 this.combinationCode2 = (byte) (((data3 & 0x0F) << 4) | ((address >> 8) & 0x0F)); // 计算校验码 this.checksum = calculateChecksum(); } /** * 计算组合码1 * 校验位 = (字节1的高4位 + 字节1的低4位 + 字节2的高4位) % 16 */ private byte calculateCombinationCode1() { int headerHigh = (header >> 4) & 0x0F; int headerLow = header & 0x0F; int versionInfo = VERSION; int checkBit = (headerHigh + headerLow + versionInfo) % 16; return (byte) ((versionInfo << 4) | checkBit); } /** * 计算校验码 * 字节8 = (字节1 + 字节2 + 字节3 + 字节4 + 字节5 + 字节6 + 字节7) % 256 */ private byte calculateChecksum() { int sum = (header & 0xFF) + (combinationCode1 & 0xFF) + (addressLow & 0xFF) + (instructionCode & 0xFF) + (data1 & 0xFF) + (data2 & 0xFF) + (combinationCode2 & 0xFF); return (byte) (sum % 256); } /** * 重新计算校验码 */ public void recalculateChecksum() { this.combinationCode1 = calculateCombinationCode1(); this.checksum = calculateChecksum(); } /** * 获取完整地址 */ public int getFullAddress() { return ((combinationCode2 & 0x0F) << 8) | (addressLow & 0xFF); } /** * 获取数据3 */ public byte getData3() { return (byte) ((combinationCode2 >> 4) & 0x0F); } /** * 转换为字节数组 */ public byte[] toByteArray() { return new byte[]{ header, combinationCode1, addressLow, instructionCode, data1, data2, combinationCode2, checksum }; } /** * 从字节数组创建指令 */ public static PTZInstructionFormat fromByteArray(byte[] bytes) { if (bytes == null || bytes.length != 8) { throw new IllegalArgumentException("指令字节数组长度必须为8"); } PTZInstructionFormat instruction = new PTZInstructionFormat(); instruction.header = bytes[0]; instruction.combinationCode1 = bytes[1]; instruction.addressLow = bytes[2]; instruction.instructionCode = bytes[3]; instruction.data1 = bytes[4]; instruction.data2 = bytes[5]; instruction.combinationCode2 = bytes[6]; instruction.checksum = bytes[7]; return instruction; } /** * 转换为十六进制字符串 */ public String toHexString() { StringBuilder sb = new StringBuilder(); for (byte b : toByteArray()) { sb.append(String.format("%02X", b & 0xFF)); } return sb.toString(); } /** * 从十六进制字符串解析 */ public static PTZInstructionFormat fromHexString(String hexString) { if (hexString == null || hexString.length() != 16) { throw new IllegalArgumentException("十六进制字符串长度必须为16"); } byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) { String hex = hexString.substring(i * 2, i * 2 + 2); bytes[i] = (byte) Integer.parseInt(hex, 16); } return fromByteArray(bytes); } /** * 验证指令格式是否正确 */ public boolean isValid() { // 验证首字节 if (header != INSTRUCTION_HEADER) { return false; } // 验证校验码 byte expectedChecksum = calculateChecksum(); return checksum == expectedChecksum; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionDemo.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionDemo.java
package io.github.lunasaw.gb28181.common.entity.control.instruction; import io.github.lunasaw.gb28181.common.entity.control.instruction.builder.PTZInstructionBuilder; import io.github.lunasaw.gb28181.common.entity.control.instruction.enums.PTZControlEnum; import io.github.lunasaw.gb28181.common.entity.control.instruction.manager.PTZInstructionManager; import io.github.lunasaw.gb28181.common.entity.control.instruction.serializer.PTZInstructionSerializer; /** * PTZ指令系统演示 */ public class PTZInstructionDemo { public static void main(String[] args) { System.out.println("=== PTZ指令系统演示 ==="); // 1. 使用Builder模式创建PTZ控制指令 PTZInstructionFormat rightMoveInstruction = PTZInstructionBuilder.create() .address(0x001) // 设备地址 .addPTZControl(PTZControlEnum.PAN_RIGHT) // 右移控制 .horizontalSpeed(0x40) // 水平速度 .verticalSpeed(0x20) // 垂直速度 .zoomSpeed(0x0F) // 变倍速度 .build(); System.out.println("1. 右移指令: " + rightMoveInstruction.toHexString()); System.out.println(" 指令有效性: " + rightMoveInstruction.isValid()); // 2. 序列化演示 String hexString = PTZInstructionSerializer.serializeToHex(rightMoveInstruction); String base64String = PTZInstructionSerializer.serializeToBase64(rightMoveInstruction); System.out.println("2. 序列化结果:"); System.out.println(" 十六进制: " + hexString); System.out.println(" Base64: " + base64String); // 3. 反序列化验证 PTZInstructionFormat deserialized = PTZInstructionSerializer.deserializeFromHex(hexString); System.out.println("3. 反序列化验证: " + deserialized.isValid()); // 4. 指令管理器演示 PTZInstructionManager.InstructionType type = PTZInstructionManager.getInstructionType((byte) 0x01); String description = PTZInstructionManager.getInstructionDescription((byte) 0x01); System.out.println("4. 指令管理:"); System.out.println(" 指令类型: " + (type != null ? type.getName() : "未知")); System.out.println(" 指令描述: " + description); // 5. 统计信息 PTZInstructionManager.InstructionStatistics stats = PTZInstructionManager.getStatistics(); System.out.println("5. 系统统计:"); System.out.println(" 总指令数: " + stats.getTotalCount()); System.out.println("\n=== 演示完成 ==="); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionCoreValidation.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionCoreValidation.java
package io.github.lunasaw.gb28181.common.entity.control.instruction; import io.github.lunasaw.gb28181.common.entity.control.instruction.builder.PTZInstructionBuilder; import io.github.lunasaw.gb28181.common.entity.control.instruction.enums.*; import io.github.lunasaw.gb28181.common.entity.control.instruction.manager.PTZInstructionManager; /** * PTZ指令系统核心验证程序(无外部依赖版本) * 验证所有核心指令生成和解析功能 */ public class PTZInstructionCoreValidation { private static int testCount = 0; private static int passCount = 0; private static int failCount = 0; public static void main(String[] args) { System.out.println("==============================================="); System.out.println("PTZ指令系统核心验证程序"); System.out.println("==============================================="); try { // 核心功能验证 validateCoreInstructions(); validateInstructionFormat(); validateBoundaryValues(); validateBasicSerialization(); validateInstructionManager(); } catch (Exception e) { System.err.println("验证过程中发生异常: " + e.getMessage()); e.printStackTrace(); failCount++; } // 输出验证结果 System.out.println("==============================================="); System.out.println("验证结果汇总:"); System.out.println("总测试数: " + testCount); System.out.println("通过数: " + passCount); System.out.println("失败数: " + failCount); System.out.println("成功率: " + String.format("%.2f%%", (double) passCount / testCount * 100)); System.out.println("==============================================="); if (failCount == 0) { System.out.println("🎉 所有核心测试通过!PTZ指令系统验证成功!"); } else { System.out.println("❌ 有 " + failCount + " 个测试失败!"); } } private static void validateCoreInstructions() { System.out.println("\\n1. 核心指令验证..."); // PTZ指令验证 test("PTZ停止指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.STOP) .build(); return instruction.getInstructionCode() == (byte) 0x00 && instruction.isValid(); }); test("PTZ右移指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0x40) .build(); return instruction.getInstructionCode() == (byte) 0x01 && instruction.getData1() == (byte) 0x40 && instruction.isValid(); }); test("PTZ组合控制指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PanDirection.RIGHT, PTZControlEnum.TiltDirection.UP, PTZControlEnum.ZoomDirection.OUT) .horizontalSpeed(0x50) .build(); return instruction.getInstructionCode() == (byte) 0x29 && instruction.isValid(); }); // FI指令验证 test("FI光圈放大指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x002) .addFIControl(FIControlEnum.IRIS_OPEN) .irisSpeed(0x60) .build(); return instruction.getInstructionCode() == (byte) 0x44 && instruction.getData2() == (byte) 0x60 && instruction.isValid(); }); // 预置位指令验证 test("设置预置位指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x004) .addPresetControl(PresetControlEnum.SET_PRESET, 10) .build(); return instruction.getInstructionCode() == (byte) 0x81 && instruction.getData2() == (byte) 0x0A && instruction.isValid(); }); // 巡航指令验证 test("设置巡航速度指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x006) .addCruiseControl(CruiseControlEnum.SET_CRUISE_SPEED, 1, 1, 4095) .build(); return instruction.getInstructionCode() == (byte) 0x86 && instruction.getData2() == (byte) 0xFF && instruction.getData3() == (byte) 0x0F && instruction.isValid(); }); // 扫描指令验证 test("设置扫描速度指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x008) .addScanSpeedControl(2, 2048) .build(); return instruction.getInstructionCode() == (byte) 0x8A && instruction.getData1() == (byte) 0x02 && instruction.getData2() == (byte) 0x00 && instruction.getData3() == (byte) 0x08 && instruction.isValid(); }); // 辅助开关指令验证 test("开关开启指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x00A) .addAuxiliaryControl(AuxiliaryControlEnum.SWITCH_ON, 1) .build(); return instruction.getInstructionCode() == (byte) 0x8C && instruction.getData1() == (byte) 0x01 && instruction.isValid(); }); } private static void validateInstructionFormat() { System.out.println("\\n2. 指令格式验证..."); test("指令格式基本要求", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x123) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0x40) .verticalSpeed(0x80) .zoomSpeed(0x0F) .build(); return instruction.getHeader() == (byte) 0xA5 && instruction.toByteArray().length == 8 && instruction.toHexString().length() == 16 && instruction.getFullAddress() == 0x123 && instruction.getData1() == (byte) 0x40 && instruction.getData2() == (byte) 0x80 && instruction.getData3() == (byte) 0x0F && instruction.isValid(); }); test("校验码计算", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.STOP) .build(); byte[] bytes = instruction.toByteArray(); int sum = 0; for (int i = 0; i < 7; i++) { sum += (bytes[i] & 0xFF); } byte expectedChecksum = (byte) (sum % 256); return instruction.getChecksum() == expectedChecksum && instruction.isValid(); }); } private static void validateBoundaryValues() { System.out.println("\\n3. 边界值验证..."); test("地址边界值", () -> { // 最小地址 PTZInstructionFormat minAddr = PTZInstructionBuilder.create() .address(0x000) .addPTZControl(PTZControlEnum.STOP) .build(); // 最大地址 PTZInstructionFormat maxAddr = PTZInstructionBuilder.create() .address(0xFFF) .addPTZControl(PTZControlEnum.STOP) .build(); return minAddr.getFullAddress() == 0x000 && minAddr.isValid() && maxAddr.getFullAddress() == 0xFFF && maxAddr.isValid(); }); test("速度边界值", () -> { PTZInstructionFormat maxSpeed = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0xFF) .verticalSpeed(0xFF) .zoomSpeed(0x0F) .build(); return maxSpeed.getData1() == (byte) 0xFF && maxSpeed.getData2() == (byte) 0xFF && maxSpeed.getData3() == (byte) 0x0F && maxSpeed.isValid(); }); test("预置位边界值", () -> { PTZInstructionFormat minPreset = PTZInstructionBuilder.create() .address(0x001) .addPresetControl(PresetControlEnum.SET_PRESET, 1) .build(); PTZInstructionFormat maxPreset = PTZInstructionBuilder.create() .address(0x001) .addPresetControl(PresetControlEnum.SET_PRESET, 255) .build(); return minPreset.getData2() == (byte) 1 && minPreset.isValid() && maxPreset.getData2() == (byte) 0xFF && maxPreset.isValid(); }); } private static void validateBasicSerialization() { System.out.println("\\n4. 基础序列化验证..."); test("字节数组序列化", () -> { PTZInstructionFormat original = PTZInstructionBuilder.create() .address(0x200) .addFIControl(FIControlEnum.IRIS_OPEN) .irisSpeed(0x90) .build(); byte[] bytes = original.toByteArray(); PTZInstructionFormat reconstructed = PTZInstructionFormat.fromByteArray(bytes); return bytes.length == 8 && original.getInstructionCode() == reconstructed.getInstructionCode() && original.getData2() == reconstructed.getData2() && reconstructed.isValid(); }); test("十六进制序列化", () -> { PTZInstructionFormat original = PTZInstructionBuilder.create() .address(0x123) .addPTZControl(PTZControlEnum.PAN_LEFT) .horizontalSpeed(0x60) .build(); String hex = original.toHexString(); PTZInstructionFormat reconstructed = PTZInstructionFormat.fromHexString(hex); return hex.length() == 16 && hex.startsWith("A5") && original.getInstructionCode() == reconstructed.getInstructionCode() && reconstructed.isValid(); }); } private static void validateInstructionManager() { System.out.println("\\n5. 指令管理器验证..."); test("指令类型识别", () -> { return PTZInstructionManager.getInstructionType((byte) 0x01) == PTZInstructionManager.InstructionType.PTZ_CONTROL && PTZInstructionManager.getInstructionType((byte) 0x40) == PTZInstructionManager.InstructionType.FI_CONTROL && PTZInstructionManager.getInstructionType((byte) 0x81) == PTZInstructionManager.InstructionType.PRESET_CONTROL; }); test("枚举获取", () -> { return PTZInstructionManager.getPTZControlEnum((byte) 0x01) == PTZControlEnum.PAN_RIGHT && PTZInstructionManager.getFIControlEnum((byte) 0x40) == FIControlEnum.STOP && PTZInstructionManager.getPresetControlEnum((byte) 0x81) == PresetControlEnum.SET_PRESET; }); test("统计信息", () -> { PTZInstructionManager.InstructionStatistics stats = PTZInstructionManager.getStatistics(); return stats.getTotalCount() > 0 && stats.getCountsByType().size() > 0; }); } // 测试范例生成验证 private static void demonstrateInstructionExamples() { System.out.println("\\n6. 指令生成示例演示..."); // 演示表A.5中的PTZ指令示例 System.out.println("\\n表A.5 PTZ指令示例验证:"); // 序号7: 停止指令 PTZInstructionFormat stopCmd = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.STOP) .build(); System.out.println("停止指令: " + stopCmd.toHexString()); // 序号6: 向右指令 PTZInstructionFormat rightCmd = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0x40) .verticalSpeed(0x20) .build(); System.out.println("右移指令: " + rightCmd.toHexString()); // 序号8: 组合指令示例 PTZInstructionFormat combinedCmd = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PanDirection.RIGHT, PTZControlEnum.TiltDirection.UP, PTZControlEnum.ZoomDirection.OUT) .horizontalSpeed(0x50) .verticalSpeed(0x60) .zoomSpeed(0x08) .build(); System.out.println("组合指令: " + combinedCmd.toHexString()); // 演示表A.7中的FI指令示例 System.out.println("\\n表A.7 FI指令示例验证:"); // 序号1: 光圈缩小 PTZInstructionFormat irisClose = PTZInstructionBuilder.create() .address(0x001) .addFIControl(FIControlEnum.IRIS_CLOSE) .irisSpeed(0x80) .build(); System.out.println("光圈缩小: " + irisClose.toHexString()); // 序号3: 聚焦近 PTZInstructionFormat focusNear = PTZInstructionBuilder.create() .address(0x001) .addFIControl(FIControlEnum.FOCUS_NEAR) .focusSpeed(0x70) .build(); System.out.println("聚焦近: " + focusNear.toHexString()); // 演示表A.8中的预置位指令 System.out.println("\\n表A.8 预置位指令示例验证:"); // 设置预置位 PTZInstructionFormat setPreset = PTZInstructionBuilder.create() .address(0x001) .addPresetControl(PresetControlEnum.SET_PRESET, 5) .build(); System.out.println("设置预置位5: " + setPreset.toHexString()); // 调用预置位 PTZInstructionFormat callPreset = PTZInstructionBuilder.create() .address(0x001) .addPresetControl(PresetControlEnum.CALL_PRESET, 10) .build(); System.out.println("调用预置位10: " + callPreset.toHexString()); } private static void test(String testName, TestFunction testFunction) { testCount++; try { boolean result = testFunction.run(); if (result) { System.out.println(" ✓ " + testName + " - 通过"); passCount++; } else { System.out.println(" ✗ " + testName + " - 失败"); failCount++; } } catch (Exception e) { System.out.println(" ✗ " + testName + " - 异常: " + e.getMessage()); failCount++; } } @FunctionalInterface private interface TestFunction { boolean run() throws Exception; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionCompleteValidation.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/PTZInstructionCompleteValidation.java
package io.github.lunasaw.gb28181.common.entity.control.instruction; import io.github.lunasaw.gb28181.common.entity.control.instruction.builder.PTZInstructionBuilder; import io.github.lunasaw.gb28181.common.entity.control.instruction.enums.*; import io.github.lunasaw.gb28181.common.entity.control.instruction.manager.PTZInstructionManager; import io.github.lunasaw.gb28181.common.entity.control.instruction.serializer.PTZInstructionSerializer; /** * PTZ指令系统完整验证程序 * 手动验证所有指令的生成和解析是否正确 */ public class PTZInstructionCompleteValidation { private static int testCount = 0; private static int passCount = 0; private static int failCount = 0; public static void main(String[] args) { System.out.println("==============================================="); System.out.println("PTZ指令系统完整验证程序"); System.out.println("==============================================="); try { // 1. PTZ控制指令验证 validatePTZControlInstructions(); // 2. FI控制指令验证 validateFIControlInstructions(); // 3. 预置位指令验证 validatePresetInstructions(); // 4. 巡航指令验证 validateCruiseInstructions(); // 5. 扫描指令验证 validateScanInstructions(); // 6. 辅助开关指令验证 validateAuxiliaryInstructions(); // 7. 指令格式验证 validateInstructionFormat(); // 8. 边界值验证 validateBoundaryValues(); // 9. 序列化验证 validateSerialization(); // 10. 管理器验证 validateInstructionManager(); } catch (Exception e) { System.err.println("验证过程中发生异常: " + e.getMessage()); e.printStackTrace(); failCount++; } // 输出验证结果 System.out.println("==============================================="); System.out.println("验证结果汇总:"); System.out.println("总测试数: " + testCount); System.out.println("通过数: " + passCount); System.out.println("失败数: " + failCount); System.out.println("成功率: " + String.format("%.2f%%", (double) passCount / testCount * 100)); System.out.println("==============================================="); if (failCount == 0) { System.out.println("🎉 所有测试通过!PTZ指令系统验证成功!"); } else { System.out.println("❌ 有 " + failCount + " 个测试失败!"); } } private static void validatePTZControlInstructions() { System.out.println("\\n1. PTZ控制指令验证..."); // 测试停止指令 test("PTZ停止指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.STOP) .build(); assert instruction.getInstructionCode() == (byte) 0x00 : "停止指令码应为0x00"; assert instruction.isValid() : "指令应有效"; assert instruction.toHexString().startsWith("A5") : "应以A5开头"; return true; }); // 测试右移指令 test("PTZ右移指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0x40) .build(); assert instruction.getInstructionCode() == (byte) 0x01 : "右移指令码应为0x01"; assert instruction.getData1() == (byte) 0x40 : "水平速度应为0x40"; assert instruction.isValid() : "指令应有效"; return true; }); // 测试组合控制指令 test("PTZ组合控制指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PanDirection.RIGHT, PTZControlEnum.TiltDirection.UP, PTZControlEnum.ZoomDirection.OUT) .horizontalSpeed(0x50) .verticalSpeed(0x60) .zoomSpeed(0x08) .build(); // 右(0x01) + 上(0x08) + 缩小(0x20) = 0x29 assert instruction.getInstructionCode() == (byte) 0x29 : "组合指令码应为0x29"; assert instruction.getData1() == (byte) 0x50 : "水平速度应为0x50"; assert instruction.getData2() == (byte) 0x60 : "垂直速度应为0x60"; assert instruction.getData3() == (byte) 0x08 : "变倍速度应为0x08"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validateFIControlInstructions() { System.out.println("\\n2. FI控制指令验证..."); // 测试光圈放大指令 test("FI光圈放大指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x002) .addFIControl(FIControlEnum.IRIS_OPEN) .irisSpeed(0x60) .build(); assert instruction.getInstructionCode() == (byte) 0x44 : "光圈放大指令码应为0x44"; assert instruction.getData2() == (byte) 0x60 : "光圈速度应为0x60"; assert instruction.isValid() : "指令应有效"; // 验证FI指令的位模式 byte code = instruction.getInstructionCode(); assert (code & 0xF0) == 0x40 : "FI指令高4位应为0100"; return true; }); // 测试聚焦近指令 test("FI聚焦近指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x003) .addFIControl(FIControlEnum.FOCUS_NEAR) .focusSpeed(0x90) .build(); assert instruction.getInstructionCode() == (byte) 0x42 : "聚焦近指令码应为0x42"; assert instruction.getData1() == (byte) 0x90 : "聚焦速度应为0x90"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validatePresetInstructions() { System.out.println("\\n3. 预置位指令验证..."); // 测试设置预置位指令 test("设置预置位指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x004) .addPresetControl(PresetControlEnum.SET_PRESET, 10) .build(); assert instruction.getInstructionCode() == (byte) 0x81 : "设置预置位指令码应为0x81"; assert instruction.getData1() == (byte) 0x00 : "字节5应为0x00"; assert instruction.getData2() == (byte) 0x0A : "预置位号应为10"; assert instruction.isValid() : "指令应有效"; return true; }); // 测试调用预置位指令 test("调用预置位指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x005) .addPresetControl(PresetControlEnum.CALL_PRESET, 255) .build(); assert instruction.getInstructionCode() == (byte) 0x82 : "调用预置位指令码应为0x82"; assert instruction.getData2() == (byte) 0xFF : "预置位号应为255"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validateCruiseInstructions() { System.out.println("\\n4. 巡航指令验证..."); // 测试设置巡航速度指令 test("设置巡航速度指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x006) .addCruiseControl(CruiseControlEnum.SET_CRUISE_SPEED, 1, 1, 4095) .build(); assert instruction.getInstructionCode() == (byte) 0x86 : "设置巡航速度指令码应为0x86"; assert instruction.getData1() == (byte) 0x01 : "巡航组号应为1"; assert instruction.getData2() == (byte) 0xFF : "速度低8位应为0xFF"; assert instruction.getData3() == (byte) 0x0F : "速度高4位应为0x0F"; assert instruction.isValid() : "指令应有效"; // 验证数据解码 int decodedSpeed = (instruction.getData2() & 0xFF) | ((instruction.getData3() & 0x0F) << 8); assert decodedSpeed == 4095 : "解码速度应为4095"; return true; }); // 测试开始巡航指令 test("开始巡航指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x007) .addCruiseControl(CruiseControlEnum.START_CRUISE, 5) .build(); assert instruction.getInstructionCode() == (byte) 0x88 : "开始巡航指令码应为0x88"; assert instruction.getData1() == (byte) 0x05 : "巡航组号应为5"; assert instruction.getData2() == (byte) 0x00 : "字节6应为0x00"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validateScanInstructions() { System.out.println("\\n5. 扫描指令验证..."); // 测试设置扫描速度指令 test("设置扫描速度指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x008) .addScanSpeedControl(2, 2048) .build(); assert instruction.getInstructionCode() == (byte) 0x8A : "设置扫描速度指令码应为0x8A"; assert instruction.getData1() == (byte) 0x02 : "扫描组号应为2"; assert instruction.getData2() == (byte) 0x00 : "速度低8位应为0x00"; assert instruction.getData3() == (byte) 0x08 : "速度高4位应为0x08"; assert instruction.isValid() : "指令应有效"; return true; }); // 测试开始扫描指令 test("开始扫描指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x009) .addScanControl(ScanControlEnum.START_AUTO_SCAN, 3, ScanControlEnum.ScanOperationType.START) .build(); assert instruction.getInstructionCode() == (byte) 0x89 : "开始扫描指令码应为0x89"; assert instruction.getData1() == (byte) 0x03 : "扫描组号应为3"; assert instruction.getData2() == (byte) 0x00 : "操作类型应为0x00"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validateAuxiliaryInstructions() { System.out.println("\\n6. 辅助开关指令验证..."); // 测试开关开启指令 test("开关开启指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x00A) .addAuxiliaryControl(AuxiliaryControlEnum.SWITCH_ON, 1) .build(); assert instruction.getInstructionCode() == (byte) 0x8C : "开关开启指令码应为0x8C"; assert instruction.getData1() == (byte) 0x01 : "开关编号应为1"; assert instruction.isValid() : "指令应有效"; return true; }); // 测试开关关闭指令 test("开关关闭指令", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x00B) .addAuxiliaryControl(AuxiliaryControlEnum.SWITCH_OFF, 255) .build(); assert instruction.getInstructionCode() == (byte) 0x8D : "开关关闭指令码应为0x8D"; assert instruction.getData1() == (byte) 0xFF : "开关编号应为255"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validateInstructionFormat() { System.out.println("\\n7. 指令格式验证..."); // 测试指令格式基本要求 test("指令格式基本要求", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x123) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0x40) .verticalSpeed(0x80) .zoomSpeed(0x0F) .build(); // 验证首字节 assert instruction.getHeader() == (byte) 0xA5 : "首字节应为0xA5"; // 验证长度 assert instruction.toByteArray().length == 8 : "字节数组长度应为8"; assert instruction.toHexString().length() == 16 : "十六进制字符串长度应为16"; // 验证地址编码 assert instruction.getFullAddress() == 0x123 : "完整地址应为0x123"; assert instruction.getAddressLow() == (byte) 0x23 : "地址低8位应为0x23"; assert (instruction.getCombinationCode2() & 0x0F) == 0x01 : "地址高4位应为0x01"; // 验证数据编码 assert instruction.getData1() == (byte) 0x40 : "数据1应为0x40"; assert instruction.getData2() == (byte) 0x80 : "数据2应为0x80"; assert instruction.getData3() == (byte) 0x0F : "数据3应为0x0F"; assert instruction.isValid() : "指令应有效"; return true; }); // 测试校验码计算 test("校验码计算", () -> { PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.STOP) .build(); // 手动计算校验码 byte[] bytes = instruction.toByteArray(); int sum = 0; for (int i = 0; i < 7; i++) { sum += (bytes[i] & 0xFF); } byte expectedChecksum = (byte) (sum % 256); assert instruction.getChecksum() == expectedChecksum : "校验码计算错误"; assert instruction.isValid() : "指令应有效"; return true; }); } private static void validateBoundaryValues() { System.out.println("\\n8. 边界值验证..."); // 测试地址边界值 test("地址边界值", () -> { // 最小地址 PTZInstructionFormat minAddr = PTZInstructionBuilder.create() .address(0x000) .addPTZControl(PTZControlEnum.STOP) .build(); assert minAddr.getFullAddress() == 0x000 : "最小地址应为0x000"; assert minAddr.isValid() : "最小地址指令应有效"; // 最大地址 PTZInstructionFormat maxAddr = PTZInstructionBuilder.create() .address(0xFFF) .addPTZControl(PTZControlEnum.STOP) .build(); assert maxAddr.getFullAddress() == 0xFFF : "最大地址应为0xFFF"; assert maxAddr.isValid() : "最大地址指令应有效"; return true; }); // 测试速度边界值 test("速度边界值", () -> { // 最大速度值 PTZInstructionFormat maxSpeed = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0xFF) .verticalSpeed(0xFF) .zoomSpeed(0x0F) .build(); assert maxSpeed.getData1() == (byte) 0xFF : "最大水平速度应为0xFF"; assert maxSpeed.getData2() == (byte) 0xFF : "最大垂直速度应为0xFF"; assert maxSpeed.getData3() == (byte) 0x0F : "最大变倍速度应为0x0F"; assert maxSpeed.isValid() : "最大速度指令应有效"; return true; }); } private static void validateSerialization() { System.out.println("\\n9. 序列化验证..."); // 测试序列化一致性 test("序列化一致性", () -> { PTZInstructionFormat original = PTZInstructionBuilder.create() .address(0x200) .addFIControl(FIControlEnum.IRIS_OPEN) .irisSpeed(0x90) .build(); // 十六进制序列化 String hex = PTZInstructionSerializer.serializeToHex(original); PTZInstructionFormat fromHex = PTZInstructionSerializer.deserializeFromHex(hex); assert original.getInstructionCode() == fromHex.getInstructionCode() : "十六进制序列化不一致"; assert fromHex.isValid() : "从十六进制反序列化的指令应有效"; // Base64序列化 String base64 = PTZInstructionSerializer.serializeToBase64(original); PTZInstructionFormat fromBase64 = PTZInstructionSerializer.deserializeFromBase64(base64); assert original.getInstructionCode() == fromBase64.getInstructionCode() : "Base64序列化不一致"; assert fromBase64.isValid() : "从Base64反序列化的指令应有效"; return true; }); } private static void validateInstructionManager() { System.out.println("\\n10. 指令管理器验证..."); // 测试指令管理器功能 test("指令管理器功能", () -> { // 测试指令类型识别 assert PTZInstructionManager.getInstructionType((byte) 0x01) == PTZInstructionManager.InstructionType.PTZ_CONTROL : "PTZ指令类型识别错误"; assert PTZInstructionManager.getInstructionType((byte) 0x40) == PTZInstructionManager.InstructionType.FI_CONTROL : "FI指令类型识别错误"; assert PTZInstructionManager.getInstructionType((byte) 0x81) == PTZInstructionManager.InstructionType.PRESET_CONTROL : "预置位指令类型识别错误"; // 测试枚举获取 assert PTZInstructionManager.getPTZControlEnum((byte) 0x01) == PTZControlEnum.PAN_RIGHT : "PTZ枚举获取错误"; assert PTZInstructionManager.getFIControlEnum((byte) 0x40) == FIControlEnum.STOP : "FI枚举获取错误"; // 测试统计信息 PTZInstructionManager.InstructionStatistics stats = PTZInstructionManager.getStatistics(); assert stats.getTotalCount() > 0 : "统计总数应大于0"; return true; }); } private static void test(String testName, TestFunction testFunction) { testCount++; try { boolean result = testFunction.run(); if (result) { System.out.println(" ✓ " + testName + " - 通过"); passCount++; } else { System.out.println(" ✗ " + testName + " - 失败"); failCount++; } } catch (Exception e) { System.out.println(" ✗ " + testName + " - 异常: " + e.getMessage()); failCount++; } } @FunctionalInterface private interface TestFunction { boolean run() throws Exception; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/builder/PTZInstructionBuilder.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/builder/PTZInstructionBuilder.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.builder; import io.github.lunasaw.gb28181.common.entity.control.instruction.PTZInstructionFormat; import io.github.lunasaw.gb28181.common.entity.control.instruction.enums.*; /** * PTZ指令构建器 - Builder设计模式实现 * 提供流式API构建各种PTZ控制指令 */ public class PTZInstructionBuilder { private int address = 0; private byte instructionCode = 0; private byte data1 = 0; private byte data2 = 0; private byte data3 = 0; /** * 创建构建器实例 */ public static PTZInstructionBuilder create() { return new PTZInstructionBuilder(); } /** * 设置设备地址 * * @param address 设备地址 (0x000-0xFFF) * @return this */ public PTZInstructionBuilder address(int address) { if (address < 0 || address > 0xFFF) { throw new IllegalArgumentException("地址范围必须在0x000-0xFFF之间"); } this.address = address; return this; } /** * 添加PTZ控制指令 * * @param control PTZ控制类型 * @return this */ public PTZInstructionBuilder addPTZControl(PTZControlEnum control) { this.instructionCode = control.getInstructionCode(); return this; } /** * 添加PTZ控制指令 - 支持组合控制 * * @param pan 水平方向控制 * @param tilt 垂直方向控制 * @param zoom 变倍控制 * @return this */ public PTZInstructionBuilder addPTZControl(PTZControlEnum.PanDirection pan, PTZControlEnum.TiltDirection tilt, PTZControlEnum.ZoomDirection zoom) { byte code = 0; // 设置水平方向控制位 switch (pan) { case LEFT: code |= 0x02; break; case RIGHT: code |= 0x01; break; } // 设置垂直方向控制位 switch (tilt) { case UP: code |= 0x08; break; case DOWN: code |= 0x04; break; } // 设置变倍控制位 switch (zoom) { case IN: code |= 0x10; break; case OUT: code |= 0x20; break; } this.instructionCode = code; return this; } /** * 添加FI控制指令 * * @param control FI控制类型 * @return this */ public PTZInstructionBuilder addFIControl(FIControlEnum control) { this.instructionCode = control.getInstructionCode(); return this; } /** * 添加FI控制指令 - 支持组合控制 * * @param iris 光圈控制 * @param focus 聚焦控制 * @return this */ public PTZInstructionBuilder addFIControl(FIControlEnum.IrisDirection iris, FIControlEnum.FocusDirection focus) { byte code = 0x40; // FI指令固定前缀 // 设置光圈控制位 switch (iris) { case OPEN: code |= 0x04; break; case CLOSE: code |= 0x08; break; } // 设置聚焦控制位 switch (focus) { case NEAR: code |= 0x02; break; case FAR: code |= 0x01; break; } this.instructionCode = code; return this; } /** * 添加预置位控制指令 * * @param control 预置位控制类型 * @param presetNumber 预置位号 (1-255) * @return this */ public PTZInstructionBuilder addPresetControl(PresetControlEnum control, int presetNumber) { if (!PresetControlEnum.isValidPresetNumber(presetNumber)) { throw new IllegalArgumentException("预置位号必须在1-255之间"); } this.instructionCode = control.getInstructionCode(); this.data1 = 0x00; // 字节5固定为00H this.data2 = (byte) presetNumber; // 字节6为预置位号 return this; } /** * 添加巡航控制指令 * * @param control 巡航控制类型 * @param groupNumber 巡航组号 (0-255) * @return this */ public PTZInstructionBuilder addCruiseControl(CruiseControlEnum control, int groupNumber) { if (!CruiseControlEnum.isValidGroupNumber(groupNumber)) { throw new IllegalArgumentException("巡航组号必须在0-255之间"); } this.instructionCode = control.getInstructionCode(); this.data1 = (byte) groupNumber; // 字节5为巡航组号 return this; } /** * 添加巡航控制指令 - 带预置位号 * * @param control 巡航控制类型 * @param groupNumber 巡航组号 (0-255) * @param presetNumber 预置位号 (1-255) * @return this */ public PTZInstructionBuilder addCruiseControl(CruiseControlEnum control, int groupNumber, int presetNumber) { addCruiseControl(control, groupNumber); if (!CruiseControlEnum.isValidPresetNumber(presetNumber)) { throw new IllegalArgumentException("预置位号必须在1-255之间"); } this.data2 = (byte) presetNumber; // 字节6为预置位号 return this; } /** * 添加巡航控制指令 - 带速度或时间数据 * * @param control 巡航控制类型 * @param groupNumber 巡航组号 (0-255) * @param presetNumber 预置位号 (1-255) * @param speedOrTime 速度或时间 (0-4095) * @return this */ public PTZInstructionBuilder addCruiseControl(CruiseControlEnum control, int groupNumber, int presetNumber, int speedOrTime) { addCruiseControl(control, groupNumber, presetNumber); if (!CruiseControlEnum.isValidSpeed(speedOrTime)) { throw new IllegalArgumentException("速度或时间数据必须在0-4095之间"); } this.data2 = (byte) (speedOrTime & 0xFF); // 低8位 this.data3 = (byte) ((speedOrTime >> 8) & 0x0F); // 高4位 return this; } /** * 添加扫描控制指令 * * @param control 扫描控制类型 * @param groupNumber 扫描组号 (0-255) * @param operationType 操作类型 * @return this */ public PTZInstructionBuilder addScanControl(ScanControlEnum control, int groupNumber, ScanControlEnum.ScanOperationType operationType) { if (!ScanControlEnum.isValidGroupNumber(groupNumber)) { throw new IllegalArgumentException("扫描组号必须在0-255之间"); } this.instructionCode = control.getInstructionCode(); this.data1 = (byte) groupNumber; // 字节5为扫描组号 this.data2 = (byte) operationType.getValue(); // 字节6为操作类型 return this; } /** * 添加扫描速度控制指令 * * @param groupNumber 扫描组号 (0-255) * @param speed 扫描速度 (0-4095) * @return this */ public PTZInstructionBuilder addScanSpeedControl(int groupNumber, int speed) { if (!ScanControlEnum.isValidGroupNumber(groupNumber)) { throw new IllegalArgumentException("扫描组号必须在0-255之间"); } if (!ScanControlEnum.isValidSpeed(speed)) { throw new IllegalArgumentException("扫描速度必须在0-4095之间"); } this.instructionCode = ScanControlEnum.SET_SCAN_SPEED.getInstructionCode(); this.data1 = (byte) groupNumber; // 字节5为扫描组号 this.data2 = (byte) (speed & 0xFF); // 低8位 this.data3 = (byte) ((speed >> 8) & 0x0F); // 高4位 return this; } /** * 添加辅助开关控制指令 * * @param control 辅助开关控制类型 * @param switchNumber 开关编号 (0-255) * @return this */ public PTZInstructionBuilder addAuxiliaryControl(AuxiliaryControlEnum control, int switchNumber) { if (!AuxiliaryControlEnum.isValidSwitchNumber(switchNumber)) { throw new IllegalArgumentException("开关编号必须在0-255之间"); } this.instructionCode = control.getInstructionCode(); this.data1 = (byte) switchNumber; // 字节5为开关编号 return this; } /** * 设置水平控制速度 * * @param speed 水平速度 (0x00-0xFF) * @return this */ public PTZInstructionBuilder horizontalSpeed(int speed) { if (speed < 0 || speed > 0xFF) { throw new IllegalArgumentException("水平速度必须在0x00-0xFF之间"); } this.data1 = (byte) speed; return this; } /** * 设置垂直控制速度 * * @param speed 垂直速度 (0x00-0xFF) * @return this */ public PTZInstructionBuilder verticalSpeed(int speed) { if (speed < 0 || speed > 0xFF) { throw new IllegalArgumentException("垂直速度必须在0x00-0xFF之间"); } this.data2 = (byte) speed; return this; } /** * 设置变倍控制速度 * * @param speed 变倍速度 (0x0-0xF) * @return this */ public PTZInstructionBuilder zoomSpeed(int speed) { if (speed < 0 || speed > 0xF) { throw new IllegalArgumentException("变倍速度必须在0x0-0xF之间"); } this.data3 = (byte) speed; return this; } /** * 设置聚焦速度 * * @param speed 聚焦速度 (0x00-0xFF) * @return this */ public PTZInstructionBuilder focusSpeed(int speed) { if (speed < 0 || speed > 0xFF) { throw new IllegalArgumentException("聚焦速度必须在0x00-0xFF之间"); } this.data1 = (byte) speed; return this; } /** * 设置光圈速度 * * @param speed 光圈速度 (0x00-0xFF) * @return this */ public PTZInstructionBuilder irisSpeed(int speed) { if (speed < 0 || speed > 0xFF) { throw new IllegalArgumentException("光圈速度必须在0x00-0xFF之间"); } this.data2 = (byte) speed; return this; } /** * 构建PTZ指令 * * @return PTZ指令格式对象 */ public PTZInstructionFormat build() { return new PTZInstructionFormat(address, instructionCode, data1, data2, data3); } /** * 构建并转换为十六进制字符串 * * @return 十六进制字符串 */ public String buildToHex() { return build().toHexString(); } /** * 构建并转换为字节数组 * * @return 字节数组 */ public byte[] buildToBytes() { return build().toByteArray(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/manager/PTZInstructionManager.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/manager/PTZInstructionManager.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.manager; import io.github.lunasaw.gb28181.common.entity.control.instruction.enums.*; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * PTZ指令映射管理器 * 统一管理所有PTZ控制指令的映射关系和静态枚举 */ @Slf4j public class PTZInstructionManager { // 指令码到枚举的映射缓存 private static final Map<Byte, InstructionType> INSTRUCTION_TYPE_MAP = new ConcurrentHashMap<>(); private static final Map<Byte, Object> ALL_INSTRUCTIONS_MAP = new ConcurrentHashMap<>(); // 名称到枚举的映射缓存 private static final Map<String, Object> NAME_TO_ENUM_MAP = new ConcurrentHashMap<>(); static { initializeMappings(); } /** * 初始化所有指令映射 */ private static void initializeMappings() { log.info("初始化PTZ指令映射..."); // 初始化PTZ控制指令 for (PTZControlEnum ptz : PTZControlEnum.values()) { INSTRUCTION_TYPE_MAP.put(ptz.getInstructionCode(), InstructionType.PTZ_CONTROL); ALL_INSTRUCTIONS_MAP.put(ptz.getInstructionCode(), ptz); NAME_TO_ENUM_MAP.put(ptz.getName(), ptz); } // 初始化FI控制指令 for (FIControlEnum fi : FIControlEnum.values()) { INSTRUCTION_TYPE_MAP.put(fi.getInstructionCode(), InstructionType.FI_CONTROL); ALL_INSTRUCTIONS_MAP.put(fi.getInstructionCode(), fi); NAME_TO_ENUM_MAP.put(fi.getName(), fi); } // 初始化预置位控制指令 for (PresetControlEnum preset : PresetControlEnum.values()) { INSTRUCTION_TYPE_MAP.put(preset.getInstructionCode(), InstructionType.PRESET_CONTROL); ALL_INSTRUCTIONS_MAP.put(preset.getInstructionCode(), preset); NAME_TO_ENUM_MAP.put(preset.getName(), preset); } // 初始化巡航控制指令 for (CruiseControlEnum cruise : CruiseControlEnum.values()) { INSTRUCTION_TYPE_MAP.put(cruise.getInstructionCode(), InstructionType.CRUISE_CONTROL); ALL_INSTRUCTIONS_MAP.put(cruise.getInstructionCode(), cruise); NAME_TO_ENUM_MAP.put(cruise.getName(), cruise); } // 初始化扫描控制指令 for (ScanControlEnum scan : ScanControlEnum.values()) { INSTRUCTION_TYPE_MAP.put(scan.getInstructionCode(), InstructionType.SCAN_CONTROL); ALL_INSTRUCTIONS_MAP.put(scan.getInstructionCode(), scan); NAME_TO_ENUM_MAP.put(scan.getName(), scan); } // 初始化辅助开关控制指令 for (AuxiliaryControlEnum aux : AuxiliaryControlEnum.values()) { INSTRUCTION_TYPE_MAP.put(aux.getInstructionCode(), InstructionType.AUXILIARY_CONTROL); ALL_INSTRUCTIONS_MAP.put(aux.getInstructionCode(), aux); NAME_TO_ENUM_MAP.put(aux.getName(), aux); } log.info("PTZ指令映射初始化完成,总计{}个指令", ALL_INSTRUCTIONS_MAP.size()); } /** * 根据指令码获取指令类型 * * @param instructionCode 指令码 * @return 指令类型 */ public static InstructionType getInstructionType(byte instructionCode) { return INSTRUCTION_TYPE_MAP.get(instructionCode); } /** * 根据指令码获取具体的枚举对象 * * @param instructionCode 指令码 * @return 枚举对象 */ public static Object getInstructionEnum(byte instructionCode) { return ALL_INSTRUCTIONS_MAP.get(instructionCode); } /** * 根据指令码获取PTZ控制枚举 * * @param instructionCode 指令码 * @return PTZ控制枚举 */ public static PTZControlEnum getPTZControlEnum(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); return instruction instanceof PTZControlEnum ? (PTZControlEnum) instruction : null; } /** * 根据指令码获取FI控制枚举 * * @param instructionCode 指令码 * @return FI控制枚举 */ public static FIControlEnum getFIControlEnum(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); return instruction instanceof FIControlEnum ? (FIControlEnum) instruction : null; } /** * 根据指令码获取预置位控制枚举 * * @param instructionCode 指令码 * @return 预置位控制枚举 */ public static PresetControlEnum getPresetControlEnum(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); return instruction instanceof PresetControlEnum ? (PresetControlEnum) instruction : null; } /** * 根据指令码获取巡航控制枚举 * * @param instructionCode 指令码 * @return 巡航控制枚举 */ public static CruiseControlEnum getCruiseControlEnum(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); return instruction instanceof CruiseControlEnum ? (CruiseControlEnum) instruction : null; } /** * 根据指令码获取扫描控制枚举 * * @param instructionCode 指令码 * @return 扫描控制枚举 */ public static ScanControlEnum getScanControlEnum(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); return instruction instanceof ScanControlEnum ? (ScanControlEnum) instruction : null; } /** * 根据指令码获取辅助开关控制枚举 * * @param instructionCode 指令码 * @return 辅助开关控制枚举 */ public static AuxiliaryControlEnum getAuxiliaryControlEnum(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); return instruction instanceof AuxiliaryControlEnum ? (AuxiliaryControlEnum) instruction : null; } /** * 根据名称获取枚举对象 * * @param name 指令名称 * @return 枚举对象 */ public static Object getInstructionByName(String name) { return NAME_TO_ENUM_MAP.get(name); } /** * 获取所有支持的指令码 * * @return 指令码集合 */ public static Set<Byte> getAllSupportedInstructionCodes() { return new HashSet<>(ALL_INSTRUCTIONS_MAP.keySet()); } /** * 获取指定类型的所有指令码 * * @param type 指令类型 * @return 指令码集合 */ public static Set<Byte> getInstructionCodesByType(InstructionType type) { Set<Byte> codes = new HashSet<>(); for (Map.Entry<Byte, InstructionType> entry : INSTRUCTION_TYPE_MAP.entrySet()) { if (entry.getValue() == type) { codes.add(entry.getKey()); } } return codes; } /** * 检查指令码是否被支持 * * @param instructionCode 指令码 * @return 是否支持 */ public static boolean isSupportedInstructionCode(byte instructionCode) { return ALL_INSTRUCTIONS_MAP.containsKey(instructionCode); } /** * 获取指令的描述信息 * * @param instructionCode 指令码 * @return 描述信息 */ public static String getInstructionDescription(byte instructionCode) { Object instruction = ALL_INSTRUCTIONS_MAP.get(instructionCode); if (instruction == null) { return "未知指令"; } if (instruction instanceof PTZControlEnum) { return ((PTZControlEnum) instruction).getDescription(); } else if (instruction instanceof FIControlEnum) { return ((FIControlEnum) instruction).getDescription(); } else if (instruction instanceof PresetControlEnum) { return ((PresetControlEnum) instruction).getDescription(); } else if (instruction instanceof CruiseControlEnum) { return ((CruiseControlEnum) instruction).getDescription(); } else if (instruction instanceof ScanControlEnum) { return ((ScanControlEnum) instruction).getDescription(); } else if (instruction instanceof AuxiliaryControlEnum) { return ((AuxiliaryControlEnum) instruction).getDescription(); } return "未知指令类型"; } /** * 获取指令统计信息 * * @return 统计信息 */ public static InstructionStatistics getStatistics() { Map<InstructionType, Integer> counts = new HashMap<>(); for (InstructionType type : InstructionType.values()) { counts.put(type, getInstructionCodesByType(type).size()); } return new InstructionStatistics(counts, ALL_INSTRUCTIONS_MAP.size()); } /** * 指令类型枚举 */ @Getter public enum InstructionType { PTZ_CONTROL("PTZ控制", "云台平移、倾斜、变倍控制"), FI_CONTROL("FI控制", "聚焦和光圈控制"), PRESET_CONTROL("预置位控制", "预置位设置、调用、删除"), CRUISE_CONTROL("巡航控制", "巡航路径和速度控制"), SCAN_CONTROL("扫描控制", "自动扫描边界和速度控制"), AUXILIARY_CONTROL("辅助控制", "辅助开关和设备控制"); private final String name; private final String description; InstructionType(String name, String description) { this.name = name; this.description = description; } } /** * 指令统计信息类 */ public static class InstructionStatistics { @Getter private final Map<InstructionType, Integer> countsByType; @Getter private final int totalCount; public InstructionStatistics(Map<InstructionType, Integer> countsByType, int totalCount) { this.countsByType = countsByType; this.totalCount = totalCount; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("PTZ指令统计信息:\n"); sb.append("总指令数: ").append(totalCount).append("\n"); for (Map.Entry<InstructionType, Integer> entry : countsByType.entrySet()) { sb.append(entry.getKey().getName()).append(": ").append(entry.getValue()).append("个\n"); } return sb.toString(); } } /** * 重新加载指令映射 (用于动态更新) */ public static synchronized void reloadMappings() { log.info("重新加载PTZ指令映射..."); INSTRUCTION_TYPE_MAP.clear(); ALL_INSTRUCTIONS_MAP.clear(); NAME_TO_ENUM_MAP.clear(); initializeMappings(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/serializer/PTZInstructionSerializer.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/serializer/PTZInstructionSerializer.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.serializer; import io.github.lunasaw.gb28181.common.entity.control.instruction.PTZInstructionFormat; import lombok.extern.slf4j.Slf4j; import java.io.*; import java.nio.ByteBuffer; import java.util.Base64; /** * PTZ指令序列化器 * 提供多种序列化/反序列化方式 */ @Slf4j public class PTZInstructionSerializer { /** * 序列化为字节数组 * * @param instruction PTZ指令 * @return 字节数组 */ public static byte[] serializeToBytes(PTZInstructionFormat instruction) { if (instruction == null) { throw new IllegalArgumentException("指令不能为null"); } return instruction.toByteArray(); } /** * 从字节数组反序列化 * * @param bytes 字节数组 * @return PTZ指令 */ public static PTZInstructionFormat deserializeFromBytes(byte[] bytes) { if (bytes == null || bytes.length != 8) { throw new IllegalArgumentException("指令字节数组长度必须为8"); } return PTZInstructionFormat.fromByteArray(bytes); } /** * 序列化为十六进制字符串 * * @param instruction PTZ指令 * @return 十六进制字符串 */ public static String serializeToHex(PTZInstructionFormat instruction) { if (instruction == null) { throw new IllegalArgumentException("指令不能为null"); } return instruction.toHexString(); } /** * 从十六进制字符串反序列化 * * @param hexString 十六进制字符串 * @return PTZ指令 */ public static PTZInstructionFormat deserializeFromHex(String hexString) { if (hexString == null || hexString.length() != 16) { throw new IllegalArgumentException("十六进制字符串长度必须为16"); } return PTZInstructionFormat.fromHexString(hexString); } /** * 序列化为Base64字符串 * * @param instruction PTZ指令 * @return Base64字符串 */ public static String serializeToBase64(PTZInstructionFormat instruction) { if (instruction == null) { throw new IllegalArgumentException("指令不能为null"); } byte[] bytes = instruction.toByteArray(); return Base64.getEncoder().encodeToString(bytes); } /** * 从Base64字符串反序列化 * * @param base64String Base64字符串 * @return PTZ指令 */ public static PTZInstructionFormat deserializeFromBase64(String base64String) { if (base64String == null || base64String.isEmpty()) { throw new IllegalArgumentException("Base64字符串不能为空"); } try { byte[] bytes = Base64.getDecoder().decode(base64String); return deserializeFromBytes(bytes); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("无效的Base64字符串", e); } } /** * 序列化为Java对象流 * * @param instruction PTZ指令 * @return 序列化后的字节数组 * @throws IOException 序列化异常 */ public static byte[] serializeToObjectStream(PTZInstructionFormat instruction) throws IOException { if (instruction == null) { throw new IllegalArgumentException("指令不能为null"); } try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { // 序列化指令的基本数据 oos.writeInt(instruction.getFullAddress()); oos.writeByte(instruction.getInstructionCode()); oos.writeByte(instruction.getData1()); oos.writeByte(instruction.getData2()); oos.writeByte(instruction.getData3()); oos.flush(); return baos.toByteArray(); } } /** * 从Java对象流反序列化 * * @param bytes 序列化的字节数组 * @return PTZ指令 * @throws IOException 反序列化异常 * @throws ClassNotFoundException 类未找到异常 */ public static PTZInstructionFormat deserializeFromObjectStream(byte[] bytes) throws IOException, ClassNotFoundException { if (bytes == null || bytes.length == 0) { throw new IllegalArgumentException("字节数组不能为空"); } try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais)) { int address = ois.readInt(); byte instructionCode = ois.readByte(); byte data1 = ois.readByte(); byte data2 = ois.readByte(); byte data3 = ois.readByte(); return new PTZInstructionFormat(address, instructionCode, data1, data2, data3); } } /** * 序列化为紧凑的字节缓冲区 * * @param instruction PTZ指令 * @return ByteBuffer */ public static ByteBuffer serializeToByteBuffer(PTZInstructionFormat instruction) { if (instruction == null) { throw new IllegalArgumentException("指令不能为null"); } ByteBuffer buffer = ByteBuffer.allocate(8); byte[] bytes = instruction.toByteArray(); buffer.put(bytes); buffer.flip(); return buffer; } /** * 从ByteBuffer反序列化 * * @param buffer ByteBuffer * @return PTZ指令 */ public static PTZInstructionFormat deserializeFromByteBuffer(ByteBuffer buffer) { if (buffer == null || buffer.remaining() != 8) { throw new IllegalArgumentException("ByteBuffer剩余字节数必须为8"); } byte[] bytes = new byte[8]; buffer.get(bytes); return PTZInstructionFormat.fromByteArray(bytes); } /** * 验证序列化的完整性 * * @param original 原始指令 * @param serialized 序列化后的数据 * @param deserializer 反序列化函数 * @return 是否一致 */ public static boolean validateSerialization(PTZInstructionFormat original, Object serialized, SerializationFunction<Object, PTZInstructionFormat> deserializer) { try { PTZInstructionFormat deserialized = deserializer.apply(serialized); return original.equals(deserialized) && original.isValid() && deserialized.isValid(); } catch (Exception e) { log.error("序列化验证失败", e); return false; } } /** * 序列化函数接口 */ @FunctionalInterface public interface SerializationFunction<T, R> { R apply(T t) throws Exception; } /** * 序列化格式枚举 */ public enum SerializationFormat { BYTES("字节数组"), HEX("十六进制字符串"), BASE64("Base64字符串"), OBJECT_STREAM("Java对象流"), BYTE_BUFFER("ByteBuffer"); private final String description; SerializationFormat(String description) { this.description = description; } public String getDescription() { return description; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/examples/PTZInstructionExamples.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/examples/PTZInstructionExamples.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.examples; import io.github.lunasaw.gb28181.common.entity.control.instruction.PTZInstructionFormat; import io.github.lunasaw.gb28181.common.entity.control.instruction.builder.PTZInstructionBuilder; import io.github.lunasaw.gb28181.common.entity.control.instruction.crypto.PTZInstructionCrypto; import io.github.lunasaw.gb28181.common.entity.control.instruction.enums.*; import io.github.lunasaw.gb28181.common.entity.control.instruction.manager.PTZInstructionManager; import io.github.lunasaw.gb28181.common.entity.control.instruction.serializer.PTZInstructionSerializer; import lombok.extern.slf4j.Slf4j; import javax.crypto.SecretKey; import java.util.Set; /** * PTZ指令系统使用示例 * 展示如何使用所有组件构建、序列化、加密和管理PTZ指令 */ @Slf4j public class PTZInstructionExamples { /** * 基础PTZ控制示例 */ public static void basicPTZControlExample() { log.info("=== 基础PTZ控制示例 ==="); // 使用Builder模式创建云台右移指令 PTZInstructionFormat rightMoveInstruction = PTZInstructionBuilder.create() .address(0x001) // 设备地址 .addPTZControl(PTZControlEnum.PAN_RIGHT) // 右移控制 .horizontalSpeed(0x40) // 水平速度 .verticalSpeed(0x20) // 垂直速度 .zoomSpeed(0x0F) // 变倍速度 .build(); log.info("右移指令: {}", rightMoveInstruction.toHexString()); log.info("指令有效性: {}", rightMoveInstruction.isValid()); // 使用组合控制创建右上移动+放大指令 PTZInstructionFormat combinedInstruction = PTZInstructionBuilder.create() .address(0x002) .addPTZControl(PTZControlEnum.PanDirection.RIGHT, PTZControlEnum.TiltDirection.UP, PTZControlEnum.ZoomDirection.IN) .horizontalSpeed(0x60) .verticalSpeed(0x40) .zoomSpeed(0x08) .build(); log.info("组合控制指令: {}", combinedInstruction.toHexString()); // 停止所有PTZ动作 PTZInstructionFormat stopInstruction = PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.STOP) .build(); log.info("停止指令: {}", stopInstruction.toHexString()); } /** * FI(聚焦/光圈)控制示例 */ public static void fiControlExample() { log.info("=== FI控制示例 ==="); // 光圈放大指令 PTZInstructionFormat irisOpenInstruction = PTZInstructionBuilder.create() .address(0x003) .addFIControl(FIControlEnum.IRIS_OPEN) .focusSpeed(0x80) .irisSpeed(0x60) .build(); log.info("光圈放大指令: {}", irisOpenInstruction.toHexString()); // 聚焦近点指令 PTZInstructionFormat focusNearInstruction = PTZInstructionBuilder.create() .address(0x003) .addFIControl(FIControlEnum.FOCUS_NEAR) .focusSpeed(0x90) .build(); log.info("聚焦近点指令: {}", focusNearInstruction.toHexString()); // 组合FI控制:光圈缩小+聚焦远 PTZInstructionFormat combinedFIInstruction = PTZInstructionBuilder.create() .address(0x003) .addFIControl(FIControlEnum.IrisDirection.CLOSE, FIControlEnum.FocusDirection.FAR) .focusSpeed(0x70) .irisSpeed(0x50) .build(); log.info("组合FI控制指令: {}", combinedFIInstruction.toHexString()); } /** * 预置位控制示例 */ public static void presetControlExample() { log.info("=== 预置位控制示例 ==="); // 设置预置位1 PTZInstructionFormat setPresetInstruction = PTZInstructionBuilder.create() .address(0x004) .addPresetControl(PresetControlEnum.SET_PRESET, 1) .build(); log.info("设置预置位1指令: {}", setPresetInstruction.toHexString()); // 调用预置位5 PTZInstructionFormat callPresetInstruction = PTZInstructionBuilder.create() .address(0x004) .addPresetControl(PresetControlEnum.CALL_PRESET, 5) .build(); log.info("调用预置位5指令: {}", callPresetInstruction.toHexString()); // 删除预置位10 PTZInstructionFormat deletePresetInstruction = PTZInstructionBuilder.create() .address(0x004) .addPresetControl(PresetControlEnum.DELETE_PRESET, 10) .build(); log.info("删除预置位10指令: {}", deletePresetInstruction.toHexString()); } /** * 巡航控制示例 */ public static void cruiseControlExample() { log.info("=== 巡航控制示例 ==="); // 向巡航组1添加预置位3 PTZInstructionFormat addCruisePointInstruction = PTZInstructionBuilder.create() .address(0x005) .addCruiseControl(CruiseControlEnum.ADD_CRUISE_POINT, 1, 3) .build(); log.info("添加巡航点指令: {}", addCruisePointInstruction.toHexString()); // 设置巡航组1的速度为100 PTZInstructionFormat setCruiseSpeedInstruction = PTZInstructionBuilder.create() .address(0x005) .addCruiseControl(CruiseControlEnum.SET_CRUISE_SPEED, 1, 1, 100) .build(); log.info("设置巡航速度指令: {}", setCruiseSpeedInstruction.toHexString()); // 开始巡航组1 PTZInstructionFormat startCruiseInstruction = PTZInstructionBuilder.create() .address(0x005) .addCruiseControl(CruiseControlEnum.START_CRUISE, 1) .build(); log.info("开始巡航指令: {}", startCruiseInstruction.toHexString()); } /** * 扫描控制示例 */ public static void scanControlExample() { log.info("=== 扫描控制示例 ==="); // 设置扫描组1的左边界 PTZInstructionFormat setLeftBoundaryInstruction = PTZInstructionBuilder.create() .address(0x006) .addScanControl(ScanControlEnum.SET_LEFT_BOUNDARY, 1, ScanControlEnum.ScanOperationType.SET_LEFT_BOUNDARY) .build(); log.info("设置左边界指令: {}", setLeftBoundaryInstruction.toHexString()); // 设置扫描组1的速度为200 PTZInstructionFormat setScanSpeedInstruction = PTZInstructionBuilder.create() .address(0x006) .addScanSpeedControl(1, 200) .build(); log.info("设置扫描速度指令: {}", setScanSpeedInstruction.toHexString()); // 开始自动扫描 PTZInstructionFormat startScanInstruction = PTZInstructionBuilder.create() .address(0x006) .addScanControl(ScanControlEnum.START_AUTO_SCAN, 1, ScanControlEnum.ScanOperationType.START) .build(); log.info("开始扫描指令: {}", startScanInstruction.toHexString()); } /** * 辅助开关控制示例 */ public static void auxiliaryControlExample() { log.info("=== 辅助开关控制示例 ==="); // 开启雨刷(开关1) PTZInstructionFormat wiperOnInstruction = PTZInstructionBuilder.create() .address(0x007) .addAuxiliaryControl(AuxiliaryControlEnum.SWITCH_ON, 1) .build(); log.info("开启雨刷指令: {}", wiperOnInstruction.toHexString()); // 关闭雨刷 PTZInstructionFormat wiperOffInstruction = PTZInstructionBuilder.create() .address(0x007) .addAuxiliaryControl(AuxiliaryControlEnum.SWITCH_OFF, 1) .build(); log.info("关闭雨刷指令: {}", wiperOffInstruction.toHexString()); } /** * 序列化和反序列化示例 */ public static void serializationExample() { log.info("=== 序列化示例 ==="); PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x100) .addPTZControl(PTZControlEnum.PAN_LEFT) .horizontalSpeed(0x80) .build(); // 十六进制序列化 String hexString = PTZInstructionSerializer.serializeToHex(instruction); log.info("十六进制序列化: {}", hexString); // Base64序列化 String base64String = PTZInstructionSerializer.serializeToBase64(instruction); log.info("Base64序列化: {}", base64String); // 反序列化验证 PTZInstructionFormat deserializedFromHex = PTZInstructionSerializer.deserializeFromHex(hexString); PTZInstructionFormat deserializedFromBase64 = PTZInstructionSerializer.deserializeFromBase64(base64String); log.info("反序列化验证 - 十六进制: {}", deserializedFromHex.isValid()); log.info("反序列化验证 - Base64: {}", deserializedFromBase64.isValid()); } /** * 加密解密示例 */ public static void encryptionExample() { log.info("=== 加密解密示例 ==="); PTZInstructionFormat instruction = PTZInstructionBuilder.create() .address(0x200) .addFIControl(FIControlEnum.IRIS_OPEN) .irisSpeed(0xA0) .build(); // AES-GCM加密 SecretKey aesKey = PTZInstructionCrypto.generateAESKey(256); byte[] encrypted = PTZInstructionCrypto.encryptAESGCM(instruction, aesKey); log.info("AES-GCM加密数据长度: {} bytes", encrypted.length); PTZInstructionFormat decrypted = PTZInstructionCrypto.decryptAESGCM(encrypted, aesKey); log.info("AES-GCM解密验证: {}", decrypted.isValid()); // XOR加密 byte[] xorKey = PTZInstructionCrypto.generateRandomKey(8); byte[] xorEncrypted = PTZInstructionCrypto.encryptXOR(instruction, xorKey); log.info("XOR加密数据: {}", bytesToHex(xorEncrypted)); PTZInstructionFormat xorDecrypted = PTZInstructionCrypto.decryptXOR(xorEncrypted, xorKey); log.info("XOR解密验证: {}", xorDecrypted.isValid()); // 完整性验证 byte[] hash = PTZInstructionCrypto.calculateSHA256Hash(instruction); boolean integrityOk = PTZInstructionCrypto.verifyIntegrity(instruction, hash, "SHA-256"); log.info("完整性验证: {}", integrityOk); } /** * 指令管理器示例 */ public static void instructionManagerExample() { log.info("=== 指令管理器示例 ==="); // 获取指令统计信息 PTZInstructionManager.InstructionStatistics stats = PTZInstructionManager.getStatistics(); log.info("指令统计信息:\\n{}", stats); // 检查指令支持情况 byte[] testCodes = {(byte) 0x01, (byte) 0x40, (byte) 0x81, (byte) 0x89, (byte) 0xFF}; for (byte code : testCodes) { boolean supported = PTZInstructionManager.isSupportedInstructionCode(code); String description = PTZInstructionManager.getInstructionDescription(code); log.info("指令码 0x{}: 支持={}, 描述={}", String.format("%02X", code), supported, description); } // 获取各类型指令码 for (PTZInstructionManager.InstructionType type : PTZInstructionManager.InstructionType.values()) { Set<Byte> codes = PTZInstructionManager.getInstructionCodesByType(type); log.info("{} 指令码数量: {}", type.getName(), codes.size()); } } /** * 综合应用示例:完整的PTZ控制流程 */ public static void comprehensiveExample() { log.info("=== 综合应用示例 ==="); try { // 1. 创建加密密钥 SecretKey encryptionKey = PTZInstructionCrypto.generateAESKeyFromPassword("MySecretPassword123"); // 2. 构建一系列PTZ控制指令 PTZInstructionFormat[] instructions = { // 设置预置位1 PTZInstructionBuilder.create() .address(0x001) .addPresetControl(PresetControlEnum.SET_PRESET, 1) .build(), // 云台移动到指定位置 PTZInstructionBuilder.create() .address(0x001) .addPTZControl(PTZControlEnum.PAN_RIGHT) .horizontalSpeed(0x60) .build(), // 调用预置位1 PTZInstructionBuilder.create() .address(0x001) .addPresetControl(PresetControlEnum.CALL_PRESET, 1) .build() }; // 3. 序列化、加密并发送指令 for (int i = 0; i < instructions.length; i++) { PTZInstructionFormat instruction = instructions[i]; // 验证指令有效性 if (!instruction.isValid()) { log.error("指令{}无效", i + 1); continue; } // 序列化为十六进制 String hexString = PTZInstructionSerializer.serializeToHex(instruction); // 加密指令 byte[] encrypted = PTZInstructionCrypto.encryptAESGCM(instruction, encryptionKey); String encryptedBase64 = PTZInstructionSerializer.serializeToBase64( PTZInstructionFormat.fromByteArray(encrypted)); // 获取指令描述 String description = PTZInstructionManager.getInstructionDescription( instruction.getInstructionCode()); log.info("指令{}: {} - 原始={}, 加密={}", i + 1, description, hexString, encryptedBase64.substring(0, 16) + "..."); // 模拟发送延迟 Thread.sleep(100); } log.info("综合示例执行完成"); } catch (Exception e) { log.error("综合示例执行失败", e); } } /** * 字节数组转十六进制字符串工具方法 */ private static String bytesToHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02X", b)); } return sb.toString(); } /** * 主方法:运行所有示例 */ public static void main(String[] args) { log.info("开始PTZ指令系统示例演示"); basicPTZControlExample(); fiControlExample(); presetControlExample(); cruiseControlExample(); scanControlExample(); auxiliaryControlExample(); serializationExample(); encryptionExample(); instructionManagerExample(); comprehensiveExample(); log.info("PTZ指令系统示例演示完成"); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/crypto/PTZInstructionCrypto.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/crypto/PTZInstructionCrypto.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.crypto; import io.github.lunasaw.gb28181.common.entity.control.instruction.PTZInstructionFormat; import lombok.extern.slf4j.Slf4j; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; /** * PTZ指令加密解密器 * 提供多种加密算法支持 */ @Slf4j public class PTZInstructionCrypto { private static final String AES_ALGORITHM = "AES"; private static final String AES_GCM_TRANSFORMATION = "AES/GCM/NoPadding"; private static final int GCM_IV_LENGTH = 12; private static final int GCM_TAG_LENGTH = 16; /** * 生成AES密钥 * * @param keySize 密钥长度 (128, 192, 256) * @return AES密钥 */ public static SecretKey generateAESKey(int keySize) { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(AES_ALGORITHM); keyGenerator.init(keySize); return keyGenerator.generateKey(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("不支持的AES算法", e); } } /** * 从密码生成AES密钥 * * @param password 密码 * @return AES密钥 */ public static SecretKey generateAESKeyFromPassword(String password) { try { MessageDigest sha = MessageDigest.getInstance("SHA-256"); byte[] key = sha.digest(password.getBytes(StandardCharsets.UTF_8)); return new SecretKeySpec(key, AES_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("不支持的SHA-256算法", e); } } /** * AES-GCM加密 * * @param instruction PTZ指令 * @param secretKey 密钥 * @return 加密结果 (包含IV + 密文 + 认证标签) */ public static byte[] encryptAESGCM(PTZInstructionFormat instruction, SecretKey secretKey) { try { Cipher cipher = Cipher.getInstance(AES_GCM_TRANSFORMATION); // 生成随机IV byte[] iv = new byte[GCM_IV_LENGTH]; new SecureRandom().nextBytes(iv); GCMParameterSpec parameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec); // 加密指令数据 byte[] plaintext = instruction.toByteArray(); byte[] ciphertext = cipher.doFinal(plaintext); // 组合IV和密文 byte[] encryptedData = new byte[GCM_IV_LENGTH + ciphertext.length]; System.arraycopy(iv, 0, encryptedData, 0, GCM_IV_LENGTH); System.arraycopy(ciphertext, 0, encryptedData, GCM_IV_LENGTH, ciphertext.length); return encryptedData; } catch (Exception e) { throw new RuntimeException("AES-GCM加密失败", e); } } /** * AES-GCM解密 * * @param encryptedData 加密数据 (包含IV + 密文 + 认证标签) * @param secretKey 密钥 * @return PTZ指令 */ public static PTZInstructionFormat decryptAESGCM(byte[] encryptedData, SecretKey secretKey) { try { if (encryptedData.length < GCM_IV_LENGTH + GCM_TAG_LENGTH) { throw new IllegalArgumentException("加密数据长度不足"); } Cipher cipher = Cipher.getInstance(AES_GCM_TRANSFORMATION); // 提取IV byte[] iv = Arrays.copyOfRange(encryptedData, 0, GCM_IV_LENGTH); // 提取密文 byte[] ciphertext = Arrays.copyOfRange(encryptedData, GCM_IV_LENGTH, encryptedData.length); GCMParameterSpec parameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec); // 解密 byte[] plaintext = cipher.doFinal(ciphertext); return PTZInstructionFormat.fromByteArray(plaintext); } catch (Exception e) { throw new RuntimeException("AES-GCM解密失败", e); } } /** * 简单XOR加密 (适用于轻量级场景) * * @param instruction PTZ指令 * @param key 密钥 (8字节) * @return 加密后的字节数组 */ public static byte[] encryptXOR(PTZInstructionFormat instruction, byte[] key) { if (key == null || key.length != 8) { throw new IllegalArgumentException("XOR密钥长度必须为8字节"); } byte[] data = instruction.toByteArray(); byte[] encrypted = new byte[data.length]; for (int i = 0; i < data.length; i++) { encrypted[i] = (byte) (data[i] ^ key[i]); } return encrypted; } /** * 简单XOR解密 * * @param encryptedData 加密数据 * @param key 密钥 (8字节) * @return PTZ指令 */ public static PTZInstructionFormat decryptXOR(byte[] encryptedData, byte[] key) { if (key == null || key.length != 8) { throw new IllegalArgumentException("XOR密钥长度必须为8字节"); } if (encryptedData == null || encryptedData.length != 8) { throw new IllegalArgumentException("加密数据长度必须为8字节"); } byte[] decrypted = new byte[encryptedData.length]; for (int i = 0; i < encryptedData.length; i++) { decrypted[i] = (byte) (encryptedData[i] ^ key[i]); } return PTZInstructionFormat.fromByteArray(decrypted); } /** * 计算指令数据的MD5哈希 * * @param instruction PTZ指令 * @return MD5哈希值 */ public static byte[] calculateMD5Hash(PTZInstructionFormat instruction) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); return md5.digest(instruction.toByteArray()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("不支持的MD5算法", e); } } /** * 计算指令数据的SHA-256哈希 * * @param instruction PTZ指令 * @return SHA-256哈希值 */ public static byte[] calculateSHA256Hash(PTZInstructionFormat instruction) { try { MessageDigest sha256 = MessageDigest.getInstance("SHA-256"); return sha256.digest(instruction.toByteArray()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("不支持的SHA-256算法", e); } } /** * 验证指令完整性 * * @param instruction PTZ指令 * @param expectedHash 期望的哈希值 * @param algorithm 哈希算法 ("MD5" 或 "SHA-256") * @return 是否一致 */ public static boolean verifyIntegrity(PTZInstructionFormat instruction, byte[] expectedHash, String algorithm) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); byte[] actualHash = digest.digest(instruction.toByteArray()); return Arrays.equals(actualHash, expectedHash); } catch (NoSuchAlgorithmException e) { log.error("不支持的哈希算法: {}", algorithm, e); return false; } } /** * 生成安全的随机密钥 * * @param length 密钥长度 * @return 随机密钥 */ public static byte[] generateRandomKey(int length) { byte[] key = new byte[length]; new SecureRandom().nextBytes(key); return key; } /** * 带认证的加密结果 */ public static class AuthenticatedEncryption { private final byte[] encryptedData; private final byte[] authenticationTag; public AuthenticatedEncryption(byte[] encryptedData, byte[] authenticationTag) { this.encryptedData = encryptedData; this.authenticationTag = authenticationTag; } public byte[] getEncryptedData() { return encryptedData; } public byte[] getAuthenticationTag() { return authenticationTag; } /** * 组合加密数据和认证标签 */ public byte[] getCombined() { byte[] combined = new byte[encryptedData.length + authenticationTag.length]; System.arraycopy(encryptedData, 0, combined, 0, encryptedData.length); System.arraycopy(authenticationTag, 0, combined, encryptedData.length, authenticationTag.length); return combined; } } /** * 加密算法枚举 */ public enum EncryptionAlgorithm { AES_GCM("AES-GCM", "高安全性,带认证"), XOR("XOR", "轻量级,简单快速"), NONE("明文", "无加密"); private final String algorithm; private final String description; EncryptionAlgorithm(String algorithm, String description) { this.algorithm = algorithm; this.description = description; } public String getAlgorithm() { return algorithm; } public String getDescription() { return description; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/PTZControlEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/PTZControlEnum.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * PTZ控制指令枚举 * 根据 A.3.2 PTZ指令 规范实现 * <p> * 字节4位定义: * Bit7-Bit6: 固定为00 * Bit5-Bit4: 镜头变倍控制 (Zoom) * Bit3-Bit2: 云台垂直方向控制 (Tilt) * Bit1-Bit0: 云台水平方向控制 (Pan) */ @Getter @AllArgsConstructor public enum PTZControlEnum { // 基础PTZ控制 STOP("停止", (byte) 0x00, "PTZ的所有操作均停止"), // 水平方向控制 PAN_LEFT("向左", (byte) 0x02, "云台向左方向运动"), PAN_RIGHT("向右", (byte) 0x01, "云台向右方向运动"), // 垂直方向控制 TILT_UP("向上", (byte) 0x08, "云台向上方向运动"), TILT_DOWN("向下", (byte) 0x04, "云台向下方向运动"), // 组合方向控制 PAN_LEFT_TILT_UP("左上", (byte) 0x0A, "云台向左上方向运动"), PAN_RIGHT_TILT_UP("右上", (byte) 0x09, "云台向右上方向运动"), PAN_LEFT_TILT_DOWN("左下", (byte) 0x06, "云台向左下方向运动"), PAN_RIGHT_TILT_DOWN("右下", (byte) 0x05, "云台向右下方向运动"), // 镜头变倍控制 ZOOM_IN("放大", (byte) 0x10, "镜头变倍放大"), ZOOM_OUT("缩小", (byte) 0x20, "镜头变倍缩小"), // 组合控制示例 (可扩展) PAN_RIGHT_TILT_UP_ZOOM_OUT("右上缩小", (byte) 0x29, "云台右上运动同时镜头缩小"); /** * 指令名称 */ private final String name; /** * 指令码 (字节4) */ private final byte instructionCode; /** * 功能描述 */ private final String description; // 静态映射表,用于快速查找 private static final Map<Byte, PTZControlEnum> CODE_MAP = Arrays.stream(values()) .collect(Collectors.toMap(PTZControlEnum::getInstructionCode, Function.identity())); private static final Map<String, PTZControlEnum> NAME_MAP = Arrays.stream(values()) .collect(Collectors.toMap(PTZControlEnum::getName, Function.identity())); /** * 根据指令码查找枚举 */ public static PTZControlEnum getByCode(byte code) { return CODE_MAP.get(code); } /** * 根据名称查找枚举 */ public static PTZControlEnum getByName(String name) { return NAME_MAP.get(name); } /** * 检查是否包含水平方向控制 */ public boolean hasPanControl() { return (instructionCode & 0x03) != 0; } /** * 检查是否包含垂直方向控制 */ public boolean hasTiltControl() { return (instructionCode & 0x0C) != 0; } /** * 检查是否包含变倍控制 */ public boolean hasZoomControl() { return (instructionCode & 0x30) != 0; } /** * 获取水平方向控制类型 */ public PanDirection getPanDirection() { byte panBits = (byte) (instructionCode & 0x03); switch (panBits) { case 0x01: return PanDirection.RIGHT; case 0x02: return PanDirection.LEFT; default: return PanDirection.NONE; } } /** * 获取垂直方向控制类型 */ public TiltDirection getTiltDirection() { byte tiltBits = (byte) (instructionCode & 0x0C); switch (tiltBits) { case 0x04: return TiltDirection.DOWN; case 0x08: return TiltDirection.UP; default: return TiltDirection.NONE; } } /** * 获取变倍控制类型 */ public ZoomDirection getZoomDirection() { byte zoomBits = (byte) (instructionCode & 0x30); switch (zoomBits) { case 0x10: return ZoomDirection.IN; case 0x20: return ZoomDirection.OUT; default: return ZoomDirection.NONE; } } /** * 水平方向枚举 */ public enum PanDirection { NONE("无"), LEFT("左"), RIGHT("右"); @Getter private final String name; PanDirection(String name) { this.name = name; } } /** * 垂直方向枚举 */ public enum TiltDirection { NONE("无"), UP("上"), DOWN("下"); @Getter private final String name; TiltDirection(String name) { this.name = name; } } /** * 变倍方向枚举 */ public enum ZoomDirection { NONE("无"), IN("放大"), OUT("缩小"); @Getter private final String name; ZoomDirection(String name) { this.name = name; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/PresetControlEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/PresetControlEnum.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * 预置位指令枚举 * 根据 A.3.4 预置位指令 规范实现 * <p> * 预置位数目最大为255,0号预留 */ @Getter @AllArgsConstructor public enum PresetControlEnum { SET_PRESET("设置预置位", (byte) 0x81, "设置预置位"), CALL_PRESET("调用预置位", (byte) 0x82, "调用预置位"), DELETE_PRESET("删除预置位", (byte) 0x83, "删除预置位"); /** * 指令名称 */ private final String name; /** * 指令码 (字节4) */ private final byte instructionCode; /** * 功能描述 */ private final String description; // 静态映射表,用于快速查找 private static final Map<Byte, PresetControlEnum> CODE_MAP = Arrays.stream(values()) .collect(Collectors.toMap(PresetControlEnum::getInstructionCode, Function.identity())); private static final Map<String, PresetControlEnum> NAME_MAP = Arrays.stream(values()) .collect(Collectors.toMap(PresetControlEnum::getName, Function.identity())); /** * 根据指令码查找枚举 */ public static PresetControlEnum getByCode(byte code) { return CODE_MAP.get(code); } /** * 根据名称查找枚举 */ public static PresetControlEnum getByName(String name) { return NAME_MAP.get(name); } /** * 验证预置位号是否有效 * * @param presetNumber 预置位号 (1-255) * @return 是否有效 */ public static boolean isValidPresetNumber(int presetNumber) { return presetNumber >= 1 && presetNumber <= 255; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/ScanControlEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/ScanControlEnum.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * 扫描指令枚举 * 根据 A.3.6 扫描指令 规范实现 */ @Getter @AllArgsConstructor public enum ScanControlEnum { START_AUTO_SCAN("开始自动扫描", (byte) 0x89, "开始自动扫描"), SET_LEFT_BOUNDARY("设置左边界", (byte) 0x89, "设置自动扫描左边界"), SET_RIGHT_BOUNDARY("设置右边界", (byte) 0x89, "设置自动扫描右边界"), SET_SCAN_SPEED("设置扫描速度", (byte) 0x8A, "设置自动扫描速度"); /** * 指令名称 */ private final String name; /** * 指令码 (字节4) */ private final byte instructionCode; /** * 功能描述 */ private final String description; // 静态映射表,用于快速查找(注意:0x89指令码对应多个枚举,通过操作类型区分) private static final Map<String, ScanControlEnum> NAME_MAP = Arrays.stream(values()) .collect(Collectors.toMap(ScanControlEnum::getName, Function.identity())); /** * 根据指令码查找枚举 - 注意0x89指令码需要结合操作类型判断 * * @param code 指令码 * @return 扫描控制枚举(对于0x89返回START_AUTO_SCAN作为默认值) */ public static ScanControlEnum getByCode(byte code) { if (code == (byte) 0x89) { return START_AUTO_SCAN; // 默认返回开始扫描 } else if (code == (byte) 0x8A) { return SET_SCAN_SPEED; } return null; } /** * 根据指令码和操作类型查找枚举 * * @param code 指令码 * @param operationType 操作类型 * @return 扫描控制枚举 */ public static ScanControlEnum getByCodeAndOperation(byte code, ScanOperationType operationType) { if (code == (byte) 0x89) { switch (operationType) { case START: return START_AUTO_SCAN; case SET_LEFT_BOUNDARY: return SET_LEFT_BOUNDARY; case SET_RIGHT_BOUNDARY: return SET_RIGHT_BOUNDARY; default: return START_AUTO_SCAN; } } else if (code == (byte) 0x8A) { return SET_SCAN_SPEED; } return null; } /** * 根据名称查找枚举 */ public static ScanControlEnum getByName(String name) { return NAME_MAP.get(name); } /** * 验证扫描组号是否有效 * * @param groupNumber 扫描组号 (0-255) * @return 是否有效 */ public static boolean isValidGroupNumber(int groupNumber) { return groupNumber >= 0 && groupNumber <= 255; } /** * 验证扫描速度是否有效 * * @param speed 扫描速度 (数据的低8位在字节6,高4位在字节7的高4位) * @return 是否有效 */ public static boolean isValidSpeed(int speed) { return speed >= 0 && speed <= 0xFFF; // 12位数据 } /** * 扫描操作类型枚举 */ public enum ScanOperationType { START(0x00, "开始自动扫描"), SET_LEFT_BOUNDARY(0x01, "设置左边界"), SET_RIGHT_BOUNDARY(0x02, "设置右边界"); @Getter private final int value; @Getter private final String description; ScanOperationType(int value, String description) { this.value = value; this.description = description; } public static ScanOperationType getByValue(int value) { for (ScanOperationType type : values()) { if (type.value == value) { return type; } } return null; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/FIControlEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/FIControlEnum.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * FI(聚焦Focus/光圈Iris)控制指令枚举 * 根据 A.3.3 FI指令 规范实现 * <p> * 字节4位定义: * Bit7-Bit6: 固定为01 * Bit5-Bit4: 固定为00 * Bit3-Bit2: 光圈控制 (Iris) * Bit1-Bit0: 聚焦控制 (Focus) */ @Getter @AllArgsConstructor public enum FIControlEnum { // 基础控制 STOP("停止", (byte) 0x40, "镜头停止FI的所有动作"), // 光圈控制 IRIS_CLOSE("光圈缩小", (byte) 0x48, "镜头光圈缩小"), IRIS_OPEN("光圈放大", (byte) 0x44, "镜头光圈放大"), // 聚焦控制 FOCUS_NEAR("聚焦近", (byte) 0x42, "镜头聚焦近"), FOCUS_FAR("聚焦远", (byte) 0x41, "镜头聚焦远"), // 组合控制示例 IRIS_CLOSE_FOCUS_FAR("光圈缩小聚焦远", (byte) 0x49, "镜头光圈缩小同时聚焦远"); /** * 指令名称 */ private final String name; /** * 指令码 (字节4) */ private final byte instructionCode; /** * 功能描述 */ private final String description; // 静态映射表,用于快速查找 private static final Map<Byte, FIControlEnum> CODE_MAP = Arrays.stream(values()) .collect(Collectors.toMap(FIControlEnum::getInstructionCode, Function.identity())); private static final Map<String, FIControlEnum> NAME_MAP = Arrays.stream(values()) .collect(Collectors.toMap(FIControlEnum::getName, Function.identity())); /** * 根据指令码查找枚举 */ public static FIControlEnum getByCode(byte code) { return CODE_MAP.get(code); } /** * 根据名称查找枚举 */ public static FIControlEnum getByName(String name) { return NAME_MAP.get(name); } /** * 检查是否包含光圈控制 */ public boolean hasIrisControl() { return (instructionCode & 0x0C) != 0; } /** * 检查是否包含聚焦控制 */ public boolean hasFocusControl() { return (instructionCode & 0x03) != 0; } /** * 获取光圈控制类型 */ public IrisDirection getIrisDirection() { byte irisBits = (byte) (instructionCode & 0x0C); switch (irisBits) { case 0x04: return IrisDirection.OPEN; case 0x08: return IrisDirection.CLOSE; default: return IrisDirection.NONE; } } /** * 获取聚焦控制类型 */ public FocusDirection getFocusDirection() { byte focusBits = (byte) (instructionCode & 0x03); switch (focusBits) { case 0x01: return FocusDirection.FAR; case 0x02: return FocusDirection.NEAR; default: return FocusDirection.NONE; } } /** * 光圈方向枚举 */ public enum IrisDirection { NONE("无"), OPEN("放大"), CLOSE("缩小"); @Getter private final String name; IrisDirection(String name) { this.name = name; } } /** * 聚焦方向枚举 */ public enum FocusDirection { NONE("无"), NEAR("近"), FAR("远"); @Getter private final String name; FocusDirection(String name) { this.name = name; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/AuxiliaryControlEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/AuxiliaryControlEnum.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * 辅助开关控制指令枚举 * 根据 A.3.7 辅助开关控制指令 规范实现 */ @Getter @AllArgsConstructor public enum AuxiliaryControlEnum { SWITCH_ON("开关开", (byte) 0x8C, "开关开 / 模拟量步进数值增加1个单位"), SWITCH_OFF("开关关", (byte) 0x8D, "开关关 / 模拟量步进数值减少1个单位"); /** * 指令名称 */ private final String name; /** * 指令码 (字节4) */ private final byte instructionCode; /** * 功能描述 */ private final String description; // 静态映射表,用于快速查找 private static final Map<Byte, AuxiliaryControlEnum> CODE_MAP = Arrays.stream(values()) .collect(Collectors.toMap(AuxiliaryControlEnum::getInstructionCode, Function.identity())); private static final Map<String, AuxiliaryControlEnum> NAME_MAP = Arrays.stream(values()) .collect(Collectors.toMap(AuxiliaryControlEnum::getName, Function.identity())); /** * 根据指令码查找枚举 */ public static AuxiliaryControlEnum getByCode(byte code) { return CODE_MAP.get(code); } /** * 根据名称查找枚举 */ public static AuxiliaryControlEnum getByName(String name) { return NAME_MAP.get(name); } /** * 验证辅助开关编号是否有效 * * @param switchNumber 辅助开关编号 (0-255) * @return 是否有效 */ public static boolean isValidSwitchNumber(int switchNumber) { return switchNumber >= 0 && switchNumber <= 255; } /** * 辅助开关类型枚举 */ public enum AuxiliarySwitchType { WIPER(1, "雨刷控制"), LIGHT(2, "灯光控制"), HEATING(3, "加热控制"), VENTILATION(4, "通风控制"), DEFROST(5, "除霜控制"), CUSTOM(0, "自定义控制"); @Getter private final int value; @Getter private final String description; AuxiliarySwitchType(int value, String description) { this.value = value; this.description = description; } public static AuxiliarySwitchType getByValue(int value) { for (AuxiliarySwitchType type : values()) { if (type.value == value) { return type; } } return CUSTOM; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/CruiseControlEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/control/instruction/enums/CruiseControlEnum.java
package io.github.lunasaw.gb28181.common.entity.control.instruction.enums; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * 巡航指令枚举 * 根据 A.3.5 巡航指令 规范实现 */ @Getter @AllArgsConstructor public enum CruiseControlEnum { ADD_CRUISE_POINT("加入巡航点", (byte) 0x84, "加入巡航点"), DELETE_CRUISE_POINT("删除巡航点", (byte) 0x85, "删除一个巡航点"), SET_CRUISE_SPEED("设置巡航速度", (byte) 0x86, "设置巡航速度"), SET_CRUISE_STAY_TIME("设置巡航停留时间", (byte) 0x87, "设置巡航停留时间"), START_CRUISE("开始巡航", (byte) 0x88, "开始巡航"); /** * 指令名称 */ private final String name; /** * 指令码 (字节4) */ private final byte instructionCode; /** * 功能描述 */ private final String description; // 静态映射表,用于快速查找 private static final Map<Byte, CruiseControlEnum> CODE_MAP = Arrays.stream(values()) .collect(Collectors.toMap(CruiseControlEnum::getInstructionCode, Function.identity())); private static final Map<String, CruiseControlEnum> NAME_MAP = Arrays.stream(values()) .collect(Collectors.toMap(CruiseControlEnum::getName, Function.identity())); /** * 根据指令码查找枚举 */ public static CruiseControlEnum getByCode(byte code) { return CODE_MAP.get(code); } /** * 根据名称查找枚举 */ public static CruiseControlEnum getByName(String name) { return NAME_MAP.get(name); } /** * 验证巡航组号是否有效 * * @param groupNumber 巡航组号 (0-255) * @return 是否有效 */ public static boolean isValidGroupNumber(int groupNumber) { return groupNumber >= 0 && groupNumber <= 255; } /** * 验证预置位号是否有效 * * @param presetNumber 预置位号 (1-255) * @return 是否有效 */ public static boolean isValidPresetNumber(int presetNumber) { return presetNumber >= 1 && presetNumber <= 255; } /** * 验证速度值是否有效 * * @param speed 速度 (数据的低8位在字节6,高4位在字节7的高4位) * @return 是否有效 */ public static boolean isValidSpeed(int speed) { return speed >= 0 && speed <= 0xFFF; // 12位数据 } /** * 验证停留时间是否有效 * * @param stayTime 停留时间(秒) (数据的低8位在字节6,高4位在字节7的高4位) * @return 是否有效 */ public static boolean isValidStayTime(int stayTime) { return stayTime >= 0 && stayTime <= 0xFFF; // 12位数据 } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/TransModeEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/TransModeEnum.java
package io.github.lunasaw.gb28181.common.entity.enums; /** * @author luna * @date 2023/10/13 */ public enum TransModeEnum { /** * 传输模式 */ UDP("UDP", "UDP"), TCP("TCP", "TCP"), ; private final String type; private final String desc; TransModeEnum(String type, String desc) { this.type = type; this.desc = desc; } public static boolean isValid(String sort) { return UDP.getType().equals(sort) || TCP.getType().equals(sort); } public String getType() { return type; } public String getDesc() { return desc; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/StreamModeEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/StreamModeEnum.java
package io.github.lunasaw.gb28181.common.entity.enums; /** * @author luna * @date 2023/10/13 */ public enum StreamModeEnum { /** * 数据流传输模式 */ UDP("UDP", "UDP"), TCP_ACTIVE("TCP-ACTIVE", "TCP主动"), TCP_PASSIVE("TCP-PASSIVE", "TCP被动"), ; private final String type; private final String desc; StreamModeEnum(String type, String desc) { this.type = type; this.desc = desc; } public static boolean isValid(String sort) { return UDP.getType().equals(sort) || TCP_ACTIVE.getType().equals(sort) || TCP_PASSIVE.getType().equals(sort); } public String getType() { return type; } public String getDesc() { return desc; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/CmdTypeEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/CmdTypeEnum.java
package io.github.lunasaw.gb28181.common.entity.enums; /** * @author luna * @date 2023/10/13 */ public enum CmdTypeEnum { /** * server请求类型 */ DEVICE_INFO("DeviceInfo", "查询设备信息"), DEVICE_STATUS("DeviceStatus", "查询设备状态"), CATALOG("Catalog", "设备目录"), RECORD_INFO("RecordInfo", "查询设备录像信息"), ALARM("Alarm", "查询设备告警信息"), CONFIG_DOWNLOAD("ConfigDownload", "设备配置下载"), PRESET_QUERY("PresetQuery", "查询预置位"), MOBILE_POSITION("MobilePosition", "移动位置信息"), DEVICE_CONTROL("DeviceControl", "设备控制"), BROADCAST("Broadcast", "设备广播"), DEVICE_CONFIG("DeviceConfig", "设备配置"), MEDIA_STATUS("MediaStatus", "媒体状态信息"), KEEPALIVE("Keepalive", "心跳"), // client REGISTER("REGISTER", "注册"), ; private final String type; private final String desc; CmdTypeEnum(String type, String desc) { this.type = type; this.desc = desc; } public String getType() { return type; } public String getDesc() { return desc; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/InviteSessionNameEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/InviteSessionNameEnum.java
package io.github.lunasaw.gb28181.common.entity.enums; /** * @author luna * @date 2023/10/13 */ public enum InviteSessionNameEnum { /** * */ PLAY("Play", "点播"), PLAY_BACK("PlayBack", "回放"), ; private final String type; private final String desc; InviteSessionNameEnum(String type, String desc) { this.type = type; this.desc = desc; } public static boolean isValid(String sort) { return PLAY.getType().equals(sort) || PLAY_BACK.getType().equals(sort); } public String getType() { return type; } public String getDesc() { return desc; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/ManufacturerEnum.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/ManufacturerEnum.java
package io.github.lunasaw.gb28181.common.entity.enums; /** * @author luna * @date 2023/10/13 */ public enum ManufacturerEnum { /** * 硬件厂家 */ TP_LINK("TP-LINK", "TP-LINK"), ; private final String type; private final String desc; ManufacturerEnum(String type, String desc) { this.type = type; this.desc = desc; } public String getType() { return type; } public String getDesc() { return desc; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/DeviceGbType.java
gb28181-common/src/main/java/io/github/lunasaw/gb28181/common/entity/enums/DeviceGbType.java
package io.github.lunasaw.gb28181.common.entity.enums; import java.util.HashMap; import java.util.Map; public enum DeviceGbType { CENTER_SERVER(200, "中心服务器"), DVR(111, "DVR"), NVR(118, "NVR"), CAMERA(132, "摄像机"), VIRTUAL_ORGANIZATION_DIRECTORY(215, "虚拟组织目录"), CENTER_SIGNAL_CONTROL_SERVER(216, "中心信令控制服务器"); private static final Map<Integer, DeviceGbType> CODE_TO_TYPE_MAP = new HashMap<>(); static { for (DeviceGbType type : values()) { CODE_TO_TYPE_MAP.put(type.code, type); } } private final int code; private final String description; DeviceGbType(int code, String description) { this.code = code; this.description = description; } public static DeviceGbType fromCode(int code) { return CODE_TO_TYPE_MAP.get(code); } public int getCode() { return code; } public String getDescription() { return description; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/test/java/io/github/lunasaw/sip/common/service/impl/TimeSyncServiceImplTest.java
sip-common/src/test/java/io/github/lunasaw/sip/common/service/impl/TimeSyncServiceImplTest.java
package io.github.lunasaw.sip.common.service.impl; import io.github.lunasaw.sip.common.config.SipCommonProperties; import io.github.lunasaw.sip.common.service.TimeSyncService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.when; /** * 时间同步服务测试类 * * @author luna */ @ExtendWith(MockitoExtension.class) class TimeSyncServiceImplTest { @Mock private SipCommonProperties sipCommonProperties; @Mock private SipCommonProperties.TimeSync timeSyncConfig; private TimeSyncService timeSyncService; @BeforeEach void setUp() { timeSyncService = new TimeSyncServiceImpl(); ReflectionTestUtils.setField(timeSyncService, "gb28181Properties", sipCommonProperties); // 设置默认的mock行为 when(sipCommonProperties.getTimeSync()).thenReturn(timeSyncConfig); when(timeSyncConfig.isEnabled()).thenReturn(true); when(timeSyncConfig.getOffsetThreshold()).thenReturn(1000L); } @Test void testSyncTimeFromSip_Success() { // 准备测试数据 LocalDateTime testTime = LocalDateTime.now(); String dateValue = testTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")); // 执行测试 boolean result = timeSyncService.syncTimeFromSip(dateValue); // 验证结果 assertTrue(result); assertNotNull(timeSyncService.getLastSyncTime()); } @Test void testSyncTimeFromSip_DisabledConfig() { // 设置时间同步功能为禁用 when(timeSyncConfig.isEnabled()).thenReturn(false); // 执行测试 boolean result = timeSyncService.syncTimeFromSip("2024-01-01T12:00:00.000"); // 验证结果 assertFalse(result); } @Test void testSyncTimeFromSip_InvalidDateFormat() { // 使用无效的日期格式 String invalidDate = "invalid-date-format"; // 执行测试 boolean result = timeSyncService.syncTimeFromSip(invalidDate); // 验证结果 assertFalse(result); } @Test void testSyncTimeFromSip_NullOrEmpty() { // 测试null值 boolean result1 = timeSyncService.syncTimeFromSip(null); assertFalse(result1); // 测试空字符串 boolean result2 = timeSyncService.syncTimeFromSip(""); assertFalse(result2); // 测试空白字符串 boolean result3 = timeSyncService.syncTimeFromSip(" "); assertFalse(result3); } @Test void testSyncTimeFromNtp_DisabledConfig() { // 设置时间同步功能为禁用 when(timeSyncConfig.isEnabled()).thenReturn(false); // 执行测试 boolean result = timeSyncService.syncTimeFromNtp("pool.ntp.org"); // 验证结果 assertFalse(result); } @Test void testSyncTimeFromNtp_NullOrEmptyServer() { // 测试null值 boolean result1 = timeSyncService.syncTimeFromNtp(null); assertFalse(result1); // 测试空字符串 boolean result2 = timeSyncService.syncTimeFromNtp(""); assertFalse(result2); // 测试空白字符串 boolean result3 = timeSyncService.syncTimeFromNtp(" "); assertFalse(result3); } @Test void testTimeOffsetOperations() { // 测试设置时间偏差 long testOffset = 500L; timeSyncService.setTimeOffset(testOffset); // 验证结果 assertEquals(testOffset, timeSyncService.getTimeOffset()); assertNotNull(timeSyncService.getLastSyncTime()); } @Test void testNeedsTimeSync() { // 测试不需要校时的情况(偏差小于阈值) timeSyncService.setTimeOffset(500L); // 小于1000ms阈值 assertFalse(timeSyncService.needsTimeSync()); // 测试需要校时的情况(偏差超过阈值) timeSyncService.setTimeOffset(1500L); // 大于1000ms阈值 assertTrue(timeSyncService.needsTimeSync()); // 测试禁用时间同步的情况 when(timeSyncConfig.isEnabled()).thenReturn(false); assertFalse(timeSyncService.needsTimeSync()); } @Test void testGetCorrectedTime() { // 设置时间偏差 long offset = 1000L; // 1秒 timeSyncService.setTimeOffset(offset); // 获取修正后的时间 LocalDateTime correctedTime = timeSyncService.getCorrectedTime(); LocalDateTime currentTime = LocalDateTime.now(); // 验证修正后的时间应该比当前时间早大约1秒 assertNotNull(correctedTime); assertTrue(correctedTime.isBefore(currentTime)); } @Test void testSipDateParsing() { // 测试各种SIP日期格式 String[] validDateFormats = { "2024-01-01T12:00:00.000", "2024-12-31T23:59:59.999", "2024-06-15T08:30:45.123" }; for (String dateFormat : validDateFormats) { boolean result = timeSyncService.syncTimeFromSip(dateFormat); assertTrue(result, "Failed to parse date format: " + dateFormat); } } @Test void testTimeSyncWithLargeOffset() { // 设置较大的偏差阈值 when(timeSyncConfig.getOffsetThreshold()).thenReturn(100L); // 使用一个过去的时间来产生较大的偏差 LocalDateTime pastTime = LocalDateTime.now().minusMinutes(5); String dateValue = pastTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")); // 执行时间同步 boolean result = timeSyncService.syncTimeFromSip(dateValue); // 验证结果 assertTrue(result); assertTrue(timeSyncService.needsTimeSync()); // 应该需要校时 } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/test/java/io/github/lunasaw/sip/common/test/ApplicationTest.java
sip-common/src/test/java/io/github/lunasaw/sip/common/test/ApplicationTest.java
package io.github.lunasaw.sip.common.test; import com.luna.common.os.SystemInfoUtil; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.CustomerSipListener; import org.junit.jupiter.api.BeforeEach; /** * @author luna * @date 2023/10/13 */ public class ApplicationTest { private SipLayer sipLayer; @BeforeEach public void setUp() { sipLayer = new SipLayer(); sipLayer.setSipListener(CustomerSipListener.getInstance()); sipLayer.addListeningPoint(SystemInfoUtil.getIP(), 5060); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/test/java/io/github/lunasaw/sip/common/utils/TraceUtilsTest.java
sip-common/src/test/java/io/github/lunasaw/sip/common/utils/TraceUtilsTest.java
package io.github.lunasaw.sip.common.utils; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.MDC; import static org.junit.jupiter.api.Assertions.*; /** * TraceUtils测试类 * * @author luna */ @Slf4j class TraceUtilsTest { @BeforeEach void setUp() { // 确保每个测试前清理traceId TraceUtils.clearTraceId(); } @AfterEach void tearDown() { // 确保每个测试后清理traceId TraceUtils.clearTraceId(); } @Test void testSetAndGetTraceId() { // 设置traceId String traceId = "test-trace-123"; TraceUtils.setTraceId(traceId); // 验证获取到的traceId assertEquals(traceId, TraceUtils.getTraceId()); assertEquals(traceId, TraceUtils.getCurrentTraceId()); // 验证MDC中是否设置 assertEquals(traceId, MDC.get(TraceUtils.TRACE_ID_KEY)); log.info("测试设置和获取traceId: {}", TraceUtils.getTraceId()); } @Test void testAutoGenerateTraceId() { // 获取traceId(应该自动生成) String traceId = TraceUtils.getTraceId(); // 验证traceId不为空且长度为16 assertNotNull(traceId); assertEquals(16, traceId.length()); // 验证MDC中是否设置 assertEquals(traceId, MDC.get(TraceUtils.TRACE_ID_KEY)); log.info("测试自动生成traceId: {}", traceId); } @Test void testClearTraceId() { // 设置traceId String traceId = "test-trace-456"; TraceUtils.setTraceId(traceId); // 验证设置成功 assertEquals(traceId, TraceUtils.getTraceId()); // 清除traceId TraceUtils.clearTraceId(); // 验证清除成功 assertNull(TraceUtils.getCurrentTraceId()); assertNull(MDC.get(TraceUtils.TRACE_ID_KEY)); // 验证getTraceId会重新生成 String newTraceId = TraceUtils.getTraceId(); assertNotNull(newTraceId); assertNotEquals(traceId, newTraceId); log.info("测试清除traceId后重新生成: {}", newTraceId); } @Test void testHasTraceId() { // 初始状态应该没有traceId assertFalse(TraceUtils.hasTraceId()); // 设置traceId后应该有 TraceUtils.setTraceId("test-trace-789"); assertTrue(TraceUtils.hasTraceId()); // 清除后应该没有 TraceUtils.clearTraceId(); assertFalse(TraceUtils.hasTraceId()); } @Test void testSetEmptyTraceId() { // 设置空traceId应该被忽略 TraceUtils.setTraceId(""); assertFalse(TraceUtils.hasTraceId()); TraceUtils.setTraceId(null); assertFalse(TraceUtils.hasTraceId()); TraceUtils.setTraceId(" "); assertFalse(TraceUtils.hasTraceId()); } @Test void testGenerateTraceId() { String traceId1 = TraceUtils.generateTraceId(); String traceId2 = TraceUtils.generateTraceId(); // 验证生成的traceId格式 assertNotNull(traceId1); assertNotNull(traceId2); assertEquals(16, traceId1.length()); assertEquals(16, traceId2.length()); // 验证每次生成的traceId都不同 assertNotEquals(traceId1, traceId2); // 验证只包含十六进制字符 assertTrue(traceId1.matches("[0-9a-f]{16}")); assertTrue(traceId2.matches("[0-9a-f]{16}")); log.info("测试生成traceId: {} vs {}", traceId1, traceId2); } @Test void testThreadLocalIsolation() throws InterruptedException { // 在主线程设置traceId String mainThreadTraceId = "main-thread-trace"; TraceUtils.setTraceId(mainThreadTraceId); // 创建子线程 Thread childThread = new Thread(() -> { // 子线程应该没有traceId assertFalse(TraceUtils.hasTraceId()); assertNull(TraceUtils.getCurrentTraceId()); // 在子线程中设置traceId String childThreadTraceId = "child-thread-trace"; TraceUtils.setTraceId(childThreadTraceId); // 验证子线程的traceId assertEquals(childThreadTraceId, TraceUtils.getTraceId()); log.info("子线程traceId: {}", TraceUtils.getTraceId()); }); childThread.start(); childThread.join(); // 主线程的traceId应该保持不变 assertEquals(mainThreadTraceId, TraceUtils.getTraceId()); log.info("主线程traceId: {}", TraceUtils.getTraceId()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/test/java/io/github/lunasaw/sip/common/transmit/SipSenderRefactorTest.java
sip-common/src/test/java/io/github/lunasaw/sip/common/transmit/SipSenderRefactorTest.java
package io.github.lunasaw.sip.common.transmit; import com.luna.common.os.SystemInfoUtil; import gov.nist.javax.sip.SipProviderImpl; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.strategy.SipRequestStrategy; import io.github.lunasaw.sip.common.transmit.strategy.SipRequestStrategyFactory; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; import javax.sip.SipListener; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; /** * SipSender重构后的测试类 * 验证新API的功能和兼容性 * * @author lin */ @Slf4j @ExtendWith(MockitoExtension.class) class SipSenderRefactorTest { @Mock private FromDevice fromDevice; @Mock private ToDevice toDevice; @Mock private Event errorEvent; @Mock private Event okEvent; @Mock private SipProviderImpl sipProvider; @Mock private javax.sip.header.CallIdHeader callIdHeader; private SipLayer sipLayer; @BeforeEach void setUp() { // 创建SipLayer实例,使用mock的SipListener sipLayer = new SipLayer(); fromDevice = FromDevice.getInstance("34020000001320000001", "127.0.0.1", 5060); toDevice = ToDevice.getInstance("34020000001320000002", "127.0.0.1", 5060); // 初始化监听点,确保测试环境正确设置 sipLayer.setSipListener(CustomerSipListener.getInstance()); sipLayer.addListeningPoint("127.0.0.1", 5060); } @Test void testRequestBuilder() { // 使用MockedStatic来mock静态方法 try (MockedStatic<SipLayer> sipLayerMock = mockStatic(SipLayer.class)) { // Mock静态方法 - 确保在构造函数调用之前生效 sipLayerMock.when(() -> SipLayer.getUdpSipProvider("127.0.0.1")).thenReturn(sipProvider); sipLayerMock.when(() -> SipLayer.getUdpSipProvider()).thenReturn(sipProvider); when(sipProvider.getNewCallId()).thenReturn(callIdHeader); // 测试MESSAGE请求建造者 SipSender.SipRequestBuilder messageBuilder = SipSender.request(fromDevice, toDevice, "MESSAGE"); assertNotNull(messageBuilder); // 测试建造者链式调用 messageBuilder.content("Hello World") .errorEvent(errorEvent) .okEvent(okEvent); // 验证建造者设置 assertNotNull(messageBuilder); } } @Test void testStrategyFactory() { // 测试获取策略 SipRequestStrategy messageStrategy = SipRequestStrategyFactory.getStrategy("MESSAGE"); assertNotNull(messageStrategy); SipRequestStrategy inviteStrategy = SipRequestStrategyFactory.getStrategy("INVITE"); assertNotNull(inviteStrategy); SipRequestStrategy subscribeStrategy = SipRequestStrategyFactory.getStrategy("SUBSCRIBE"); assertNotNull(subscribeStrategy); SipRequestStrategy notifyStrategy = SipRequestStrategyFactory.getStrategy("NOTIFY"); assertNotNull(notifyStrategy); SipRequestStrategy byeStrategy = SipRequestStrategyFactory.getStrategy("BYE"); assertNotNull(byeStrategy); SipRequestStrategy ackStrategy = SipRequestStrategyFactory.getStrategy("ACK"); assertNotNull(ackStrategy); SipRequestStrategy infoStrategy = SipRequestStrategyFactory.getStrategy("INFO"); assertNotNull(infoStrategy); } @Test void testRegisterStrategy() { // 测试注册策略 SipRequestStrategy registerStrategy = SipRequestStrategyFactory.getRegisterStrategy(3600); assertNotNull(registerStrategy); SipRequestStrategy registerStrategy2 = SipRequestStrategyFactory.getRegisterStrategy(7200); assertNotNull(registerStrategy2); } @Test void testCustomStrategyRegistration() { // 测试自定义策略注册 SipRequestStrategy customStrategy = mock(SipRequestStrategy.class); // 注册自定义策略 SipRequestStrategyFactory.registerStrategy("CUSTOM", customStrategy); // 获取自定义策略 SipRequestStrategy retrievedStrategy = SipRequestStrategyFactory.getStrategy("CUSTOM"); assertNotNull(retrievedStrategy); assertEquals(customStrategy, retrievedStrategy); // 移除自定义策略 SipRequestStrategyFactory.removeStrategy("CUSTOM"); // 验证策略已被移除 SipRequestStrategy removedStrategy = SipRequestStrategyFactory.getStrategy("CUSTOM"); assertNull(removedStrategy); } @Test void testUnsupportedMethod() { // 测试不支持的方法 SipRequestStrategy unsupportedStrategy = SipRequestStrategyFactory.getStrategy("UNSUPPORTED"); assertNull(unsupportedStrategy); } @Test void testCompatibilityMethods() { // 测试兼容性方法的存在性 // 这些方法应该存在但可能抛出异常(因为依赖外部组件) // 验证方法存在 assertDoesNotThrow(() -> { // 这些方法调用可能会因为缺少依赖而失败,但我们只验证方法存在 SipSender.class.getMethod("doMessageRequest", FromDevice.class, ToDevice.class, String.class); SipSender.class.getMethod("doInviteRequest", FromDevice.class, ToDevice.class, String.class, String.class); SipSender.class.getMethod("doSubscribeRequest", FromDevice.class, ToDevice.class, String.class, SubscribeInfo.class); SipSender.class.getMethod("doRegisterRequest", FromDevice.class, ToDevice.class, Integer.class); }); } @Test void testBuilderChaining() { // 使用MockedStatic来mock静态方法 try (MockedStatic<SipLayer> sipLayerMock = mockStatic(SipLayer.class)) { // Mock静态方法 - 确保在构造函数调用之前生效 sipLayerMock.when(() -> SipLayer.getUdpSipProvider("127.0.0.1")).thenReturn(sipProvider); sipLayerMock.when(SipLayer::getUdpSipProvider).thenReturn(sipProvider); when(sipProvider.getNewCallId()).thenReturn(callIdHeader); // 测试建造者链式调用 SipSender.SipRequestBuilder builder = SipSender.request(fromDevice, toDevice, "MESSAGE") .content("Test Content") .errorEvent(errorEvent) .okEvent(okEvent) .callId("test-call-id"); assertNotNull(builder); // 验证链式调用返回的是同一个对象 SipSender.SipRequestBuilder chainedBuilder = builder .content("New Content") .errorEvent(null); assertEquals(builder, chainedBuilder); } } @Test void testStrategyFactorySingleton() { // 测试策略工厂的单例特性 SipRequestStrategy strategy1 = SipRequestStrategyFactory.getStrategy("MESSAGE"); SipRequestStrategy strategy2 = SipRequestStrategyFactory.getStrategy("MESSAGE"); // 应该返回相同的策略实例 assertEquals(strategy1, strategy2); } @Test void testBuilderWithDifferentMethods() { // 使用MockedStatic来mock静态方法 try (MockedStatic<SipLayer> sipLayerMock = mockStatic(SipLayer.class)) { // Mock静态方法 - 确保在构造函数调用之前生效 sipLayerMock.when(() -> SipLayer.getUdpSipProvider("127.0.0.1")).thenReturn(sipProvider); sipLayerMock.when(() -> SipLayer.getUdpSipProvider()).thenReturn(sipProvider); when(sipProvider.getNewCallId()).thenReturn(callIdHeader); // 测试不同方法的建造者 // 测试MESSAGE方法 SipSender.SipRequestBuilder messageBuilder = SipSender.request(fromDevice, toDevice, "MESSAGE"); assertNotNull(messageBuilder); // 测试INVITE方法 SipSender.SipRequestBuilder inviteBuilder = SipSender.request(fromDevice, toDevice, "INVITE"); assertNotNull(inviteBuilder); // 测试SUBSCRIBE方法 SipSender.SipRequestBuilder subscribeBuilder = SipSender.request(fromDevice, toDevice, "SUBSCRIBE"); assertNotNull(subscribeBuilder); // 测试NOTIFY方法 SipSender.SipRequestBuilder notifyBuilder = SipSender.request(fromDevice, toDevice, "NOTIFY"); assertNotNull(notifyBuilder); // 测试BYE方法 SipSender.SipRequestBuilder byeBuilder = SipSender.request(fromDevice, toDevice, "BYE"); assertNotNull(byeBuilder); // 测试ACK方法 SipSender.SipRequestBuilder ackBuilder = SipSender.request(fromDevice, toDevice, "ACK"); assertNotNull(ackBuilder); // 测试INFO方法 SipSender.SipRequestBuilder infoBuilder = SipSender.request(fromDevice, toDevice, "INFO"); assertNotNull(infoBuilder); } } @Test void testBuilderWithSubscribeInfo() { // 使用MockedStatic来mock静态方法 try (MockedStatic<SipLayer> sipLayerMock = mockStatic(SipLayer.class)) { // Mock静态方法 - 确保在构造函数调用之前生效 sipLayerMock.when(() -> SipLayer.getUdpSipProvider("127.0.0.1")).thenReturn(sipProvider); sipLayerMock.when(() -> SipLayer.getUdpSipProvider()).thenReturn(sipProvider); when(sipProvider.getNewCallId()).thenReturn(callIdHeader); // 测试带有SubscribeInfo的建造者 SubscribeInfo subscribeInfo = mock(SubscribeInfo.class); SipSender.SipRequestBuilder builder = SipSender.request(fromDevice, toDevice, "SUBSCRIBE") .subscribeInfo(subscribeInfo) .expires(3600); assertNotNull(builder); } } @Test void testBuilderWithSubject() { // 使用MockedStatic来mock静态方法 try (MockedStatic<SipLayer> sipLayerMock = mockStatic(SipLayer.class)) { // Mock静态方法 - 确保在构造函数调用之前生效 sipLayerMock.when(() -> SipLayer.getUdpSipProvider("127.0.0.1")).thenReturn(sipProvider); sipLayerMock.when(() -> SipLayer.getUdpSipProvider()).thenReturn(sipProvider); when(sipProvider.getNewCallId()).thenReturn(callIdHeader); // 测试带有Subject的建造者 SipSender.SipRequestBuilder builder = SipSender.request(fromDevice, toDevice, "INVITE") .subject("test-subject") .content("test-content"); assertNotNull(builder); } } @Test void testSipLayerConstructorInjection() { // 测试SipLayer的构造器注入 assertNotNull(sipLayer); // 验证SipLayer实例已正确创建 assertDoesNotThrow(() -> { sipLayer.addListeningPoint("127.0.0.1", 8117); }); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/test/java/io/github/lunasaw/sip/common/transmit/ResponseCmdTest.java
sip-common/src/test/java/io/github/lunasaw/sip/common/transmit/ResponseCmdTest.java
package io.github.lunasaw.sip.common.transmit; import com.luna.common.os.SystemInfoUtil; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.enums.ContentTypeEnum; import io.github.lunasaw.sip.common.test.ApplicationTest; import lombok.SneakyThrows; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; import javax.sip.SipFactory; import javax.sip.address.Address; import javax.sip.address.AddressFactory; import javax.sip.address.SipURI; import javax.sip.header.*; import javax.sip.message.MessageFactory; import java.util.ArrayList; import java.util.List; import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.when; /** * ResponseCmd 重构后的单元测试 * * @author luna */ @ExtendWith(MockitoExtension.class) class ResponseCmdTest extends ApplicationTest { @Mock private RequestEvent requestEvent; @Mock private SIPRequest sipRequest; @Mock private ServerTransaction serverTransaction; private MessageFactory messageFactory; private HeaderFactory headerFactory; private AddressFactory addressFactory; // 使用真实的SIP Header对象而不是mock对象 private ContactHeader contactHeader; private ContentTypeHeader contentTypeHeader; @BeforeEach @SneakyThrows public void setUp() { super.setUp(); // 初始化SIP协议栈 initializeSipStack(); // 创建真实的SIP请求对象 sipRequest = createRealSipRequest(); // 创建真实的SIP Header对象 createRealSipHeaders(); // 设置mock行为 when(requestEvent.getRequest()).thenReturn(sipRequest); when(requestEvent.getServerTransaction()).thenReturn(serverTransaction); } /** * 初始化SIP协议栈 */ private void initializeSipStack() throws Exception { SipFactory sipFactory = SipFactory.getInstance(); sipFactory.setPathName("gov.nist"); messageFactory = sipFactory.createMessageFactory(); headerFactory = sipFactory.createHeaderFactory(); addressFactory = sipFactory.createAddressFactory(); Properties properties = new Properties(); properties.setProperty("javax.sip.STACK_NAME", "test-stack"); properties.setProperty("javax.sip.IP_ADDRESS", "127.0.0.1"); properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "0"); properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "sipdebug.txt"); properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "siplog.txt"); properties.setProperty("gov.nist.javax.sip.MAX_MESSAGE_SIZE", "1048576"); properties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "1"); properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true"); } /** * 创建真实的SIP Header对象 */ private void createRealSipHeaders() throws Exception { // 创建真实的ContactHeader SipURI contactUri = addressFactory.createSipURI("test-user", "127.0.0.1:5060"); Address contactAddress = addressFactory.createAddress(contactUri); contactHeader = headerFactory.createContactHeader(contactAddress); // 创建真实的ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("application", "xml"); } /** * 创建真实的SIP请求对象 */ private SIPRequest createRealSipRequest() throws Exception { // 创建CallId CallIdHeader callIdHeader = headerFactory.createCallIdHeader("test-call-id"); // 创建CSeq CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1L, "MESSAGE"); // 创建From SipURI fromUri = addressFactory.createSipURI("test-user", "127.0.0.1:5060"); Address fromAddress = addressFactory.createAddress(fromUri); FromHeader fromHeader = headerFactory.createFromHeader(fromAddress, "from-tag"); // 创建To SipURI toUri = addressFactory.createSipURI("test-user", "127.0.0.1:5060"); Address toAddress = addressFactory.createAddress(toUri); ToHeader toHeader = headerFactory.createToHeader(toAddress, "to-tag"); // 创建Via ViaHeader viaHeader = headerFactory.createViaHeader(SystemInfoUtil.getIP(), 5060, "UDP", "branch-test"); List<ViaHeader> viaHeaders = new ArrayList<>(); viaHeaders.add(viaHeader); // 创建MaxForwards MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70); // 创建RequestURI SipURI requestUri = addressFactory.createSipURI("test-user", "127.0.0.1:5060"); // 创建真实的SIP请求 SIPRequest request = (SIPRequest) messageFactory.createRequest( requestUri, "MESSAGE", callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader ); return request; } @Test void testResponseBuilderBasicUsage() { // 设置mock行为 when(requestEvent.getRequest()).thenReturn(sipRequest); when(requestEvent.getServerTransaction()).thenReturn(serverTransaction); // 测试基本用法 assertDoesNotThrow(() -> { ResponseCmd.response(200) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderWithPhrase() { // 测试带短语的响应 assertDoesNotThrow(() -> { ResponseCmd.response(200) .phrase("OK") .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderWithContent() { // 测试带内容的响应 String content = "<?xml version=\"1.0\"?><Response>OK</Response>"; ContentTypeHeader contentType = ContentTypeEnum.APPLICATION_XML.getContentTypeHeader(); assertDoesNotThrow(() -> { ResponseCmd.response(200) .content(content) .contentType(contentType) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderWithHeaders() { // 测试带响应头的响应 assertDoesNotThrow(() -> { ResponseCmd.response(200) .requestEvent(requestEvent) .request(sipRequest) .header(contactHeader) .send(); }); } @Test void testResponseBuilderMultipleHeaders() { // 测试多个响应头 assertDoesNotThrow(() -> { ResponseCmd.response(200) .requestEvent(requestEvent) .request(sipRequest) .headers(contactHeader, contentTypeHeader) .send(); }); } @Test void testResponseBuilderWithCustomIp() { // 测试自定义IP地址 assertDoesNotThrow(() -> { ResponseCmd.response(200) .requestEvent(requestEvent) .request(sipRequest) .ip("10.0.0.1") .send(); }); } @Test void testConvenienceMethods() { // 测试便捷方法 assertDoesNotThrow(() -> { ResponseCmd.sendResponse(200, requestEvent); ResponseCmd.sendResponse(200, "OK", requestEvent); ResponseCmd.sendResponseNoTransaction(200, requestEvent); ResponseCmd.sendResponseNoTransaction(200, "OK", requestEvent); }); } @Test void testConvenienceMethodsWithContent() { // 测试带内容的便捷方法 String content = "test content"; ContentTypeHeader contentType = ContentTypeEnum.APPLICATION_XML.getContentTypeHeader(); assertDoesNotThrow(() -> { ResponseCmd.sendResponse(200, content, contentType, requestEvent); ResponseCmd.sendResponseNoTransaction(200, content, contentType, requestEvent); }); } @Test void testDeprecatedMethodsStillWork() { // 测试废弃方法仍然可用 assertDoesNotThrow(() -> { ResponseCmd.doResponseCmd(200, requestEvent); ResponseCmd.doResponseCmd(200, "OK", requestEvent); ResponseCmd.doResponseCmdNoTransaction(200, requestEvent); }); } @Test void testComplexResponseBuilder() { // 测试复杂的响应构建 String content = "<?xml version=\"1.0\"?><Response>OK</Response>"; ContentTypeHeader contentType = ContentTypeEnum.APPLICATION_XML.getContentTypeHeader(); assertDoesNotThrow(() -> { ResponseCmd.response(200) .phrase("OK") .content(content) .contentType(contentType) .requestEvent(requestEvent) .request(sipRequest) .header(contactHeader) .ip(SystemInfoUtil.getIP()) .send(); }); } @Test void testResponseBuilderWithNullTransaction() { // 测试空事务的情况 - 应该自动降级到无事务模式 when(requestEvent.getServerTransaction()).thenReturn(null); assertDoesNotThrow(() -> { ResponseCmd.response(200) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderChaining() { // 测试方法链式调用 ResponseCmd.SipResponseBuilder builder = ResponseCmd.response(200) .phrase("OK") .content("test") .contentType(contentTypeHeader) .requestEvent(requestEvent) .request(sipRequest) .header(contactHeader) .ip(SystemInfoUtil.getIP()); assertNotNull(builder); assertDoesNotThrow(builder::send); } @Test void testResponseBuilderWithDifferentStatusCodes() { // 测试不同的状态码 int[] statusCodes = {100, 200, 400, 401, 404, 500, 503}; for (int statusCode : statusCodes) { final int code = statusCode; assertDoesNotThrow(() -> { ResponseCmd.response(code) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } } @Test void testResponseBuilderWithEmptyContent() { // 测试空内容 assertDoesNotThrow(() -> { ResponseCmd.response(200) .content("") .contentType(contentTypeHeader) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderWithNullContent() { // 测试null内容 assertDoesNotThrow(() -> { ResponseCmd.response(200) .content(null) .contentType(contentTypeHeader) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderWithEmptyPhrase() { // 测试空短语 assertDoesNotThrow(() -> { ResponseCmd.response(200) .phrase("") .requestEvent(requestEvent) .request(sipRequest) .send(); }); } @Test void testResponseBuilderWithNullPhrase() { // 测试null短语 assertDoesNotThrow(() -> { ResponseCmd.response(200) .phrase(null) .requestEvent(requestEvent) .request(sipRequest) .send(); }); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/test/java/io/github/lunasaw/sip/common/transmit/request/SipRequestBuilderFactoryTest.java
sip-common/src/test/java/io/github/lunasaw/sip/common/transmit/request/SipRequestBuilderFactoryTest.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.message.Request; import gov.nist.javax.sip.message.SIPRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import static org.junit.jupiter.api.Assertions.*; /** * SIP请求构建器工厂测试类 * * @author luna */ @ExtendWith(MockitoExtension.class) class SipRequestBuilderFactoryTest { @Test void testCreateMessageRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); String content = "<test>message content</test>"; String callId = "test-call-id-123"; // 执行测试 SIPRequest request = (SIPRequest) SipRequestBuilderFactory.createMessageRequest(fromDevice, toDevice, content, callId); // 验证结果 assertNotNull(request); assertEquals(Request.MESSAGE, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); assertEquals(content, request.getContent()); } @Test void testCreateInviteRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); String content = "v=0\r\no=- 0 0 IN IP4 192.168.1.100\r\ns=Play\r\nc=IN IP4 192.168.1.100\r\nt=0 0\r\nm=video 6000 RTP/AVP 96\r\na=recvonly\r\na=rtpmap:96 PS/90000\r\n"; String subject = "34020000001320000001:0,34020000001320000002:0"; String callId = "test-call-id-456"; // 执行测试 Request request = SipRequestBuilderFactory.createInviteRequest(fromDevice, toDevice, content, subject, callId); // 验证结果 assertNotNull(request); assertEquals(Request.INVITE, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); assertEquals(content, request.getContent()); assertNotNull(request.getHeader("Subject")); } @Test void testCreateByeRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); String callId = "test-call-id-789"; // 执行测试 Request request = SipRequestBuilderFactory.createByeRequest(fromDevice, toDevice, callId); // 验证结果 assertNotNull(request); assertEquals(Request.BYE, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); } @Test void testCreateRegisterRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); Integer expires = 3600; String callId = "test-call-id-101"; // 执行测试 Request request = SipRequestBuilderFactory.createRegisterRequest(fromDevice, toDevice, expires, callId); // 验证结果 assertNotNull(request); assertEquals(Request.REGISTER, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); assertNotNull(request.getHeader("Expires")); } @Test void testCreateAckRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); String callId = "test-call-id-202"; // 执行测试 Request request = SipRequestBuilderFactory.createAckRequest(fromDevice, toDevice, callId); // 验证结果 assertNotNull(request); assertEquals(Request.ACK, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); } @Test void testCreateAckRequestWithContent() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); String content = "v=0\r\no=- 0 0 IN IP4 192.168.1.100\r\ns=Play\r\nc=IN IP4 192.168.1.100\r\nt=0 0\r\nm=video 6000 RTP/AVP 96\r\na=recvonly\r\na=rtpmap:96 PS/90000\r\n"; String callId = "test-call-id-303"; // 执行测试 Request request = SipRequestBuilderFactory.createAckRequest(fromDevice, toDevice, content, callId); // 验证结果 assertNotNull(request); assertEquals(Request.ACK, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); assertEquals(content, request.getContent()); } @Test void testCreateInfoRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); String content = "<test>info content</test>"; String callId = "test-call-id-404"; // 执行测试 Request request = SipRequestBuilderFactory.createInfoRequest(fromDevice, toDevice, content, callId); // 验证结果 assertNotNull(request); assertEquals(Request.INFO, request.getMethod()); assertEquals(callId, ((SIPRequest) request).getCallIdHeader().getCallId()); assertEquals(content, request.getContent()); } @Test void testCreateSipRequest() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); SipMessage sipMessage = SipMessage.getMessageBody(); sipMessage.setMethod(Request.MESSAGE); sipMessage.setContent("test content"); sipMessage.setCallId("test-call-id-505"); // 执行测试 Request request = SipRequestBuilderFactory.createSipRequest(fromDevice, toDevice, sipMessage); // 验证结果 assertNotNull(request); assertEquals(Request.MESSAGE, request.getMethod()); assertEquals("test-call-id-505", ((SIPRequest) request).getCallIdHeader().getCallId()); assertEquals("test content", request.getContent()); } @Test void testCreateSipRequestWithUnsupportedMethod() { // 准备测试数据 FromDevice fromDevice = FromDevice.getInstance("34020000001320000001", "192.168.1.100", 5060); ToDevice toDevice = ToDevice.getInstance("34020000001320000002", "192.168.1.200", 5060); SipMessage sipMessage = SipMessage.getMessageBody(); sipMessage.setMethod("UNSUPPORTED_METHOD"); sipMessage.setCallId("test-call-id-606"); // 执行测试并验证异常 assertThrows(IllegalArgumentException.class, () -> { SipRequestBuilderFactory.createSipRequest(fromDevice, toDevice, sipMessage); }); } @Test void testGetBuilders() { // 验证所有构建器都能正常获取 assertNotNull(SipRequestBuilderFactory.getMessageBuilder()); assertNotNull(SipRequestBuilderFactory.getInviteBuilder()); assertNotNull(SipRequestBuilderFactory.getByeBuilder()); assertNotNull(SipRequestBuilderFactory.getRegisterBuilder()); assertNotNull(SipRequestBuilderFactory.getSubscribeBuilder()); assertNotNull(SipRequestBuilderFactory.getInfoBuilder()); assertNotNull(SipRequestBuilderFactory.getAckBuilder()); assertNotNull(SipRequestBuilderFactory.getNotifyBuilder()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/SipCommonApplication.java
sip-common/src/main/java/io/github/lunasaw/sip/common/SipCommonApplication.java
package io.github.lunasaw.sip.common; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author luna * @date 2023/10/12 */ @SpringBootApplication public class SipCommonApplication { public static void main(String[] args) { SpringApplication.run(SipCommonApplication.class, args); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/constant/Constant.java
sip-common/src/main/java/io/github/lunasaw/sip/common/constant/Constant.java
package io.github.lunasaw.sip.common.constant; /** * @author luna * @date 2023/10/12 */ public class Constant { public static final String TCP = "TCP"; public static final String UDP = "UDP"; public static final String AGENT = "LunaSaw-GB28181-Proxy"; public static final String PASSWORD_HEADER = "AUTH_PASSWORD"; public static final String UTF_8 = "UTF-8"; public static void main(String[] args) { System.out.println(2 << 0); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/constant/package-info.java
sip-common/src/main/java/io/github/lunasaw/sip/common/constant/package-info.java
/** * Contains constants used in the SIP protocol. * 包含SIP协议中使用的常量 * * @author luna * @date 2023/11/20 */ package io.github.lunasaw.sip.common.constant;
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/ClientDeviceSupplier.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/ClientDeviceSupplier.java
package io.github.lunasaw.sip.common.service; import io.github.lunasaw.sip.common.entity.FromDevice; /** * 客户端设备提供器接口 * 扩展DeviceSupplier接口,提供客户端特定的设备获取能力 * <p> * 设计原则: * 1. 继承基础设备提供器接口,保持接口的一致性 * 2. 提供客户端发送方设备信息获取能力 * 3. 支持客户端SIP消息发送时的设备标识 * * @author luna * @date 2025/01/23 */ public interface ClientDeviceSupplier extends DeviceSupplier { /** * 获取客户端发送方设备信息 * 用于客户端发送SIP消息时标识发送方设备 * * @return 客户端发送方设备信息,如果不存在则返回null */ FromDevice getClientFromDevice(); /** * 设置客户端发送方设备信息 * 用于配置客户端的发送方设备标识 * * @param fromDevice 客户端发送方设备信息 */ void setClientFromDevice(FromDevice fromDevice); }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/TimeSyncService.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/TimeSyncService.java
package io.github.lunasaw.sip.common.service; import java.time.LocalDateTime; /** * 时间同步服务接口 * 支持SIP和NTP两种校时方式 * * @author luna */ public interface TimeSyncService { /** * SIP校时 - 从Date头域解析时间并同步 * * @param dateHeaderValue Date头域的值 (格式: yyyy-MM-dd'T'HH:mm:ss.SSS) * @return 是否同步成功 */ boolean syncTimeFromSip(String dateHeaderValue); /** * NTP校时 - 从NTP服务器同步时间 * * @param ntpServer NTP服务器地址 * @return 是否同步成功 */ boolean syncTimeFromNtp(String ntpServer); /** * 获取当前系统与标准时间的偏差 * * @return 时间偏差(毫秒),正值表示本地时间快于标准时间 */ long getTimeOffset(); /** * 设置时间偏差 * * @param offset 时间偏差(毫秒) */ void setTimeOffset(long offset); /** * 获取经过校时修正的当前时间 * * @return 修正后的当前时间 */ LocalDateTime getCorrectedTime(); /** * 检查是否需要校时 * 当时间偏差超过配置的阈值时返回true * * @return 是否需要校时 */ boolean needsTimeSync(); /** * 获取上次校时的时间 * * @return 上次校时的时间 */ LocalDateTime getLastSyncTime(); }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/SipUserGenerate.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/SipUserGenerate.java
package io.github.lunasaw.sip.common.service; import javax.sip.RequestEvent; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.utils.SipUtils; /** * @author luna * @date 2023/10/17 */ public interface SipUserGenerate { /** * 接受设备 * * @param userId sip用户id * @return ToDevice */ Device getToDevice(String userId); /** * 发送设备 * * @return FromDevice */ Device getFromDevice(); /** * 设备检查 * * @param evt * @return */ default boolean checkDevice(RequestEvent evt) { SIPRequest request = (SIPRequest)evt.getRequest(); // 在接收端看来 收到请求的时候fromHeader还是服务端的 toHeader才是自己的,这里是要查询自己的信息 String userId = SipUtils.getUserIdFromToHeader(request); // 获取设备 FromDevice fromDevice = (FromDevice)getFromDevice(); if (fromDevice == null) { return false; } return userId.equals(fromDevice.getUserId()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/DeviceSupplier.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/DeviceSupplier.java
package io.github.lunasaw.sip.common.service; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.sip.common.entity.ToDevice; import org.springframework.util.Assert; import java.util.List; /** * 设备提供器接口 * 用于动态获取设备列表的hook机制,支持外部实现自定义的设备获取逻辑 * <p> * 设计原则: * 1. 业务方通过userId获取设备数据,项目本身不关心设备类型 * 2. 简化接口设计,减少不必要的复杂性 * 3. 支持动态设备管理和更新 * * @author luna * @date 2025/01/23 */ public interface DeviceSupplier { /** * 根据用户ID获取指定设备 * 这是设备获取的核心方法,业务方通过userId获取设备数据 * * @param userId 用户ID * @return 设备信息,如果不存在则返回null */ Device getDevice(String userId); /** * 获取设备提供器的名称标识 * * @return 提供器名称 */ default String getName() { return this.getClass().getSimpleName(); } default ToDevice getToDevice(String deviceId) { Assert.notNull(deviceId, "设备Id不能为空"); Device device = getDevice(deviceId); Assert.notNull(device, "查询不到设备信息"); return getToDevice(device); } default ToDevice getToDevice(Device device) { if (device == null) { return null; } ToDevice toDevice = new ToDevice(); toDevice.setHostAddress(device.getHostAddress()); toDevice.setUserId(device.getUserId()); toDevice.setRealm(device.getRealm()); toDevice.setTransport(device.getTransport()); toDevice.setStreamMode(device.getStreamMode()); toDevice.setIp(device.getIp()); toDevice.setPort(device.getPort()); toDevice.setPassword(device.getPassword()); toDevice.setCharset(device.getCharset()); return toDevice; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/ServerDeviceSupplier.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/ServerDeviceSupplier.java
package io.github.lunasaw.sip.common.service; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.utils.SipUtils; import javax.sip.RequestEvent; /** * 服务端设备提供器接口 * 扩展DeviceSupplier接口,提供服务端特定的设备获取能力 * <p> * 设计原则: * 1. 继承基础设备提供器接口,保持接口的一致性 * 2. 提供服务端发送方设备信息获取能力 * 3. 支持服务端SIP消息发送时的设备标识 * * @author luna * @date 2025/01/23 */ public interface ServerDeviceSupplier extends DeviceSupplier { /** * 获取服务端发送方设备信息 * 用于服务端发送SIP消息时标识发送方设备 * * @return 服务端发送方设备信息,如果不存在则返回null */ FromDevice getServerFromDevice(); /** * 设置服务端发送方设备信息 * 用于配置服务端的发送方设备标识 * * @param fromDevice 服务端发送方设备信息 */ void setServerFromDevice(FromDevice fromDevice); /** * 设备检查 * * @param evt * @return */ default boolean checkDevice(RequestEvent evt) { SIPRequest request = (SIPRequest) evt.getRequest(); // 在接收端看来 收到请求的时候fromHeader还是服务端的 toHeader才是自己的,这里是要查询自己的信息 String userId = SipUtils.getUserIdFromToHeader(request); // 获取当前作为服务端的配置 FromDevice fromDevice = getServerFromDevice(); if (fromDevice == null) { return false; } return userId.equals(fromDevice.getUserId()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/impl/TimeSyncServiceImpl.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/impl/TimeSyncServiceImpl.java
package io.github.lunasaw.sip.common.service.impl; import io.github.lunasaw.sip.common.config.SipCommonProperties; import io.github.lunasaw.sip.common.service.TimeSyncService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * 时间同步服务实现类 * 支持SIP和NTP两种校时方式 * * @author luna */ @Slf4j @Service public class TimeSyncServiceImpl implements TimeSyncService { private static final DateTimeFormatter SIP_DATE_FORMATTER_WITH_MILLIS = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); private static final DateTimeFormatter SIP_DATE_FORMATTER_WITHOUT_MILLIS = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"); // NTP时间戳偏移量 (1900年1月1日到1970年1月1日的秒数) private static final long NTP_TIMESTAMP_OFFSET = 2208988800L; // 时间偏差(毫秒) private final AtomicLong timeOffset = new AtomicLong(0); // 上次校时时间 private final AtomicReference<LocalDateTime> lastSyncTime = new AtomicReference<>(); @Autowired private SipCommonProperties sipCommonProperties; /** * 解析SIP Date头域时间,支持有无毫秒两种格式 * * @param dateTime 时间字符串 * @return 解析后的LocalDateTime * @throws DateTimeParseException 解析失败时抛出异常 */ private LocalDateTime parseSipDateTime(String dateTime) throws DateTimeParseException { try { // 首先尝试解析带毫秒的格式 return LocalDateTime.parse(dateTime, SIP_DATE_FORMATTER_WITH_MILLIS); } catch (DateTimeParseException e) { // 如果失败,尝试解析不带毫秒的格式 return LocalDateTime.parse(dateTime, SIP_DATE_FORMATTER_WITHOUT_MILLIS); } } @Override public boolean syncTimeFromSip(String dateHeaderValue) { SipCommonProperties.TimeSync timeSyncConfig = sipCommonProperties.getTimeSync(); if (!timeSyncConfig.isEnabled()) { log.debug("时间同步功能已禁用"); return false; } if (dateHeaderValue == null || dateHeaderValue.trim().isEmpty()) { log.warn("SIP Date头域值为空,无法进行时间同步"); return false; } try { // 解析SIP Date头域的时间,支持有无毫秒两种格式 LocalDateTime serverTime = parseSipDateTime(dateHeaderValue.trim()); LocalDateTime localTime = LocalDateTime.now(); // 计算时间偏差 long offset = java.time.Duration.between(serverTime, localTime).toMillis(); log.info("SIP校时 - 服务器时间: {}, 本地时间: {}, 偏差: {}ms", serverTime, localTime, offset); // 更新时间偏差 timeOffset.set(offset); lastSyncTime.set(LocalDateTime.now()); long offsetThreshold = timeSyncConfig.getOffsetThreshold(); if (Math.abs(offset) > offsetThreshold) { log.warn("时间偏差较大: {}ms,超过阈值: {}ms", offset, offsetThreshold); } else { log.info("SIP时间同步成功,偏差: {}ms", offset); } return true; } catch (DateTimeParseException e) { log.error("解析SIP Date头域失败: {}", dateHeaderValue, e); return false; } catch (Exception e) { log.error("SIP时间同步异常", e); return false; } } @Override public boolean syncTimeFromNtp(String ntpServer) { SipCommonProperties.TimeSync timeSyncConfig = sipCommonProperties.getTimeSync(); if (!timeSyncConfig.isEnabled()) { log.debug("时间同步功能已禁用"); return false; } if (ntpServer == null || ntpServer.trim().isEmpty()) { log.warn("NTP服务器地址为空,无法进行时间同步"); return false; } try (DatagramSocket socket = new DatagramSocket()) { socket.setSoTimeout(5000); // 5秒超时 InetAddress address = InetAddress.getByName(ntpServer); // 构建NTP请求包 byte[] requestData = new byte[48]; requestData[0] = 0x1B; // LI=0, VN=3, Mode=3 (client) DatagramPacket requestPacket = new DatagramPacket( requestData, requestData.length, address, 123); long localTimeBefore = System.currentTimeMillis(); socket.send(requestPacket); // 接收响应 byte[] responseData = new byte[48]; DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length); socket.receive(responsePacket); long localTimeAfter = System.currentTimeMillis(); // 解析NTP时间戳 (从字节32-35,网络字节序) long ntpTime = 0; for (int i = 40; i <= 43; i++) { ntpTime = (ntpTime << 8) | (responseData[i] & 0xff); } // 转换为Unix时间戳 long serverTime = (ntpTime - NTP_TIMESTAMP_OFFSET) * 1000; long localTime = (localTimeBefore + localTimeAfter) / 2; long offset = localTime - serverTime; log.info("NTP校时 - 服务器时间: {}, 本地时间: {}, 偏差: {}ms", new java.util.Date(serverTime), new java.util.Date(localTime), offset); // 更新时间偏差 timeOffset.set(offset); lastSyncTime.set(LocalDateTime.now()); long offsetThreshold = timeSyncConfig.getOffsetThreshold(); if (Math.abs(offset) > offsetThreshold) { log.warn("时间偏差较大: {}ms,超过阈值: {}ms", offset, offsetThreshold); } else { log.info("NTP时间同步成功,偏差: {}ms", offset); } return true; } catch (Exception e) { log.error("NTP时间同步失败: {}", ntpServer, e); return false; } } @Override public long getTimeOffset() { return timeOffset.get(); } @Override public void setTimeOffset(long offset) { timeOffset.set(offset); lastSyncTime.set(LocalDateTime.now()); log.info("手动设置时间偏差: {}ms", offset); } @Override public LocalDateTime getCorrectedTime() { long offset = timeOffset.get(); return LocalDateTime.now().minusNanos(offset * 1_000_000); } @Override public boolean needsTimeSync() { SipCommonProperties.TimeSync timeSyncConfig = sipCommonProperties.getTimeSync(); if (!timeSyncConfig.isEnabled()) { return false; } long offset = Math.abs(timeOffset.get()); return offset > timeSyncConfig.getOffsetThreshold(); } @Override public LocalDateTime getLastSyncTime() { return lastSyncTime.get(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/service/impl/NtpTimeSyncScheduler.java
sip-common/src/main/java/io/github/lunasaw/sip/common/service/impl/NtpTimeSyncScheduler.java
package io.github.lunasaw.sip.common.service.impl; import io.github.lunasaw.sip.common.config.SipCommonProperties; import io.github.lunasaw.sip.common.service.TimeSyncService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * NTP定时校时任务 * 根据配置定期执行NTP时间同步 * * @author luna */ @Slf4j @Component @ConditionalOnProperty(prefix = "sip.gb28181.time-sync", name = "enabled", havingValue = "true", matchIfMissing = true) public class NtpTimeSyncScheduler { @Autowired private TimeSyncService timeSyncService; @Autowired private SipCommonProperties sipCommonProperties; /** * 定时执行NTP校时 * 根据配置的同步间隔执行 */ @Scheduled(fixedRateString = "#{${sip.gb28181.time-sync.ntp-sync-interval:3600} * 1000}") public void performNtpSync() { SipCommonProperties.TimeSync timeSyncConfig = sipCommonProperties.getTimeSync(); // 检查是否启用NTP校时 if (!timeSyncConfig.isEnabled()) { return; } SipCommonProperties.TimeSyncMode mode = timeSyncConfig.getMode(); if (mode != SipCommonProperties.TimeSyncMode.NTP && mode != SipCommonProperties.TimeSyncMode.BOTH) { return; } String ntpServer = timeSyncConfig.getNtpServer(); if (ntpServer == null || ntpServer.trim().isEmpty()) { log.warn("NTP服务器地址未配置,跳过NTP校时"); return; } log.debug("开始执行定时NTP校时,服务器: {}", ntpServer); try { boolean success = timeSyncService.syncTimeFromNtp(ntpServer); if (success) { log.info("定时NTP校时成功"); } else { log.warn("定时NTP校时失败,服务器: {}", ntpServer); } } catch (Exception e) { log.error("定时NTP校时异常,服务器: {}", ntpServer, e); } } /** * 检查时间同步状态 * 每5分钟检查一次时间偏差状态 */ @Scheduled(fixedRate = 300000) // 5分钟 public void checkTimeSyncStatus() { SipCommonProperties.TimeSync timeSyncConfig = sipCommonProperties.getTimeSync(); if (!timeSyncConfig.isEnabled()) { return; } try { if (timeSyncService.needsTimeSync()) { long offset = timeSyncService.getTimeOffset(); log.warn("时间偏差较大: {}ms,超过阈值: {}ms", offset, timeSyncConfig.getOffsetThreshold()); // 如果配置了NTP作为备用校时方式,尝试NTP校时 if (timeSyncConfig.getMode() == SipCommonProperties.TimeSyncMode.BOTH) { log.info("尝试使用NTP进行时间校正"); timeSyncService.syncTimeFromNtp(timeSyncConfig.getNtpServer()); } } } catch (Exception e) { log.error("检查时间同步状态异常", e); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/cache/CacheConfig.java
sip-common/src/main/java/io/github/lunasaw/sip/common/cache/CacheConfig.java
package io.github.lunasaw.sip.common.cache; import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.Duration; import java.util.Arrays; /** * 缓存配置类 - 使用Caffeine替代ConcurrentHashMap提升性能 * * @author luna * @date 2024/1/6 */ @Configuration @EnableCaching public class CacheConfig { /** * 默认缓存管理器 - 使用ConcurrentMapCacheManager作为后备 */ @Bean @ConditionalOnMissingBean(CacheManager.class) public CacheManager cacheManager() { return new ConcurrentMapCacheManager("devices", "subscribes", "transactions", "sipMessages"); } /** * Caffeine设备信息缓存 */ @Bean("deviceCaffeine") public com.github.benmanes.caffeine.cache.Cache<String, Object> deviceCache() { return Caffeine.newBuilder() .maximumSize(50000) // 支持更多设备 .expireAfterWrite(Duration.ofHours(2)) // 写入后2小时过期 .expireAfterAccess(Duration.ofMinutes(30)) // 访问后30分钟过期 .recordStats() .build(); } /** * Caffeine订阅信息缓存 */ @Bean("subscribeCaffeine") public com.github.benmanes.caffeine.cache.Cache<String, Object> subscribeCache() { return Caffeine.newBuilder() .maximumSize(5000) .expireAfterWrite(Duration.ofMinutes(5)) // 订阅信息5分钟过期 .expireAfterAccess(Duration.ofMinutes(2)) .recordStats() .build(); } /** * Caffeine事务缓存 */ @Bean("transactionCaffeine") public com.github.benmanes.caffeine.cache.Cache<String, Object> transactionCache() { return Caffeine.newBuilder() .maximumSize(2000) .expireAfterWrite(Duration.ofMinutes(1)) // 事务信息1分钟过期 .recordStats() .build(); } /** * Caffeine SIP消息缓存 */ @Bean("sipMessageCaffeine") public com.github.benmanes.caffeine.cache.Cache<String, Object> sipMessageCache() { return Caffeine.newBuilder() .maximumSize(10000) .expireAfterWrite(Duration.ofMinutes(30)) // 写入后30分钟过期 .expireAfterAccess(Duration.ofMinutes(15)) // 访问后15分钟过期 .recordStats() .build(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/cache/CacheService.java
sip-common/src/main/java/io/github/lunasaw/sip/common/cache/CacheService.java
package io.github.lunasaw.sip.common.cache; import com.github.benmanes.caffeine.cache.Cache; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import lombok.extern.slf4j.Slf4j; import java.util.Optional; /** * 缓存服务类 - 统一管理Caffeine缓存操作 * * @author luna * @date 2024/1/6 */ @Slf4j @Service public class CacheService { private final Cache<String, Object> deviceCache; private final Cache<String, Object> subscribeCache; private final Cache<String, Object> transactionCache; private final Cache<String, Object> sipMessageCache; public CacheService( @Qualifier("deviceCaffeine") Cache<String, Object> deviceCache, @Qualifier("subscribeCaffeine") Cache<String, Object> subscribeCache, @Qualifier("transactionCaffeine") Cache<String, Object> transactionCache, @Qualifier("sipMessageCaffeine") Cache<String, Object> sipMessageCache) { this.deviceCache = deviceCache; this.subscribeCache = subscribeCache; this.transactionCache = transactionCache; this.sipMessageCache = sipMessageCache; } // ==================== 设备缓存操作 ==================== /** * 获取设备信息 */ @SuppressWarnings("unchecked") public <T> Optional<T> getDevice(String deviceId, Class<T> type) { try { Object value = deviceCache.getIfPresent(deviceId); if (value != null && type.isInstance(value)) { return Optional.of((T)value); } } catch (Exception e) { log.warn("Failed to get device from cache: {}", deviceId, e); } return Optional.empty(); } /** * 存储设备信息 */ public void putDevice(String deviceId, Object device) { try { deviceCache.put(deviceId, device); log.debug("Device cached: {}", deviceId); } catch (Exception e) { log.warn("Failed to cache device: {}", deviceId, e); } } /** * 移除设备信息 */ public void removeDevice(String deviceId) { try { deviceCache.invalidate(deviceId); log.debug("Device removed from cache: {}", deviceId); } catch (Exception e) { log.warn("Failed to remove device from cache: {}", deviceId, e); } } // ==================== 订阅缓存操作 ==================== /** * 获取订阅信息 */ @SuppressWarnings("unchecked") public <T> Optional<T> getSubscribe(String subscribeId, Class<T> type) { try { Object value = subscribeCache.getIfPresent(subscribeId); if (value != null && type.isInstance(value)) { return Optional.of((T)value); } } catch (Exception e) { log.warn("Failed to get subscribe from cache: {}", subscribeId, e); } return Optional.empty(); } /** * 存储订阅信息 */ public void putSubscribe(String subscribeId, Object subscribe) { try { subscribeCache.put(subscribeId, subscribe); log.debug("Subscribe cached: {}", subscribeId); } catch (Exception e) { log.warn("Failed to cache subscribe: {}", subscribeId, e); } } /** * 移除订阅信息 */ public void removeSubscribe(String subscribeId) { try { subscribeCache.invalidate(subscribeId); log.debug("Subscribe removed from cache: {}", subscribeId); } catch (Exception e) { log.warn("Failed to remove subscribe from cache: {}", subscribeId, e); } } // ==================== 事务缓存操作 ==================== /** * 获取事务信息 */ @SuppressWarnings("unchecked") public <T> Optional<T> getTransaction(String transactionId, Class<T> type) { try { Object value = transactionCache.getIfPresent(transactionId); if (value != null && type.isInstance(value)) { return Optional.of((T)value); } } catch (Exception e) { log.warn("Failed to get transaction from cache: {}", transactionId, e); } return Optional.empty(); } /** * 存储事务信息 */ public void putTransaction(String transactionId, Object transaction) { try { transactionCache.put(transactionId, transaction); log.debug("Transaction cached: {}", transactionId); } catch (Exception e) { log.warn("Failed to cache transaction: {}", transactionId, e); } } /** * 移除事务信息 */ public void removeTransaction(String transactionId) { try { transactionCache.invalidate(transactionId); log.debug("Transaction removed from cache: {}", transactionId); } catch (Exception e) { log.warn("Failed to remove transaction from cache: {}", transactionId, e); } } // ==================== SIP消息缓存操作 ==================== /** * 获取SIP消息 */ @SuppressWarnings("unchecked") public <T> Optional<T> getSipMessage(String messageId, Class<T> type) { try { Object value = sipMessageCache.getIfPresent(messageId); if (value != null && type.isInstance(value)) { return Optional.of((T)value); } } catch (Exception e) { log.warn("Failed to get SIP message from cache: {}", messageId, e); } return Optional.empty(); } /** * 存储SIP消息 */ public void putSipMessage(String messageId, Object message) { try { sipMessageCache.put(messageId, message); log.debug("SIP message cached: {}", messageId); } catch (Exception e) { log.warn("Failed to cache SIP message: {}", messageId, e); } } /** * 移除SIP消息 */ public void removeSipMessage(String messageId) { try { sipMessageCache.invalidate(messageId); log.debug("SIP message removed from cache: {}", messageId); } catch (Exception e) { log.warn("Failed to remove SIP message from cache: {}", messageId, e); } } // ==================== 缓存统计 ==================== /** * 获取缓存统计信息 */ public String getCacheStats() { StringBuilder stats = new StringBuilder(); stats.append("Device Cache Stats: ").append(deviceCache.stats()).append("\n"); stats.append("Subscribe Cache Stats: ").append(subscribeCache.stats()).append("\n"); stats.append("Transaction Cache Stats: ").append(transactionCache.stats()).append("\n"); stats.append("SIP Message Cache Stats: ").append(sipMessageCache.stats()).append("\n"); return stats.toString(); } /** * 清空所有缓存 */ public void clearAllCaches() { try { deviceCache.invalidateAll(); subscribeCache.invalidateAll(); transactionCache.invalidateAll(); sipMessageCache.invalidateAll(); log.info("All caches cleared"); } catch (Exception e) { log.error("Failed to clear caches", e); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipPoolConfig.java
sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipPoolConfig.java
package io.github.lunasaw.sip.common.pool; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import lombok.Data; /** * SIP连接池配置 * 定义连接池的各种参数和行为 * * @author luna * @date 2024/01/01 */ @Data @Component @ConfigurationProperties(prefix = "sip.pool") public class SipPoolConfig { /** * 是否启用连接池 */ private boolean enabled = true; /** * 最大连接数 */ private int maxConnections = 100; /** * 核心连接数(预创建的连接数) */ private int coreConnections = 10; /** * 每个地址的最大空闲连接数 */ private int maxIdleConnections = 5; /** * 连接超时时间(毫秒) */ private long connectionTimeoutMillis = 30000L; /** * 连接空闲超时时间(毫秒) */ private long idleTimeoutMillis = 300000L; /** * 连接验证间隔(毫秒) */ private long validationIntervalMillis = 60000L; /** * 是否在借用时验证连接 */ private boolean testOnBorrow = true; /** * 是否在归还时验证连接 */ private boolean testOnReturn = false; /** * 是否在空闲时验证连接 */ private boolean testWhileIdle = true; /** * 清理任务执行间隔(毫秒) */ private long cleanupIntervalMillis = 120000L; /** * 是否启用连接统计 */ private boolean enableStatistics = true; /** * 是否在关闭时强制清理所有连接 */ private boolean forceCleanupOnShutdown = true; /** * 最大等待时间(毫秒) */ private long maxWaitMillis = 10000L; /** * 验证连接有效性时调用的方法参数 */ private String validationQuery = "OPTIONS"; }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipPoolManager.java
sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipPoolManager.java
package io.github.lunasaw.sip.common.pool; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * SIP连接池管理器 * 负责连接池的定期维护、监控和清理工作 * * @author luna * @date 2024/01/01 */ @Slf4j @Component public class SipPoolManager { private final SipConnectionPool connectionPool; private final SipPoolConfig poolConfig; private ScheduledExecutorService scheduledExecutor; @Autowired public SipPoolManager(SipConnectionPool connectionPool, SipPoolConfig poolConfig) { this.connectionPool = connectionPool; this.poolConfig = poolConfig; } @PostConstruct public void initialize() { if (!poolConfig.isEnabled()) { log.info("SIP连接池未启用,跳过管理器初始化"); return; } // 创建定时任务执行器 scheduledExecutor = new ScheduledThreadPoolExecutor(2, r -> { Thread thread = new Thread(r, "sip-pool-manager"); thread.setDaemon(true); return thread; }); // 启动定期清理任务 startCleanupTask(); // 启动状态监控任务 startMonitoringTask(); log.info("SIP连接池管理器初始化完成"); } /** * 启动清理任务 */ private void startCleanupTask() { long interval = poolConfig.getCleanupIntervalMillis(); scheduledExecutor.scheduleWithFixedDelay(() -> { try { log.debug("执行SIP连接池清理任务"); connectionPool.cleanupIdleConnections(); } catch (Exception e) { log.error("SIP连接池清理任务异常", e); } }, interval, interval, TimeUnit.MILLISECONDS); log.info("SIP连接池清理任务已启动,间隔: {}ms", interval); } /** * 启动监控任务 */ private void startMonitoringTask() { if (!poolConfig.isEnableStatistics()) { log.info("SIP连接池统计功能未启用,跳过监控任务"); return; } // 每5分钟输出一次连接池状态 scheduledExecutor.scheduleWithFixedDelay(() -> { try { SipPoolStatus status = connectionPool.getPoolStatus(); if (status.getTotalConnections() > 0) { log.info("SIP连接池状态: {}", status.getSummary()); // 如果利用率过高,输出警告 if (status.getUtilizationRate() > 80) { log.warn("SIP连接池利用率过高: {:.1f}%, 考虑增加最大连接数", status.getUtilizationRate()); } } } catch (Exception e) { log.error("SIP连接池监控任务异常", e); } }, 300000, 300000, TimeUnit.MILLISECONDS); // 5分钟间隔 log.info("SIP连接池监控任务已启动"); } /** * 获取连接池状态 */ public SipPoolStatus getPoolStatus() { return connectionPool.getPoolStatus(); } /** * 获取详细状态报告 */ public String getDetailedStatusReport() { return connectionPool.getPoolStatus().getDetailedReport(); } /** * 手动触发清理任务 */ public void triggerCleanup() { log.info("手动触发SIP连接池清理"); connectionPool.cleanupIdleConnections(); } /** * 释放指定地址的连接池 */ public void releasePool(String address, String transport) { log.info("释放SIP连接池: {}:{}", address, transport); connectionPool.releasePool(address, transport); } /** * 检查连接池健康状态 */ public boolean isHealthy() { try { SipPoolStatus status = connectionPool.getPoolStatus(); // 检查连接数是否超过阈值 if (status.getUtilizationRate() > 95) { log.warn("连接池利用率过高: {:.1f}%", status.getUtilizationRate()); return false; } // 检查是否有异常的连接池 for (SipPoolStatus.PoolEntry entry : status.getPoolEntries()) { entry.calculateUtilization(); if (entry.getPoolUtilization() > 100) { log.warn("发现异常连接池: {}, 利用率: {:.1f}%", entry.getPoolKey(), entry.getPoolUtilization()); return false; } } return true; } catch (Exception e) { log.error("检查连接池健康状态异常", e); return false; } } /** * 获取配置信息 */ public String getConfigInfo() { return String.format("SIP连接池配置 - 启用: %b, 最大连接: %d, 核心连接: %d, 最大空闲: %d, 清理间隔: %dms", poolConfig.isEnabled(), poolConfig.getMaxConnections(), poolConfig.getCoreConnections(), poolConfig.getMaxIdleConnections(), poolConfig.getCleanupIntervalMillis()); } @PreDestroy public void destroy() { if (scheduledExecutor != null && !scheduledExecutor.isShutdown()) { log.info("关闭SIP连接池管理器定时任务..."); scheduledExecutor.shutdown(); try { if (!scheduledExecutor.awaitTermination(10, TimeUnit.SECONDS)) { scheduledExecutor.shutdownNow(); log.warn("强制关闭SIP连接池管理器定时任务"); } } catch (InterruptedException e) { scheduledExecutor.shutdownNow(); Thread.currentThread().interrupt(); } } log.info("SIP连接池管理器已关闭"); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipConnectionPool.java
sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipConnectionPool.java
package io.github.lunasaw.sip.common.pool; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import jakarta.annotation.PreDestroy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import gov.nist.javax.sip.SipProviderImpl; import io.github.lunasaw.sip.common.exception.SipConfigurationException; import io.github.lunasaw.sip.common.exception.SipException; import io.github.lunasaw.sip.common.exception.SipErrorType; import lombok.extern.slf4j.Slf4j; /** * SIP连接池 * 管理SIP连接的创建、复用和释放,提升资源利用效率 * * @author luna * @date 2024/01/01 */ @Slf4j @Component public class SipConnectionPool { private final SipPoolConfig poolConfig; /** * 连接池映射:地址 -> 连接池 */ private final ConcurrentHashMap<String, SipConnectionPoolEntry> connectionPools = new ConcurrentHashMap<>(); /** * 全局连接计数器 */ private final AtomicInteger totalConnections = new AtomicInteger(0); @Autowired public SipConnectionPool(SipPoolConfig poolConfig) { this.poolConfig = poolConfig; log.info("SIP连接池初始化 - 最大连接数: {}, 核心连接数: {}, 连接超时: {}ms", poolConfig.getMaxConnections(), poolConfig.getCoreConnections(), poolConfig.getConnectionTimeoutMillis()); } /** * 获取SIP连接 * * @param address 地址标识 (ip:port) * @param transport 传输协议 (UDP/TCP) * @return SIP提供者 */ public SipProviderImpl getConnection(String address, String transport) { String poolKey = buildPoolKey(address, transport); SipConnectionPoolEntry poolEntry = connectionPools.computeIfAbsent(poolKey, key -> new SipConnectionPoolEntry(address, transport)); return poolEntry.borrowConnection(); } /** * 归还SIP连接 * * @param address 地址标识 * @param transport 传输协议 * @param provider SIP提供者 */ public void returnConnection(String address, String transport, SipProviderImpl provider) { String poolKey = buildPoolKey(address, transport); SipConnectionPoolEntry poolEntry = connectionPools.get(poolKey); if (poolEntry != null) { poolEntry.returnConnection(provider); } else { log.warn("尝试归还连接到不存在的连接池: {}", poolKey); } } /** * 释放指定地址的连接池 * * @param address 地址标识 * @param transport 传输协议 */ public void releasePool(String address, String transport) { String poolKey = buildPoolKey(address, transport); SipConnectionPoolEntry poolEntry = connectionPools.remove(poolKey); if (poolEntry != null) { poolEntry.destroy(); log.info("释放SIP连接池: {}", poolKey); } } /** * 获取连接池状态信息 */ public SipPoolStatus getPoolStatus() { SipPoolStatus status = new SipPoolStatus(); status.setTotalConnections(totalConnections.get()); status.setTotalPools(connectionPools.size()); status.setMaxConnections(poolConfig.getMaxConnections()); connectionPools.forEach((key, pool) -> { SipPoolStatus.PoolEntry entry = new SipPoolStatus.PoolEntry(); entry.setPoolKey(key); entry.setActiveConnections(pool.getActiveConnections()); entry.setIdleConnections(pool.getIdleConnections()); entry.setTotalBorrowed(pool.getTotalBorrowed()); status.addPoolEntry(entry); }); return status; } /** * 清理空闲连接 */ public void cleanupIdleConnections() { log.debug("开始清理空闲SIP连接..."); connectionPools.values().forEach(pool -> { int cleaned = pool.cleanupIdleConnections(); if (cleaned > 0) { log.debug("清理空闲连接: {} 个", cleaned); } }); } /** * 构建连接池键值 */ private String buildPoolKey(String address, String transport) { return String.format("%s:%s", address, transport.toUpperCase()); } @PreDestroy public void destroy() { log.info("开始销毁SIP连接池..."); connectionPools.values().forEach(SipConnectionPoolEntry::destroy); connectionPools.clear(); log.info("SIP连接池销毁完成,总连接数: {}", totalConnections.get()); } /** * 连接池条目,管理单个地址的连接 */ private class SipConnectionPoolEntry { private final String address; private final String transport; private final ConcurrentLinkedQueue<SipProviderImpl> idleConnections = new ConcurrentLinkedQueue<>(); private final AtomicInteger activeConnections = new AtomicInteger(0); private final AtomicInteger totalBorrowed = new AtomicInteger(0); private volatile boolean destroyed = false; public SipConnectionPoolEntry(String address, String transport) { this.address = address; this.transport = transport; } /** * 借用连接 */ public SipProviderImpl borrowConnection() { if (destroyed) { throw new SipException(SipErrorType.RESOURCE_INSUFFICIENT, "POOL_DESTROYED", "连接池已销毁: " + address); } // 检查全局连接数限制 if (totalConnections.get() >= poolConfig.getMaxConnections()) { throw new SipException(SipErrorType.RESOURCE_INSUFFICIENT, "CONNECTION_LIMIT_EXCEEDED", "已达到最大连接数限制: " + poolConfig.getMaxConnections()); } // 尝试从空闲连接中获取 SipProviderImpl provider = idleConnections.poll(); if (provider != null && isConnectionValid(provider)) { activeConnections.incrementAndGet(); totalBorrowed.incrementAndGet(); log.debug("复用SIP连接: {}", address); return provider; } // 创建新连接 provider = createNewConnection(); if (provider != null) { activeConnections.incrementAndGet(); totalConnections.incrementAndGet(); totalBorrowed.incrementAndGet(); log.debug("创建新SIP连接: {}", address); } return provider; } /** * 归还连接 */ public void returnConnection(SipProviderImpl provider) { if (destroyed || provider == null) { return; } if (isConnectionValid(provider) && idleConnections.size() < poolConfig.getMaxIdleConnections()) { idleConnections.offer(provider); log.debug("归还SIP连接到池: {}", address); } else { // 连接池已满或连接无效,直接关闭 closeConnection(provider); totalConnections.decrementAndGet(); log.debug("关闭多余SIP连接: {}", address); } activeConnections.decrementAndGet(); } /** * 创建新连接 */ private SipProviderImpl createNewConnection() { try { // 这里应该根据实际需要创建SIP连接 // 暂时返回null,需要集成到具体的SIP层实现中 log.debug("创建SIP连接: {} 协议: {}", address, transport); return null; // 待实现 } catch (Exception e) { throw new SipConfigurationException(address, "创建SIP连接失败", e); } } /** * 检查连接有效性 */ private boolean isConnectionValid(SipProviderImpl provider) { // 简单的有效性检查,实际应该根据SIP协议特性实现 return provider != null; } /** * 关闭连接 */ private void closeConnection(SipProviderImpl provider) { try { if (provider != null) { // 实际的连接关闭逻辑 log.debug("关闭SIP连接: {}", address); } } catch (Exception e) { log.error("关闭SIP连接异常: {}", address, e); } } /** * 清理空闲连接 */ public int cleanupIdleConnections() { int cleaned = 0; SipProviderImpl provider; while ((provider = idleConnections.poll()) != null) { if (!isConnectionValid(provider)) { closeConnection(provider); totalConnections.decrementAndGet(); cleaned++; } else { // 连接仍然有效,放回队列 idleConnections.offer(provider); break; } } return cleaned; } /** * 销毁连接池 */ public void destroy() { destroyed = true; SipProviderImpl provider; while ((provider = idleConnections.poll()) != null) { closeConnection(provider); totalConnections.decrementAndGet(); } log.debug("销毁SIP连接池: {} 剩余活跃连接: {}", address, activeConnections.get()); } public int getActiveConnections() { return activeConnections.get(); } public int getIdleConnections() { return idleConnections.size(); } public int getTotalBorrowed() { return totalBorrowed.get(); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipPoolStatus.java
sip-common/src/main/java/io/github/lunasaw/sip/common/pool/SipPoolStatus.java
package io.github.lunasaw.sip.common.pool; import java.util.ArrayList; import java.util.List; import lombok.Data; /** * SIP连接池状态信息 * 用于监控和诊断连接池的运行状态 * * @author luna * @date 2024/01/01 */ @Data public class SipPoolStatus { /** * 总连接数 */ private int totalConnections; /** * 总连接池数 */ private int totalPools; /** * 最大允许连接数 */ private int maxConnections; /** * 连接池利用率(百分比) */ private double utilizationRate; /** * 各个连接池的详细信息 */ private List<PoolEntry> poolEntries = new ArrayList<>(); /** * 添加连接池条目 */ public void addPoolEntry(PoolEntry entry) { poolEntries.add(entry); // 计算利用率 if (maxConnections > 0) { utilizationRate = (double)totalConnections / maxConnections * 100; } } /** * 连接池条目信息 */ @Data public static class PoolEntry { /** * 连接池标识 */ private String poolKey; /** * 活跃连接数 */ private int activeConnections; /** * 空闲连接数 */ private int idleConnections; /** * 总借用次数 */ private int totalBorrowed; /** * 连接池利用率 */ private double poolUtilization; /** * 计算连接池利用率 */ public void calculateUtilization() { int total = activeConnections + idleConnections; if (total > 0) { poolUtilization = (double)activeConnections / total * 100; } } } /** * 获取状态摘要 */ public String getSummary() { return String.format("SIP连接池状态 - 总连接: %d/%d (%.1f%%), 连接池数: %d", totalConnections, maxConnections, utilizationRate, totalPools); } /** * 获取详细状态报告 */ public String getDetailedReport() { StringBuilder report = new StringBuilder(); report.append(getSummary()).append("\n"); report.append("详细信息:\n"); for (PoolEntry entry : poolEntries) { entry.calculateUtilization(); report.append(String.format(" 池[%s]: 活跃=%d, 空闲=%d, 借用=%d, 利用率=%.1f%%\n", entry.getPoolKey(), entry.getActiveConnections(), entry.getIdleConnections(), entry.getTotalBorrowed(), entry.getPoolUtilization())); } return report.toString(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipErrorType.java
sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipErrorType.java
package io.github.lunasaw.sip.common.exception; /** * SIP错误类型枚举 * 定义SIP协议处理过程中可能出现的各种错误类型 * * @author luna * @date 2024/01/01 */ public enum SipErrorType { /** * 未知错误 */ UNKNOWN("未知错误"), /** * 协议解析错误 */ PROTOCOL_PARSE("协议解析错误"), /** * 消息格式错误 */ MESSAGE_FORMAT("消息格式错误"), /** * 网络连接错误 */ NETWORK_CONNECTION("网络连接错误"), /** * 认证失败 */ AUTHENTICATION_FAILED("认证失败"), /** * 权限不足 */ PERMISSION_DENIED("权限不足"), /** * 设备不存在 */ DEVICE_NOT_FOUND("设备不存在"), /** * 设备离线 */ DEVICE_OFFLINE("设备离线"), /** * 配置错误 */ CONFIGURATION_ERROR("配置错误"), /** * 超时错误 */ TIMEOUT("超时错误"), /** * 系统内部错误 */ SYSTEM_INTERNAL("系统内部错误"), /** * 资源不足 */ RESOURCE_INSUFFICIENT("资源不足"); private final String description; SipErrorType(String description) { this.description = description; } public String getDescription() { return description; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipConfigurationException.java
sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipConfigurationException.java
package io.github.lunasaw.sip.common.exception; /** * SIP配置异常 * 用于SIP配置相关的异常处理 * * @author luna * @date 2024/01/01 */ public class SipConfigurationException extends SipException { private static final long serialVersionUID = 1L; /** * 配置项名称 */ private final String configKey; public SipConfigurationException(String configKey, String message) { super(SipErrorType.CONFIGURATION_ERROR, "CONFIG_ERROR", message); this.configKey = configKey; } public SipConfigurationException(String configKey, String message, Throwable cause) { super(SipErrorType.CONFIGURATION_ERROR, "CONFIG_ERROR", message, cause); this.configKey = configKey; } public String getConfigKey() { return configKey; } @Override public String toString() { return String.format("SipConfigurationException{configKey='%s', errorType=%s, errorCode='%s', message='%s'}", configKey, getErrorType(), getErrorCode(), getMessage()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipProcessorException.java
sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipProcessorException.java
package io.github.lunasaw.sip.common.exception; /** * SIP处理器异常 * 用于SIP消息处理器执行过程中的异常处理 * * @author luna * @date 2024/01/01 */ public class SipProcessorException extends SipException { private static final long serialVersionUID = 1L; /** * 处理器名称 */ private final String processorName; /** * SIP方法 */ private final String sipMethod; public SipProcessorException(String processorName, String sipMethod, String message) { super(SipErrorType.SYSTEM_INTERNAL, "PROCESSOR_ERROR", message); this.processorName = processorName; this.sipMethod = sipMethod; } public SipProcessorException(String processorName, String sipMethod, String message, Throwable cause) { super(SipErrorType.SYSTEM_INTERNAL, "PROCESSOR_ERROR", message, cause); this.processorName = processorName; this.sipMethod = sipMethod; } public String getProcessorName() { return processorName; } public String getSipMethod() { return sipMethod; } @Override public String toString() { return String.format("SipProcessorException{processorName='%s', sipMethod='%s', errorType=%s, errorCode='%s', message='%s'}", processorName, sipMethod, getErrorType(), getErrorCode(), getMessage()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipException.java
sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipException.java
package io.github.lunasaw.sip.common.exception; /** * SIP异常基类 * 提供统一的SIP协议相关异常处理 * * @author luna * @date 2024/01/01 */ public class SipException extends RuntimeException { private static final long serialVersionUID = 1L; /** * 错误代码 */ private final String errorCode; /** * 错误类型 */ private final SipErrorType errorType; public SipException(String message) { this(SipErrorType.UNKNOWN, "SIP_ERROR", message); } public SipException(String message, Throwable cause) { this(SipErrorType.UNKNOWN, "SIP_ERROR", message, cause); } public SipException(SipErrorType errorType, String errorCode, String message) { super(message); this.errorType = errorType; this.errorCode = errorCode; } public SipException(SipErrorType errorType, String errorCode, String message, Throwable cause) { super(message, cause); this.errorType = errorType; this.errorCode = errorCode; } public String getErrorCode() { return errorCode; } public SipErrorType getErrorType() { return errorType; } @Override public String toString() { return String.format("SipException{errorType=%s, errorCode='%s', message='%s'}", errorType, errorCode, getMessage()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipExceptionHandler.java
sip-common/src/main/java/io/github/lunasaw/sip/common/exception/SipExceptionHandler.java
package io.github.lunasaw.sip.common.exception; import javax.sip.RequestEvent; import javax.sip.message.Response; import org.springframework.stereotype.Component; import io.github.lunasaw.sip.common.transmit.ResponseCmd; import lombok.extern.slf4j.Slf4j; /** * SIP异常处理器 * 提供统一的异常处理和错误响应生成 * * @author luna * @date 2024/01/01 */ @Slf4j @Component public class SipExceptionHandler { /** * 处理SIP异常并生成相应的响应 * * @param exception 异常信息 * @param requestEvent 原始请求事件,如果为null则只记录日志 */ public void handleException(SipException exception, RequestEvent requestEvent) { // 记录详细的异常信息 log.error("SIP异常处理 - 错误类型: {}, 错误代码: {}, 异常信息: {}", exception.getErrorType().getDescription(), exception.getErrorCode(), exception.getMessage(), exception); // 如果有请求事件,生成相应的错误响应 if (requestEvent != null) { int statusCode = mapToSipStatusCode(exception.getErrorType()); String reasonPhrase = exception.getErrorType().getDescription(); try { ResponseCmd.doResponseCmd(statusCode, reasonPhrase, requestEvent); log.info("已发送SIP错误响应: {} {}", statusCode, reasonPhrase); } catch (Exception e) { log.error("发送SIP错误响应失败", e); } } } /** * 处理一般异常 * * @param exception 异常信息 * @param requestEvent 原始请求事件 * @param context 上下文信息 */ public void handleException(Exception exception, RequestEvent requestEvent, String context) { log.error("SIP处理异常 - 上下文: {}, 异常信息: {}", context, exception.getMessage(), exception); if (requestEvent != null) { try { ResponseCmd.doResponseCmd(Response.SERVER_INTERNAL_ERROR, "内部服务器错误", requestEvent); log.info("已发送SIP错误响应: {} 内部服务器错误", Response.SERVER_INTERNAL_ERROR); } catch (Exception e) { log.error("发送SIP错误响应失败", e); } } } /** * 将SIP错误类型映射到SIP状态码 * * @param errorType 错误类型 * @return SIP状态码 */ private int mapToSipStatusCode(SipErrorType errorType) { switch (errorType) { case AUTHENTICATION_FAILED: return Response.UNAUTHORIZED; case PERMISSION_DENIED: return Response.FORBIDDEN; case DEVICE_NOT_FOUND: return Response.NOT_FOUND; case MESSAGE_FORMAT: case PROTOCOL_PARSE: return Response.BAD_REQUEST; case TIMEOUT: return Response.REQUEST_TIMEOUT; case RESOURCE_INSUFFICIENT: return Response.SERVICE_UNAVAILABLE; case DEVICE_OFFLINE: return Response.TEMPORARILY_UNAVAILABLE; case CONFIGURATION_ERROR: case SYSTEM_INTERNAL: case UNKNOWN: default: return Response.SERVER_INTERNAL_ERROR; } } /** * 创建SIP处理器异常 * * @param processorName 处理器名称 * @param sipMethod SIP方法 * @param message 异常消息 * @return SIP处理器异常 */ public static SipProcessorException createProcessorException(String processorName, String sipMethod, String message) { return new SipProcessorException(processorName, sipMethod, message); } /** * 创建SIP处理器异常 * * @param processorName 处理器名称 * @param sipMethod SIP方法 * @param message 异常消息 * @param cause 原因异常 * @return SIP处理器异常 */ public static SipProcessorException createProcessorException(String processorName, String sipMethod, String message, Throwable cause) { return new SipProcessorException(processorName, sipMethod, message, cause); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/metrics/SipMetrics.java
sip-common/src/main/java/io/github/lunasaw/sip/common/metrics/SipMetrics.java
package io.github.lunasaw.sip.common.metrics; import io.micrometer.core.instrument.*; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.ConcurrentHashMap; import java.util.Map; /** * SIP性能监控指标 - 使用Micrometer收集性能数据 * * @author luna * @date 2024/1/6 */ @Slf4j @Component public class SipMetrics { private final MeterRegistry meterRegistry; private final Counter messageProcessedCounter; private final Timer messageProcessingTimer; private final Gauge activeDevicesGauge; private final Counter errorCounter; private final Timer requestTimer; private final Timer responseTimer; private final Timer timeoutTimer; private final Gauge queueSizeGauge; // 标记是否启用监控 private final boolean metricsEnabled; // 实时统计数据 private final AtomicInteger activeDeviceCount = new AtomicInteger(0); private final AtomicInteger currentQueueSize = new AtomicInteger(0); private final Map<String, AtomicInteger> methodCounters = new ConcurrentHashMap<>(); public SipMetrics(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; this.metricsEnabled = meterRegistry != null; if (metricsEnabled) { // 消息处理计数器 this.messageProcessedCounter = Counter.builder("sip.messages.processed") .description("Total processed SIP messages") .register(meterRegistry); // 消息处理时间 this.messageProcessingTimer = Timer.builder("sip.message.processing.time") .description("SIP message processing time") .register(meterRegistry); // 活跃设备数量 this.activeDevicesGauge = Gauge.builder("sip.devices.active", this, SipMetrics::getActiveDeviceCount) .description("Number of active devices") .register(meterRegistry); // 错误计数器 this.errorCounter = Counter.builder("sip.errors") .description("Total SIP processing errors") .register(meterRegistry); // 请求处理时间 this.requestTimer = Timer.builder("sip.request.processing.time") .description("SIP request processing time") .register(meterRegistry); // 响应处理时间 this.responseTimer = Timer.builder("sip.response.processing.time") .description("SIP response processing time") .register(meterRegistry); // 超时处理时间 this.timeoutTimer = Timer.builder("sip.timeout.processing.time") .description("SIP timeout processing time") .register(meterRegistry); // 队列大小 this.queueSizeGauge = Gauge.builder("sip.queue.size", this, SipMetrics::getCurrentQueueSize) .description("Current message queue size") .register(meterRegistry); log.info("SIP metrics initialized with MeterRegistry"); } else { // 创建空的指标对象,避免NPE this.messageProcessedCounter = null; this.messageProcessingTimer = null; this.activeDevicesGauge = null; this.errorCounter = null; this.requestTimer = null; this.responseTimer = null; this.timeoutTimer = null; this.queueSizeGauge = null; log.warn("SIP metrics initialized without MeterRegistry - metrics will be disabled"); } } /** * 记录消息处理完成 */ public void recordMessageProcessed() { if (metricsEnabled && messageProcessedCounter != null) { messageProcessedCounter.increment(); } } /** * 记录消息处理完成(带标签) */ public void recordMessageProcessed(String method, String status) { if (metricsEnabled && meterRegistry != null) { Counter.builder("sip.messages.processed") .tag("method", method) .tag("status", status) .register(meterRegistry) .increment(); } } /** * 开始计时 */ public Timer.Sample startTimer() { return Timer.start(); } /** * 记录消息处理时间 */ public void recordProcessingTime(Timer.Sample sample) { if (metricsEnabled && messageProcessingTimer != null && sample != null) { sample.stop(messageProcessingTimer); } } /** * 记录请求处理时间 */ public void recordRequestProcessingTime(Timer.Sample sample) { if (metricsEnabled && requestTimer != null && sample != null) { sample.stop(requestTimer); } } /** * 记录响应处理时间 */ public void recordResponseProcessingTime(Timer.Sample sample) { if (metricsEnabled && responseTimer != null && sample != null) { sample.stop(responseTimer); } } /** * 记录超时处理时间 */ public void recordTimeoutProcessingTime(Timer.Sample sample) { if (metricsEnabled && timeoutTimer != null && sample != null) { sample.stop(timeoutTimer); } } /** * 记录错误 */ public void recordError() { if (metricsEnabled && errorCounter != null) { errorCounter.increment(); } } /** * 记录错误(带标签) */ public void recordError(String errorType, String method) { if (metricsEnabled && meterRegistry != null) { Counter.builder("sip.errors") .tag("error_type", errorType) .tag("method", method) .register(meterRegistry) .increment(); } } /** * 增加活跃设备数 */ public void incrementActiveDevices() { activeDeviceCount.incrementAndGet(); } /** * 减少活跃设备数 */ public void decrementActiveDevices() { activeDeviceCount.decrementAndGet(); } /** * 设置活跃设备数 */ public void setActiveDeviceCount(int count) { activeDeviceCount.set(count); } /** * 获取活跃设备数 */ public int getActiveDeviceCount() { return activeDeviceCount.get(); } /** * 更新队列大小 */ public void updateQueueSize(int size) { currentQueueSize.set(size); } /** * 获取当前队列大小 */ public int getCurrentQueueSize() { return currentQueueSize.get(); } /** * 记录特定方法的调用次数 */ public void recordMethodCall(String method) { if (metricsEnabled && meterRegistry != null) { methodCounters.computeIfAbsent(method, k -> { AtomicInteger counter = new AtomicInteger(0); Gauge.builder("sip.method.calls", counter, AtomicInteger::get) .tag("method", method) .description("Number of calls for SIP method: " + method) .register(meterRegistry); return counter; }).incrementAndGet(); } } /** * 记录消息大小 */ public void recordMessageSize(long size) { if (metricsEnabled && meterRegistry != null) { DistributionSummary.builder("sip.message.size") .description("SIP message size in bytes") .register(meterRegistry) .record(size); } } /** * 记录网络延迟 */ public void recordNetworkLatency(long latencyMs) { if (metricsEnabled && meterRegistry != null) { Timer.builder("sip.network.latency") .description("Network latency for SIP messages") .register(meterRegistry) .record(latencyMs, java.util.concurrent.TimeUnit.MILLISECONDS); } } /** * 创建一个自定义计时器 */ public Timer createCustomTimer(String name, String description) { if (metricsEnabled && meterRegistry != null) { return Timer.builder(name) .description(description) .register(meterRegistry); } return null; } /** * 创建一个自定义计数器 */ public Counter createCustomCounter(String name, String description) { if (metricsEnabled && meterRegistry != null) { return Counter.builder(name) .description(description) .register(meterRegistry); } return null; } /** * 获取所有监控指标的摘要 */ public String getMetricsSummary() { StringBuilder summary = new StringBuilder(); summary.append("=== SIP Metrics Summary ===\n"); summary.append("Active Devices: ").append(getActiveDeviceCount()).append("\n"); summary.append("Messages Processed: ").append(messageProcessedCounter.count()).append("\n"); summary.append("Errors: ").append(errorCounter.count()).append("\n"); summary.append("Current Queue Size: ").append(getCurrentQueueSize()).append("\n"); summary.append("Average Processing Time: ").append(messageProcessingTimer.mean(java.util.concurrent.TimeUnit.MILLISECONDS)).append("ms\n"); summary.append("Average Request Time: ").append(requestTimer.mean(java.util.concurrent.TimeUnit.MILLISECONDS)).append("ms\n"); summary.append("Average Response Time: ").append(responseTimer.mean(java.util.concurrent.TimeUnit.MILLISECONDS)).append("ms\n"); if (!methodCounters.isEmpty()) { summary.append("Method Call Counts:\n"); methodCounters.forEach((method, counter) -> summary.append(" ").append(method).append(": ").append(counter.get()).append("\n")); } return summary.toString(); } /** * 重置所有计数器(用于测试) */ public void resetCounters() { activeDeviceCount.set(0); currentQueueSize.set(0); methodCounters.clear(); log.info("SIP metrics counters reset"); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/subscribe/SubscribeTask.java
sip-common/src/main/java/io/github/lunasaw/sip/common/subscribe/SubscribeTask.java
package io.github.lunasaw.sip.common.subscribe; /** * @author lin */ public interface SubscribeTask extends Runnable { void stop(); }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/subscribe/SubscribeInfo.java
sip-common/src/main/java/io/github/lunasaw/sip/common/subscribe/SubscribeInfo.java
package io.github.lunasaw.sip.common.subscribe; import javax.sip.header.EventHeader; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPResponse; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author luna */ @Data @NoArgsConstructor @AllArgsConstructor public class SubscribeInfo { private String id; private int expires; private String eventId; private String eventType; /** * 上一次的请求 */ private SIPRequest request; private SIPResponse response; /** * 以下为可选字段 */ private String sn; private int gpsInterval; private String subscriptionState; public SubscribeInfo(SIPRequest request, String id) { this.id = id; this.request = request; this.expires = request.getExpires().getExpires(); EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME); this.eventId = eventHeader.getEventId(); this.eventType = eventHeader.getEventType(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/subscribe/SubscribeHolder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/subscribe/SubscribeHolder.java
package io.github.lunasaw.sip.common.subscribe; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.collections4.MapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import io.github.lunasaw.sip.common.utils.DynamicTask; /** * @author lin */ @Component public class SubscribeHolder { private static ConcurrentHashMap<String, SubscribeInfo> catalogMap = new ConcurrentHashMap<>(); private static ConcurrentHashMap<String, SubscribeInfo> mobilePositionMap = new ConcurrentHashMap<>(); private final String taskOverduePrefix = "subscribe_overdue_"; @Autowired private DynamicTask dynamicTask; public void putCatalogSubscribe(String userId, SubscribeInfo subscribeInfo) { catalogMap.put(userId, subscribeInfo); // 添加订阅到期 String taskOverdueKey = taskOverduePrefix + "catalog_" + userId; // 添加任务处理订阅过期 dynamicTask.startDelay(taskOverdueKey, () -> removeCatalogSubscribe(subscribeInfo.getId()), subscribeInfo.getExpires() * 1000); } public SubscribeInfo getCatalogSubscribe(String platformId) { return catalogMap.get(platformId); } public void removeCatalogSubscribe(String sipId) { catalogMap.remove(sipId); String taskOverdueKey = taskOverduePrefix + "catalog_" + sipId; Runnable runnable = dynamicTask.get(taskOverdueKey); if (runnable instanceof SubscribeTask) { SubscribeTask subscribeTask = (SubscribeTask) runnable; subscribeTask.stop(); } // 添加任务处理订阅过期 dynamicTask.stop(taskOverdueKey); } public void putMobilePositionSubscribe(String userId, String prefixKey, SubscribeTask task, SubscribeInfo subscribeInfo) { mobilePositionMap.put(userId, subscribeInfo); String key = prefixKey + userId; // 添加任务处理GPS定时推送 dynamicTask.startCron(key, task, subscribeInfo.getGpsInterval() * 1000L); String taskOverdueKey = taskOverduePrefix + prefixKey + userId; // 添加任务处理订阅过期 dynamicTask.startDelay(taskOverdueKey, () -> { removeMobilePositionSubscribe(subscribeInfo.getId(), prefixKey); }, subscribeInfo.getExpires() * 1000); } public SubscribeInfo getMobilePositionSubscribe(String userId) { return mobilePositionMap.get(userId); } public void removeMobilePositionSubscribe(String userId, String prefixKey) { mobilePositionMap.remove(userId); String key = prefixKey + "MobilePosition_" + userId; // 结束任务处理GPS定时推送 dynamicTask.stop(key); String taskOverdueKey = taskOverduePrefix + "MobilePosition_" + userId; Runnable runnable = dynamicTask.get(taskOverdueKey); if (runnable instanceof SubscribeTask) { SubscribeTask subscribeTask = (SubscribeTask) runnable; subscribeTask.stop(); } // 添加任务处理订阅过期 dynamicTask.stop(taskOverdueKey); } public List<String> getAllCatalogSubscribePlatform() { List<String> platforms = new ArrayList<>(); if (MapUtils.isNotEmpty(catalogMap)) { for (String key : catalogMap.keySet()) { platforms.add(catalogMap.get(key).getId()); } } return platforms; } public void removeAllSubscribe(String userId, String prefixKey) { removeMobilePositionSubscribe(userId, prefixKey); removeCatalogSubscribe(userId); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/utils/TraceUtils.java
sip-common/src/main/java/io/github/lunasaw/sip/common/utils/TraceUtils.java
package io.github.lunasaw.sip.common.utils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.slf4j.MDC; import java.util.Objects; import java.util.Optional; import java.util.UUID; /** * Trace跟踪工具类 * 提供traceId的ThreadLocal管理和MDC集成功能 * * @author luna */ @Slf4j public class TraceUtils { /** * TraceId的MDC键名 */ public static final String TRACE_ID_KEY = "traceId"; /** * TraceId的ThreadLocal存储 */ private static final ThreadLocal<String> TRACE_ID_THREAD_LOCAL = new ThreadLocal<>(); /** * 获取trace并启动跟踪 * 生成新的traceId,启动跟踪,并返回当前traceId * * @return 当前traceId,如果不存在则返回空字符串 */ public static String getTrace() { String traceId = generateTraceId(); genTrace(traceId); return Optional.ofNullable(getCurrentTraceId()).orElse(""); } /** * 根据traceId启动跟踪 * 如果传入的traceId为空,则使用当前traceId或生成新的traceId * * @param traceId 跟踪ID */ public static void genTrace(String traceId) { if (StringUtils.isNotBlank(traceId)) { if (Objects.equals(getCurrentTraceId(), traceId)) { // 当前有相同的traceId,直接返回 log.debug("当前已存在相同的traceId: {}", traceId); return; } else { // 启动新的跟踪 startTrace(traceId, "SIP", "Scheduled"); } } else { // traceId为空,使用当前traceId或生成新的 String genTraceId = Optional.ofNullable(getCurrentTraceId()).orElse(generateTraceId()); startTrace(genTraceId, "SIP", "Scheduled"); } // 设置MDC MDC.put(TRACE_ID_KEY, Optional.ofNullable(traceId).orElse(getCurrentTraceId())); } /** * 启动跟踪 * * @param traceId 跟踪ID * @param traceType 跟踪类型 * @param source 来源 */ private static void startTrace(String traceId, String traceType, String source) { setTraceId(traceId); log.debug("启动跟踪 - traceId: {}, type: {}, source: {}", traceId, traceType, source); } /** * 设置traceId到ThreadLocal和MDC中 * * @param traceId 跟踪ID */ public static void setTraceId(String traceId) { if (traceId == null || traceId.trim().isEmpty()) { log.warn("尝试设置空的traceId,已忽略"); return; } TRACE_ID_THREAD_LOCAL.set(traceId); MDC.put(TRACE_ID_KEY, traceId); log.debug("设置traceId: {}", traceId); } /** * 获取当前线程的traceId * 如果不存在则自动生成一个新的traceId并设置到MDC中 * * @return 当前traceId */ public static String getTraceId() { String traceId = TRACE_ID_THREAD_LOCAL.get(); if (traceId == null || traceId.trim().isEmpty()) { traceId = generateTraceId(); setTraceId(traceId); log.debug("自动生成并设置traceId: {}", traceId); } return traceId; } /** * 获取当前线程的traceId(不自动生成) * * @return 当前traceId,如果不存在则返回null */ public static String getCurrentTraceId() { return TRACE_ID_THREAD_LOCAL.get(); } /** * 清除当前线程的traceId */ public static void clearTraceId() { String traceId = TRACE_ID_THREAD_LOCAL.get(); TRACE_ID_THREAD_LOCAL.remove(); MDC.remove(TRACE_ID_KEY); log.debug("清除traceId: {}", traceId); } /** * 生成新的traceId * * @return 生成的traceId */ public static String generateTraceId() { return UUID.randomUUID().toString().replace("-", "").substring(0, 16); } /** * 检查当前线程是否有traceId * * @return 如果存在traceId则返回true,否则返回false */ public static boolean hasTraceId() { String traceId = TRACE_ID_THREAD_LOCAL.get(); return traceId != null && !traceId.trim().isEmpty(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/utils/SipRequestUtils.java
sip-common/src/main/java/io/github/lunasaw/sip/common/utils/SipRequestUtils.java
package io.github.lunasaw.sip.common.utils; import java.text.ParseException; import java.util.List; import java.util.UUID; import javax.sdp.SdpFactory; import javax.sdp.SdpParseException; import javax.sdp.SessionDescription; import javax.sip.InvalidArgumentException; import javax.sip.PeerUnavailableException; import javax.sip.SipFactory; import javax.sip.address.Address; import javax.sip.address.AddressFactory; import javax.sip.address.SipURI; import javax.sip.address.URI; import javax.sip.header.*; import javax.sip.message.MessageFactory; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.util.ObjectUtils; import com.google.common.collect.Lists; import com.luna.common.text.RandomStrUtil; import gov.nist.javax.sip.SipProviderImpl; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.layer.SipLayer; import lombok.SneakyThrows; /** * @author luna * @date 2023/10/13 */ public class SipRequestUtils { private static final MessageFactory MESSAGE_FACTORY; private static final HeaderFactory HEADER_FACTORY; private static final AddressFactory ADDRESS_FACTORY; private static final SdpFactory SDP_FACTORY; static { try { MESSAGE_FACTORY = SipFactory.getInstance().createMessageFactory(); HEADER_FACTORY = SipFactory.getInstance().createHeaderFactory(); ADDRESS_FACTORY = SipFactory.getInstance().createAddressFactory(); SDP_FACTORY = SdpFactory.getInstance(); } catch (PeerUnavailableException e) { throw new RuntimeException(e); } } /** * * @param requestUri requestURI – 此消息的请求 URI 值的新 URI 对象。 * @param method method – 此消息的方法值的新字符串。 * @param callId callId – 此消息的 callId 值的新 CallIdHeader 对象。 * @param cSeq cSeq – 此消息的 cSeq 值的新 CSeqHeader 对象。 * @param from from – 此消息的 from 值的新 FromHeader 对象。 * @param to to – 此消息的 to 值的新 ToHeader 对象。 * @param via via – 此消息的 ViaHeader 的新列表对象。 * @param maxForwards contentType – 此消息的内容类型值的新内容类型标头对象。 * @param contentType 响应类型 – 此消息的正文内容值的新对象。 * @param content 内容 */ public static Request createRequest(URI requestUri, String method, CallIdHeader callId, CSeqHeader cSeq, FromHeader from, ToHeader to, List<ViaHeader> via, MaxForwardsHeader maxForwards, ContentTypeHeader contentType, Object content) { try { if (contentType == null) { return MESSAGE_FACTORY.createRequest(requestUri, method, callId, cSeq, from, to, via, maxForwards); } return MESSAGE_FACTORY.createRequest(requestUri, method, callId, cSeq, from, to, via, maxForwards, contentType, content); } catch (ParseException e) { throw new RuntimeException(e); } } public static void setRequestHeader(Request request, List<Header> headers) { if (CollectionUtils.isEmpty(headers)) { return; } for (Header header : headers) { request.addHeader(header); } } /** * * host – 主机的新字符串值。 * port – 端口的新整数值。 * transport – tcp / udp。 * branch – 代理服务器的新字符串值。 * * @return ViaHeader */ public static ViaHeader createViaHeader(String ip, int port, String transport, String branch) { try { return HEADER_FACTORY.createViaHeader(ip, port, transport, branch); } catch (Exception e) { throw new RuntimeException(e); } } public static List<ViaHeader> createViaHeader(ViaHeader... viaHeaders) { return Lists.newArrayList(viaHeaders); } /** * * 70 maxForwards – 最大转发的新整数值。 */ public static MaxForwardsHeader createMaxForwardsHeader() { try { return HEADER_FACTORY.createMaxForwardsHeader(70); } catch (InvalidArgumentException e) { throw new RuntimeException(e); } } /** * * @param maxForwards maxForwards – 最大转发的新整数值。 */ public static MaxForwardsHeader createMaxForwardsHeader(int maxForwards) { try { return HEADER_FACTORY.createMaxForwardsHeader(maxForwards); } catch (InvalidArgumentException e) { throw new RuntimeException(e); } } public static CallIdHeader createCallIdHeader(String callId) { try { if (callId == null) { return getNewCallIdHeader(); } return HEADER_FACTORY.createCallIdHeader(callId); } catch (ParseException e) { throw new RuntimeException(e); } } public static String getNewCallId() { return getNewCallIdHeader(null, null).getCallId(); } public static CallIdHeader getNewCallIdHeader() { return getNewCallIdHeader(null, null); } public static CallIdHeader getNewCallIdHeader(String ip, String transport) { if (ObjectUtils.isEmpty(transport)) { return SipLayer.getUdpSipProvider().getNewCallId(); } SipProviderImpl sipProvider; if (ObjectUtils.isEmpty(ip)) { sipProvider = transport.equalsIgnoreCase(Constant.TCP) ? SipLayer.getTcpSipProvider() : SipLayer.getUdpSipProvider(); } else { sipProvider = transport.equalsIgnoreCase(Constant.TCP) ? SipLayer.getTcpSipProvider(ip) : SipLayer.getUdpSipProvider(ip); } if (sipProvider == null) { sipProvider = SipLayer.getUdpSipProvider(); } return sipProvider.getNewCallId(); } /** * * @param user sip用户 * @param host 主机地址 ip:port * @return SipURI */ public static SipURI createSipUri(String user, String host) { try { return ADDRESS_FACTORY.createSipURI(user, host); } catch (ParseException e) { throw new RuntimeException(e); } } public static Address createAddress(String user, String host) { SipURI sipUri = createSipUri(user, host); return createAddress(sipUri); } public static Address createAddress(SipURI sipUri) { return ADDRESS_FACTORY.createAddress(sipUri); } /** * * @param user sip用户 * @param host 主机地址 ip:port * @param tag 标签 * @return FromHeader */ public static FromHeader createFromHeader(String user, String host, String tag) { Address address = createAddress(user, host); return createFromHeader(address, tag); } /** * * @param user sip用户 * @param host 主机地址 ip:port * @param tag 标签 * @return FromHeader */ public static ToHeader createToHeader(String user, String host, String tag) { Address address = createAddress(user, host); return createToHeader(address, tag); } /** * 根据新提供的地址和标记值创建新的 FromHeader。 * * @param address – 地址的新地址对象。 * @param tag – 标签的新字符串值。 * @return FromHeader */ public static FromHeader createFromHeader(Address address, String tag) { try { return HEADER_FACTORY.createFromHeader(address, tag); } catch (ParseException e) { throw new RuntimeException(e); } } /** * 根据新提供的地址和标记值创建新的 ToHeader。 * * @param address – 地址的新地址对象。 * @param tag – 标签的新字符串值,此值可能为空。 * @return ToHeader */ public static ToHeader createToHeader(Address address, String tag) { try { return HEADER_FACTORY.createToHeader(address, tag); } catch (ParseException e) { throw new RuntimeException(e); } } /** * 基于新提供的序列号和方法值创建新的 CSeqHeader。 * * @param sequenceNumber – 序列号的新长整型值。 * @param method – 方法的新字符串值。 */ public static CSeqHeader createCSeqHeader(long sequenceNumber, String method) { try { return HEADER_FACTORY.createCSeqHeader(sequenceNumber, method); } catch (Exception e) { throw new RuntimeException(e); } } /** * 基于新提供的内容类型和内容子类型值创建新的内容类型标头。 * * @param contentType contentType – 新的字符串内容类型值。 * @param contentSubType contentSubType – 新的字符串内容子类型值。 * @return ContentTypeHeader */ public static ContentTypeHeader createContentTypeHeader(String contentType, String contentSubType) { try { return HEADER_FACTORY.createContentTypeHeader(contentType, contentSubType); } catch (ParseException e) { throw new RuntimeException(e); } } public static UserAgentHeader createUserAgentHeader() { try { return createUserAgentHeader("gbproxy"); } catch (Exception e) { throw new RuntimeException(e); } } public static UserAgentHeader createUserAgentHeader(String... agent) { List<String> agents = Lists.newArrayList(agent); try { return HEADER_FACTORY.createUserAgentHeader(agents); } catch (ParseException e) { throw new RuntimeException(e); } } public static String getNewFromTag() { return UUID.randomUUID().toString().replace("-", ""); } public static String getNewViaTag() { return "lunaProxy" + RandomStringUtils.randomNumeric(10); } /** * 联系人标头 * * @param user 用户设备编号 * @param host 主机地址 ip:port * @return ContactHeader */ public static ContactHeader createContactHeader(String user, String host) { Address address = createAddress(user, host); return HEADER_FACTORY.createContactHeader(address); } public static SubjectHeader createSubjectHeader(String subject) { try { return HEADER_FACTORY.createSubjectHeader(subject); } catch (ParseException e) { throw new RuntimeException(e); } } public static ExpiresHeader createExpiresHeader(int expires) { try { return HEADER_FACTORY.createExpiresHeader(expires); } catch (InvalidArgumentException e) { throw new RuntimeException(e); } } public static EventHeader createEventHeader(String eventType, String eventId) { try { EventHeader eventHeader = HEADER_FACTORY.createEventHeader(eventType); eventHeader.setEventId(eventId); return eventHeader; } catch (ParseException e) { throw new RuntimeException(e); } } public static EventHeader createEventHeader(String eventType) { return createEventHeader(eventType, RandomStrUtil.getValidationCode()); } public static SubscriptionStateHeader createSubscriptionStateHeader(String subscriptionState) { try { SubscriptionStateHeader subscriptionStateHeader = HEADER_FACTORY.createSubscriptionStateHeader(subscriptionState); return subscriptionStateHeader; } catch (ParseException e) { throw new RuntimeException(e); } } /** * 基于新提供的方案值创建新的授权标头。 * * @param scheme 方案的新字符串值。 * @return AuthorizationHeader */ public static AuthorizationHeader createAuthorizationHeader(String scheme) { try { return HEADER_FACTORY.createAuthorizationHeader(scheme); } catch (ParseException e) { throw new RuntimeException(e); } } public static AuthorizationHeader createAuthorizationHeader(String scheme, String user, URI requestUri, String realm, String nonce, String qop, String cNonce, String response) { AuthorizationHeader authorizationHeader = createAuthorizationHeader(scheme); try { authorizationHeader.setUsername(user); authorizationHeader.setRealm(realm); authorizationHeader.setNonce(nonce); authorizationHeader.setURI(requestUri); authorizationHeader.setResponse(response); authorizationHeader.setAlgorithm("MD5"); if (qop != null) { authorizationHeader.setQop(qop); authorizationHeader.setCNonce(cNonce); authorizationHeader.setNonceCount(1); } return authorizationHeader; } catch (ParseException e) { throw new RuntimeException(e); } } public static Header createHeader(String name, String value) { try { return HEADER_FACTORY.createHeader(name, value); } catch (ParseException e) { throw new RuntimeException(e); } } // === 以下是ResponseHeader === /** * 创建响应 * * @param statusCode 状态码 * @param request 回复的请求 * @return */ public static Response createResponse(int statusCode, Request request) { try { return MESSAGE_FACTORY.createResponse(statusCode, request); } catch (ParseException e) { throw new RuntimeException(e); } } /** * @param statusCode statusCode – 状态码 {@link Response} * @param callId callId – 此消息的 callId 值的新 CallIdHeader 对象。 * @param cSeq cSeq – 此消息的 cSeq 值的新 CSeqHeader 对象。 * @param from from – 此消息的 from 值的新 FromHeader 对象。 * @param to to – 此消息的 to 值的新 ToHeader 对象。 * @param via via – 此消息的 ViaHeader 的新列表对象。 * @param maxForwards contentType – 此消息的内容类型值的新内容类型标头对象。 * @param contentType 响应类型 – 此消息的正文内容值的新对象。 * @param content 内容 */ public static Response createResponse(int statusCode, CallIdHeader callId, CSeqHeader cSeq, FromHeader from, ToHeader to, List<ViaHeader> via, MaxForwardsHeader maxForwards, ContentTypeHeader contentType, Object content) { try { if (contentType == null) { return MESSAGE_FACTORY.createResponse(statusCode, callId, cSeq, from, to, via, maxForwards); } return MESSAGE_FACTORY.createResponse(statusCode, callId, cSeq, from, to, via, maxForwards, contentType, content); } catch (ParseException e) { throw new RuntimeException(e); } } public static Response createResponse(int statusCode, Request request, List<Header> headers) { try { Response response = MESSAGE_FACTORY.createResponse(statusCode, request); setResponseHeader(response, headers); return response; } catch (ParseException e) { throw new RuntimeException(e); } } public static void setResponseHeader(Response response, List<Header> headers) { if (CollectionUtils.isEmpty(headers)) { return; } for (Header header : headers) { response.addHeader(header); } } public static WWWAuthenticateHeader createWWWAuthenticateHeader(String scheme) { try { return HEADER_FACTORY.createWWWAuthenticateHeader(scheme); } catch (Exception e) { throw new RuntimeException(e); } } public static WWWAuthenticateHeader createWWWAuthenticateHeader(String scheme, String realm, String nonce, String algorithm) { try { WWWAuthenticateHeader wwwAuthenticateHeader = createWWWAuthenticateHeader(scheme); wwwAuthenticateHeader.setParameter("realm", realm); wwwAuthenticateHeader.setParameter("qop", "auth"); wwwAuthenticateHeader.setParameter("nonce", nonce); wwwAuthenticateHeader.setParameter("algorithm", algorithm); return wwwAuthenticateHeader; } catch (Exception e) { throw new RuntimeException(e); } } @SneakyThrows public static void setContent(Request request, ContentTypeHeader contentType, Object content) { request.setContent(content, contentType); } public static SessionDescription createSessionDescription(String sdp) { try { return SDP_FACTORY.createSessionDescription(sdp); } catch (SdpParseException e) { throw new RuntimeException(e); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/utils/SipUtils.java
sip-common/src/main/java/io/github/lunasaw/sip/common/utils/SipUtils.java
package io.github.lunasaw.sip.common.utils; import java.net.InetAddress; import java.nio.charset.Charset; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Optional; import java.util.OptionalInt; import javax.sdp.SessionDescription; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.header.FromHeader; import javax.sip.header.HeaderAddress; import javax.sip.header.SubjectHeader; import javax.sip.header.ToHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.util.ObjectUtils; import com.luna.common.text.StringTools; import gov.nist.javax.sip.address.AddressImpl; import gov.nist.javax.sip.address.SipUri; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPResponse; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.entity.GbSessionDescription; import io.github.lunasaw.sip.common.entity.RemoteAddressInfo; import io.github.lunasaw.sip.common.entity.SdpSessionDescription; import io.github.lunasaw.sip.common.entity.SipTransaction; /** * @author luna */ public class SipUtils { // NTP时间戳偏移量 (1900年1月1日到1970年1月1日的秒数) private static final long NTP_TIMESTAMP_OFFSET = 2208988800L; public static String getUserIdFromToHeader(Response response) { ToHeader toHeader = (ToHeader)response.getHeader(ToHeader.NAME); return getUserIdFromHeader(toHeader); } public static String getUserIdFromFromHeader(Response response) { FromHeader fromHeader = (FromHeader)response.getHeader(FromHeader.NAME); return getUserIdFromHeader(fromHeader); } public static String getUserIdFromToHeader(Request request) { ToHeader toHeader = (ToHeader)request.getHeader(ToHeader.NAME); return getUserIdFromHeader(toHeader); } public static String getUserIdFromFromHeader(Request request) { FromHeader fromHeader = (FromHeader)request.getHeader(FromHeader.NAME); return getUserIdFromHeader(fromHeader); } public static String getUser(Request request) { return ((SipUri)request.getRequestURI()).getUser(); } public static SipTransaction getSipTransaction(SIPResponse response) { SipTransaction sipTransaction = new SipTransaction(); sipTransaction.setCallId(response.getCallIdHeader().getCallId()); sipTransaction.setFromTag(response.getFromTag()); sipTransaction.setToTag(response.getToTag()); sipTransaction.setViaBranch(response.getTopmostViaHeader().getBranch()); return sipTransaction; } public static SipTransaction getSipTransaction(SIPRequest request) { SipTransaction sipTransaction = new SipTransaction(); sipTransaction.setCallId(request.getCallIdHeader().getCallId()); sipTransaction.setFromTag(request.getFromTag()); sipTransaction.setToTag(request.getToTag()); sipTransaction.setViaBranch(request.getTopmostViaHeader().getBranch()); return sipTransaction; } public static String getUserIdFromHeader(HeaderAddress headerAddress) { AddressImpl address = (AddressImpl)headerAddress.getAddress(); SipUri uri = (SipUri)address.getURI(); return uri.getUser(); } public static String getCallId(RequestEvent requestEvent) { return ((SIPRequest)requestEvent.getRequest()).getCallIdHeader().getCallId(); } public static String getCallId(SIPRequest request) { return request.getCallIdHeader().getCallId(); } public static RemoteAddressInfo getRemoteAddressFromRequest(SIPRequest request) { return getRemoteAddressFromRequest(request, false); } /** * 从subject读取channelId */ public static String getSubjectId(Request request) { SubjectHeader subject = (SubjectHeader)request.getHeader(SubjectHeader.NAME); if (subject == null) { // 如果缺失subject return null; } return subject.getSubject().split(":")[0]; } /** * 从请求中获取设备ip地址和端口号 * * @param request 请求 * @param sipUseSourceIpAsRemoteAddress false 从via中获取地址, true 直接获取远程地址 * @return 地址信息 */ public static RemoteAddressInfo getRemoteAddressFromRequest(SIPRequest request, boolean sipUseSourceIpAsRemoteAddress) { String remoteAddress; int remotePort; if (sipUseSourceIpAsRemoteAddress) { remoteAddress = request.getPeerPacketSourceAddress().getHostAddress(); remotePort = request.getPeerPacketSourcePort(); } else { // 判断RPort是否改变,改变则说明路由nat信息变化,修改设备信息 // 获取到通信地址等信息 remoteAddress = request.getTopmostViaHeader().getReceived(); remotePort = request.getTopmostViaHeader().getRPort(); // 解析本地地址替代 if (ObjectUtils.isEmpty(remoteAddress) || remotePort == -1) { remoteAddress = Optional.ofNullable(request.getPeerPacketSourceAddress()).map(InetAddress::getHostAddress).orElse(request.getViaHost()); remotePort = OptionalInt.of(request.getPeerPacketSourcePort()).stream().filter(e -> e != 0).findFirst().orElse(request.getViaPort()); } } return new RemoteAddressInfo(remoteAddress, remotePort); } public static String generateGB28181Code(int centerCode, int industryCode, int typeCode, int serialNumber) { String centerCodeStr = String.format("%08d", centerCode); String industryCodeStr = String.format("%02d", industryCode); String typeCodeStr = String.format("%03d", typeCode); String serialNumberStr = String.format("%07d", serialNumber); return centerCodeStr + industryCodeStr + typeCodeStr + serialNumberStr; } public static String genSsrc(String userId) { if (StringUtils.isEmpty(userId)) { // 随机生成ssrc return String.valueOf(RandomUtils.nextLong(100000, 500000)); } String ssrcPrefix = userId.substring(3, 8); return String.format("%s%04d", ssrcPrefix, RandomUtils.nextLong(1000, 9999)); } public static SdpSessionDescription parseSdp(String sdpStr) { // jainSip 不支持y= f=字段, 移除以解析。 int ssrcIndex = sdpStr.indexOf("y="); int mediaDescriptionIndex = sdpStr.indexOf("f="); // 检查是否有y字段 SessionDescription sdp; String ssrc = null; String mediaDescription = null; if (mediaDescriptionIndex == 0 && ssrcIndex == 0) { sdp = SipRequestUtils.createSessionDescription(sdpStr); } else { String lines[] = sdpStr.split("\\r?\\n"); StringBuilder stringBuilder = new StringBuilder(); for (String line : lines) { if (line.trim().startsWith("y=")) { ssrc = line.substring(2); } else if (line.trim().startsWith("f=")) { mediaDescription = line.substring(2); } else { stringBuilder.append(line.trim()).append("\r\n"); } } sdp = SipRequestUtils.createSessionDescription(stringBuilder.toString()); } return GbSessionDescription.getInstance(sdp, ssrc, mediaDescription); } public static <T> T parseRequest(RequestEvent event, String charset, Class<T> clazz) { SIPRequest sipRequest = (SIPRequest)event.getRequest(); return getObj(charset, clazz, sipRequest.getRawContent()); } public static String parseRequest(RequestEvent event, String charset) { SIPRequest sipRequest = (SIPRequest)event.getRequest(); byte[] rawContent = sipRequest.getRawContent(); if (StringUtils.isBlank(charset)) { charset = Constant.UTF_8; } return StringTools.toEncodedString(rawContent, Charset.forName(charset)); } public static <T> T getObj(String charset, Class<T> clazz, byte[] rawContent) { if (StringUtils.isBlank(charset)) { charset = Constant.UTF_8; } String xmlStr = StringTools.toEncodedString(rawContent, Charset.forName(charset)); Object o = XmlUtils.parseObj(xmlStr, clazz); return (T)o; } public static <T> T parseResponse(ResponseEvent evt, Class<T> tClass) { return parseResponse(evt, null, tClass); } public static <T> T parseResponse(ResponseEvent evt, String charset, Class<T> clazz) { Response response = evt.getResponse(); return getObj(charset, clazz, response.getRawContent()); } /** * 将 LocalDateTime 转换为 NTP 时间戳(SDP 时间格式) * * @param dateTime 本地时间 * @return NTP 时间戳(秒) */ public static long toNtpTimestamp(LocalDateTime dateTime) { if (dateTime == null) { return 0; } // 转换为 UTC 时间戳(秒) long unixTimestamp = dateTime.toEpochSecond(ZoneOffset.UTC); // 加上 NTP 偏移量得到 NTP 时间戳 return unixTimestamp + NTP_TIMESTAMP_OFFSET; } /** * 将时间字符串转换为 NTP 时间戳(SDP 时间格式) * 支持 ISO 8601 格式:2024-01-01T08:00:00 * * @param timeString 时间字符串 * @return NTP 时间戳(秒) */ public static long toNtpTimestamp(String timeString) { if (StringUtils.isBlank(timeString)) { return 0; } try { LocalDateTime dateTime = LocalDateTime.parse(timeString); return toNtpTimestamp(dateTime); } catch (Exception e) { // 如果解析失败,返回0(SDP中表示永久会话) return 0; } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/utils/SpringBeanFactory.java
sip-common/src/main/java/io/github/lunasaw/sip/common/utils/SpringBeanFactory.java
package io.github.lunasaw.sip.common.utils; import lombok.Getter; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @author luna * @description: bean获取工厂,获取spring中的已初始化的bean */ @Component public class SpringBeanFactory implements ApplicationContextAware { // Spring应用上下文环境 @Getter private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的回调方法,设置上下文环境 */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringBeanFactory.applicationContext = applicationContext; } /** * 获取对象 这里重写了bean方法,起主要作用 */ public static <T> T getBean(String beanId) throws BeansException { if (applicationContext == null) { return null; } return (T)applicationContext.getBean(beanId); } /** * 获取当前环境 */ public static String getActiveProfile() { return applicationContext.getEnvironment().getActiveProfiles()[0]; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/utils/DynamicTask.java
sip-common/src/main/java/io/github/lunasaw/sip/common/utils/DynamicTask.java
package io.github.lunasaw.sip.common.utils; import java.time.Instant; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; /** * 动态定时任务 * * @author lin */ @Component public class DynamicTask { private final Logger logger = LoggerFactory.getLogger(DynamicTask.class); private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>(); private final Map<String, Runnable> runnableMap = new ConcurrentHashMap<>(); private ThreadPoolTaskScheduler threadPoolTaskScheduler; @PostConstruct public void DynamicTask() { threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setPoolSize(200); threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true); threadPoolTaskScheduler.setAwaitTerminationSeconds(10); threadPoolTaskScheduler.initialize(); } public void startCron(String key, Runnable task, Integer duration, TimeUnit timeUnit) { long convert = TimeUnit.MILLISECONDS.convert(duration, timeUnit); startCron(key, task, convert); } /** * 循环执行的任务 * * @param key 任务ID * @param task 任务 * @param time 间隔 毫秒 * @return */ public void startCron(String key, Runnable task, long time) { if (ObjectUtils.isEmpty(key)) { return; } ScheduledFuture<?> future = futureMap.get(key); if (future != null) { if (future.isCancelled()) { logger.debug("任务【{}】已存在但是关闭状态!!!", key); } else { logger.debug("任务【{}】已存在且已启动!!!", key); return; } } // scheduleWithFixedDelay 必须等待上一个任务结束才开始计时period, time表示执行的间隔 future = threadPoolTaskScheduler.scheduleAtFixedRate(task, time); if (future != null) { futureMap.put(key, future); runnableMap.put(key, task); logger.debug("任务【{}】启动成功!!!", key); } else { logger.debug("任务【{}】启动失败!!!", key); } } /** * 延时任务 * * @param key 任务ID * @param task 任务 * @param delay 延时 /毫秒 * @return */ public void startDelay(String key, Runnable task, int delay) { if (ObjectUtils.isEmpty(key)) { return; } stop(key); // 获取执行的时刻 Instant startInstant = Instant.now().plusMillis(TimeUnit.MILLISECONDS.toMillis(delay)); ScheduledFuture future = futureMap.get(key); if (future != null) { if (future.isCancelled()) { logger.debug("任务【{}】已存在但是关闭状态!!!", key); } else { logger.debug("任务【{}】已存在且已启动!!!", key); return; } } // scheduleWithFixedDelay 必须等待上一个任务结束才开始计时period, cycleForCatalog表示执行的间隔 future = threadPoolTaskScheduler.schedule(task, startInstant); if (future != null) { futureMap.put(key, future); runnableMap.put(key, task); logger.debug("任务【{}】启动成功!!!", key); } else { logger.debug("任务【{}】启动失败!!!", key); } } public boolean stop(String key) { if (ObjectUtils.isEmpty(key)) { return false; } boolean result = false; if (!ObjectUtils.isEmpty(futureMap.get(key)) && !futureMap.get(key).isCancelled() && !futureMap.get(key).isDone()) { result = futureMap.get(key).cancel(false); futureMap.remove(key); runnableMap.remove(key); } return result; } public boolean contains(String key) { if (ObjectUtils.isEmpty(key)) { return false; } return futureMap.get(key) != null; } public Set<String> getAllKeys() { return futureMap.keySet(); } public Runnable get(String key) { if (ObjectUtils.isEmpty(key)) { return null; } return runnableMap.get(key); } /** * 每五分钟检查失效的任务,并移除 */ @Scheduled(cron = "0 0/5 * * * ?") public void execute() { if (futureMap.size() > 0) { for (String key : futureMap.keySet()) { ScheduledFuture<?> future = futureMap.get(key); if (future.isDone() || future.isCancelled()) { futureMap.remove(key); runnableMap.remove(key); } } } } public boolean isAlive(String key) { return futureMap.get(key) != null && !futureMap.get(key).isDone() && !futureMap.get(key).isCancelled(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/utils/XmlUtils.java
sip-common/src/main/java/io/github/lunasaw/sip/common/utils/XmlUtils.java
package io.github.lunasaw.sip.common.utils; import java.io.File; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.util.ResourceUtils; import com.google.common.base.Joiner; import lombok.SneakyThrows; /** * @author luna * @date 2023/10/15 */ public class XmlUtils { @SneakyThrows public static String toString(String charset, Object object) { JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, charset); StringWriter writer = new StringWriter(); marshaller.marshal(object, writer); return writer.toString(); } @SneakyThrows public static <T> Object parseObj(String xmlStr, Class<T> clazz, String charset) { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return unmarshaller.unmarshal(new StringReader(new String(xmlStr.getBytes(charset), charset))); } @SneakyThrows public static <T> Object parseObj(String xmlStr, Class<T> clazz) { return parseObj(xmlStr, clazz, "UTF-8"); } @SneakyThrows public static <T> Object parseFile(String resource, Class<T> clazz) { return parseFile(resource, clazz, StandardCharsets.UTF_8); } @SneakyThrows public static <T> Object parseFile(String resource, Class<T> clazz, Charset charset) { File file = ResourceUtils.getFile(resource); List<String> strings = Files.readAllLines(Paths.get(file.getAbsolutePath()), charset); String join = Joiner.on("\n").join(strings); return parseObj(join, clazz); } @SneakyThrows public static String getCmdType(String xmlStr) { SAXReader reader = new SAXReader(); // 清理XML字符串,移除BOM和前导空白字符 String cleanXmlStr = cleanXmlString(xmlStr); Document document = reader.read(new StringReader(cleanXmlStr)); // 获取根元素 Element root = document.getRootElement(); // 获取CmdType子元素 Element cmdType = root.element("CmdType"); if (cmdType == null) { return null; } return cmdType.getText(); } /** * 清理XML字符串,移除BOM和前导/尾随空白字符 * * @param xmlStr 原始XML字符串 * @return 清理后的XML字符串 */ private static String cleanXmlString(String xmlStr) { if (xmlStr == null) { return null; } // 移除BOM标记 (UTF-8: EF BB BF, UTF-16BE: FE FF, UTF-16LE: FF FE) String cleaned = xmlStr; if (!cleaned.isEmpty() && cleaned.charAt(0) == '\uFEFF') { cleaned = cleaned.substring(1); } // 移除前导和尾随空白字符(包括空格、制表符、换行符等) cleaned = cleaned.trim(); return cleaned; } @SneakyThrows public static String getRootType(String xmlStr) { SAXReader reader = new SAXReader(); // 清理XML字符串,移除BOM和前导空白字符 String cleanXmlStr = cleanXmlString(xmlStr); Document document = reader.read(new StringReader(cleanXmlStr)); // 获取根元素 Element root = document.getRootElement(); return root.getName(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/layer/package-info.java
sip-common/src/main/java/io/github/lunasaw/sip/common/layer/package-info.java
/** * SIP layers. * 添加SIP监听端口 * * @author luna * @date 2023/11/20 */ package io.github.lunasaw.sip.common.layer;
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/layer/SipLayer.java
sip-common/src/main/java/io/github/lunasaw/sip/common/layer/SipLayer.java
package io.github.lunasaw.sip.common.layer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TooManyListenersException; import java.util.concurrent.ConcurrentHashMap; import javax.sip.*; import com.google.common.collect.Lists; import jakarta.annotation.PreDestroy; import lombok.Setter; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import gov.nist.javax.sip.SipProviderImpl; import gov.nist.javax.sip.SipStackImpl; import io.github.lunasaw.sip.common.conf.DefaultProperties; import io.github.lunasaw.sip.common.conf.msg.StringMsgParserFactory; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * SIP协议层封装 * 提供SIP协议栈的初始化和监听点管理 * * @author luna */ @Setter @Slf4j @Component public class SipLayer implements InitializingBean { private static final Map<String, SipProviderImpl> tcpSipProviderMap = new ConcurrentHashMap<>(); private static final Map<String, SipProviderImpl> udpSipProviderMap = new ConcurrentHashMap<>(); // 记录已创建的监听点,避免重复创建 private static final Map<String, Boolean> listeningPoints = new ConcurrentHashMap<>(); // 记录SipStack实例,避免重复创建 private static final Map<String, SipStackImpl> sipStackMap = new ConcurrentHashMap<>(); // 标记是否正在关闭 private static volatile boolean isShuttingDown = false; @Getter private static final List<String> monitorIpList = Lists.newArrayList("0.0.0.0"); @Getter private SipListener sipListener; public static SipProviderImpl getUdpSipProvider(String ip) { if (ObjectUtils.isEmpty(ip)) { return udpSipProviderMap.values().stream().findFirst().orElse(null); } // 首先尝试精确匹配 SipProviderImpl provider = udpSipProviderMap.get(ip); if (provider != null) { return provider; } // 如果请求IP是0.0.0.0,尝试获取任意可用的Provider if ("0.0.0.0".equals(ip)) { return udpSipProviderMap.values().stream().findFirst().orElse(null); } // 如果Provider是0.0.0.0监听的,可以处理任意IP的请求 return udpSipProviderMap.get("0.0.0.0"); } public static SipProviderImpl getUdpSipProvider() { if (udpSipProviderMap.isEmpty()) { throw new RuntimeException("ListeningPoint Not Exist"); } return udpSipProviderMap.values().stream().findFirst().get(); } public static SipProviderImpl getTcpSipProvider() { if (tcpSipProviderMap.size() != 1) { return null; } return tcpSipProviderMap.values().stream().findFirst().get(); } public static SipProviderImpl getTcpSipProvider(String ip) { if (ObjectUtils.isEmpty(ip)) { return tcpSipProviderMap.values().stream().findFirst().orElse(null); } // 首先尝试精确匹配 SipProviderImpl provider = tcpSipProviderMap.get(ip); if (provider != null) { return provider; } // 如果请求IP是0.0.0.0,尝试获取任意可用的Provider if ("0.0.0.0".equals(ip)) { return tcpSipProviderMap.values().stream().findFirst().orElse(null); } // 如果Provider是0.0.0.0监听的,可以处理任意IP的请求 return tcpSipProviderMap.get("0.0.0.0"); } public static String getMonitorIp() { return monitorIpList.get(0); } public static boolean isShuttingDown() { return isShuttingDown; } public static Map<String, SipProviderImpl> getTcpSipProviderMap() { return new HashMap<>(tcpSipProviderMap); } public static Map<String, SipProviderImpl> getUdpSipProviderMap() { return new HashMap<>(udpSipProviderMap); } /** * 生成监听点唯一标识 */ private String getListeningPointKey(String monitorIp, int port) { return monitorIp + ":" + port; } /** * 检查监听点是否已存在 */ private boolean isListeningPointExists(String monitorIp, int port) { String key = getListeningPointKey(monitorIp, port); return listeningPoints.containsKey(key); } /** * 标记监听点已创建 */ private void markListeningPointCreated(String monitorIp, int port) { String key = getListeningPointKey(monitorIp, port); listeningPoints.put(key, true); } /** * 添加监听点(简化版本) */ public void addListeningPoint(String monitorIp, int port) { addListeningPoint(monitorIp, port, sipListener, true); } /** * 添加监听点(带日志控制) */ public void addListeningPoint(String monitorIp, int port, Boolean enableLog) { addListeningPoint(monitorIp, port, sipListener, enableLog); } /** * 添加监听点(完整版本) * 优化:避免重复创建相同IP和端口的监听点 */ public synchronized void addListeningPoint(String monitorIp, int port, SipListener listener, Boolean enableLog) { // 检查是否已存在相同的监听点 if (isListeningPointExists(monitorIp, port)) { log.info("[SIP SERVER] 监听点 {}:{} 已存在,跳过创建", monitorIp, port); return; } SipStackImpl sipStack = getOrCreateSipStack(monitorIp, enableLog); if (sipStack == null) { return; } boolean tcpSuccess = createTcpListeningPoint(sipStack, monitorIp, port, listener); boolean udpSuccess = createUdpListeningPoint(sipStack, monitorIp, port, listener); // 只有当TCP或UDP至少有一个成功时,才标记为已创建 if (tcpSuccess || udpSuccess) { markListeningPointCreated(monitorIp, port); if (!monitorIpList.contains(monitorIp)) { monitorIpList.add(monitorIp); } } } /** * 获取或创建SipStack实例 */ private SipStackImpl getOrCreateSipStack(String monitorIp, Boolean enableLog) { String stackKey = monitorIp + "_" + (enableLog ? "log" : "nolog"); if (sipStackMap.containsKey(stackKey)) { return sipStackMap.get(stackKey); } try { Properties properties = DefaultProperties.getProperties("SIP-PROXY", monitorIp, enableLog); SipFactory sipFactory = SipFactory.getInstance(); sipFactory.setPathName("gov.nist"); SipStackImpl sipStack = (SipStackImpl)sipFactory.createSipStack(properties); sipStack.setMessageParserFactory(new StringMsgParserFactory()); sipStackMap.put(stackKey, sipStack); log.info("[SIP SERVER] 创建新的SipStack实例: {}", stackKey); return sipStack; } catch (PeerUnavailableException e) { log.error("[SIP SERVER] SIP服务启动失败,监听地址{}失败,请检查ip是否正确", monitorIp, e); return null; } } /** * 创建TCP监听点 */ private boolean createTcpListeningPoint(SipStackImpl sipStack, String monitorIp, int port, SipListener listener) { try { ListeningPoint tcpListeningPoint = sipStack.createListeningPoint(monitorIp, port, "TCP"); SipProviderImpl tcpSipProvider = (SipProviderImpl)sipStack.createSipProvider(tcpListeningPoint); tcpSipProvider.setDialogErrorsAutomaticallyHandled(); tcpSipProvider.addSipListener(listener); tcpSipProviderMap.put(monitorIp, tcpSipProvider); log.info("[SIP SERVER] tcp://{}:{} 启动成功", monitorIp, port); return true; } catch (TransportNotSupportedException | TooManyListenersException | ObjectInUseException | InvalidArgumentException e) { log.error("[SIP SERVER] tcp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确", monitorIp, port, e); return false; } } /** * 创建UDP监听点 */ private boolean createUdpListeningPoint(SipStackImpl sipStack, String monitorIp, int port, SipListener listener) { try { ListeningPoint udpListeningPoint = sipStack.createListeningPoint(monitorIp, port, "UDP"); SipProviderImpl udpSipProvider = (SipProviderImpl)sipStack.createSipProvider(udpListeningPoint); udpSipProvider.addSipListener(listener); udpSipProviderMap.put(monitorIp, udpSipProvider); log.info("[SIP SERVER] udp://{}:{} 启动成功", monitorIp, port); return true; } catch (TransportNotSupportedException | TooManyListenersException | ObjectInUseException | InvalidArgumentException e) { log.error("[SIP SERVER] udp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确", monitorIp, port, e); return false; } } /** * 清理指定IP和端口的监听点 */ public synchronized void removeListeningPoint(String monitorIp, int port) { String key = getListeningPointKey(monitorIp, port); // 快速清理TCP Provider SipProviderImpl tcpProvider = tcpSipProviderMap.remove(monitorIp); if (tcpProvider != null) { try { tcpProvider.removeSipListener(sipListener); log.debug("[SIP SERVER] 清理TCP监听点: {}:{}", monitorIp, port); } catch (Exception e) { log.debug("[SIP SERVER] 清理TCP监听点异常: {}", e.getMessage()); } } // 快速清理UDP Provider SipProviderImpl udpProvider = udpSipProviderMap.remove(monitorIp); if (udpProvider != null) { try { udpProvider.removeSipListener(sipListener); log.debug("[SIP SERVER] 清理UDP监听点: {}:{}", monitorIp, port); } catch (Exception e) { log.debug("[SIP SERVER] 清理UDP监听点异常: {}", e.getMessage()); } } // 移除监听点记录 listeningPoints.remove(key); monitorIpList.remove(monitorIp); } /** * 清理所有监听点 */ public synchronized void clearAllListeningPoints() { log.debug("[SIP SERVER] 开始清理所有监听点"); // 设置关闭标志 isShuttingDown = true; // 快速清理所有TCP Provider for (SipProviderImpl provider : tcpSipProviderMap.values()) { try { if (sipListener != null) { provider.removeSipListener(sipListener); } } catch (Exception e) { log.debug("[SIP SERVER] 清理TCP Provider异常: {}", e.getMessage()); } } tcpSipProviderMap.clear(); // 快速清理所有UDP Provider for (SipProviderImpl provider : udpSipProviderMap.values()) { try { if (sipListener != null) { provider.removeSipListener(sipListener); } } catch (Exception e) { log.debug("[SIP SERVER] 清理UDP Provider异常: {}", e.getMessage()); } } udpSipProviderMap.clear(); // 清理监听点记录 listeningPoints.clear(); monitorIpList.clear(); monitorIpList.add("0.0.0.0"); // 恢复默认值 // 清理SipStack实例 sipStackMap.clear(); log.debug("[SIP SERVER] 所有监听点清理完成"); } /** * 获取当前活跃的监听点数量 */ public int getActiveListeningPointsCount() { return listeningPoints.size(); } /** * 检查指定IP和端口是否有活跃的监听点 */ public boolean hasActiveListeningPoint(String monitorIp, int port) { return isListeningPointExists(monitorIp, port); } public String getLocalIp(String deviceLocalIp) { if (!ObjectUtils.isEmpty(deviceLocalIp)) { return deviceLocalIp; } return getUdpSipProvider().getListeningPoint().getIPAddress(); } @Override public void afterPropertiesSet() { } @PreDestroy public void destroy() { log.debug("[SIP SERVER] 开始关闭SIP服务"); try { clearAllListeningPoints(); log.debug("[SIP SERVER] SIP服务关闭完成"); } catch (Exception e) { log.debug("[SIP SERVER] SIP服务关闭异常: {}", e.getMessage()); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipSender.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipSender.java
package io.github.lunasaw.sip.common.transmit; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory; import io.github.lunasaw.sip.common.transmit.strategy.SipRequestStrategy; import io.github.lunasaw.sip.common.transmit.strategy.SipRequestStrategyFactory; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import io.github.lunasaw.sip.common.context.SipTransactionContext; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import javax.sip.ServerTransaction; import javax.sip.address.SipURI; import javax.sip.message.Message; import javax.sip.message.Request; import javax.sip.message.Response; /** * SIP消息发送器(重构版) * 使用策略模式和建造者模式,提供简洁的API接口 * * @author lin */ @Slf4j public class SipSender { /** * 创建请求建造者 * * @param fromDevice 发送方设备 * @param toDevice 接收方设备 * @param method SIP方法 * @return 请求建造者 */ public static SipRequestBuilder request(FromDevice fromDevice, ToDevice toDevice, String method) { return new SipRequestBuilder(fromDevice, toDevice, method); } /** * 发送SUBSCRIBE请求 */ public static String doSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo) { return request(fromDevice, toDevice, "SUBSCRIBE") .content(content) .subscribeInfo(subscribeInfo) .send(); } // ==================== 兼容性方法 ==================== public static String doSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "SUBSCRIBE") .content(content) .errorEvent(errorEvent) .okEvent(okEvent) .send(); } /** * 发送MESSAGE请求 */ public static String doMessageRequest(FromDevice fromDevice, ToDevice toDevice, String content) { return request(fromDevice, toDevice, "MESSAGE") .content(content) .send(); } public static String doMessageRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "MESSAGE") .content(content) .errorEvent(errorEvent) .okEvent(okEvent) .send(); } /** * 发送NOTIFY请求 */ public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content) { return request(fromDevice, toDevice, "NOTIFY") .content(content) .send(); } public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "NOTIFY") .content(content) .errorEvent(errorEvent) .okEvent(okEvent) .subscribeInfo(subscribeInfo) .send(); } public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "NOTIFY") .content(content) .errorEvent(errorEvent) .okEvent(okEvent) .send(); } /** * 发送INVITE请求 */ public static String doInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject) { return request(fromDevice, toDevice, "INVITE") .content(content) .subject(subject) .send(); } public static String doInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "INVITE") .content(content) .errorEvent(errorEvent) .okEvent(okEvent) .send(); } /** * 发送INFO请求 */ public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content) { return request(fromDevice, toDevice, "INFO") .content(content) .send(); } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "INFO") .content(content) .errorEvent(errorEvent) .okEvent(okEvent) .send(); } /** * 发送BYE请求 */ public static String doByeRequest(FromDevice fromDevice, ToDevice toDevice) { return request(fromDevice, toDevice, "BYE") .send(); } /** * 发送ACK请求 */ public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice) { return request(fromDevice, toDevice, "ACK") .send(); } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return request(fromDevice, toDevice, "ACK") .content(content) .callId(callId) .send(); } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "ACK") .content(content) .okEvent(okEvent) .errorEvent(errorEvent) .callId(callId) .send(); } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { return request(fromDevice, toDevice, "ACK") .callId(callId) .send(); } public static String doAckRequest(FromDevice fromDevice, SipURI sipURI, Response sipResponse) { // 将Response转换为SIPResponse gov.nist.javax.sip.message.SIPResponse sipResponseImpl = (gov.nist.javax.sip.message.SIPResponse) sipResponse; Request messageRequest = SipRequestBuilderFactory.getAckBuilder().buildAckRequest(fromDevice, sipURI, sipResponseImpl); SipMessageTransmitter.transmitMessage(fromDevice.getIp(), messageRequest); return sipResponseImpl.getCallId().getCallId(); } /** * 发送REGISTER请求 */ public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires) { return request(fromDevice, toDevice, "REGISTER") .expires(expires) .send(); } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, Event event) { return request(fromDevice, toDevice, "REGISTER") .expires(expires) .errorEvent(event) .send(); } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, String callId, Event errorEvent, Event okEvent) { return request(fromDevice, toDevice, "REGISTER") .expires(expires) .callId(callId) .errorEvent(errorEvent) .okEvent(okEvent) .send(); } /** * 传输消息(兼容性方法) */ public static void transmitRequest(String ip, Message message) { SipMessageTransmitter.transmitMessage(ip, message); } // ==================== 消息传输方法 ==================== public static void transmitRequest(String ip, Message message, Event errorEvent) { SipMessageTransmitter.transmitMessage(ip, message, errorEvent); } public static void transmitRequestSuccess(String ip, Message message, Event okEvent) { SipMessageTransmitter.transmitMessageSuccess(ip, message, okEvent); } public static void transmitRequest(String ip, Message message, Event errorEvent, Event okEvent) { SipMessageTransmitter.transmitMessage(ip, message, errorEvent, okEvent); } /** * 获取服务器事务(兼容性方法) */ public static ServerTransaction getServerTransaction(Request request) { return SipTransactionManager.getServerTransaction(request); } // ==================== 事务管理方法 ==================== public static ServerTransaction getServerTransaction(Request request, String ip) { return SipTransactionManager.getServerTransaction(request, ip); } /** * SIP请求建造者 * 提供流式API来构建和发送SIP请求 */ public static class SipRequestBuilder { private final FromDevice fromDevice; private final ToDevice toDevice; private final String method; private String content; private String subject; private SubscribeInfo subscribeInfo; private Integer expires; private Event errorEvent; private Event okEvent; private String callId; public SipRequestBuilder(FromDevice fromDevice, ToDevice toDevice, String method) { this.fromDevice = fromDevice; this.toDevice = toDevice; this.method = method; // Call-ID优先级:ThreadLocal事务上下文 > ToDevice.callId > 新生成 String contextCallId = SipTransactionContext.getCurrentCallId(); if (StringUtils.isNotBlank(contextCallId)) { this.callId = contextCallId; log.debug("使用SIP事务上下文的Call-ID: {}", contextCallId); } else if (StringUtils.isNotBlank(toDevice.getCallId())) { this.callId = toDevice.getCallId(); log.debug("使用ToDevice的Call-ID: {}", this.callId); } else { this.callId = SipRequestUtils.getNewCallId(); log.debug("生成新的Call-ID: {}", this.callId); } } public SipRequestBuilder content(String content) { this.content = content; return this; } public SipRequestBuilder subject(String subject) { this.subject = subject; return this; } public SipRequestBuilder expires(Integer expires) { this.expires = expires; return this; } public SipRequestBuilder errorEvent(Event errorEvent) { this.errorEvent = errorEvent; return this; } public SipRequestBuilder okEvent(Event okEvent) { this.okEvent = okEvent; return this; } public SipRequestBuilder callId(String callId) { if (StringUtils.isNoneBlank(callId)) { this.callId = callId; } return this; } public SipRequestBuilder subscribeInfo(SubscribeInfo subscribeInfo) { this.subscribeInfo = subscribeInfo; return this; } public String send() { SipRequestStrategy strategy = getStrategy(); if (strategy == null) { throw new IllegalArgumentException("不支持的SIP方法: " + method); } if ("INVITE".equalsIgnoreCase(method) && subject != null) { return strategy.sendRequestWithSubject(fromDevice, toDevice, content, subject, callId, errorEvent, okEvent); } else if ("SUBSCRIBE".equalsIgnoreCase(method) && subscribeInfo != null) { return strategy.sendRequestWithSubscribe(fromDevice, toDevice, content, subscribeInfo, callId, errorEvent, okEvent); } if (subscribeInfo != null) { return strategy.sendRequestWithSubscribe(fromDevice, toDevice, content, subscribeInfo, callId, errorEvent, okEvent); } return strategy.sendRequest(fromDevice, toDevice, content, callId, errorEvent, okEvent); } private SipRequestStrategy getStrategy() { if ("REGISTER".equalsIgnoreCase(method)) { return SipRequestStrategyFactory.getRegisterStrategy(expires); } return SipRequestStrategyFactory.getStrategy(method); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/TransactionAwareResponseCmd.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/TransactionAwareResponseCmd.java
package io.github.lunasaw.sip.common.transmit; import io.github.lunasaw.sip.common.transmit.SipTransactionContext.TransactionContextInfo; import lombok.extern.slf4j.Slf4j; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; import javax.sip.TransactionState; import javax.sip.header.ContentTypeHeader; import javax.sip.message.Response; /** * 事务感知的响应命令管理器 * 扩展原有ResponseCmd,提供事务上下文感知的响应发送能力 * * @author luna */ @Slf4j public class TransactionAwareResponseCmd { /** * 事务感知的响应构建器 */ public static class TransactionAwareSipResponseBuilder extends ResponseCmd.SipResponseBuilder { private boolean useContextTransaction = true; private String contextKey; public TransactionAwareSipResponseBuilder(int statusCode) { super(statusCode); } /** * 设置是否使用上下文事务 */ public TransactionAwareSipResponseBuilder useContextTransaction(boolean useContextTransaction) { this.useContextTransaction = useContextTransaction; return this; } /** * 设置上下文键 */ public TransactionAwareSipResponseBuilder contextKey(String contextKey) { this.contextKey = contextKey; return this; } /** * 重写构建并发送响应方法 */ @Override public void send() { try { // 优先尝试使用事务上下文 if (useContextTransaction) { if (sendWithTransactionContext()) { return; // 成功发送,直接返回 } // 如果上下文事务失败,继续使用原有逻辑 log.warn("使用事务上下文发送响应失败,降级到原有逻辑"); } // 使用原有逻辑 super.send(); } catch (Exception e) { log.error("事务感知发送SIP响应失败", e); throw new RuntimeException("事务感知发送SIP响应失败", e); } } /** * 使用事务上下文发送响应 */ private boolean sendWithTransactionContext() { try { // 获取当前线程的事务上下文 TransactionContextInfo context = SipTransactionContext.getCurrentContext(); if (context == null && contextKey != null) { // 如果当前线程没有上下文,尝试根据键获取 context = SipTransactionContext.getContext(contextKey); } if (context == null) { log.debug("未找到事务上下文,无法使用上下文事务发送响应"); return false; } if (!context.checkAndUpdateValidity()) { log.debug("事务上下文无效: key={}", context.getContextKey()); return false; } ServerTransaction transaction = context.getServerTransaction(); if (transaction == null) { log.debug("事务上下文中没有ServerTransaction: key={}", context.getContextKey()); return false; } // 验证事务状态 TransactionState state = transaction.getState(); if (state == TransactionState.TERMINATED || state == TransactionState.COMPLETED) { log.debug("事务状态无效: key={}, state={}", context.getContextKey(), state); context.invalidate(); return false; } // 构建响应 Response response = buildResponseFromContext(context); // 使用事务发送响应 transaction.sendResponse(response); log.debug("使用事务上下文成功发送响应: key={}, status={}", context.getContextKey(), response.getStatusCode()); return true; } catch (Exception e) { log.warn("使用事务上下文发送响应异常: {}", e.getMessage()); return false; } } /** * 从事务上下文构建响应 */ private Response buildResponseFromContext(TransactionContextInfo context) throws Exception { // 使用原始请求构建响应 return super.buildResponse(); } } // ==================== 便捷方法 ==================== /** * 创建事务感知的响应构建器 */ public static TransactionAwareSipResponseBuilder response(int statusCode) { return new TransactionAwareSipResponseBuilder(statusCode); } /** * 事务感知的快速响应发送(自动使用当前上下文) */ public static void sendResponse(int statusCode) { response(statusCode) .useContextTransaction(true) .send(); } /** * 事务感知的快速响应发送(带短语) */ public static void sendResponse(int statusCode, String phrase) { response(statusCode) .useContextTransaction(true) .phrase(phrase) .send(); } /** * 事务感知的快速响应发送(带内容) */ public static void sendResponse(int statusCode, String content, ContentTypeHeader contentTypeHeader) { response(statusCode) .useContextTransaction(true) .content(content) .contentType(contentTypeHeader) .send(); } /** * 使用指定上下文键发送响应 */ public static void sendResponseWithContext(int statusCode, String contextKey) { response(statusCode) .contextKey(contextKey) .useContextTransaction(true) .send(); } /** * 使用指定上下文键发送带短语的响应 */ public static void sendResponseWithContext(int statusCode, String phrase, String contextKey) { response(statusCode) .useContextTransaction(true) .contextKey(contextKey) .phrase(phrase) .send(); } /** * 发送200 OK响应(事务感知) */ public static void sendOK() { sendResponse(Response.OK, "OK"); } /** * 发送400 Bad Request响应(事务感知) */ public static void sendBadRequest() { sendResponse(Response.BAD_REQUEST, "Bad Request"); } /** * 发送500 Internal Server Error响应(事务感知) */ public static void sendInternalServerError() { sendResponse(Response.SERVER_INTERNAL_ERROR, "Internal Server Error"); } // ==================== 兼容性方法 ==================== /** * 兼容原有API的响应发送(增强版) */ public static void sendResponseSafe(int statusCode, RequestEvent requestEvent, ServerTransaction serverTransaction) { try { // 优先尝试使用事务感知方式 if (SipTransactionContext.getCurrentContext() != null) { sendResponse(statusCode); return; } // 降级到原有方式 ResponseCmd.sendResponse(statusCode, requestEvent, serverTransaction); } catch (Exception e) { log.error("发送响应失败,尝试无事务模式", e); try { ResponseCmd.sendResponseNoTransaction(statusCode, requestEvent); } catch (Exception fallbackException) { log.error("无事务模式发送响应也失败", fallbackException); throw new RuntimeException("发送SIP响应失败", e); } } } /** * 兼容原有API的带短语响应发送(增强版) */ public static void sendResponseSafe(int statusCode, String phrase, RequestEvent requestEvent, ServerTransaction serverTransaction) { try { // 优先尝试使用事务感知方式 if (SipTransactionContext.getCurrentContext() != null) { sendResponse(statusCode, phrase); return; } // 降级到原有方式 ResponseCmd.sendResponse(statusCode, phrase, requestEvent, serverTransaction); } catch (Exception e) { log.error("发送响应失败,尝试无事务模式", e); try { ResponseCmd.sendResponseNoTransaction(statusCode, phrase, requestEvent); } catch (Exception fallbackException) { log.error("无事务模式发送响应也失败", fallbackException); throw new RuntimeException("发送SIP响应失败", e); } } } // ==================== 诊断和监控方法 ==================== /** * 检查当前线程是否有有效的事务上下文 */ public static boolean hasValidTransactionContext() { TransactionContextInfo context = SipTransactionContext.getCurrentContext(); return context != null && context.checkAndUpdateValidity(); } /** * 获取当前事务上下文信息 */ public static String getCurrentTransactionInfo() { TransactionContextInfo context = SipTransactionContext.getCurrentContext(); if (context == null) { return "无事务上下文"; } return String.format("上下文键: %s, 有效性: %s, 事务状态: %s, 创建时间: %d", context.getContextKey(), context.isValid(), context.getLastKnownState(), context.getCreateTime()); } /** * 强制刷新当前事务上下文状态 */ public static boolean refreshCurrentTransactionContext() { TransactionContextInfo context = SipTransactionContext.getCurrentContext(); if (context != null) { return context.checkAndUpdateValidity(); } return false; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/AbstractSipListener.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/AbstractSipListener.java
package io.github.lunasaw.sip.common.transmit; import com.alibaba.fastjson2.JSON; import io.github.lunasaw.sip.common.context.SipTransactionContext; import io.github.lunasaw.sip.common.metrics.SipMetrics; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.EventResult; import io.github.lunasaw.sip.common.transmit.event.SipSubscribe; import io.github.lunasaw.sip.common.transmit.event.request.SipRequestProcessor; import io.github.lunasaw.sip.common.transmit.event.response.SipResponseProcessor; import io.github.lunasaw.sip.common.transmit.event.timeout.ITimeoutProcessor; import io.micrometer.core.instrument.Timer; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.skywalking.apm.toolkit.trace.Trace; import javax.sip.*; import javax.sip.header.CallIdHeader; import javax.sip.header.CSeqHeader; import javax.sip.message.Request; import javax.sip.message.Response; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * SIP监听器抽象基类 * 提供基础统一的SIP事件处理能力,支持自定义Processor的添加 * * @author luna */ @Slf4j @AllArgsConstructor @NoArgsConstructor public abstract class AbstractSipListener implements SipListener { /** * 对SIP事件进行处理 */ protected static final Map<String, List<SipRequestProcessor>> REQUEST_PROCESSOR_MAP = new ConcurrentHashMap<>(); ; /** * 处理接收SIP发来的SIP协议响应消息 */ protected static final Map<String, List<SipResponseProcessor>> RESPONSE_PROCESSOR_MAP = new ConcurrentHashMap<>(); /** * 处理超时事件 */ protected static final Map<String, List<ITimeoutProcessor>> TIMEOUT_PROCESSOR_MAP = new ConcurrentHashMap<>(); /** * SIP指标收集器 */ @Getter @Setter protected SipMetrics sipMetrics = new SipMetrics(new SimpleMeterRegistry()); /** * 添加 request订阅 * * @param method 方法名 * @param processor 处理程序 */ public synchronized void addRequestProcessor(String method, SipRequestProcessor processor) { if (REQUEST_PROCESSOR_MAP.containsKey(method)) { List<SipRequestProcessor> processors = REQUEST_PROCESSOR_MAP.get(method); processors.add(processor); } else { List<SipRequestProcessor> processors = new ArrayList<>(); processors.add(processor); REQUEST_PROCESSOR_MAP.put(method, processors); } log.info("添加请求处理器: {} -> {}", method, processor.getClass().getSimpleName()); } /** * 添加 response订阅 * * @param method 方法名 * @param processor 处理程序 */ public synchronized void addResponseProcessor(String method, SipResponseProcessor processor) { if (RESPONSE_PROCESSOR_MAP.containsKey(method)) { List<SipResponseProcessor> processors = RESPONSE_PROCESSOR_MAP.get(method); processors.add(processor); } else { List<SipResponseProcessor> processors = new ArrayList<>(); processors.add(processor); RESPONSE_PROCESSOR_MAP.put(method, processors); } log.debug("添加响应处理器: {} -> {}", method, processor.getClass().getSimpleName()); } /** * 添加 超时事件订阅 * * @param method 方法名 * @param processor 处理程序 */ public synchronized void addTimeoutProcessor(String method, ITimeoutProcessor processor) { if (TIMEOUT_PROCESSOR_MAP.containsKey(method)) { List<ITimeoutProcessor> processors = TIMEOUT_PROCESSOR_MAP.get(method); processors.add(processor); } else { List<ITimeoutProcessor> processors = new ArrayList<>(); processors.add(processor); TIMEOUT_PROCESSOR_MAP.put(method, processors); } log.debug("添加超时处理器: {} -> {}", method, processor.getClass().getSimpleName()); } /** * 移除请求处理器 * * @param method 方法名 * @param processor 处理程序 */ public synchronized void removeRequestProcessor(String method, SipRequestProcessor processor) { List<SipRequestProcessor> processors = REQUEST_PROCESSOR_MAP.get(method); if (processors != null) { processors.remove(processor); if (processors.isEmpty()) { REQUEST_PROCESSOR_MAP.remove(method); } log.debug("移除请求处理器: {} -> {}", method, processor.getClass().getSimpleName()); } } /** * 移除响应处理器 * * @param method 方法名 * @param processor 处理程序 */ public synchronized void removeResponseProcessor(String method, SipResponseProcessor processor) { List<SipResponseProcessor> processors = RESPONSE_PROCESSOR_MAP.get(method); if (processors != null) { processors.remove(processor); if (processors.isEmpty()) { RESPONSE_PROCESSOR_MAP.remove(method); } log.debug("移除响应处理器: {} -> {}", method, processor.getClass().getSimpleName()); } } /** * 移除超时处理器 * * @param method 方法名 * @param processor 处理程序 */ public synchronized void removeTimeoutProcessor(String method, ITimeoutProcessor processor) { List<ITimeoutProcessor> processors = TIMEOUT_PROCESSOR_MAP.get(method); if (processors != null) { processors.remove(processor); if (processors.isEmpty()) { TIMEOUT_PROCESSOR_MAP.remove(method); } log.debug("移除超时处理器: {} -> {}", method, processor.getClass().getSimpleName()); } } /** * 获取请求处理器列表 * * @param method 方法名 * @return 处理器列表 */ public List<SipRequestProcessor> getRequestProcessors(String method) { return REQUEST_PROCESSOR_MAP.get(method); } /** * 获取响应处理器列表 * * @param method 方法名 * @return 处理器列表 */ public List<SipResponseProcessor> getResponseProcessors(String method) { return RESPONSE_PROCESSOR_MAP.get(method); } /** * 获取超时处理器列表 * * @param method 方法名 * @return 处理器列表 */ public List<ITimeoutProcessor> getTimeoutProcessors(String method) { return TIMEOUT_PROCESSOR_MAP.get(method); } /** * 分发RequestEvent事件 - 基础实现 * * @param requestEvent RequestEvent事件 */ @Override public void processRequest(RequestEvent requestEvent) { Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; String method = requestEvent.getRequest().getMethod(); ServerTransaction serverTransaction = null; try { // 全局注入SIP事务上下文 - 在最顶层入口处注入完整事务信息 try { SipTransactionContext.SipTransactionInfo transactionInfo = SipTransactionContext.SipTransactionInfo.fromRequestEvent(requestEvent); if (transactionInfo != null) { SipTransactionContext.setTransactionInfo(transactionInfo); log.debug("全局注入SIP事务上下文: {}, method={}, thread={}", transactionInfo, method, Thread.currentThread().getName()); } else { log.warn("无法提取SIP事务信息,方法: {}", method); } } catch (Exception e) { log.warn("全局注入SIP事务上下文失败: method={}, error={}", method, e.getMessage()); } // 记录方法调用 if (sipMetrics != null) { sipMetrics.recordMethodCall(method); } List<SipRequestProcessor> sipRequestProcessors = REQUEST_PROCESSOR_MAP.get(method); if (CollectionUtils.isEmpty(sipRequestProcessors)) { log.warn("暂不支持方法 {} 的请求", method); if (sipMetrics != null) { sipMetrics.recordError("UNSUPPORTED_METHOD", method); } // 调用子类自定义处理 handleUnsupportedRequest(requestEvent); return; } // 对于需要事务的请求方法,立即创建服务器事务 if (shouldCreateTransaction(method)) { try { serverTransaction = requestEvent.getServerTransaction(); if (serverTransaction == null) { SipProvider sipProvider = (SipProvider) requestEvent.getSource(); serverTransaction = sipProvider.getNewServerTransaction(requestEvent.getRequest()); log.debug("为方法 {} 创建服务器事务: {}", method, serverTransaction); } } catch (TransactionAlreadyExistsException e) { // 事务已存在,重新获取现有事务 log.debug("事务已存在,使用现有事务: {}", e.getMessage()); try { serverTransaction = requestEvent.getServerTransaction(); if (serverTransaction != null) { log.debug("成功获取现有服务器事务: {}", serverTransaction); } else { log.warn("获取现有服务器事务失败,事务为null"); } } catch (Exception ex) { log.warn("重新获取现有事务时发生异常: {}", ex.getMessage()); serverTransaction = null; } } catch (TransactionUnavailableException e) { log.warn("事务不可用,方法 {}: {}", method, e.getMessage()); serverTransaction = null; } catch (Exception e) { log.warn("为方法 {} 创建服务器事务时发生未知异常: {}", method, e.getMessage()); // 尝试获取现有事务作为回退策略 try { serverTransaction = requestEvent.getServerTransaction(); if (serverTransaction != null) { log.debug("回退策略成功,使用现有事务: {}", serverTransaction); } } catch (Exception ex) { log.warn("回退策略失败: {}", ex.getMessage()); serverTransaction = null; } } } // 同步处理请求,传入预创建的事务 for (SipRequestProcessor sipRequestProcessor : sipRequestProcessors) { // 使用新的重载方法,支持传入服务器事务 sipRequestProcessor.process(requestEvent, serverTransaction); } if (sipMetrics != null) { sipMetrics.recordMessageProcessed(); } } catch (Exception e) { log.error("processRequest::requestEvent = {} ", requestEvent, e); if (sipMetrics != null) { sipMetrics.recordError("PROCESSING_ERROR", method); sipMetrics.recordMessageProcessed(method, "ERROR"); } // 调用子类异常处理 handleRequestException(requestEvent, e); } finally { // 清理SIP事务上下文,避免内存泄漏 try { SipTransactionContext.clear(); log.debug("清理SIP事务上下文: method={}, thread={}", method, Thread.currentThread().getName()); } catch (Exception e) { log.warn("清理SIP事务上下文失败: method={}, error={}", method, e.getMessage()); } if (sipMetrics != null && sample != null) { sipMetrics.recordRequestProcessingTime(sample); } } } /** * 分发ResponseEvent事件 - 基础实现 * * @param responseEvent responseEvent事件 */ @Override public void processResponse(ResponseEvent responseEvent) { // 测试钩子:捕获401 REGISTER响应 Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; Response response = responseEvent.getResponse(); int status = response.getStatusCode(); try { // Success if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) { CSeqHeader cseqHeader = (CSeqHeader) responseEvent.getResponse().getHeader(CSeqHeader.NAME); String method = cseqHeader.getMethod(); if (sipMetrics != null) { sipMetrics.recordMethodCall(method + "_RESPONSE"); } List<SipResponseProcessor> sipResponseProcessors = RESPONSE_PROCESSOR_MAP.get(method); if (CollectionUtils.isNotEmpty(sipResponseProcessors)) { for (SipResponseProcessor sipResponseProcessor : sipResponseProcessors) { if (sipResponseProcessor.isNeedProcess(responseEvent)) { sipResponseProcessor.process(responseEvent); } } } if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && SipSubscribe.getOkSubscribesSize() > 0) { SipSubscribe.publishOkEvent(responseEvent); } if (sipMetrics != null) { sipMetrics.recordMessageProcessed("RESPONSE", "SUCCESS"); } } else if ((status >= Response.TRYING) && (status < Response.OK)) { // 增加其它无需回复的响应,如101、180等 if (sipMetrics != null) { sipMetrics.recordMessageProcessed("RESPONSE", "PROVISIONAL"); } } else { log.warn("接收到失败的response响应!status:" + status + ",message:" + response.getReasonPhrase() + " response = {}", responseEvent.getResponse()); if (sipMetrics != null) { sipMetrics.recordError("FAILED_RESPONSE", String.valueOf(status)); } if (responseEvent.getResponse() != null && SipSubscribe.getErrorSubscribesSize() > 0) { CallIdHeader callIdHeader = (CallIdHeader) responseEvent.getResponse().getHeader(CallIdHeader.NAME); if (callIdHeader != null) { Event subscribe = SipSubscribe.getErrorSubscribe(callIdHeader.getCallId()); if (subscribe != null) { EventResult eventResult = new EventResult(responseEvent); subscribe.response(eventResult); SipSubscribe.removeErrorSubscribe(callIdHeader.getCallId()); } } } if (responseEvent.getDialog() != null) { responseEvent.getDialog().delete(); } if (sipMetrics != null) { sipMetrics.recordMessageProcessed("RESPONSE", "ERROR"); } } } catch (Exception e) { log.error("processResponse error", e); if (sipMetrics != null) { sipMetrics.recordError("RESPONSE_PROCESSING_ERROR", String.valueOf(status)); } // 调用子类异常处理 handleResponseException(responseEvent, e); } finally { if (sipMetrics != null && sample != null) { sipMetrics.recordResponseProcessingTime(sample); } } } /** * 向超时订阅发送消息 - 基础实现 * * @param timeoutEvent timeoutEvent事件 */ @Override public void processTimeout(TimeoutEvent timeoutEvent) { Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; ClientTransaction clientTransaction = timeoutEvent.getClientTransaction(); if (clientTransaction == null) { return; } Request request = clientTransaction.getRequest(); if (request == null) { return; } try { CSeqHeader cseqHeader = (CSeqHeader) request.getHeader(CSeqHeader.NAME); String method = cseqHeader.getMethod(); if (sipMetrics != null) { sipMetrics.recordMethodCall(method + "_TIMEOUT"); } List<ITimeoutProcessor> timeoutProcessors = TIMEOUT_PROCESSOR_MAP.get(method); if (CollectionUtils.isNotEmpty(timeoutProcessors)) { for (ITimeoutProcessor timeoutProcessor : timeoutProcessors) { timeoutProcessor.process(timeoutEvent); } } CallIdHeader callIdHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME); if (callIdHeader != null) { Event subscribe = SipSubscribe.getErrorSubscribe(callIdHeader.getCallId()); EventResult eventResult = new EventResult(timeoutEvent); if (subscribe != null) { subscribe.response(eventResult); } SipSubscribe.removeOkSubscribe(callIdHeader.getCallId()); SipSubscribe.removeErrorSubscribe(callIdHeader.getCallId()); } if (sipMetrics != null) { sipMetrics.recordMessageProcessed("TIMEOUT", "SUCCESS"); } } catch (Exception e) { log.error("processTimeout error", e); if (sipMetrics != null) { sipMetrics.recordError("TIMEOUT_PROCESSING_ERROR", "TIMEOUT"); } } finally { if (sipMetrics != null && sample != null) { sipMetrics.recordTimeoutProcessingTime(sample); } } } @Override public void processIOException(IOExceptionEvent exceptionEvent) { log.error("processIOException::exceptionEvent = {} ", JSON.toJSONString(exceptionEvent)); // 调用子类异常处理 handleIOException(exceptionEvent); } /** * 事物结束 - 基础实现 * * @param timeoutEvent -- an event that indicates that the * transaction has transitioned into the terminated state. */ @Override public void processTransactionTerminated(TransactionTerminatedEvent timeoutEvent) { EventResult eventResult = new EventResult(timeoutEvent); Event timeOutSubscribe = SipSubscribe.getErrorSubscribe(eventResult.getCallId()); if (timeOutSubscribe != null) { timeOutSubscribe.response(eventResult); } } /** * 会话结束 - 基础实现 * * @param dialogTerminatedEvent -- an event that indicates that the * dialog has transitioned into the terminated state. */ @Override public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { EventResult eventResult = new EventResult(dialogTerminatedEvent); Event timeOutSubscribe = SipSubscribe.getErrorSubscribe(eventResult.getCallId()); if (timeOutSubscribe != null) { timeOutSubscribe.response(eventResult); } } /** * 判断是否需要为特定方法创建服务器事务 * * @param method SIP方法名 * @return 是否需要创建事务 */ protected boolean shouldCreateTransaction(String method) { // MESSAGE、INFO、NOTIFY等需要响应的方法需要事务支持 // ACK方法通常不需要服务器事务 return !"ACK".equals(method); } // ==================== 子类可重写的方法 ==================== /** * 处理不支持的请求(子类可重写) * * @param requestEvent 请求事件 */ protected void handleUnsupportedRequest(RequestEvent requestEvent) { // 默认实现为空,子类可重写 } /** * 处理请求异常(子类可重写) * * @param requestEvent 请求事件 * @param exception 异常 */ protected void handleRequestException(RequestEvent requestEvent, Exception exception) { // 默认实现为空,子类可重写 } /** * 处理响应异常(子类可重写) * * @param responseEvent 响应事件 * @param exception 异常 */ protected void handleResponseException(ResponseEvent responseEvent, Exception exception) { // 默认实现为空,子类可重写 } /** * 处理IO异常(子类可重写) * * @param exceptionEvent IO异常事件 */ protected void handleIOException(IOExceptionEvent exceptionEvent) { // 默认实现为空,子类可重写 } /** * 获取处理器统计信息 * * @return 统计信息 */ public String getProcessorStats() { int requestProcessorCount = REQUEST_PROCESSOR_MAP.values().stream() .mapToInt(List::size) .sum(); int responseProcessorCount = RESPONSE_PROCESSOR_MAP.values().stream() .mapToInt(List::size) .sum(); int timeoutProcessorCount = TIMEOUT_PROCESSOR_MAP.values().stream() .mapToInt(List::size) .sum(); return String.format("RequestProcessors: %d (methods: %d), ResponseProcessors: %d (methods: %d), TimeoutProcessors: %d (methods: %d)", requestProcessorCount, REQUEST_PROCESSOR_MAP.size(), responseProcessorCount, RESPONSE_PROCESSOR_MAP.size(), timeoutProcessorCount, TIMEOUT_PROCESSOR_MAP.size()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/AsyncSipListener.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/AsyncSipListener.java
package io.github.lunasaw.sip.common.transmit; import io.github.lunasaw.sip.common.utils.TraceUtils; import io.micrometer.core.instrument.Timer; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import javax.sip.*; import javax.sip.message.Response; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * 异步SIP监听器 * 继承AbstractSipListener,提供异步消息处理能力 * 使用本地创建的默认线程池实现高性能消息处理 * * @author luna */ @Setter @Getter @Slf4j public abstract class AsyncSipListener extends AbstractSipListener { private ThreadPoolTaskExecutor messageExecutor; public AsyncSipListener() { // 创建本地默认线程池 this.messageExecutor = createDefaultThreadPool(); log.info("AsyncSipListener初始化完成,使用本地默认线程池"); } /** * 创建默认线程池 * 使用本地创建的线程池,不依赖Spring注入 * 注意:方法为protected以支持测试时通过反射调用(CGLIB代理需要) * * @return 默认线程池 */ protected ThreadPoolTaskExecutor createDefaultThreadPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置线程池参数 executor.setCorePoolSize(10); executor.setMaxPoolSize(50); executor.setQueueCapacity(1000); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("async-sip-"); executor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy()); // 自定义线程工厂 executor.setThreadFactory(new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "async-sip-" + threadNumber.getAndIncrement()); thread.setDaemon(false); thread.setPriority(Thread.NORM_PRIORITY); return thread; } }); // 初始化线程池 executor.initialize(); log.info("创建本地默认线程池: coreSize={}, maxSize={}, queueCapacity={}", executor.getCorePoolSize(), executor.getMaxPoolSize(), executor.getQueueCapacity()); return executor; } /** * 异步处理RequestEvent事件 * 重写父类方法,提供异步处理能力 * * @param requestEvent RequestEvent事件 */ @Override public void processRequest(RequestEvent requestEvent) { Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; String method = requestEvent.getRequest().getMethod(); try { // 记录方法调用 if (sipMetrics != null) { sipMetrics.recordMethodCall(method); } log.debug("异步处理SIP请求: method={}", method); String traceId = TraceUtils.getTraceId(); // 异步调用父类的同步处理逻辑 messageExecutor.execute(() -> { try { TraceUtils.setTraceId(traceId); // 调用父类的processRequest方法进行实际处理 super.processRequest(requestEvent); if (sipMetrics != null) { sipMetrics.recordMessageProcessed(method, "ASYNC_SUCCESS"); } } catch (Exception e) { log.error("异步处理请求失败: method={}", method, e); if (sipMetrics != null) { sipMetrics.recordError("ASYNC_PROCESSING_ERROR", method); sipMetrics.recordMessageProcessed(method, "ASYNC_ERROR"); } // 调用子类异常处理 handleRequestException(requestEvent, e); } finally { TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("异步处理请求异常: method={}", method, e); if (sipMetrics != null) { sipMetrics.recordError("ASYNC_DISPATCH_ERROR", method); sipMetrics.recordMessageProcessed(method, "ASYNC_DISPATCH_ERROR"); } // 调用子类异常处理 handleRequestException(requestEvent, e); } finally { if (sipMetrics != null && sample != null) { sipMetrics.recordRequestProcessingTime(sample); } TraceUtils.clearTraceId(); } } /** * 异步处理ResponseEvent事件 * 重写父类方法,提供异步处理能力 * * @param responseEvent ResponseEvent事件 */ @Override @Async("sipMessageProcessor") public void processResponse(ResponseEvent responseEvent) { Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; Response response = responseEvent.getResponse(); int status = response.getStatusCode(); try { // 记录方法调用 if (sipMetrics != null) { sipMetrics.recordMethodCall("RESPONSE_" + status); } log.debug("异步处理SIP响应: status={}", status); String traceId = TraceUtils.getTraceId(); // 异步调用父类的同步处理逻辑 messageExecutor.execute(() -> { try { TraceUtils.setTraceId(traceId); // 调用父类的processResponse方法进行实际处理 super.processResponse(responseEvent); if (sipMetrics != null) { sipMetrics.recordMessageProcessed("RESPONSE", "ASYNC_SUCCESS"); } } catch (Exception e) { log.error("异步处理响应失败: status={}", status, e); if (sipMetrics != null) { sipMetrics.recordError("ASYNC_RESPONSE_ERROR", String.valueOf(status)); sipMetrics.recordMessageProcessed("RESPONSE", "ASYNC_ERROR"); } // 调用子类异常处理 handleResponseException(responseEvent, e); } finally { TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("异步处理响应异常: status={}", status, e); if (sipMetrics != null) { sipMetrics.recordError("ASYNC_RESPONSE_DISPATCH_ERROR", String.valueOf(status)); sipMetrics.recordMessageProcessed("RESPONSE", "ASYNC_DISPATCH_ERROR"); } // 调用子类异常处理 handleResponseException(responseEvent, e); } finally { if (sipMetrics != null && sample != null) { sipMetrics.recordResponseProcessingTime(sample); } TraceUtils.clearTraceId(); } } /** * 异步处理TimeoutEvent事件 * 重写父类方法,提供异步处理能力 * * @param timeoutEvent TimeoutEvent事件 */ @Override @Async("sipMessageProcessor") public void processTimeout(TimeoutEvent timeoutEvent) { try { log.debug("异步处理SIP超时事件"); String traceId = TraceUtils.getTraceId(); // 异步调用父类的同步处理逻辑 messageExecutor.execute(() -> { try { TraceUtils.setTraceId(traceId); // 调用父类的processTimeout方法进行实际处理 super.processTimeout(timeoutEvent); } catch (Exception e) { log.error("异步处理超时事件失败", e); } finally { TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("异步处理超时事件异常", e); } finally { TraceUtils.clearTraceId(); } } /** * 异步处理IOExceptionEvent事件 * 重写父类方法,提供异步处理能力 * * @param exceptionEvent IOExceptionEvent事件 */ @Override @Async("sipMessageProcessor") public void processIOException(IOExceptionEvent exceptionEvent) { try { log.debug("异步处理SIP IO异常事件"); String traceId = TraceUtils.getTraceId(); // 异步调用父类的同步处理逻辑 messageExecutor.execute(() -> { try { TraceUtils.setTraceId(traceId); // 调用父类的processIOException方法进行实际处理 super.processIOException(exceptionEvent); } catch (Exception e) { log.error("异步处理IO异常事件失败", e); } finally { TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("异步处理IO异常事件异常", e); } finally { TraceUtils.clearTraceId(); } } /** * 异步处理TransactionTerminatedEvent事件 * 重写父类方法,提供异步处理能力 * * @param timeoutEvent TransactionTerminatedEvent事件 */ @Override @Async("sipMessageProcessor") public void processTransactionTerminated(TransactionTerminatedEvent timeoutEvent) { try { log.debug("异步处理SIP事务终止事件"); String traceId = TraceUtils.getTraceId(); // 异步调用父类的同步处理逻辑 messageExecutor.execute(() -> { try { TraceUtils.setTraceId(traceId); // 调用父类的processTransactionTerminated方法进行实际处理 super.processTransactionTerminated(timeoutEvent); } catch (Exception e) { log.error("异步处理事务终止事件失败", e); } finally { TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("异步处理事务终止事件异常", e); } finally { TraceUtils.clearTraceId(); } } /** * 异步处理DialogTerminatedEvent事件 * 重写父类方法,提供异步处理能力 * * @param dialogTerminatedEvent DialogTerminatedEvent事件 */ @Override @Async("sipMessageProcessor") public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { try { log.debug("异步处理SIP会话终止事件"); String traceId = TraceUtils.getTraceId(); // 异步调用父类的同步处理逻辑 messageExecutor.execute(() -> { try { TraceUtils.setTraceId(traceId); // 调用父类的processDialogTerminated方法进行实际处理 super.processDialogTerminated(dialogTerminatedEvent); } catch (Exception e) { log.error("异步处理会话终止事件失败", e); } finally { TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("异步处理会话终止事件异常", e); } finally { TraceUtils.clearTraceId(); } } /** * 获取异步监听器统计信息 * * @return 统计信息 */ @Override public String getProcessorStats() { return String.format("AsyncSipListener[%s, ThreadPoolSize=%d, ActiveThreads=%d]", super.getProcessorStats(), messageExecutor.getPoolSize(), messageExecutor.getActiveCount()); } /** * 销毁线程池资源 * 在应用关闭时调用,确保资源正确释放 */ public void destroy() { if (messageExecutor != null) { log.info("销毁AsyncSipListener本地线程池"); messageExecutor.shutdown(); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipTransactionContext.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipTransactionContext.java
package io.github.lunasaw.sip.common.transmit; import io.github.lunasaw.sip.common.entity.SipTransaction; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.skywalking.apm.toolkit.trace.TraceContext; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; import javax.sip.TransactionState; import javax.sip.message.Request; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * SIP事务上下文管理器 * 提供线程安全的事务信息传递和管理能力 * * @author luna */ @Slf4j public class SipTransactionContext { /** * 事务上下文存储 * Key: CallId + FromTag + CSeq * Value: 事务上下文信息 */ public static final ConcurrentHashMap<String, TransactionContextInfo> TRANSACTION_CONTEXTS = new ConcurrentHashMap<>(); /** * 读写锁保护事务操作 */ private static final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); /** * 线程本地存储当前事务上下文 */ private static final ThreadLocal<TransactionContextInfo> CURRENT_CONTEXT = new ThreadLocal<>(); /** * * 事务上下文信息 */ @Data public static class TransactionContextInfo { private final String contextKey; private final SipTransaction sipTransaction; private final ServerTransaction serverTransaction; private final RequestEvent originalEvent; private final Request originalRequest; private final String traceId; private final long createTime; private volatile TransactionState lastKnownState; private volatile boolean isValid = true; public TransactionContextInfo(RequestEvent requestEvent, ServerTransaction serverTransaction) { this.originalEvent = requestEvent; this.originalRequest = requestEvent.getRequest(); this.serverTransaction = serverTransaction; this.contextKey = generateContextKey(originalRequest); this.sipTransaction = extractSipTransaction(originalRequest); this.traceId = TraceContext.traceId(); this.createTime = System.currentTimeMillis(); this.lastKnownState = serverTransaction != null ? serverTransaction.getState() : null; } /** * 检查事务是否仍然有效 */ public boolean checkAndUpdateValidity() { if (!isValid) { return false; } if (serverTransaction != null) { TransactionState currentState = serverTransaction.getState(); this.lastKnownState = currentState; // 检查事务状态是否有效 if (currentState == TransactionState.TERMINATED || currentState == TransactionState.COMPLETED) { this.isValid = false; log.debug("事务状态无效: contextKey={}, state={}", contextKey, currentState); return false; } // 检查事务超时(SIP标准32秒) long age = System.currentTimeMillis() - createTime; if (age > 32000) { this.isValid = false; log.debug("事务超时: contextKey={}, age={}ms", contextKey, age); return false; } } return isValid; } /** * 手动标记事务为无效 */ public void invalidate() { this.isValid = false; } } /** * 创建并存储事务上下文 */ public static TransactionContextInfo createContext(RequestEvent requestEvent, ServerTransaction serverTransaction) { TransactionContextInfo context = new TransactionContextInfo(requestEvent, serverTransaction); rwLock.writeLock().lock(); try { TRANSACTION_CONTEXTS.put(context.getContextKey(), context); CURRENT_CONTEXT.set(context); log.debug("创建事务上下文: key={}, traceId={}", context.getContextKey(), context.getTraceId()); return context; } finally { rwLock.writeLock().unlock(); } } /** * 获取事务上下文 */ public static TransactionContextInfo getContext(String contextKey) { rwLock.readLock().lock(); try { TransactionContextInfo context = TRANSACTION_CONTEXTS.get(contextKey); if (context != null && !context.checkAndUpdateValidity()) { // 如果上下文无效,移除它 removeContext(contextKey); return null; } return context; } finally { rwLock.readLock().unlock(); } } /** * 获取当前线程的事务上下文 */ public static TransactionContextInfo getCurrentContext() { TransactionContextInfo context = CURRENT_CONTEXT.get(); if (context != null && !context.checkAndUpdateValidity()) { CURRENT_CONTEXT.remove(); return null; } return context; } /** * 设置当前线程的事务上下文 */ public static void setCurrentContext(TransactionContextInfo context) { CURRENT_CONTEXT.set(context); } /** * 传递事务上下文到新线程 */ public static void propagateContextToThread(String contextKey) { TransactionContextInfo context = getContext(contextKey); if (context != null) { CURRENT_CONTEXT.set(context); // 传递TraceId if (context.getTraceId() != null) { try { // 这里可以设置TraceContext,具体实现依赖于你的链路追踪框架 log.debug("传递事务上下文到线程: key={}, traceId={}", contextKey, context.getTraceId()); } catch (Exception e) { log.warn("传递TraceId失败: {}", e.getMessage()); } } } } /** * 移除事务上下文 */ public static void removeContext(String contextKey) { rwLock.writeLock().lock(); try { TransactionContextInfo removed = TRANSACTION_CONTEXTS.remove(contextKey); if (removed != null) { removed.invalidate(); log.debug("移除事务上下文: key={}", contextKey); } } finally { rwLock.writeLock().unlock(); } } /** * 清理当前线程的上下文 */ public static void clearCurrentContext() { CURRENT_CONTEXT.remove(); } /** * 清理过期的事务上下文 */ public static void cleanupExpiredContexts() { rwLock.writeLock().lock(); try { long now = System.currentTimeMillis(); TRANSACTION_CONTEXTS.entrySet().removeIf(entry -> { TransactionContextInfo context = entry.getValue(); // 清理超过5分钟的上下文 if (now - context.getCreateTime() > 300000 || !context.checkAndUpdateValidity()) { context.invalidate(); log.debug("清理过期事务上下文: key={}", entry.getKey()); return true; } return false; }); } finally { rwLock.writeLock().unlock(); } } /** * 获取事务上下文统计信息 */ public static String getContextStats() { rwLock.readLock().lock(); try { int total = TRANSACTION_CONTEXTS.size(); long valid = TRANSACTION_CONTEXTS.values().stream() .mapToLong(ctx -> ctx.checkAndUpdateValidity() ? 1 : 0) .sum(); return String.format("总上下文数: %d, 有效上下文数: %d", total, valid); } finally { rwLock.readLock().unlock(); } } /** * 生成上下文键 */ private static String generateContextKey(Request request) { try { String callId = request.getHeader("Call-ID").toString().split(":")[1].trim(); String fromTag = null; String cseq = request.getHeader("CSeq").toString().split(":")[1].trim(); // 尝试获取From标签 String fromHeader = request.getHeader("From").toString(); if (fromHeader.contains("tag=")) { fromTag = fromHeader.substring(fromHeader.indexOf("tag=") + 4); int semicolon = fromTag.indexOf(';'); if (semicolon != -1) { fromTag = fromTag.substring(0, semicolon); } } return callId + "_" + (fromTag != null ? fromTag : "notag") + "_" + cseq; } catch (Exception e) { log.warn("生成上下文键失败,使用默认键: {}", e.getMessage()); return "unknown_" + System.currentTimeMillis(); } } /** * 提取SIP事务信息 */ private static SipTransaction extractSipTransaction(Request request) { SipTransaction transaction = new SipTransaction(); try { // 提取Call-ID String callIdHeader = request.getHeader("Call-ID").toString(); if (callIdHeader.contains(":")) { transaction.setCallId(callIdHeader.split(":", 2)[1].trim()); } // 提取From Tag String fromHeader = request.getHeader("From").toString(); if (fromHeader.contains("tag=")) { String fromTag = fromHeader.substring(fromHeader.indexOf("tag=") + 4); int semicolon = fromTag.indexOf(';'); if (semicolon != -1) { fromTag = fromTag.substring(0, semicolon); } transaction.setFromTag(fromTag); } // 提取To Tag (如果存在) String toHeader = request.getHeader("To").toString(); if (toHeader.contains("tag=")) { String toTag = toHeader.substring(toHeader.indexOf("tag=") + 4); int semicolon = toTag.indexOf(';'); if (semicolon != -1) { toTag = toTag.substring(0, semicolon); } transaction.setToTag(toTag); } // 提取Via Branch String viaHeader = request.getHeader("Via").toString(); if (viaHeader.contains("branch=")) { String viaBranch = viaHeader.substring(viaHeader.indexOf("branch=") + 7); int semicolon = viaBranch.indexOf(';'); if (semicolon != -1) { viaBranch = viaBranch.substring(0, semicolon); } transaction.setViaBranch(viaBranch); } } catch (Exception e) { log.warn("提取SIP事务信息失败: {}", e.getMessage()); } return transaction; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipMessageTransmitter.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipMessageTransmitter.java
package io.github.lunasaw.sip.common.transmit; import gov.nist.javax.sip.SipProviderImpl; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.SipSubscribe; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import lombok.extern.slf4j.Slf4j; import javax.sip.SipException; import javax.sip.header.CallIdHeader; import javax.sip.header.UserAgentHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Message; import javax.sip.message.Request; import javax.sip.message.Response; /** * SIP消息传输器 * 负责SIP消息的传输和事件订阅管理 * * @author lin */ @Slf4j public class SipMessageTransmitter { /** * 传输消息 * * @param ip 目标IP * @param message 消息 */ public static void transmitMessage(String ip, Message message) { transmitMessage(ip, message, null, null); } /** * 传输消息(带错误事件) * * @param ip 目标IP * @param message 消息 * @param errorEvent 错误事件 */ public static void transmitMessage(String ip, Message message, Event errorEvent) { transmitMessage(ip, message, errorEvent, null); } /** * 传输消息(带成功事件) * * @param ip 目标IP * @param message 消息 * @param okEvent 成功事件 */ public static void transmitMessageSuccess(String ip, Message message, Event okEvent) { transmitMessage(ip, message, null, okEvent); } /** * 传输消息(带事件处理) * * @param ip 目标IP * @param message 消息 * @param errorEvent 错误事件 * @param okEvent 成功事件 */ public static void transmitMessage(String ip, Message message, Event errorEvent, Event okEvent) { // 预处理消息 preprocessMessage(message); // 设置事件订阅 setupEventSubscriptions(message, errorEvent, okEvent); // 发送消息 sendMessage(ip, message); } /** * 预处理消息 * * @param message 消息 */ private static void preprocessMessage(Message message) { // 添加User-Agent头 if (message.getHeader(UserAgentHeader.NAME) == null) { message.addHeader(SipRequestUtils.createUserAgentHeader(Constant.AGENT)); } } /** * 设置事件订阅 * * @param message 消息 * @param errorEvent 错误事件 * @param okEvent 成功事件 */ private static void setupEventSubscriptions(Message message, Event errorEvent, Event okEvent) { CallIdHeader callIdHeader = (CallIdHeader)message.getHeader(CallIdHeader.NAME); if (callIdHeader == null) { return; } // 添加错误订阅 if (errorEvent != null) { SipSubscribe.addErrorSubscribe(callIdHeader.getCallId(), (eventResult -> { errorEvent.response(eventResult); SipSubscribe.removeErrorSubscribe(eventResult.getCallId()); SipSubscribe.removeOkSubscribe(eventResult.getCallId()); })); } // 添加成功订阅 if (okEvent != null) { SipSubscribe.addOkSubscribe(callIdHeader.getCallId(), eventResult -> { okEvent.response(eventResult); SipSubscribe.removeOkSubscribe(eventResult.getCallId()); SipSubscribe.removeErrorSubscribe(eventResult.getCallId()); }); } } /** * 发送消息 * * @param ip 目标IP * @param message 消息 */ private static void sendMessage(String ip, Message message) { String transport = getTransport(message); try { if (Constant.TCP.equalsIgnoreCase(transport)) { sendTcpMessage(ip, message); } else if (Constant.UDP.equalsIgnoreCase(transport)) { sendUdpMessage(ip, message); } } catch (SipException e) { log.error("发送SIP消息失败", e); throw new RuntimeException("发送SIP消息失败", e); } } /** * 发送TCP消息 * * @param ip 目标IP * @param message 消息 * @throws SipException SIP异常 */ private static void sendTcpMessage(String ip, Message message) throws SipException { SipProviderImpl tcpSipProvider = SipLayer.getTcpSipProvider(ip); if (tcpSipProvider == null) { log.error("[发送信息失败] 未找到tcp://{}的监听信息", ip); return; } if (message instanceof Request) { tcpSipProvider.sendRequest((Request)message); } else if (message instanceof Response) { tcpSipProvider.sendResponse((Response)message); } } /** * 发送UDP消息 * * @param ip 目标IP * @param message 消息 * @throws SipException SIP异常 */ private static void sendUdpMessage(String ip, Message message) throws SipException { SipProviderImpl sipProvider = SipLayer.getUdpSipProvider(ip); if (sipProvider == null) { log.error("[发送信息失败] 未找到udp://{}的监听信息", ip); return; } if (message instanceof Request) { sipProvider.sendRequest((Request)message); } else if (message instanceof Response) { sipProvider.sendResponse((Response)message); } } /** * 获取传输协议 * * @param message 消息 * @return 传输协议 */ private static String getTransport(Message message) { ViaHeader viaHeader = (ViaHeader)message.getHeader(ViaHeader.NAME); String transport = "UDP"; if (viaHeader == null) { log.warn("[消息头缺失]: ViaHeader, 使用默认的UDP方式处理数据"); } else { transport = viaHeader.getTransport(); } return transport; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipTransactionManager.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipTransactionManager.java
package io.github.lunasaw.sip.common.transmit; import gov.nist.javax.sip.SipProviderImpl; import gov.nist.javax.sip.SipStackImpl; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.stack.SIPServerTransaction; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.layer.SipLayer; import lombok.extern.slf4j.Slf4j; import javax.sip.ServerTransaction; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import java.util.Objects; /** * SIP事务管理器 * 负责SIP事务的创建和管理 * * @author lin */ @Slf4j public class SipTransactionManager { /** * 获取服务器事务 * * @param request 请求 * @return 服务器事务 */ public static ServerTransaction getServerTransaction(Request request) { return getServerTransaction(request, SipLayer.getMonitorIp()); } /** * 根据请求获取服务器事务 * * @param request 请求 * @param ip 监听IP * @return 服务器事务 */ public static ServerTransaction getServerTransaction(Request request, String ip) { // 检查是否正在关闭 if (SipLayer.isShuttingDown()) { log.debug("服务正在关闭,跳过事务创建"); return null; } if (ip == null) { ip = SipLayer.getMonitorIp(); } String transport = getTransport(request); boolean isTcp = Constant.TCP.equalsIgnoreCase(transport); try { ServerTransaction serverTransaction = null; if (isTcp) { SipProviderImpl sipProvider = SipLayer.getTcpSipProvider(ip); if (sipProvider == null) { log.warn("[发送信息失败] 未找到tcp://{}的监听信息,可能服务正在关闭", ip); return null; } SipStackImpl stack = (SipStackImpl)sipProvider.getSipStack(); serverTransaction = (SIPServerTransaction)stack.findTransaction((SIPRequest)request, true); if (serverTransaction == null) { serverTransaction = sipProvider.getNewServerTransaction(request); } } else { SipProviderImpl udpSipProvider = SipLayer.getUdpSipProvider(ip); if (udpSipProvider == null) { log.warn("[发送信息失败] 未找到udp://{}的监听信息,可能服务正在关闭", ip); return null; } SipStackImpl stack = (SipStackImpl)udpSipProvider.getSipStack(); serverTransaction = (SIPServerTransaction)stack.findTransaction((SIPRequest)request, true); if (serverTransaction == null) { serverTransaction = udpSipProvider.getNewServerTransaction(request); } } return serverTransaction; } catch (Exception e) { log.error("获取服务器事务失败", e); // 返回null而不是抛出异常,让调用者处理 return null; } } /** * 获取传输协议 * * @param request 请求 * @return 传输协议 */ private static String getTransport(Request request) { ViaHeader viaHeader = (ViaHeader)request.getHeader(ViaHeader.NAME); String transport = "UDP"; if (viaHeader == null) { log.warn("[消息头缺失]: ViaHeader, 使用默认的UDP方式处理数据"); } else { transport = viaHeader.getTransport(); } return transport; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/DefaultSipListener.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/DefaultSipListener.java
package io.github.lunasaw.sip.common.transmit; import io.github.lunasaw.sip.common.metrics.SipMetrics; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; /** * 默认SIP监听器 * 继承AsyncSipListener,使用Spring传入的线程池 * 作为Spring管理的Bean,支持依赖注入和配置管理 * * @author luna */ @Slf4j @Component @NoArgsConstructor public class DefaultSipListener extends AsyncSipListener { /** * 构造函数 * 使用Spring传入的线程池和SIP指标收集器 * * @param messageExecutor Spring管理的线程池执行器 * @param sipMetrics SIP指标收集器 */ public DefaultSipListener(@Qualifier("sipMessageProcessor") ThreadPoolTaskExecutor messageExecutor, SipMetrics sipMetrics) { if (messageExecutor != null) { setMessageExecutor(messageExecutor); } if (sipMetrics != null) { setSipMetrics(sipMetrics); } } /** * 设置消息执行器 * 覆盖父类的本地线程池,使用Spring管理的线程池 * * @param messageExecutor Spring管理的线程池执行器 */ @Override public void setMessageExecutor(ThreadPoolTaskExecutor messageExecutor) { try { log.info("成功设置Spring线程池: coreSize={}, maxSize={}, queueCapacity={}", messageExecutor.getCorePoolSize(), messageExecutor.getMaxPoolSize(), messageExecutor.getQueueCapacity()); super.setMessageExecutor(messageExecutor); } catch (Exception e) { log.error("设置Spring线程池失败", e); throw new RuntimeException("设置Spring线程池失败", e); } } /** * 获取默认监听器统计信息 * * @return 统计信息 */ @Override public String getProcessorStats() { return String.format("DefaultSipListener[%s]", super.getProcessorStats()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/ResponseCmd.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/ResponseCmd.java
package io.github.lunasaw.sip.common.transmit; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; import javax.sip.address.SipURI; import javax.sip.header.*; import javax.sip.message.Request; import javax.sip.message.Response; import gov.nist.javax.sip.header.CallID; import gov.nist.javax.sip.header.CallInfo; import org.apache.commons.lang3.StringUtils; import com.luna.common.check.Assert; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import io.github.lunasaw.sip.common.context.SipTransactionContext; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * SIP响应命令构建器(重构版) * 使用建造者模式提供流式API,支持事务和非事务响应 * * @author luna * @date 2023/10/19 */ @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ResponseCmd { /** * SIP响应构建器 * 提供流式API来构建和发送SIP响应 */ public static class SipResponseBuilder { private final int statusCode; private String phrase; private String content; private ContentTypeHeader contentTypeHeader; private List<Header> headers = new ArrayList<>(); private RequestEvent requestEvent; private Request request; private ServerTransaction serverTransaction; private String ip; private boolean useTransaction = true; public SipResponseBuilder(int statusCode) { this.statusCode = statusCode; } /** * 设置响应短语 */ public SipResponseBuilder phrase(String phrase) { this.phrase = phrase; return this; } /** * 设置响应内容 */ public SipResponseBuilder content(String content) { this.content = content; return this; } /** * 设置内容类型 */ public SipResponseBuilder contentType(ContentTypeHeader contentTypeHeader) { this.contentTypeHeader = contentTypeHeader; return this; } /** * 添加响应头 */ public SipResponseBuilder header(Header header) { this.headers.add(header); return this; } /** * 添加多个响应头 */ public SipResponseBuilder headers(Header... headers) { this.headers.addAll(Arrays.asList(headers)); return this; } /** * 添加响应头列表 */ public SipResponseBuilder headers(List<Header> headers) { this.headers.addAll(headers); return this; } /** * 设置请求事件 */ public SipResponseBuilder requestEvent(RequestEvent requestEvent) { this.requestEvent = requestEvent; this.request = requestEvent.getRequest(); return this; } /** * 设置请求 */ public SipResponseBuilder request(Request request) { this.request = request; return this; } /** * 设置服务器事务 */ public SipResponseBuilder serverTransaction(ServerTransaction serverTransaction) { this.serverTransaction = serverTransaction; return this; } /** * 设置IP地址 */ public SipResponseBuilder ip(String ip) { this.ip = ip; return this; } /** * 设置是否使用事务 */ public SipResponseBuilder useTransaction(boolean useTransaction) { this.useTransaction = useTransaction; return this; } /** * 构建并发送响应 */ public void send() { try { Response response = buildResponse(); if (useTransaction) { sendWithTransaction(response); } else { sendWithoutTransaction(response); } } catch (Exception e) { log.error("发送SIP响应失败: statusCode={}, phrase={}", statusCode, phrase, e); throw new RuntimeException("发送SIP响应失败", e); } } /** * 构建响应对象 */ public Response buildResponse() { try { Assert.notNull(request, "请求不能为null"); Response response = SipRequestUtils.createResponse(statusCode, request); if (StringUtils.isNotBlank(phrase)) { response.setReasonPhrase(phrase); } if (StringUtils.isNotBlank(content)) { response.setContent(content, contentTypeHeader); } SipRequestUtils.setResponseHeader(response, headers); // 确保响应使用与原请求相同的Call-ID(事务一致性) ensureCallIdConsistency(response); return response; } catch (Exception e) { log.error("构建响应对象失败: statusCode={}, phrase={}", statusCode, phrase, e); throw new RuntimeException("构建响应对象失败", e); } } /** * 确保Call-ID一致性 * 如果存在事务上下文,则确保响应使用原请求的Call-ID */ private void ensureCallIdConsistency(Response response) { // SIP响应必须与原始请求完全匹配,不能修改任何头部信息 // MESSAGE_FACTORY.createResponse已经确保了完全的头部匹配 // 这里只做调试验证,不做任何修改 try { String contextCallId = SipTransactionContext.getCurrentCallId(); if (StringUtils.isNotBlank(contextCallId)) { // 验证响应的Call-ID是否与事务上下文一致 String responseCallId = ((CallID) response.getHeader("Call-ID")).getCallId(); if (!contextCallId.equals(responseCallId)) { log.warn("响应Call-ID与事务上下文不一致: response={}, context={}, 但保持原请求Call-ID不变以确保事务匹配", responseCallId, contextCallId); // 关键:不修改Call-ID!响应必须与原始请求的事务完全匹配 } else { log.debug("响应Call-ID与事务上下文一致: {}", contextCallId); } } } catch (Exception e) { log.warn("检查Call-ID一致性时发生异常,将继续执行", e); } } /** * 使用事务发送响应 */ private void sendWithTransaction(Response response) { try { ServerTransaction transaction = getServerTransaction(); if (transaction != null) { // 验证事务与响应的匹配性 log.debug("发送事务响应: transaction={}, response-callId={}, response-cseq={}", transaction, response.getHeader("Call-ID"), response.getHeader("CSeq")); transaction.sendResponse(response); } else { // 如果没有事务,降级到无事务模式 log.warn("无法获取服务器事务,降级到无事务模式发送响应"); sendWithoutTransaction(response); } } catch (Exception e) { log.error("使用事务发送响应失败,尝试降级到无事务模式", e); try { sendWithoutTransaction(response); } catch (Exception fallbackException) { log.error("无事务模式发送响应也失败", fallbackException); throw new RuntimeException("发送SIP响应失败", e); } } } /** * 不使用事务发送响应 */ private void sendWithoutTransaction(Response response) { SIPRequest sipRequest = (SIPRequest) request; String targetIp = getTargetIp(sipRequest); SipSender.transmitRequest(targetIp, response); } /** * 获取服务器事务 */ private ServerTransaction getServerTransaction() { // 其次尝试从RequestEvent中获取事务 if (requestEvent != null) { serverTransaction = requestEvent.getServerTransaction(); if (serverTransaction != null) { log.debug("从RequestEvent获取服务器事务: {}", serverTransaction); return serverTransaction; } if (request == null) { request = requestEvent.getRequest(); } } // 关键修复:尝试从SIPRequest直接获取事务(NIST-SIP实现特定方法) if (request instanceof SIPRequest) { try { // 使用NIST-SIP的内部方法直接从请求对象获取事务 Object transaction = ((SIPRequest) request).getTransaction(); if (transaction instanceof ServerTransaction) { serverTransaction = (ServerTransaction) transaction; log.debug("从SIPRequest直接获取服务器事务: {}", serverTransaction); return serverTransaction; } else if (transaction != null) { log.warn("SIPRequest.getTransaction()返回了非ServerTransaction类型: {}", transaction.getClass()); } } catch (Exception e) { log.debug("从SIPRequest获取事务时发生异常: {}", e.getMessage()); } } // 禁止创建新事务!这会导致"Response does not belong to this transaction"错误 // 因为新创建的事务与原始请求的Branch参数和SentBy信息不匹配 return null; } } private static String getTargetIp(SIPRequest sipRequest) { String targetIp; if (sipRequest.getLocalAddress() != null) { targetIp = sipRequest.getLocalAddress().getHostAddress(); } else { // 如果本地地址为空,尝试从Via头获取地址 ViaHeader viaHeader = (ViaHeader) sipRequest.getHeader(ViaHeader.NAME); if (viaHeader != null) { targetIp = viaHeader.getHost(); } else { // 如果Via头也为空,使用默认地址 targetIp = "127.0.0.1"; } } return targetIp; } // ==================== 便捷方法 ==================== /** * 创建响应构建器 */ public static SipResponseBuilder response(int statusCode) { return new SipResponseBuilder(statusCode); } /** * 快速发送简单响应(使用预创建的事务) * * @param statusCode 状态码 * @param requestEvent 请求事件 * @param serverTransaction 预创建的服务器事务 */ public static void sendResponse(int statusCode, RequestEvent requestEvent, ServerTransaction serverTransaction) { response(statusCode) .requestEvent(requestEvent) .serverTransaction(serverTransaction) .send(); } /** * 快速发送带短语的响应(使用预创建的事务) * * @param statusCode 状态码 * @param phrase 响应短语 * @param requestEvent 请求事件 * @param serverTransaction 预创建的服务器事务 */ public static void sendResponse(int statusCode, String phrase, RequestEvent requestEvent, ServerTransaction serverTransaction) { response(statusCode) .phrase(phrase) .requestEvent(requestEvent) .serverTransaction(serverTransaction) .send(); } /** * 快速发送带内容的响应(使用预创建的事务) * * @param statusCode 状态码 * @param content 响应内容 * @param contentTypeHeader 内容类型头 * @param requestEvent 请求事件 * @param serverTransaction 预创建的服务器事务 */ public static void sendResponse(int statusCode, String content, ContentTypeHeader contentTypeHeader, RequestEvent requestEvent, ServerTransaction serverTransaction) { response(statusCode) .content(content) .contentType(contentTypeHeader) .requestEvent(requestEvent) .serverTransaction(serverTransaction) .send(); } /** * 快速发送简单响应(使用事务) */ public static void sendResponse(int statusCode, RequestEvent requestEvent) { response(statusCode) .requestEvent(requestEvent) .send(); } /** * 快速发送带短语的响应(使用事务) */ public static void sendResponse(int statusCode, String phrase, RequestEvent requestEvent) { response(statusCode) .phrase(phrase) .requestEvent(requestEvent) .send(); } /** * 快速发送带内容的响应(使用事务) */ public static void sendResponse(int statusCode, String content, ContentTypeHeader contentTypeHeader, RequestEvent requestEvent) { response(statusCode) .content(content) .contentType(contentTypeHeader) .requestEvent(requestEvent) .send(); } /** * 快速发送简单响应(不使用事务) */ public static void sendResponseNoTransaction(int statusCode, RequestEvent requestEvent) { response(statusCode) .requestEvent(requestEvent) .useTransaction(false) .send(); } /** * 快速发送带短语的响应(不使用事务) */ public static void sendResponseNoTransaction(int statusCode, String phrase, RequestEvent requestEvent) { response(statusCode) .phrase(phrase) .requestEvent(requestEvent) .useTransaction(false) .send(); } /** * 快速发送带内容的响应(不使用事务) */ public static void sendResponseNoTransaction(int statusCode, String content, ContentTypeHeader contentTypeHeader, RequestEvent requestEvent) { response(statusCode) .content(content) .contentType(contentTypeHeader) .requestEvent(requestEvent) .useTransaction(false) .send(); } // ==================== 兼容性方法 ==================== /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmdNoTransaction(int statusCode, String phrase, String content, ContentTypeHeader contentTypeHeader, RequestEvent request) { SipURI sipURI = (SipURI) request.getRequest().getRequestURI(); ContactHeader contactHeader = SipRequestUtils.createContactHeader(sipURI.getUser(), sipURI.getHost() + ":" + sipURI.getPort()); response(statusCode) .phrase(phrase) .content(content) .contentType(contentTypeHeader) .requestEvent(request) .header(contactHeader) .useTransaction(false) .send(); } /** * @deprecated 使用 {@link #sendResponseNoTransaction(int, RequestEvent)} 替代 */ @Deprecated public static void doResponseCmdNoTransaction(int statusCode, RequestEvent request) { sendResponseNoTransaction(statusCode, request); } /** * @deprecated 使用 {@link #sendResponse(int, RequestEvent)} 替代 */ @Deprecated public static void doResponseCmd(int statusCode, RequestEvent request) { sendResponse(statusCode, request); } /** * @deprecated 使用 {@link #sendResponse(int, String, RequestEvent)} 替代 */ @Deprecated public static void doResponseCmd(int statusCode, String phrase, RequestEvent request) { sendResponse(statusCode, phrase, request); } /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmd(int statusCode, String phrase, RequestEvent request, Header... headers) { response(statusCode) .phrase(phrase) .requestEvent(request) .headers(headers) .send(); } /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmd(int statusCode, String phrase, RequestEvent event, List<Header> headers) { response(statusCode) .phrase(phrase) .requestEvent(event) .headers(headers) .send(); } public static void sendResponse(int statusCode, String content, ContentTypeHeader contentTypeHeader, RequestEvent event, Header... headers) { response(statusCode) .content(content) .contentType(contentTypeHeader) .requestEvent(event) .headers(headers) .send(); } public static void doResponseCmd(int statusCode, String phrase, String content, ContentTypeHeader contentTypeHeader, RequestEvent event, List<Header> headers) { response(statusCode) .phrase(phrase) .content(content) .contentType(contentTypeHeader) .requestEvent(event) .headers(headers) .send(); } public static void doResponseCmd(int statusCode, String phrase, String content, ContentTypeHeader contentTypeHeader, String ip, Request request, List<Header> headers) { response(statusCode) .phrase(phrase) .content(content) .contentType(contentTypeHeader) .request(request) .ip(ip) .headers(headers) .send(); } /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmdNoTransaction(int statusCode, String phrase, Request request, List<Header> headers) { response(statusCode) .phrase(phrase) .request(request) .headers(headers) .useTransaction(false) .send(); } /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmdNoTransaction(int statusCode, String phrase, String content, ContentTypeHeader contentTypeHeader, Request request, List<Header> headers) { response(statusCode) .phrase(phrase) .content(content) .contentType(contentTypeHeader) .request(request) .headers(headers) .useTransaction(false) .send(); } /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmd(int statusCode, String phrase, String content, ContentTypeHeader contentTypeHeader, Request request, ServerTransaction serverTransaction, List<Header> headers) { response(statusCode) .phrase(phrase) .content(content) .contentType(contentTypeHeader) .request(request) .serverTransaction(serverTransaction) .headers(headers) .send(); } /** * @deprecated 使用 {@link #response(int)} 替代 */ @Deprecated public static void doResponseCmd(int statusCode, String phrase, String content, ContentTypeHeader contentTypeHeader, RequestEvent evt) { SipURI sipURI = (SipURI) evt.getRequest().getRequestURI(); ContactHeader contactHeader = SipRequestUtils.createContactHeader(sipURI.getUser(), sipURI.getHost() + ":" + sipURI.getPort()); response(statusCode) .phrase(phrase) .content(content) .contentType(contentTypeHeader) .requestEvent(evt) .header(contactHeader) .send(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/CustomerSipListener.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/CustomerSipListener.java
package io.github.lunasaw.sip.common.transmit; import lombok.extern.slf4j.Slf4j; /** * SIP信令处理类观察者 * 继承AbstractSipListener,提供默认的SIP事件处理实现 * * @author luna */ @Slf4j public class CustomerSipListener extends AbstractSipListener { /** * 单实例 */ private static volatile AbstractSipListener instance; /** * 私有构造函数 */ private CustomerSipListener() { // 私有构造函数,防止外部实例化 } /** * 获取单实例 * * @return SipListener实例 */ public static AbstractSipListener getInstance() { if (instance == null) { synchronized (CustomerSipListener.class) { if (instance == null) { instance = new CustomerSipListener(); } } } return instance; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/TransactionAwareAsyncSipListener.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/TransactionAwareAsyncSipListener.java
package io.github.lunasaw.sip.common.transmit; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.transmit.SipTransactionContext.TransactionContextInfo; import io.github.lunasaw.sip.common.utils.TraceUtils; import io.micrometer.core.instrument.Timer; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import javax.sip.*; import javax.sip.message.Response; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 事务感知的异步SIP监听器 * 继承AsyncSipListener,增强事务上下文管理能力 * 确保多线程异步处理时事务信息的正确传递和维护 * * @author luna */ @Setter @Getter @Slf4j @Service public abstract class TransactionAwareAsyncSipListener extends AsyncSipListener { /** * 事务上下文清理调度器 */ private ScheduledThreadPoolExecutor contextCleanupScheduler; /** * 是否启用事务上下文管理 */ private boolean enableTransactionContext = true; public TransactionAwareAsyncSipListener() { super(); initializeContextCleanup(); log.info("TransactionAwareAsyncSipListener初始化完成,启用事务上下文管理"); } /** * 初始化上下文清理调度器 */ private void initializeContextCleanup() { this.contextCleanupScheduler = new ScheduledThreadPoolExecutor(1, r -> { Thread thread = new Thread(r, "sip-context-cleanup"); thread.setDaemon(true); return thread; }); // 每5分钟清理一次过期的事务上下文 contextCleanupScheduler.scheduleAtFixedRate(() -> { try { log.info("开始定期清理过期事务上下文"); SipTransactionContext.cleanupExpiredContexts(); log.info("定期清理事务上下文完成: 清理了过期上下文, 统计信息: {}", SipTransactionContext.getContextStats()); } catch (Exception e) { log.error("清理事务上下文失败", e); } }, 5, 5, TimeUnit.MINUTES); log.info("事务上下文清理调度器已启动,清理间隔: 5分钟"); } /** * 事务感知的异步请求处理 * 创建并传递事务上下文到异步线程 */ @Override public void processRequest(RequestEvent requestEvent) { Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; String method = requestEvent.getRequest().getMethod(); try { // 记录方法调用 if (sipMetrics != null) { sipMetrics.recordMethodCall(method); } log.info("开始事务感知异步处理SIP请求: method={}, callId={}, traceId={}", method, requestEvent.getRequest().getHeader("Call-ID") != null ? requestEvent.getRequest().getHeader("Call-ID").toString().split(":")[1].trim() : "unknown", TraceUtils.getTraceId()); // 创建事务上下文 TransactionContextInfo transactionContext = null; if (enableTransactionContext && !SipLayer.isShuttingDown()) { try { ServerTransaction serverTransaction = requestEvent.getServerTransaction(); if (serverTransaction == null) { // 尝试获取或创建服务器事务 serverTransaction = SipTransactionManager.getServerTransaction(requestEvent.getRequest()); if (serverTransaction == null) { log.debug("无法获取服务器事务,可能服务正在关闭,继续处理"); } } if (serverTransaction != null) { transactionContext = SipTransactionContext.createContext(requestEvent, serverTransaction); log.info("成功创建事务上下文: key={}, method={}, transactionId={}", transactionContext.getContextKey(), method, serverTransaction.getBranchId()); } else { log.info("服务器事务为空,跳过事务上下文创建,method={}", method); } } catch (Exception e) { log.warn("创建事务上下文失败,继续处理: method={}, error={}", method, e.getMessage(), e); } } else if (SipLayer.isShuttingDown()) { log.info("服务正在关闭,跳过事务上下文创建,method={}", method); } else { log.info("事务上下文管理已禁用,跳过上下文创建,method={}", method); } String traceId = TraceUtils.getTraceId(); final TransactionContextInfo finalContext = transactionContext; // 异步执行实际处理逻辑 log.info("提交请求到异步执行器: method={}, hasContext={}", method, transactionContext != null); getMessageExecutor().execute(() -> { TransactionContextInfo currentContext = null; try { // 设置TraceId TraceUtils.setTraceId(traceId); // 传递事务上下文到当前线程 if (finalContext != null) { SipTransactionContext.setCurrentContext(finalContext); currentContext = finalContext; log.info("成功传递事务上下文到异步线程: key={}, threadName={}", finalContext.getContextKey(), Thread.currentThread().getName()); } else { log.info("无事务上下文需要传递到异步线程: threadName={}", Thread.currentThread().getName()); } // 调用父类的处理逻辑 log.info("开始调用父类处理逻辑: method={}", method); super.processRequest(requestEvent); log.info("父类处理逻辑执行完成: method={}", method); if (sipMetrics != null) { sipMetrics.recordMessageProcessed(method, "TRANSACTION_ASYNC_SUCCESS"); } log.info("请求异步处理成功: method={}, traceId={}", method, TraceUtils.getTraceId()); } catch (Exception e) { log.error("事务感知异步处理请求失败: method={}, contextKey={}, traceId={}", method, currentContext != null ? currentContext.getContextKey() : "none", TraceUtils.getTraceId(), e); if (sipMetrics != null) { sipMetrics.recordError("TRANSACTION_ASYNC_PROCESSING_ERROR", method); sipMetrics.recordMessageProcessed(method, "TRANSACTION_ASYNC_ERROR"); } // 调用异常处理 handleRequestExceptionWithContext(requestEvent, e, currentContext); } finally { // 清理线程本地上下文 log.info("清理异步线程上下文: method={}, contextKey={}, threadName={}", method, currentContext != null ? currentContext.getContextKey() : "none", Thread.currentThread().getName()); SipTransactionContext.clearCurrentContext(); TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("事务感知异步分发请求异常: method={}, traceId={}", method, TraceUtils.getTraceId(), e); if (sipMetrics != null) { sipMetrics.recordError("TRANSACTION_ASYNC_DISPATCH_ERROR", method); sipMetrics.recordMessageProcessed(method, "TRANSACTION_ASYNC_DISPATCH_ERROR"); } handleRequestException(requestEvent, e); } finally { if (sipMetrics != null && sample != null) { sipMetrics.recordRequestProcessingTime(sample); } } } /** * 事务感知的异步响应处理 */ @Override @Async("sipMessageProcessor") public void processResponse(ResponseEvent responseEvent) { Timer.Sample sample = sipMetrics != null ? sipMetrics.startTimer() : null; Response response = responseEvent.getResponse(); int status = response.getStatusCode(); try { // 记录方法调用 if (sipMetrics != null) { sipMetrics.recordMethodCall("RESPONSE_" + status); } log.info("开始事务感知异步处理SIP响应: status={}, callId={}, traceId={}", status, response.getHeader("Call-ID") != null ? response.getHeader("Call-ID").toString().split(":")[1].trim() : "unknown", TraceUtils.getTraceId()); String traceId = TraceUtils.getTraceId(); // 尝试匹配已有的事务上下文 TransactionContextInfo existingContext = null; if (enableTransactionContext) { try { // 从响应中提取上下文键信息 String contextKey = generateContextKeyFromResponse(response); existingContext = SipTransactionContext.getContext(contextKey); if (existingContext != null) { log.info("找到匹配的事务上下文: key={}, status={}, contextAge={}ms", contextKey, status, System.currentTimeMillis() - existingContext.getCreateTime()); } else { log.info("未找到匹配的事务上下文: generatedKey={}, status={}", contextKey, status); } } catch (Exception e) { log.warn("匹配事务上下文失败: status={}, error={}", status, e.getMessage(), e); } } final TransactionContextInfo finalContext = existingContext; // 异步执行响应处理 log.info("提交响应到异步执行器: status={}, hasContext={}", status, existingContext != null); getMessageExecutor().execute(() -> { try { // 设置TraceId TraceUtils.setTraceId(traceId); // 传递事务上下文到当前线程 if (finalContext != null) { SipTransactionContext.setCurrentContext(finalContext); log.info("成功传递事务上下文到响应处理线程: key={}, threadName={}", finalContext.getContextKey(), Thread.currentThread().getName()); } else { log.info("无事务上下文需要传递到响应处理线程: status={}, threadName={}", status, Thread.currentThread().getName()); } // 调用父类的响应处理逻辑 log.info("开始调用父类响应处理逻辑: status={}", status); super.processResponse(responseEvent); log.info("父类响应处理逻辑执行完成: status={}", status); if (sipMetrics != null) { sipMetrics.recordMessageProcessed("RESPONSE_" + status, "TRANSACTION_ASYNC_SUCCESS"); } log.info("响应异步处理成功: status={}, traceId={}", status, TraceUtils.getTraceId()); } catch (Exception e) { log.error("事务感知异步处理响应失败: status={}, contextKey={}, traceId={}", status, finalContext != null ? finalContext.getContextKey() : "none", TraceUtils.getTraceId(), e); if (sipMetrics != null) { sipMetrics.recordError("TRANSACTION_ASYNC_RESPONSE_ERROR", "RESPONSE_" + status); sipMetrics.recordMessageProcessed("RESPONSE_" + status, "TRANSACTION_ASYNC_ERROR"); } handleResponseExceptionWithContext(responseEvent, e, finalContext); } finally { // 清理线程本地上下文 log.info("清理响应处理线程上下文: status={}, contextKey={}, threadName={}", status, finalContext != null ? finalContext.getContextKey() : "none", Thread.currentThread().getName()); SipTransactionContext.clearCurrentContext(); TraceUtils.clearTraceId(); } }); } catch (Exception e) { log.error("事务感知异步分发响应异常: status={}, traceId={}", status, TraceUtils.getTraceId(), e); if (sipMetrics != null) { sipMetrics.recordError("TRANSACTION_ASYNC_RESPONSE_DISPATCH_ERROR", "RESPONSE_" + status); } handleResponseException(responseEvent, e); } finally { if (sipMetrics != null && sample != null) { sipMetrics.recordResponseProcessingTime(sample); } } } /** * 从响应中生成上下文键 */ private String generateContextKeyFromResponse(Response response) { try { log.debug("开始从响应生成上下文键: status={}", response.getStatusCode()); String callId = response.getHeader("Call-ID").toString().split(":")[1].trim(); String fromTag = null; String cseq = response.getHeader("CSeq").toString().split(":")[1].trim(); // 从To头提取tag(响应中的To tag对应请求中的From tag) String toHeader = response.getHeader("To").toString(); if (toHeader.contains("tag=")) { fromTag = toHeader.substring(toHeader.indexOf("tag=") + 4); int semicolon = fromTag.indexOf(';'); if (semicolon != -1) { fromTag = fromTag.substring(0, semicolon); } } String contextKey = callId + "_" + (fromTag != null ? fromTag : "notag") + "_" + cseq; log.debug("成功生成上下文键: callId={}, fromTag={}, cseq={}, contextKey={}", callId, fromTag, cseq, contextKey); return contextKey; } catch (Exception e) { log.warn("从响应生成上下文键失败: status={}, error={}", response.getStatusCode(), e.getMessage(), e); String fallbackKey = "response_unknown_" + System.currentTimeMillis(); log.info("使用备用上下文键: {}", fallbackKey); return fallbackKey; } } /** * 带事务上下文的请求异常处理 */ protected void handleRequestExceptionWithContext(RequestEvent requestEvent, Exception e, TransactionContextInfo context) { String method = requestEvent.getRequest().getMethod(); log.error("请求处理异常,method={}, 上下文: {}, traceId={}", method, context != null ? context.getContextKey() : "无", TraceUtils.getTraceId(), e); // 子类可以重写此方法提供特定的异常处理逻辑 handleRequestException(requestEvent, e); } /** * 带事务上下文的响应异常处理 */ protected void handleResponseExceptionWithContext(ResponseEvent responseEvent, Exception e, TransactionContextInfo context) { int status = responseEvent.getResponse().getStatusCode(); log.error("响应处理异常,status={}, 上下文: {}, traceId={}", status, context != null ? context.getContextKey() : "无", TraceUtils.getTraceId(), e); // 子类可以重写此方法提供特定的异常处理逻辑 handleResponseException(responseEvent, e); } /** * 响应异常处理(原方法不存在,添加默认实现) */ protected void handleResponseException(ResponseEvent responseEvent, Exception e) { log.error("响应处理异常: status={}", responseEvent.getResponse().getStatusCode(), e); // 子类可以重写此方法 } /** * 获取事务上下文统计信息 */ public String getTransactionContextStats() { return SipTransactionContext.getContextStats(); } /** * 手动清理事务上下文 */ public void cleanupTransactionContexts() { log.info("开始手动清理事务上下文"); SipTransactionContext.cleanupExpiredContexts(); log.info("手动清理事务上下文完成: 清理了过期上下文, 统计信息: {}", getTransactionContextStats()); } /** * 关闭资源 */ public void shutdown() { log.info("开始关闭TransactionAwareAsyncSipListener"); if (contextCleanupScheduler != null && !contextCleanupScheduler.isShutdown()) { log.info("关闭事务上下文清理调度器"); contextCleanupScheduler.shutdown(); try { if (!contextCleanupScheduler.awaitTermination(5, TimeUnit.SECONDS)) { contextCleanupScheduler.shutdownNow(); } } catch (InterruptedException e) { log.warn("等待调度器关闭时被中断,强制关闭"); contextCleanupScheduler.shutdownNow(); Thread.currentThread().interrupt(); } log.info("事务上下文清理调度器已关闭"); } else { log.info("事务上下文清理调度器已经关闭或未初始化"); } log.info("TransactionAwareAsyncSipListener关闭完成"); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/Event.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/Event.java
package io.github.lunasaw.sip.common.transmit.event; public interface Event { /** * 回调 * * @param eventResult */ void response(EventResult eventResult); }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/SipMethod.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/SipMethod.java
package io.github.lunasaw.sip.common.transmit.event; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * SIP方法注解,用于标记处理器支持的SIP方法类型 * 替代反射获取method字段的方式,提升性能和安全性 * * @author luna * @date 2024/01/01 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface SipMethod { /** * SIP方法名称 * 如:MESSAGE, REGISTER, INVITE, BYE, ACK, CANCEL, INFO, SUBSCRIBE, NOTIFY * * @return SIP方法名称 */ String value(); /** * 处理器优先级,数值越小优先级越高 * 当有多个处理器处理同一种方法时,按优先级排序 * * @return 优先级 */ int priority() default 100; }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/EventResultType.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/EventResultType.java
package io.github.lunasaw.sip.common.transmit.event; import javax.sip.IOExceptionEvent; /** * 事件类型 * @author luna */ public enum EventResultType { // ack ack, // 超时 timeout, // 回复 response, // 事务已结束 transactionTerminated, // 会话已结束 dialogTerminated, // 设备未找到 deviceNotFoundEvent, // 设备未找到 cmdSendFailEvent, }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/SipSubscribe.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/SipSubscribe.java
package io.github.lunasaw.sip.common.transmit.event; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.header.CallIdHeader; import javax.sip.message.Response; import java.time.Instant; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * @author lin */ @Slf4j @Component @Getter @Setter public class SipSubscribe { public static final Map<String, Event> errorSubscribes = new ConcurrentHashMap<>(); public static final Map<String, Event> okSubscribes = new ConcurrentHashMap<>(); public static final Map<String, Instant> okTimeSubscribes = new ConcurrentHashMap<>(); public static final Map<String, Instant> errorTimeSubscribes = new ConcurrentHashMap<>(); public synchronized static void addErrorSubscribe(String key, Event event) { errorSubscribes.put(key, event); errorTimeSubscribes.put(key, Instant.now()); } public synchronized static void addOkSubscribe(String key, Event event) { okSubscribes.put(key, event); okTimeSubscribes.put(key, Instant.now()); } public static Event getErrorSubscribe(String key) { return errorSubscribes.get(key); } public synchronized static void removeErrorSubscribe(String key) { if (key == null) { return; } errorSubscribes.remove(key); errorTimeSubscribes.remove(key); } public static Event getOkSubscribe(String key) { return okSubscribes.get(key); } public synchronized static void removeOkSubscribe(String key) { if (key == null) { return; } okSubscribes.remove(key); okTimeSubscribes.remove(key); } public static int getErrorSubscribesSize() { return errorSubscribes.size(); } public static int getOkSubscribesSize() { return okSubscribes.size(); } public static void publishOkEvent(ResponseEvent evt) { Response response = evt.getResponse(); CallIdHeader callIdHeader = (CallIdHeader) response.getHeader(CallIdHeader.NAME); String callId = callIdHeader.getCallId(); Event event = okSubscribes.get(callId); if (event != null) { removeOkSubscribe(callId); event.response(new EventResult(evt)); } } public static void publishAckEvent(RequestEvent evt) { String callId = evt.getDialog().getCallId().getCallId(); Event event = okSubscribes.get(callId); if (event != null) { removeOkSubscribe(callId); event.response(new EventResult(evt)); } } // @Scheduled(cron="*/5 * * * * ?") //每五秒执行一次 // @Scheduled(fixedRate= 100 * 60 * 60 ) @Scheduled(cron = "0 0/5 * * * ?") // 每5分钟执行一次 public void execute() { log.info("[定时任务] 清理过期的SIP订阅信息"); Instant instant = Instant.now().minusMillis(TimeUnit.MINUTES.toMillis(5)); for (String key : okTimeSubscribes.keySet()) { if (okTimeSubscribes.get(key).isBefore(instant)) { okSubscribes.remove(key); okTimeSubscribes.remove(key); } } for (String key : errorTimeSubscribes.keySet()) { if (errorTimeSubscribes.get(key).isBefore(instant)) { errorSubscribes.remove(key); errorTimeSubscribes.remove(key); } } log.debug("okTimeSubscribes.size:{}", okTimeSubscribes.size()); log.debug("okSubscribes.size:{}", okSubscribes.size()); log.debug("errorTimeSubscribes.size:{}", errorTimeSubscribes.size()); log.debug("errorSubscribes.size:{}", errorSubscribes.size()); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/EventResult.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/EventResult.java
package io.github.lunasaw.sip.common.transmit.event; import javax.sip.*; import javax.sip.header.CallIdHeader; import javax.sip.message.Response; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.transmit.event.result.DeviceNotFoundEvent; import lombok.Data; /** * 事件结果 * * @author luna */ @Data public class EventResult<T> { public int statusCode; public EventResultType type; public String msg; public String callId; public Dialog dialog; public T event; public EventResult() {} public EventResult(T event) { this.event = event; if (event instanceof ResponseEvent) { ResponseEvent responseEvent = (ResponseEvent)event; Response response = responseEvent.getResponse(); this.type = EventResultType.response; if (response != null) { this.msg = response.getReasonPhrase(); this.statusCode = response.getStatusCode(); } assert response != null; this.callId = ((CallIdHeader)response.getHeader(CallIdHeader.NAME)).getCallId(); } else if (event instanceof TimeoutEvent) { TimeoutEvent timeoutEvent = (TimeoutEvent)event; this.type = EventResultType.timeout; this.msg = "消息超时未回复"; this.statusCode = -1024; if (timeoutEvent.isServerTransaction()) { this.callId = ((SIPRequest)timeoutEvent.getServerTransaction().getRequest()).getCallIdHeader().getCallId(); this.dialog = timeoutEvent.getServerTransaction().getDialog(); } else { this.callId = ((SIPRequest)timeoutEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId(); this.dialog = timeoutEvent.getClientTransaction().getDialog(); } } else if (event instanceof TransactionTerminatedEvent) { TransactionTerminatedEvent transactionTerminatedEvent = (TransactionTerminatedEvent)event; this.type = EventResultType.transactionTerminated; this.msg = "事务已结束"; this.statusCode = -1024; if (transactionTerminatedEvent.isServerTransaction()) { this.callId = ((SIPRequest)transactionTerminatedEvent.getServerTransaction().getRequest()).getCallIdHeader().getCallId(); this.dialog = transactionTerminatedEvent.getServerTransaction().getDialog(); } else { this.callId = ((SIPRequest) transactionTerminatedEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId(); this.dialog = transactionTerminatedEvent.getClientTransaction().getDialog(); this.dialog = transactionTerminatedEvent.getClientTransaction().getDialog(); } } else if (event instanceof DialogTerminatedEvent) { DialogTerminatedEvent dialogTerminatedEvent = (DialogTerminatedEvent)event; this.type = EventResultType.dialogTerminated; this.msg = "会话已结束"; this.statusCode = -1024; this.callId = dialogTerminatedEvent.getDialog().getCallId().getCallId(); this.dialog = dialogTerminatedEvent.getDialog(); } else if (event instanceof RequestEvent) { RequestEvent requestEvent = (RequestEvent) event; this.type = EventResultType.ack; this.msg = "ack event"; this.callId = requestEvent.getDialog().getCallId().getCallId(); this.dialog = requestEvent.getDialog(); } else if (event instanceof DeviceNotFoundEvent) { this.type = EventResultType.deviceNotFoundEvent; this.msg = "设备未找到"; this.statusCode = -1024; this.callId = ((DeviceNotFoundEvent)event).getCallId(); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/result/DeviceNotFoundEvent.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/result/DeviceNotFoundEvent.java
package io.github.lunasaw.sip.common.transmit.event.result; import lombok.Getter; import java.util.EventObject; import javax.sip.Dialog; /** * @author luna */ @Getter public class DeviceNotFoundEvent extends EventObject { private String callId; /** * Constructs a prototypical Event. * * @param dialog * @throws IllegalArgumentException if source is null. */ public DeviceNotFoundEvent(Dialog dialog) { super(dialog); } public void setCallId(String callId) { this.callId = callId; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/MessageHandler.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/MessageHandler.java
package io.github.lunasaw.sip.common.transmit.event.message; import io.github.lunasaw.sip.common.transmit.event.handler.RequestHandler; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; /** * 对message类型的请求单独抽象,根据cmdType进行处理 */ public interface MessageHandler extends RequestHandler { String QUERY = "Query"; String CONTROL = "Control"; String NOTIFY = "Notify"; String RESPONSE = "Response"; /** * 响应ack * * @param event 请求事件 */ void responseAck(RequestEvent event); /** * 响应ack(使用预创建的事务) * * @param event 请求事件 * @param serverTransaction 预创建的服务器事务(可为null) */ default void responseAck(RequestEvent event, ServerTransaction serverTransaction) { // 默认实现调用原有方法,向后兼容 responseAck(event); } /** * 响应error * * @param event 请求事件 */ void responseError(RequestEvent event); /** * 自定义错误回复 * * @param event * @param code * @param error */ void responseError(RequestEvent event, Integer code, String error); /** * 自定义错误回复(使用预创建的事务) * * @param event * @param code * @param error * @param serverTransaction 预创建的服务器事务(可为null) */ default void responseError(RequestEvent event, Integer code, String error, ServerTransaction serverTransaction) { // 默认实现调用原有方法,向后兼容 responseError(event, code, error); } /** * 处理消息 * * @param event */ void handForEvt(RequestEvent event); /** * 处理标签 * * @return */ String getRootType(); /** * 处理消息类型 * * @return */ String getCmdType(); /** * 获取处理方法 * * @return */ String getMethod(); /** * 当前接受到的原始消息 */ void setXmlStr(String xmlStr); /** * 是否需要响应ack * * @return */ default boolean needResponseAck() { return true; }; }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/SipMessageRequestProcessorAbstract.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/SipMessageRequestProcessorAbstract.java
package io.github.lunasaw.sip.common.transmit.event.message; import io.github.lunasaw.sip.common.transmit.event.request.SipRequestProcessorAbstract; import lombok.extern.slf4j.Slf4j; /** * @author luna */ @Slf4j public abstract class SipMessageRequestProcessorAbstract extends SipRequestProcessorAbstract { }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/TransactionAwareMessageHandlerAbstract.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/TransactionAwareMessageHandlerAbstract.java
package io.github.lunasaw.sip.common.transmit.event.message; import com.luna.common.text.StringTools; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.entity.DeviceSession; import io.github.lunasaw.sip.common.transmit.ResponseCmd; import io.github.lunasaw.sip.common.transmit.TransactionAwareResponseCmd; import io.github.lunasaw.sip.common.transmit.SipTransactionContext; import io.github.lunasaw.sip.common.transmit.SipTransactionContext.TransactionContextInfo; import io.github.lunasaw.sip.common.utils.XmlUtils; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; import javax.sip.message.Response; import java.nio.charset.Charset; /** * 事务感知的消息处理器抽象基类 * 继承原有MessageHandlerAbstract,增强事务管理能力 * * @author weidian * @author luna (enhanced) */ @Getter @Setter @Slf4j public abstract class TransactionAwareMessageHandlerAbstract implements MessageHandler, InitializingBean { private String xmlStr; /** * 解析请求内容为对象(静态方法保持兼容) */ public static <T> T parseRequest(RequestEvent event, String charset, Class<T> clazz) { SIPRequest sipRequest = (SIPRequest) event.getRequest(); byte[] rawContent = sipRequest.getRawContent(); if (StringUtils.isBlank(charset)) { charset = Constant.UTF_8; } String xmlStr = StringTools.toEncodedString(rawContent, Charset.forName(charset)); Object o = XmlUtils.parseObj(xmlStr, clazz); return (T) o; } /** * 解析请求内容为字符串(静态方法保持兼容) */ public static String parseRequest(RequestEvent event, String charset) { SIPRequest sipRequest = (SIPRequest) event.getRequest(); byte[] rawContent = sipRequest.getRawContent(); if (StringUtils.isBlank(charset)) { charset = Constant.UTF_8; } return StringTools.toEncodedString(rawContent, Charset.forName(charset)); } @Override public void afterPropertiesSet() { SipMessageRequestProcessorAbstract.addHandler(this); } @Override public void handForEvt(RequestEvent event) { // 子类实现具体处理逻辑 } @Override public String getRootType() { return null; } public String getMethod() { return null; } @Override public String getCmdType() { return null; } @Override public void setXmlStr(String xmlStr) { this.xmlStr = xmlStr; } /** * 获取设备会话(子类可重写) */ public DeviceSession getDeviceSession(RequestEvent event) { return null; } // ==================== 事务感知的响应方法 ==================== /** * 事务感知的ACK响应(优先使用事务上下文) */ public void responseAck(RequestEvent event) { try { // 优先使用事务感知方式 if (TransactionAwareResponseCmd.hasValidTransactionContext()) { TransactionAwareResponseCmd.sendOK(); log.debug("使用事务上下文发送OK响应成功"); return; } // 降级到原有方式 log.debug("未找到有效事务上下文,使用原有方式发送OK响应"); ResponseCmd.doResponseCmd(Response.OK, "OK", event); } catch (Exception e) { log.error("发送OK响应失败,尝试无事务模式", e); try { ResponseCmd.sendResponseNoTransaction(Response.OK, "OK", event); } catch (Exception fallbackException) { log.error("无事务模式发送OK响应也失败", fallbackException); throw new RuntimeException("发送ACK响应失败", e); } } } /** * 事务感知的ACK响应(使用预创建的事务) */ @Override public void responseAck(RequestEvent event, ServerTransaction serverTransaction) { try { // 优先使用事务感知方式 if (TransactionAwareResponseCmd.hasValidTransactionContext()) { TransactionAwareResponseCmd.sendOK(); log.debug("使用事务上下文发送OK响应成功(忽略传入的serverTransaction)"); return; } // 使用传入的事务 if (serverTransaction != null) { ResponseCmd.sendResponse(Response.OK, "OK", event, serverTransaction); log.debug("使用传入的ServerTransaction发送OK响应成功"); return; } // 降级到无事务方式 log.debug("未找到有效事务,使用无事务方式发送OK响应"); responseAck(event); } catch (Exception e) { log.error("发送OK响应失败: {}", e.getMessage(), e); // 最后的降级尝试 try { ResponseCmd.sendResponseNoTransaction(Response.OK, "OK", event); log.debug("使用无事务模式成功发送OK响应"); } catch (Exception fallbackException) { log.error("无事务模式发送OK响应也失败", fallbackException); throw new RuntimeException("发送ACK响应失败", e); } } } /** * 事务感知的错误响应 */ public void responseError(RequestEvent event) { try { // 优先使用事务感知方式 if (TransactionAwareResponseCmd.hasValidTransactionContext()) { TransactionAwareResponseCmd.sendInternalServerError(); log.debug("使用事务上下文发送服务器错误响应成功"); return; } // 降级到原有方式 log.debug("未找到有效事务上下文,使用原有方式发送服务器错误响应"); ResponseCmd.doResponseCmd(Response.SERVER_INTERNAL_ERROR, "SERVER ERROR", event); } catch (Exception e) { log.error("发送服务器错误响应失败", e); try { ResponseCmd.sendResponseNoTransaction(Response.SERVER_INTERNAL_ERROR, "SERVER ERROR", event); } catch (Exception fallbackException) { log.error("无事务模式发送服务器错误响应也失败", fallbackException); throw new RuntimeException("发送错误响应失败", e); } } } /** * 事务感知的自定义错误响应 */ public void responseError(RequestEvent event, Integer code, String error) { try { // 优先使用事务感知方式 if (TransactionAwareResponseCmd.hasValidTransactionContext()) { TransactionAwareResponseCmd.sendResponse(code, error); log.debug("使用事务上下文发送自定义错误响应成功: code={}, error={}", code, error); return; } // 降级到原有方式 log.debug("未找到有效事务上下文,使用原有方式发送自定义错误响应: code={}, error={}", code, error); ResponseCmd.doResponseCmd(code, error, event); } catch (Exception e) { log.error("发送自定义错误响应失败: code={}, error={}", code, error, e); try { ResponseCmd.sendResponseNoTransaction(code, error, event); } catch (Exception fallbackException) { log.error("无事务模式发送自定义错误响应也失败", fallbackException); throw new RuntimeException("发送自定义错误响应失败", e); } } } // ==================== 事务上下文辅助方法 ==================== /** * 获取当前事务上下文信息 */ protected TransactionContextInfo getCurrentTransactionContext() { return SipTransactionContext.getCurrentContext(); } /** * 检查当前是否有有效的事务上下文 */ protected boolean hasValidTransactionContext() { return TransactionAwareResponseCmd.hasValidTransactionContext(); } /** * 获取当前事务上下文的详细信息(用于日志和调试) */ protected String getCurrentTransactionInfo() { return TransactionAwareResponseCmd.getCurrentTransactionInfo(); } /** * 记录事务上下文状态(用于调试) */ protected void logTransactionContextStatus(String operation) { if (log.isDebugEnabled()) { TransactionContextInfo context = getCurrentTransactionContext(); if (context != null) { log.debug("操作: {}, 事务上下文: key={}, 有效性={}, 状态={}", operation, context.getContextKey(), context.isValid(), context.getLastKnownState()); } else { log.debug("操作: {}, 无事务上下文", operation); } } } /** * 安全执行需要事务上下文的操作 */ protected void executeWithTransactionContext(String operation, Runnable action) { logTransactionContextStatus("开始-" + operation); try { action.run(); logTransactionContextStatus("完成-" + operation); } catch (Exception e) { logTransactionContextStatus("失败-" + operation); log.error("执行事务感知操作失败: {}", operation, e); throw e; } } /** * 事务感知的消息处理模板方法 * 子类可以重写此方法来利用事务上下文进行处理 */ protected void handleWithTransactionContext(RequestEvent event, String operation) { executeWithTransactionContext(operation, () -> { try { // 调用子类的具体处理逻辑 doHandleWithContext(event); // 自动发送ACK响应 responseAck(event); } catch (Exception e) { log.error("事务感知消息处理失败: operation={}", operation, e); responseError(event); throw e; } }); } /** * 子类实现的具体处理逻辑(在事务上下文中执行) * 子类可以重写此方法来实现具体的业务逻辑 */ protected void doHandleWithContext(RequestEvent event) { // 默认调用原有的处理方法 handForEvt(event); } // ==================== 调试和监控方法 ==================== /** * 获取处理器状态信息 */ public String getHandlerStatusInfo() { StringBuilder info = new StringBuilder(); info.append("处理器类型: ").append(this.getClass().getSimpleName()).append("\n"); info.append("根类型: ").append(getRootType()).append("\n"); info.append("命令类型: ").append(getCmdType()).append("\n"); info.append("方法: ").append(getMethod()).append("\n"); info.append("当前事务状态: ").append(getCurrentTransactionInfo()).append("\n"); return info.toString(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/MessageHandlerAbstract.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/message/MessageHandlerAbstract.java
package io.github.lunasaw.sip.common.transmit.event.message; import com.luna.common.text.StringTools; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.entity.DeviceSession; import io.github.lunasaw.sip.common.transmit.ResponseCmd; import io.github.lunasaw.sip.common.utils.XmlUtils; import lombok.Getter; import lombok.Setter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.InitializingBean; import javax.sip.RequestEvent; import javax.sip.message.Response; import java.nio.charset.Charset; /** * @author weidian */ @Getter @Setter public abstract class MessageHandlerAbstract implements MessageHandler, InitializingBean { private String xmlStr; public static <T> T parseRequest(RequestEvent event, String charset, Class<T> clazz) { SIPRequest sipRequest = (SIPRequest) event.getRequest(); byte[] rawContent = sipRequest.getRawContent(); if (StringUtils.isBlank(charset)) { charset = Constant.UTF_8; } String xmlStr = StringTools.toEncodedString(rawContent, Charset.forName(charset)); Object o = XmlUtils.parseObj(xmlStr, clazz); return (T) o; } public static String parseRequest(RequestEvent event, String charset) { SIPRequest sipRequest = (SIPRequest) event.getRequest(); byte[] rawContent = sipRequest.getRawContent(); if (StringUtils.isBlank(charset)) { charset = Constant.UTF_8; } return StringTools.toEncodedString(rawContent, Charset.forName(charset)); } @Override public void afterPropertiesSet() { SipMessageRequestProcessorAbstract.addHandler(this); } @Override public void handForEvt(RequestEvent event) { } @Override public String getRootType() { return null; } public String getMethod() { return null; } @Override public String getCmdType() { return null; } @Override public void setXmlStr(String xmlStr) { this.xmlStr = xmlStr; } public DeviceSession getDeviceSession(RequestEvent event) { return null; } public void responseAck(RequestEvent event) { ResponseCmd.doResponseCmd(Response.OK, "OK", event); } @Override public void responseAck(RequestEvent event, javax.sip.ServerTransaction serverTransaction) { if (serverTransaction != null) { // 使用预创建的事务 ResponseCmd.sendResponse(Response.OK, "OK", event, serverTransaction); } else { // 降级到原有方法 responseAck(event); } } public void responseError(RequestEvent event) { ResponseCmd.doResponseCmd(Response.SERVER_INTERNAL_ERROR, "SERVER ERROR", event); } public void responseError(RequestEvent event, Integer code, String error) { ResponseCmd.doResponseCmd(code, error, event); } @Override public void responseError(RequestEvent event, Integer code, String error, javax.sip.ServerTransaction serverTransaction) { if (serverTransaction != null) { // 使用预创建的事务 ResponseCmd.sendResponse(code, error, event, serverTransaction); } else { // 降级到原有方法 responseError(event, code, error); } } public <T> T parseXml(Class<T> clazz) { if (StringUtils.isBlank(xmlStr)) { return null; } return (T) XmlUtils.parseObj(xmlStr, clazz); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/handler/RequestHandler.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/handler/RequestHandler.java
package io.github.lunasaw.sip.common.transmit.event.handler; /** * @author luna * @version 1.0 * @date 2023/12/12 * @description: */ public interface RequestHandler { }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/response/AbstractSipResponseProcessor.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/response/AbstractSipResponseProcessor.java
package io.github.lunasaw.sip.common.transmit.event.response; import gov.nist.javax.sip.message.SIPResponse; import org.springframework.stereotype.Component; import javax.sip.ResponseEvent; /** * @author luna */ @Component public abstract class AbstractSipResponseProcessor implements SipResponseProcessor { public SIPResponse getResponse(ResponseEvent evt) { if (evt == null || evt.getResponse() == null) { throw new IllegalArgumentException("ResponseEvent or its response cannot be null"); } return (SIPResponse) evt.getResponse(); } public String getCallId(ResponseEvent evt) { if (evt == null) { throw new IllegalArgumentException("ResponseEvent cannot be null"); } return getResponse(evt).getCallIdHeader().getCallId(); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/response/SipResponseProcessor.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/response/SipResponseProcessor.java
package io.github.lunasaw.sip.common.transmit.event.response; import javax.sip.ResponseEvent; /** * 处理接收IPCamera发来的SIP协议响应消息 * * @author swwheihei */ public interface SipResponseProcessor { /** * 是否需要处理 */ default boolean isNeedProcess(ResponseEvent evt) { return true; } /** * 获取SIP方法类型 * * @return SIP方法类型 */ String getMethod(); /** * 处理接收IPCamera发来的SIP协议响应消息 * @param evt 消息对象 */ void process(ResponseEvent evt); }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/request/SipRequestProcessorAbstract.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/request/SipRequestProcessorAbstract.java
package io.github.lunasaw.sip.common.transmit.event.request; import com.alibaba.fastjson2.JSON; import com.google.common.collect.Maps; import com.luna.common.text.StringTools; import gov.nist.javax.sip.message.SIPRequest; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.entity.Device; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.transmit.event.message.MessageHandler; import io.github.lunasaw.sip.common.utils.XmlUtils; import io.github.lunasaw.sip.common.context.SipTransactionContext; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.MapUtils; import org.springframework.beans.factory.InitializingBean; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; import javax.sip.message.Response; import java.nio.charset.Charset; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author luna */ @Getter @Setter @Slf4j public abstract class SipRequestProcessorAbstract implements SipRequestProcessor { public static final Map<String, Map<String, MessageHandler>> MESSAGE_HANDLER_CMD_MAP = new ConcurrentHashMap<>(); public static void addHandler(MessageHandler messageHandler) { if (messageHandler == null) { return; } String key = messageHandler.getMethod() + "_" + messageHandler.getCmdType(); // 打印添加的处理器 log.info("添加消息处理器: key = {}, rootType = {}, cmdType = {}, method = {}", key, messageHandler.getRootType(), messageHandler.getCmdType(), messageHandler.getMethod()); if (MESSAGE_HANDLER_CMD_MAP.containsKey(messageHandler.getRootType())) { MESSAGE_HANDLER_CMD_MAP.get(messageHandler.getRootType()).put(key, messageHandler); } else { ConcurrentMap<String, MessageHandler> newedConcurrentMap = Maps.newConcurrentMap(); newedConcurrentMap.put(key, messageHandler); MESSAGE_HANDLER_CMD_MAP.put(messageHandler.getRootType(), newedConcurrentMap); } } public void doMessageHandForEvt(RequestEvent evt, FromDevice fromDevice) { doMessageHandForEvt(evt, fromDevice, null); } public void doMessageHandForEvt(RequestEvent evt, FromDevice fromDevice, ServerTransaction serverTransaction) { SIPRequest request = (SIPRequest) evt.getRequest(); processMessageRequest(evt, fromDevice, serverTransaction, request); } /** * 处理SIP MESSAGE请求的核心逻辑 */ private void processMessageRequest(RequestEvent evt, FromDevice fromDevice, ServerTransaction serverTransaction, SIPRequest request) { String charset = Optional.of(fromDevice).map(Device::getCharset).orElse(Constant.UTF_8); // 解析xml byte[] rawContent = request.getRawContent(); String xmlStr = StringTools.toEncodedString(rawContent, Charset.forName(charset)); log.info("开始处理消息 doMessageHandForEvt::fromDevice = {}, xmlStr = {}", JSON.toJSONString(fromDevice), xmlStr); String cmdType = XmlUtils.getCmdType(xmlStr); String rootType = XmlUtils.getRootType(xmlStr); String method = request.getMethod(); if (cmdType == null) { log.warn("XML消息中缺少CmdType元素,跳过处理: {}", xmlStr); return; } Map<String, MessageHandler> messageHandlerMap = MESSAGE_HANDLER_CMD_MAP.get(rootType); if (MapUtils.isEmpty(messageHandlerMap)) { // 没有对应的消息处理器 log.warn("doMessageHandForEvt::未找到对应的消息处理器, method = {}, rootType = {}, cmdType = {}", method, rootType, cmdType); return; } MessageHandler messageHandler = messageHandlerMap.get(method + "_" + cmdType); if (messageHandler == null) { // 没有对应的消息处理器 log.warn("doMessageHandForEvt::未找到对应的消息处理器, method = {}, rootType = {}, cmdType = {}", method, rootType, cmdType); return; } try { // GB28181协议要求:先发送200 OK响应(Step 2),然后再处理业务逻辑(Step 3) if (messageHandler.needResponseAck()) { // 立即发送200 OK响应,确保事务一致性 log.debug("立即发送200 OK响应,CmdType={}, rootType={}", cmdType, rootType); messageHandler.responseAck(evt, serverTransaction); } // 处理业务逻辑 messageHandler.setXmlStr(xmlStr); messageHandler.handForEvt(evt); } catch (Exception e) { log.error("process::evt = {}, e", evt, e); messageHandler.responseError(evt, Response.SERVER_INTERNAL_ERROR, e.getMessage(), serverTransaction); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/request/SipRequestProcessor.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/request/SipRequestProcessor.java
package io.github.lunasaw.sip.common.transmit.event.request; import javax.sip.RequestEvent; import javax.sip.ServerTransaction; /** * 对SIP事件进行处理,包括request, response, timeout, ioException, transactionTerminated,dialogTerminated * * @author luna */ public interface SipRequestProcessor { /** * 对SIP事件进行处理 * * @param event SIP事件 */ void process(RequestEvent event); /** * 对SIP事件进行处理(带预创建的服务器事务) * * @param event SIP事件 * @param serverTransaction 预创建的服务器事务(可为null) */ default void process(RequestEvent event, ServerTransaction serverTransaction) { // 默认实现调用原有方法,向后兼容 process(event); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/timeout/ITimeoutProcessor.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/event/timeout/ITimeoutProcessor.java
package io.github.lunasaw.sip.common.transmit.event.timeout; import javax.sip.TimeoutEvent; public interface ITimeoutProcessor { void process(TimeoutEvent event); }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/response/SipResponseProvider.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/response/SipResponseProvider.java
package io.github.lunasaw.sip.common.transmit.response; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import org.assertj.core.util.Lists; import javax.sip.header.*; import javax.sip.message.Response; import java.util.List; /** * @author luna * @date 2023/10/18 */ public class SipResponseProvider { public static Response createSipResponse(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { CallIdHeader callIdHeader = SipRequestUtils.createCallIdHeader(sipMessage.getCallId()); // via ViaHeader viaHeader = SipRequestUtils.createViaHeader(fromDevice.getIp(), fromDevice.getPort(), toDevice.getTransport(), sipMessage.getViaTag()); List<ViaHeader> viaHeaders = Lists.newArrayList(viaHeader); // from FromHeader fromHeader = SipRequestUtils.createFromHeader(fromDevice.getUserId(), fromDevice.getHostAddress(), fromDevice.getFromTag()); // to ToHeader toHeader = SipRequestUtils.createToHeader(toDevice.getUserId(), toDevice.getHostAddress(), toDevice.getToTag()); // Forwards MaxForwardsHeader maxForwards = SipRequestUtils.createMaxForwardsHeader(); // ceq CSeqHeader cSeqHeader = SipRequestUtils.createCSeqHeader(sipMessage.getSequence(), sipMessage.getMethod()); // request Response response = SipRequestUtils.createResponse(sipMessage.getStatusCode(), callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards, sipMessage.getContentTypeHeader(), sipMessage.getContent()); SipRequestUtils.setResponseHeader(response, sipMessage.getHeaders()); return response; } /** * 创建响应 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param callId callId * @return Request */ public static Response createOkResponse(FromDevice fromDevice, ToDevice toDevice, String method, Integer statusCode, String callId) { SipMessage sipMessage = SipMessage.getResponse(statusCode); sipMessage.setCallId(callId); sipMessage.setMethod(method); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipResponse(fromDevice, toDevice, sipMessage); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/InviteRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/InviteRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.header.ContactHeader; import javax.sip.header.SubjectHeader; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * INVITE请求构建器 * * @author luna */ public class InviteRequestBuilder extends AbstractSipRequestBuilder { /** * 创建INVITE请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param subject 主题 * @param callId 呼叫ID * @return INVITE请求 */ public Request buildInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) { SipMessage sipMessage = SipMessage.getInviteBody(); sipMessage.setMethod(Request.INVITE); sipMessage.setContent(content); sipMessage.setCallId(callId); // 临时设置subject到toDevice,用于构建请求 String originalSubject = toDevice.getSubject(); try { toDevice.setSubject(subject); return build(fromDevice, toDevice, sipMessage); } finally { // 恢复原始subject toDevice.setSubject(originalSubject); } } /** * 创建回放INVITE请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param subject 主题 * @param callId 呼叫ID * @return 回放INVITE请求 */ public Request buildPlaybackInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) { return buildInviteRequest(fromDevice, toDevice, content, subject, callId); } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); // 添加Contact头部 ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); request.addHeader(contactHeader); // 添加Subject头部(如果有的话) if (toDevice.getSubject() != null) { SubjectHeader subjectHeader = SipRequestUtils.createSubjectHeader(toDevice.getSubject()); request.addHeader(subjectHeader); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/SubscribeRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/SubscribeRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.header.ContactHeader; import javax.sip.header.EventHeader; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import com.luna.common.check.Assert; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * SUBSCRIBE请求构建器 * * @author luna */ public class SubscribeRequestBuilder extends AbstractSipRequestBuilder { /** * 创建SUBSCRIBE请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param subscribeInfo 订阅信息 * @param callId 呼叫ID * @return SUBSCRIBE请求 */ public Request buildSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId) { Assert.notNull(subscribeInfo, "subscribeInfo is null"); SipMessage sipMessage = SipMessage.getSubscribeBody(); sipMessage.setMethod(Request.SUBSCRIBE); sipMessage.setContent(content); sipMessage.setCallId(callId); return build(fromDevice, toDevice, sipMessage, subscribeInfo); } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); // 添加Contact头部 ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); request.addHeader(contactHeader); // 添加Event头部(如果有的话) if (toDevice.getEventType() != null) { EventHeader eventHeader = SipRequestUtils.createEventHeader(toDevice.getEventType(), toDevice.getEventId()); request.addHeader(eventHeader); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/AbstractSipRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/AbstractSipRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import java.util.List; import java.util.Optional; import javax.sip.address.SipURI; import javax.sip.header.*; import javax.sip.message.Request; import org.assertj.core.util.Lists; import com.luna.common.check.Assert; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPResponse; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * SIP请求构建器抽象基类 * 提供通用的SIP请求构建逻辑和模板方法 * * @author luna */ public abstract class AbstractSipRequestBuilder { /** * 构建SIP请求的模板方法 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param sipMessage SIP消息内容 * @param subscribeInfo 订阅信息(可选) * @return SIP请求 */ public Request build(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage, SubscribeInfo subscribeInfo) { // 参数校验 validateParameters(fromDevice, toDevice, sipMessage); // 处理订阅信息 processSubscribeInfo(sipMessage, subscribeInfo); // 构建基础请求 Request request = buildBaseRequest(fromDevice, toDevice, sipMessage); // 添加自定义头部 addCustomHeaders(request, sipMessage); // 子类特定的构建逻辑 customizeRequest(request, fromDevice, toDevice, sipMessage); return request; } /** * 构建SIP请求的模板方法(无订阅信息) * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param sipMessage SIP消息内容 * @return SIP请求 */ public Request build(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { return build(fromDevice, toDevice, sipMessage, null); } /** * 参数校验 */ protected void validateParameters(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { Assert.notNull(fromDevice, "发送设备不能为null"); Assert.notNull(toDevice, "接收设备不能为null"); Assert.notNull(sipMessage, "SIP消息不能为null"); } /** * 处理订阅信息 */ protected void processSubscribeInfo(SipMessage sipMessage, SubscribeInfo subscribeInfo) { if (subscribeInfo == null) { return; } // 设置CallId Optional.ofNullable(subscribeInfo.getRequest()) .map(SIPRequest::getCallIdHeader) .map(CallIdHeader::getCallId) .ifPresent(sipMessage::setCallId); // 添加过期时间头部 if (subscribeInfo.getExpires() > 0) { ExpiresHeader expiresHeader = SipRequestUtils.createExpiresHeader(subscribeInfo.getExpires()); sipMessage.addHeader(expiresHeader); } // 添加事件头部 if (subscribeInfo.getEventType() != null && subscribeInfo.getEventId() != null) { EventHeader eventHeader = SipRequestUtils.createEventHeader( subscribeInfo.getEventType(), subscribeInfo.getEventId()); sipMessage.addHeader(eventHeader); } // 添加订阅状态头部 if (subscribeInfo.getSubscriptionState() != null) { SubscriptionStateHeader subscriptionStateHeader = SipRequestUtils.createSubscriptionStateHeader( subscribeInfo.getSubscriptionState()); sipMessage.addHeader(subscriptionStateHeader); } } /** * 构建基础SIP请求 */ protected Request buildBaseRequest(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 创建CallId头部 CallIdHeader callIdHeader = SipRequestUtils.createCallIdHeader(sipMessage.getCallId()); // 创建请求URI SipURI requestUri = SipRequestUtils.createSipUri(toDevice.getUserId(), toDevice.getHostAddress()); // 创建Via头部 ViaHeader viaHeader = SipRequestUtils.createViaHeader( fromDevice.getIp(), fromDevice.getPort(), toDevice.getTransport(), sipMessage.getViaTag()); List<ViaHeader> viaHeaders = Lists.newArrayList(viaHeader); // 创建From头部 FromHeader fromHeader = SipRequestUtils.createFromHeader( fromDevice.getUserId(), fromDevice.getHostAddress(), fromDevice.getFromTag()); // 创建To头部 ToHeader toHeader = SipRequestUtils.createToHeader( toDevice.getUserId(), toDevice.getHostAddress(), toDevice.getToTag()); // 创建MaxForwards头部 MaxForwardsHeader maxForwards = SipRequestUtils.createMaxForwardsHeader(); // 创建CSeq头部 CSeqHeader cSeqHeader = SipRequestUtils.createCSeqHeader(sipMessage.getSequence(), sipMessage.getMethod()); // 创建请求 return SipRequestUtils.createRequest( requestUri, sipMessage.getMethod(), callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards, sipMessage.getContentTypeHeader(), sipMessage.getContent()); } /** * 添加自定义头部 */ protected void addCustomHeaders(Request request, SipMessage sipMessage) { SipRequestUtils.setRequestHeader(request, sipMessage.getHeaders()); } /** * 子类特定的请求定制化逻辑 * 默认空实现,子类可以重写 */ protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 默认空实现 } /** * 基于SIP响应构建请求的模板方法 */ public Request buildFromResponse(SipURI requestUri, SipMessage sipMessage, SIPResponse sipResponse) { Assert.notNull(requestUri, "请求URI不能为null"); Assert.notNull(sipMessage, "SIP消息不能为null"); Assert.notNull(sipResponse, "SIP响应不能为null"); // 创建Via头部 String hostAddress = sipResponse.getLocalAddress().getHostAddress(); int localPort = sipResponse.getLocalPort(); ViaHeader viaHeader = SipRequestUtils.createViaHeader( hostAddress, localPort, sipResponse.getTopmostViaHeader().getTransport(), sipMessage.getViaTag()); List<ViaHeader> viaHeaders = Lists.newArrayList(viaHeader); // 创建MaxForwards头部 MaxForwardsHeader maxForwards = SipRequestUtils.createMaxForwardsHeader(); // 创建CSeq头部 CSeqHeader cSeqHeader = SipRequestUtils.createCSeqHeader(sipMessage.getSequence(), sipMessage.getMethod()); // 创建请求 Request request = SipRequestUtils.createRequest( requestUri, sipMessage.getMethod(), sipResponse.getCallIdHeader(), cSeqHeader, sipResponse.getFromHeader(), sipResponse.getToHeader(), viaHeaders, maxForwards, sipMessage.getContentTypeHeader(), sipMessage.getContent()); // 添加自定义头部 addCustomHeaders(request, sipMessage); return request; } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/SipRequestProvider.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/SipRequestProvider.java
package io.github.lunasaw.sip.common.transmit.request; import java.text.ParseException; import java.util.List; import java.util.Optional; import java.util.UUID; import javax.sip.address.SipURI; import javax.sip.address.URI; import javax.sip.header.*; import javax.sip.message.Request; import org.apache.commons.lang3.StringUtils; import org.assertj.core.util.Lists; import org.springframework.util.DigestUtils; import com.luna.common.check.Assert; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPResponse; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.enums.ContentTypeEnum; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * Sip命令request创造器 * * @deprecated 请使用 {@link SipRequestBuilderFactory} 替代此类 * 此类保留是为了向后兼容,新代码建议使用新的构建器模式 */ @Deprecated public class SipRequestProvider { /** * 带订阅创建SIP请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param sipMessage 内容 * @param subscribeInfo 订阅消息 * @return */ public static Request createSipRequest(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage, SubscribeInfo subscribeInfo) { if (subscribeInfo != null) { Optional.ofNullable(subscribeInfo.getRequest()).map(SIPRequest::getCallIdHeader).map(CallIdHeader::getCallId) .ifPresent(sipMessage::setCallId); Optional.ofNullable(subscribeInfo.getResponse()).map(SIPResponse::getToTag).ifPresent(fromDevice::setFromTag); Optional.ofNullable(subscribeInfo.getRequest()).map(SIPRequest::getFromTag).ifPresent(toDevice::setToTag); if (subscribeInfo.getExpires() > 0) { ExpiresHeader expiresHeader = SipRequestUtils.createExpiresHeader(subscribeInfo.getExpires()); sipMessage.addHeader(expiresHeader); } if (subscribeInfo.getEventType() != null && subscribeInfo.getEventId() != null) { EventHeader eventHeader = SipRequestUtils.createEventHeader(subscribeInfo.getEventType(), subscribeInfo.getEventId()); sipMessage.addHeader(eventHeader); } if (subscribeInfo.getSubscriptionState() != null) { SubscriptionStateHeader subscriptionStateHeader = SipRequestUtils.createSubscriptionStateHeader(subscribeInfo.getSubscriptionState()); sipMessage.addHeader(subscriptionStateHeader); } } return createSipRequest(fromDevice, toDevice, sipMessage); } /** * 创建SIP请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param sipMessage 内容 * @return Request */ public static Request createSipRequest(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { Assert.notNull(fromDevice, "发送设备不能为null"); Assert.notNull(toDevice, "发送设备不能为null"); CallIdHeader callIdHeader = SipRequestUtils.createCallIdHeader(sipMessage.getCallId()); // sipUri SipURI requestUri = SipRequestUtils.createSipUri(toDevice.getUserId(), toDevice.getHostAddress()); // via ViaHeader viaHeader = SipRequestUtils.createViaHeader(fromDevice.getIp(), fromDevice.getPort(), toDevice.getTransport(), sipMessage.getViaTag()); List<ViaHeader> viaHeaders = Lists.newArrayList(viaHeader); // from FromHeader fromHeader = SipRequestUtils.createFromHeader(fromDevice.getUserId(), fromDevice.getHostAddress(), fromDevice.getFromTag()); // to ToHeader toHeader = SipRequestUtils.createToHeader(toDevice.getUserId(), toDevice.getHostAddress(), toDevice.getToTag()); // Forwards MaxForwardsHeader maxForwards = SipRequestUtils.createMaxForwardsHeader(); // ceq CSeqHeader cSeqHeader = SipRequestUtils.createCSeqHeader(sipMessage.getSequence(), sipMessage.getMethod()); // request Request request = SipRequestUtils.createRequest(requestUri, sipMessage.getMethod(), callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards, sipMessage.getContentTypeHeader(), sipMessage.getContent()); SipRequestUtils.setRequestHeader(request, sipMessage.getHeaders()); return request; } public static Request createSipRequest(SipURI requestUri, SipMessage sipMessage, SIPResponse sipResponse) { Assert.notNull(requestUri, "发送设备不能为null"); Assert.notNull(sipMessage, "发送设备不能为null"); // via String hostAddress = sipResponse.getLocalAddress().getHostAddress(); int localPort = sipResponse.getLocalPort(); ViaHeader viaHeader = SipRequestUtils.createViaHeader(hostAddress, localPort, sipResponse.getTopmostViaHeader().getTransport(), sipMessage.getViaTag()); List<ViaHeader> viaHeaders = Lists.newArrayList(viaHeader); // Forwards MaxForwardsHeader maxForwards = SipRequestUtils.createMaxForwardsHeader(); // ceq CSeqHeader cSeqHeader = SipRequestUtils.createCSeqHeader(sipMessage.getSequence(), sipMessage.getMethod()); // request Request request = SipRequestUtils.createRequest(requestUri, sipMessage.getMethod(), sipResponse.getCallIdHeader(), cSeqHeader, sipResponse.getFromHeader(), sipResponse.getToHeader(), viaHeaders, maxForwards, sipMessage.getContentTypeHeader(), sipMessage.getContent()); SipRequestUtils.setRequestHeader(request, sipMessage.getHeaders()); return request; } /** * 创建Message请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param content 内容 * @param callId callId * @return Request */ public static Request createMessageRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getMessageBody(); sipMessage.setMethod(Request.MESSAGE); sipMessage.setContent(content); sipMessage.setCallId(callId); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); sipMessage.addHeader(userAgentHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } /** * 创建Invite请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param content 内容 * @param callId callId * @return Request */ public static Request createInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) { SipMessage sipMessage = SipMessage.getInviteBody(); sipMessage.setMethod(Request.INVITE); sipMessage.setContent(content); sipMessage.setCallId(callId); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); SubjectHeader subjectHeader = SipRequestUtils.createSubjectHeader(subject); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader).addHeader(subjectHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } public Request createPlaybackInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) { return createInviteRequest(fromDevice, toDevice, content, subject, callId); } /** * 创建Bye请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param callId callId * @return Request */ public static Request createByeRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { SipMessage sipMessage = SipMessage.getByeBody(); sipMessage.setMethod(Request.BYE); sipMessage.setCallId(callId); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } /** * 创建Register请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param callId callId * @return Request */ public static Request createRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, String callId) { SipMessage sipMessage = SipMessage.getRegisterBody(); sipMessage.setMethod(Request.REGISTER); sipMessage.setCallId(callId); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); ExpiresHeader expiresHeader = SipRequestUtils.createExpiresHeader(expires); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader).addHeader(expiresHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } /** * 带签名的注册构造器 * * @param www 认证头 * @return Request */ public static Request createRegisterRequestWithAuth(FromDevice fromDevice, ToDevice toDevice, String callId, Integer expires, WWWAuthenticateHeader www) { return SipRequestBuilderFactory.createRegisterRequestWithAuth(fromDevice, toDevice, callId, expires, www); } /** * 创建Subscribe请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param content 内容 * @param callId callId * @return Request */ public static Request createSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getSubscribeBody(); sipMessage.setMethod(Request.SUBSCRIBE); sipMessage.setContent(content); sipMessage.setCallId(callId); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } /** * 创建INFO 请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param content 内容 * @param callId callId * @return Request */ public static Request createInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getInfoBody(); sipMessage.setMethod(Request.INFO); sipMessage.setContent(content); sipMessage.setCallId(callId); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } /** * 创建ACK请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param callId callId * @return Request */ public static Request createAckRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { return createAckRequest(fromDevice, toDevice, null, callId); } public static Request createAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getAckBody(); sipMessage.setMethod(Request.ACK); sipMessage.setCallId(callId); if (StringUtils.isNotBlank(content)) { sipMessage.setContent(content); sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_SDP.getContentTypeHeader()); } UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } public static Request createAckRequest(FromDevice fromDevice, SipURI sipURI, SIPResponse sipResponse) { return createAckRequest(fromDevice, sipURI, null, sipResponse); } public static Request createAckRequest(FromDevice fromDevice, SipURI sipURI, String content, SIPResponse sipResponse) { SipMessage sipMessage = SipMessage.getAckBody(sipResponse); sipMessage.setMethod(Request.ACK); sipMessage.setCallId(sipResponse.getCallId().getCallId()); if (StringUtils.isNotBlank(content)) { sipMessage.setContent(content); sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_SDP.getContentTypeHeader()); } UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipRequest(sipURI, sipMessage, sipResponse); } /** * 创建Notify请求 * * @param fromDevice 发送设备 * @param toDevice 发送目的设备 * @param content 内容 * @param callId callId * @return Request */ public static Request createNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getNotifyBody(); sipMessage.setMethod(Request.NOTIFY); sipMessage.setCallId(callId); sipMessage.setContent(content); UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); sipMessage.addHeader(userAgentHeader).addHeader(contactHeader); return createSipRequest(fromDevice, toDevice, sipMessage); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/AckRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/AckRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.address.SipURI; import javax.sip.header.ContactHeader; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import org.apache.commons.lang3.StringUtils; import gov.nist.javax.sip.message.SIPResponse; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.enums.ContentTypeEnum; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * ACK请求构建器 * * @author luna */ public class AckRequestBuilder extends AbstractSipRequestBuilder { /** * 创建ACK请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param callId 呼叫ID * @return ACK请求 */ public Request buildAckRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { return buildAckRequest(fromDevice, toDevice, null, callId); } /** * 创建带内容的ACK请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param callId 呼叫ID * @return ACK请求 */ public Request buildAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getAckBody(); sipMessage.setMethod(Request.ACK); sipMessage.setCallId(callId); if (StringUtils.isNotBlank(content)) { sipMessage.setContent(content); sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_SDP.getContentTypeHeader()); } return build(fromDevice, toDevice, sipMessage); } /** * 基于SIP响应创建ACK请求 * * @param fromDevice 发送设备 * @param sipURI 请求URI * @param sipResponse SIP响应 * @return ACK请求 */ public Request buildAckRequest(FromDevice fromDevice, SipURI sipURI, SIPResponse sipResponse) { return buildAckRequest(fromDevice, sipURI, null, sipResponse); } /** * 基于SIP响应创建带内容的ACK请求 * * @param fromDevice 发送设备 * @param sipURI 请求URI * @param content 消息内容 * @param sipResponse SIP响应 * @return ACK请求 */ public Request buildAckRequest(FromDevice fromDevice, SipURI sipURI, String content, SIPResponse sipResponse) { SipMessage sipMessage = SipMessage.getAckBody(sipResponse); sipMessage.setMethod(Request.ACK); sipMessage.setCallId(sipResponse.getCallId().getCallId()); if (StringUtils.isNotBlank(content)) { sipMessage.setContent(content); sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_SDP.getContentTypeHeader()); } return buildFromResponse(sipURI, sipMessage, sipResponse); } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); // 添加Contact头部 ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); request.addHeader(contactHeader); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/NotifyRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/NotifyRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.header.ContactHeader; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * NOTIFY请求构建器 * * @author luna */ public class NotifyRequestBuilder extends AbstractSipRequestBuilder { /** * 创建NOTIFY请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param subscribeInfo 订阅信息 * @param callId 呼叫ID * @return NOTIFY请求 */ public Request buildNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId) { SipMessage sipMessage = SipMessage.getNotifyBody(); sipMessage.setMethod(Request.NOTIFY); sipMessage.setCallId(callId); sipMessage.setContent(content); return build(fromDevice, toDevice, sipMessage, subscribeInfo); } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); // 添加Contact头部 ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); request.addHeader(contactHeader); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/SipRequestBuilderFactory.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/SipRequestBuilderFactory.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.message.Request; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; /** * SIP请求构建器工厂类 * 提供统一的构建器获取接口和便捷的构建方法 * * @author luna */ public class SipRequestBuilderFactory { // 单例构建器实例 private static final MessageRequestBuilder MESSAGE_BUILDER = new MessageRequestBuilder(); private static final InviteRequestBuilder INVITE_BUILDER = new InviteRequestBuilder(); private static final ByeRequestBuilder BYE_BUILDER = new ByeRequestBuilder(); private static final RegisterRequestBuilder REGISTER_BUILDER = new RegisterRequestBuilder(); private static final SubscribeRequestBuilder SUBSCRIBE_BUILDER = new SubscribeRequestBuilder(); private static final InfoRequestBuilder INFO_BUILDER = new InfoRequestBuilder(); private static final AckRequestBuilder ACK_BUILDER = new AckRequestBuilder(); private static final NotifyRequestBuilder NOTIFY_BUILDER = new NotifyRequestBuilder(); /** * 获取MESSAGE请求构建器 */ public static MessageRequestBuilder getMessageBuilder() { return MESSAGE_BUILDER; } /** * 获取INVITE请求构建器 */ public static InviteRequestBuilder getInviteBuilder() { return INVITE_BUILDER; } /** * 获取BYE请求构建器 */ public static ByeRequestBuilder getByeBuilder() { return BYE_BUILDER; } /** * 获取REGISTER请求构建器 */ public static RegisterRequestBuilder getRegisterBuilder() { return REGISTER_BUILDER; } /** * 获取SUBSCRIBE请求构建器 */ public static SubscribeRequestBuilder getSubscribeBuilder() { return SUBSCRIBE_BUILDER; } /** * 获取INFO请求构建器 */ public static InfoRequestBuilder getInfoBuilder() { return INFO_BUILDER; } /** * 获取ACK请求构建器 */ public static AckRequestBuilder getAckBuilder() { return ACK_BUILDER; } /** * 获取NOTIFY请求构建器 */ public static NotifyRequestBuilder getNotifyBuilder() { return NOTIFY_BUILDER; } // ========== 便捷构建方法 ========== /** * 创建MESSAGE请求 */ public static Request createMessageRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return MESSAGE_BUILDER.buildMessageRequest(fromDevice, toDevice, content, callId); } /** * 创建INVITE请求 */ public static Request createInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) { return INVITE_BUILDER.buildInviteRequest(fromDevice, toDevice, content, subject, callId); } /** * 创建回放INVITE请求 */ public static Request createPlaybackInviteRequest(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) { return INVITE_BUILDER.buildPlaybackInviteRequest(fromDevice, toDevice, content, subject, callId); } /** * 创建BYE请求 */ public static Request createByeRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { return BYE_BUILDER.buildByeRequest(fromDevice, toDevice, callId); } /** * 创建REGISTER请求 */ public static Request createRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, String callId) { return REGISTER_BUILDER.buildRegisterRequest(fromDevice, toDevice, expires, callId); } /** * 创建带认证的REGISTER请求 */ public static Request createRegisterRequestWithAuth(FromDevice fromDevice, ToDevice toDevice, String callId, Integer expires, javax.sip.header.WWWAuthenticateHeader www) { return REGISTER_BUILDER.buildRegisterRequestWithAuth(fromDevice, toDevice, callId, expires, www); } /** * 创建SUBSCRIBE请求 */ public static Request createSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId) { return SUBSCRIBE_BUILDER.buildSubscribeRequest(fromDevice, toDevice, content, subscribeInfo, callId); } /** * 创建INFO请求 */ public static Request createInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return INFO_BUILDER.buildInfoRequest(fromDevice, toDevice, content, callId); } /** * 创建ACK请求 */ public static Request createAckRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { return ACK_BUILDER.buildAckRequest(fromDevice, toDevice, callId); } /** * 创建带内容的ACK请求 */ public static Request createAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return ACK_BUILDER.buildAckRequest(fromDevice, toDevice, content, callId); } /** * 创建NOTIFY请求 */ public static Request createNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return NOTIFY_BUILDER.buildNotifyRequest(fromDevice, toDevice, content, null, callId); } /** * 通用SIP请求构建方法 */ public static Request createSipRequest(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { return createSipRequest(fromDevice, toDevice, sipMessage, null); } /** * 通用SIP请求构建方法(带订阅信息) */ public static Request createSipRequest(FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage, SubscribeInfo subscribeInfo) { // 根据方法类型选择合适的构建器 switch (sipMessage.getMethod()) { case Request.MESSAGE: return MESSAGE_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.INVITE: return INVITE_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.BYE: return BYE_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.REGISTER: return REGISTER_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.SUBSCRIBE: return SUBSCRIBE_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.INFO: return INFO_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.ACK: return ACK_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); case Request.NOTIFY: return NOTIFY_BUILDER.build(fromDevice, toDevice, sipMessage, subscribeInfo); default: throw new IllegalArgumentException("Unsupported SIP method: " + sipMessage.getMethod()); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/MessageRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/MessageRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * MESSAGE请求构建器 * * @author luna */ public class MessageRequestBuilder extends AbstractSipRequestBuilder { /** * 创建MESSAGE请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param callId 呼叫ID * @return MESSAGE请求 */ public Request buildMessageRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getMessageBody(); sipMessage.setMethod(Request.MESSAGE); sipMessage.setContent(content); sipMessage.setCallId(callId); return build(fromDevice, toDevice, sipMessage); } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/InfoRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/InfoRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import javax.sip.header.ContactHeader; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * INFO请求构建器 * * @author luna */ public class InfoRequestBuilder extends AbstractSipRequestBuilder { /** * 创建INFO请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param content 消息内容 * @param callId 呼叫ID * @return INFO请求 */ public Request buildInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { SipMessage sipMessage = SipMessage.getInfoBody(); sipMessage.setMethod(Request.INFO); sipMessage.setContent(content); // 确保callId不为null,如果为null则生成一个新的 if (callId == null || callId.trim().isEmpty()) { callId = SipRequestUtils.getNewCallId(); } sipMessage.setCallId(callId); return build(fromDevice, toDevice, sipMessage); } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); // 添加Contact头部 ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); request.addHeader(contactHeader); } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false
lunasaw/gb28181-proxy
https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/RegisterRequestBuilder.java
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/RegisterRequestBuilder.java
package io.github.lunasaw.sip.common.transmit.request; import java.text.ParseException; import java.util.UUID; import javax.sip.address.URI; import javax.sip.header.AuthorizationHeader; import javax.sip.header.ContactHeader; import javax.sip.header.ExpiresHeader; import javax.sip.header.UserAgentHeader; import javax.sip.header.WWWAuthenticateHeader; import javax.sip.message.Request; import org.springframework.util.DigestUtils; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.SipMessage; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.utils.SipRequestUtils; /** * REGISTER请求构建器 * * @author luna */ public class RegisterRequestBuilder extends AbstractSipRequestBuilder { /** * 创建REGISTER请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param expires 过期时间 * @param callId 呼叫ID * @return REGISTER请求 */ public Request buildRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, String callId) { SipMessage sipMessage = SipMessage.getRegisterBody(); sipMessage.setMethod(Request.REGISTER); sipMessage.setCallId(callId); // 临时设置expires到toDevice,用于构建请求 Integer originalExpires = toDevice.getExpires(); try { toDevice.setExpires(expires); return build(fromDevice, toDevice, sipMessage); } finally { // 恢复原始expires toDevice.setExpires(originalExpires); } } /** * 创建带认证的REGISTER请求 * * @param fromDevice 发送设备 * @param toDevice 接收设备 * @param callId 呼叫ID * @param expires 过期时间 * @param www 认证头 * @return 带认证的REGISTER请求 */ public Request buildRegisterRequestWithAuth(FromDevice fromDevice, ToDevice toDevice, String callId, Integer expires, WWWAuthenticateHeader www) { Request registerRequest = buildRegisterRequest(fromDevice, toDevice, expires, callId); URI requestURI = registerRequest.getRequestURI(); String userId = toDevice.getUserId(); String password = toDevice.getPassword(); if (www == null) { try { AuthorizationHeader authorizationHeader = SipRequestUtils.createAuthorizationHeader("Digest"); String username = fromDevice.getUserId(); authorizationHeader.setUsername(username); authorizationHeader.setURI(requestURI); authorizationHeader.setAlgorithm("MD5"); registerRequest.addHeader(authorizationHeader); return registerRequest; } catch (ParseException e) { throw new RuntimeException(e); } } String realm = www.getRealm(); String nonce = www.getNonce(); String scheme = www.getScheme(); String qop = www.getQop(); String cNonce = null; String nc = "00000001"; if (qop != null) { if ("auth".equalsIgnoreCase(qop)) { cNonce = UUID.randomUUID().toString(); } else if ("auth-int".equalsIgnoreCase(qop)) { // TODO: 实现auth-int逻辑 } } String HA1 = DigestUtils.md5DigestAsHex((userId + ":" + realm + ":" + password).getBytes()); String HA2 = DigestUtils.md5DigestAsHex((Request.REGISTER + ":" + requestURI.toString()).getBytes()); StringBuilder reStr = new StringBuilder(200); reStr.append(HA1); reStr.append(":"); reStr.append(nonce); reStr.append(":"); if (qop != null) { reStr.append(nc); reStr.append(":"); reStr.append(cNonce); reStr.append(":"); reStr.append(qop); reStr.append(":"); } reStr.append(HA2); String RESPONSE = DigestUtils.md5DigestAsHex(reStr.toString().getBytes()); AuthorizationHeader authorizationHeader = SipRequestUtils.createAuthorizationHeader( scheme, userId, requestURI, realm, nonce, qop, cNonce, RESPONSE); registerRequest.addHeader(authorizationHeader); return registerRequest; } @Override protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) { // 添加User-Agent头部 UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent()); request.addHeader(userAgentHeader); // 添加Contact头部 ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress()); request.addHeader(contactHeader); // 添加Expires头部 if (toDevice.getExpires() != null) { ExpiresHeader expiresHeader = SipRequestUtils.createExpiresHeader(toDevice.getExpires()); request.addHeader(expiresHeader); } } }
java
Apache-2.0
540577abe2124425b68b6288de9e9fc341b1f1fc
2026-01-05T02:36:27.870323Z
false