index
int64 0
36.5k
| proj_name
stringclasses 162
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
51
| masked_class
stringlengths 68
9.82k
| func_body
stringlengths 46
9.61k
| len_func_body
int64 1
5.26k
| len_input
int64 27
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
|
---|---|---|---|---|---|---|---|---|---|---|
36,021 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/common/StreamURL.java | StreamURL | toString | class StreamURL implements Serializable,Cloneable {
@Schema(description = "协议")
private String protocol;
@Schema(description = "主机地址")
private String host;
@Schema(description = "端口")
private int port = -1;
@Schema(description = "定位位置")
private String file;
@Schema(description = "拼接后的地址")
private String url;
public StreamURL() {
}
public StreamURL(String protocol, String host, int port, String file) {
this.protocol = protocol;
this.host = host;
this.port = port;
this.file = file;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getUrl() {
return this.toString();
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
@Override
public StreamURL clone() throws CloneNotSupportedException {
return (StreamURL) super.clone();
}
} |
if (protocol != null && host != null && port != -1 ) {
return String.format("%s://%s:%s/%s", protocol, host, port, file);
}else {
return null;
}
| 73 | 412 | 63 | 475 |
36,022 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ApiAccessFilter.java | ApiAccessFilter | doFilterInternal | class ApiAccessFilter extends OncePerRequestFilter {
private final static Logger logger = LoggerFactory.getLogger(ApiAccessFilter.class);
@Autowired
private UserSetting userSetting;
@Autowired
private ILogService logService;
@Override
protected void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
/**
* 获取IP地址
*
* @param request 请求
* @return request发起客户端的IP地址
*/
private String getIP(HttpServletRequest request) {
if (request == null) {
return "0.0.0.0";
}
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
String UNKNOWN_IP = "unknown";
if (StringUtils.isNotEmpty(XFor) && !UNKNOWN_IP.equalsIgnoreCase(XFor)) {
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if (index != -1) {
return XFor.substring(0, index);
} else {
return XFor;
}
}
XFor = Xip;
if (StringUtils.isNotEmpty(XFor) && !UNKNOWN_IP.equalsIgnoreCase(XFor)) {
return XFor;
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || UNKNOWN_IP.equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
} |
String username = null;
if (SecurityUtils.getUserInfo() == null) {
username = servletRequest.getParameter("username");
}else {
username = SecurityUtils.getUserInfo().getUsername();
}
long start = System.currentTimeMillis(); // 请求进入时间
String uriName = ApiSaveConstant.getVal(servletRequest.getRequestURI());
filterChain.doFilter(servletRequest, servletResponse);
if (uriName != null && userSetting != null && userSetting.getLogInDatabase() != null && userSetting.getLogInDatabase()) {
LogDto logDto = new LogDto();
logDto.setName(uriName);
if (ObjectUtils.isEmpty(username)) {
username = "";
}
logDto.setUsername(username);
logDto.setAddress(servletRequest.getRemoteAddr());
logDto.setResult(HttpStatus.valueOf(servletResponse.getStatus()).toString());
logDto.setTiming(System.currentTimeMillis() - start);
logDto.setType(servletRequest.getMethod());
logDto.setUri(servletRequest.getRequestURI());
logDto.setCreateTime(DateUtil.getNow());
logService.add(logDto);
}
| 306 | 657 | 340 | 997 |
36,023 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/CivilCodeFileConf.java | CivilCodeFileConf | run | class CivilCodeFileConf implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(CivilCodeFileConf.class);
@Autowired
@Lazy
private UserSetting userSetting;
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
} |
if (ObjectUtils.isEmpty(userSetting.getCivilCodeFile())) {
logger.warn("[行政区划] 文件未设置,可能造成目录刷新结果不完整");
return;
}
InputStream inputStream;
if (userSetting.getCivilCodeFile().startsWith("classpath:")){
String filePath = userSetting.getCivilCodeFile().substring("classpath:".length());
ClassPathResource civilCodeFile = new ClassPathResource(filePath);
if (!civilCodeFile.exists()) {
logger.warn("[行政区划] 文件<{}>不存在,可能造成目录刷新结果不完整", userSetting.getCivilCodeFile());
return;
}
inputStream = civilCodeFile.getInputStream();
}else {
File civilCodeFile = new File(userSetting.getCivilCodeFile());
if (!civilCodeFile.exists()) {
logger.warn("[行政区划] 文件<{}>不存在,可能造成目录刷新结果不完整", userSetting.getCivilCodeFile());
return;
}
inputStream = Files.newInputStream(civilCodeFile.toPath());
}
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(inputStream));
int index = -1;
String line;
List<CivilCodePo> civilCodePoList = new ArrayList<>();
while ((line = inputStreamReader.readLine()) != null) {
index ++;
if (index == 0) {
continue;
}
String[] infoArray = line.split(",");
CivilCodePo civilCodePo = CivilCodePo.getInstance(infoArray);
civilCodePoList.add(civilCodePo);
}
CivilCodeUtil.INSTANCE.add(civilCodePoList);
inputStreamReader.close();
inputStream.close();
if (civilCodePoList.isEmpty()) {
logger.warn("[行政区划] 文件内容为空,可能造成目录刷新结果不完整");
}else {
logger.info("[行政区划] 加载成功,共加载数据{}条", civilCodePoList.size());
}
| 522 | 88 | 547 | 635 |
36,024 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/CloudRecordTimer.java | CloudRecordTimer | execute | class CloudRecordTimer {
private final static Logger logger = LoggerFactory.getLogger(CloudRecordTimer.class);
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private CloudRecordServiceMapper cloudRecordServiceMapper;
/**
* 定时查询待删除的录像文件
*/
// @Scheduled(fixedRate = 10000) //每五秒执行一次,方便测试
@Scheduled(cron = "0 0 0 * * ?") //每天的0点执行
public void execute(){<FILL_FUNCTION_BODY>}
} |
logger.info("[录像文件定时清理] 开始清理过期录像文件");
// 获取配置了assist的流媒体节点
List<MediaServer> mediaServerItemList = mediaServerService.getAllOnline();
if (mediaServerItemList.isEmpty()) {
return;
}
long result = 0;
for (MediaServer mediaServerItem : mediaServerItemList) {
Calendar lastCalendar = Calendar.getInstance();
if (mediaServerItem.getRecordDay() > 0) {
lastCalendar.setTime(new Date());
// 获取保存的最后截至日[期,因为每个节点都有一个日期,也就是支持每个节点设置不同的保存日期,
lastCalendar.add(Calendar.DAY_OF_MONTH, -mediaServerItem.getRecordDay());
Long lastDate = lastCalendar.getTimeInMillis();
// 获取到截至日期之前的录像文件列表,文件列表满足未被收藏和保持的。这两个字段目前共能一致,
// 为我自己业务系统相关的代码,大家使用的时候直接使用收藏(collect)这一个类型即可
List<CloudRecordItem> cloudRecordItemList = cloudRecordServiceMapper.queryRecordListForDelete(lastDate, mediaServerItem.getId());
if (cloudRecordItemList.isEmpty()) {
continue;
}
// TODO 后续可以删除空了的过期日期文件夹
for (CloudRecordItem cloudRecordItem : cloudRecordItemList) {
String date = new File(cloudRecordItem.getFilePath()).getParentFile().getName();
boolean deleteResult = mediaServerService.deleteRecordDirectory(mediaServerItem, cloudRecordItem.getApp(),
cloudRecordItem.getStream(), date, cloudRecordItem.getFileName());
if (deleteResult) {
logger.warn("[录像文件定时清理] 删除磁盘文件成功: {}", cloudRecordItem.getFilePath());
}
}
result += cloudRecordServiceMapper.deleteList(cloudRecordItemList);
}
}
logger.info("[录像文件定时清理] 共清理{}个过期录像文件", result);
| 548 | 160 | 533 | 693 |
36,025 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/DynamicTask.java | DynamicTask | contains | class DynamicTask {
private final Logger logger = LoggerFactory.getLogger(DynamicTask.class);
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private final Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
private final Map<String, Runnable> runnableMap = new ConcurrentHashMap<>();
@PostConstruct
public void DynamicTask() {
threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(300);
threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
threadPoolTaskScheduler.setAwaitTerminationSeconds(10);
threadPoolTaskScheduler.initialize();
}
/**
* 循环执行的任务
* @param key 任务ID
* @param task 任务
* @param cycleForCatalog 间隔 毫秒
* @return
*/
public void startCron(String key, Runnable task, int cycleForCatalog) {
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, cycleForCatalog表示执行的间隔
future = threadPoolTaskScheduler.scheduleAtFixedRate(task, new Date(System.currentTimeMillis() + cycleForCatalog), cycleForCatalog);
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) {<FILL_FUNCTION_BODY>}
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();
}
} |
if(ObjectUtils.isEmpty(key)) {
return false;
}
return futureMap.get(key) != null;
| 46 | 1,314 | 37 | 1,351 |
36,026 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/GlobalResponseAdvice.java | GlobalResponseAdvice | beforeBodyWrite | class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType, @NotNull MediaType selectedContentType, @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType, @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {<FILL_FUNCTION_BODY>}
/**
* 防止返回string时出错
* @return
*/
/*@Bean
public HttpMessageConverters custHttpMessageConverter() {
return new HttpMessageConverters(new FastJsonHttpMessageConverter());
}*/
} |
// 排除api文档的接口,这个接口不需要统一
String[] excludePath = {"/v3/api-docs","/api/v1","/index/hook","/api/video-"};
for (String path : excludePath) {
if (request.getURI().getPath().startsWith(path)) {
return body;
}
}
if (body instanceof WVPResult) {
return body;
}
if (body instanceof ErrorCode) {
ErrorCode errorCode = (ErrorCode) body;
return new WVPResult<>(errorCode.getCode(), errorCode.getMsg(), null);
}
if (body instanceof String) {
return JSON.toJSONString(WVPResult.success(body));
}
return WVPResult.success(body);
| 216 | 197 | 207 | 404 |
36,028 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/MybatisConfig.java | MybatisConfig | databaseIdProvider | class MybatisConfig {
@Autowired
private UserSetting userSetting;
@Bean
public DatabaseIdProvider databaseIdProvider() {<FILL_FUNCTION_BODY>}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource, DatabaseIdProvider databaseIdProvider) throws Exception {
final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
if (userSetting.getSqlLog()){
config.setLogImpl(StdOutImpl.class);
}
config.setMapUnderscoreToCamelCase(true);
sqlSessionFactory.setConfiguration(config);
sqlSessionFactory.setDatabaseIdProvider(databaseIdProvider);
return sqlSessionFactory.getObject();
}
} |
VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
Properties properties = new Properties();
properties.setProperty("Oracle", "oracle");
properties.setProperty("MySQL", "mysql");
properties.setProperty("DB2", "db2");
properties.setProperty("Derby", "derby");
properties.setProperty("H2", "h2");
properties.setProperty("HSQL", "hsql");
properties.setProperty("Informix", "informix");
properties.setProperty("MS-SQL", "ms-sql");
properties.setProperty("PostgreSQL", "postgresql");
properties.setProperty("Sybase", "sybase");
properties.setProperty("Hana", "hana");
properties.setProperty("DM", "dm");
properties.setProperty("KingbaseES", "kingbase");
properties.setProperty("KingBase8", "kingbase");
databaseIdProvider.setProperties(properties);
return databaseIdProvider;
| 172 | 227 | 246 | 473 |
36,029 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ProxyServletConfig.java | RecordProxyServlet | rewriteUrlFromRequest | class RecordProxyServlet extends ProxyServlet{
@Override
protected String rewriteQueryStringFromRequest(HttpServletRequest servletRequest, String queryString) {
String queryStr = super.rewriteQueryStringFromRequest(servletRequest, queryString);
MediaServer mediaInfo = getMediaInfoByUri(servletRequest.getRequestURI());
if (mediaInfo == null) {
return null;
}
String remoteHost = String.format("http://%s:%s", mediaInfo.getStreamIp(), mediaInfo.getRecordAssistPort());
if (!ObjectUtils.isEmpty(queryStr)) {
queryStr += "&remoteHost=" + remoteHost;
}else {
queryStr = "remoteHost=" + remoteHost;
}
return queryStr;
}
@Override
protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
HttpRequest proxyRequest) throws IOException {
HttpResponse response = super.doExecute(servletRequest, servletResponse, proxyRequest);
String origin = servletRequest.getHeader("origin");
response.setHeader("Access-Control-Allow-Origin",origin);
response.setHeader("Access-Control-Allow-Credentials","true");
return response;
}
/**
* 异常处理
*/
@Override
protected void handleRequestException(HttpRequest proxyRequest, HttpResponse proxyResponse, Exception e){
try {
super.handleRequestException(proxyRequest, proxyResponse, e);
} catch (ServletException servletException) {
logger.error("录像服务 代理失败: ", e);
} catch (IOException ioException) {
if (ioException instanceof ConnectException) {
logger.error("录像服务 连接失败");
// }else if (ioException instanceof ClientAbortException) {
// /**
// * TODO 使用这个代理库实现代理在遇到代理视频文件时,如果是206结果,会遇到报错蛋市目前功能正常,
// * TODO 暂时去除异常处理。后续使用其他代理框架修改测试
// */
}else {
logger.error("录像服务 代理失败: ", e);
}
} catch (RuntimeException exception){
logger.error("录像服务 代理失败: ", e);
}
}
/**
* 对于为按照格式请求的可以直接返回404
*/
@Override
protected String getTargetUri(HttpServletRequest servletRequest) {
String requestURI = servletRequest.getRequestURI();
MediaServer mediaInfo = getMediaInfoByUri(requestURI);
String uri = null;
if (mediaInfo != null) {
// String realRequestURI = requestURI.substring(requestURI.indexOf(mediaInfo.getId())+ mediaInfo.getId().length());
uri = String.format("http://%s:%s", mediaInfo.getIp(), mediaInfo.getRecordAssistPort());
}else {
uri = "http://127.0.0.1:" + serverPort +"/index/hook/null"; // 只是一个能返回404的请求而已, 其他的也可以
}
return uri;
}
/**
* 动态替换请求目标
*/
@Override
protected HttpHost getTargetHost(HttpServletRequest servletRequest) {
String requestURI = servletRequest.getRequestURI();
MediaServer mediaInfo = getMediaInfoByUri(requestURI);
HttpHost host;
if (mediaInfo != null) {
host = new HttpHost(mediaInfo.getIp(), mediaInfo.getRecordAssistPort());
}else {
host = new HttpHost("127.0.0.1", serverPort);
}
return host;
}
/**
* 根据uri获取流媒体信息
*/
MediaServer getMediaInfoByUri(String uri){
String[] split = uri.split("/");
String mediaServerId = split[2];
if ("default".equalsIgnoreCase(mediaServerId)) {
return mediaServerService.getDefaultMediaServer();
}else {
return mediaServerService.getOne(mediaServerId);
}
}
/**
* 去掉url中的标志信息
*/
@Override
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {<FILL_FUNCTION_BODY>}
} |
String requestURI = servletRequest.getRequestURI();
MediaServer mediaInfo = getMediaInfoByUri(requestURI);
String url = super.rewriteUrlFromRequest(servletRequest);
if (mediaInfo == null) {
logger.error("[录像服务访问代理],错误:处理url信息时未找到流媒体信息=>{}", requestURI);
return url;
}
if (!ObjectUtils.isEmpty(mediaInfo.getId())) {
url = url.replace(mediaInfo.getId() + "/", "");
}
return url.replace("default/", "");
| 178 | 1,095 | 150 | 1,245 |
36,030 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ServiceInfo.java | ServiceInfo | onApplicationEvent | class ServiceInfo implements ApplicationListener<WebServerInitializedEvent> {
private final Logger logger = LoggerFactory.getLogger(ServiceInfo.class);
private static int serverPort;
public static int getServerPort() {
return serverPort;
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {<FILL_FUNCTION_BODY>}
public void setServerPort(int serverPort) {
ServiceInfo.serverPort = serverPort;
}
} |
// 项目启动获取启动的端口号
ServiceInfo.serverPort = event.getWebServer().getPort();
logger.info("项目启动获取启动的端口号: " + ServiceInfo.serverPort);
| 36 | 128 | 56 | 184 |
36,031 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SipConfig.java | SipConfig | getShowIp | class SipConfig {
private String ip;
private String showIp;
private Integer port;
private String domain;
private String id;
private String password;
Integer ptzSpeed = 50;
Integer registerTimeInterval = 120;
private boolean alarm;
public void setIp(String ip) {
this.ip = ip;
}
public void setPort(Integer port) {
this.port = port;
}
public void setDomain(String domain) {
this.domain = domain;
}
public void setId(String id) {
this.id = id;
}
public void setPassword(String password) {
this.password = password;
}
public void setPtzSpeed(Integer ptzSpeed) {
this.ptzSpeed = ptzSpeed;
}
public void setRegisterTimeInterval(Integer registerTimeInterval) {
this.registerTimeInterval = registerTimeInterval;
}
public String getIp() {
return ip;
}
public Integer getPort() {
return port;
}
public String getDomain() {
return domain;
}
public String getId() {
return id;
}
public String getPassword() {
return password;
}
public Integer getPtzSpeed() {
return ptzSpeed;
}
public Integer getRegisterTimeInterval() {
return registerTimeInterval;
}
public boolean isAlarm() {
return alarm;
}
public void setAlarm(boolean alarm) {
this.alarm = alarm;
}
public String getShowIp() {<FILL_FUNCTION_BODY>}
public void setShowIp(String showIp) {
this.showIp = showIp;
}
} |
if (this.showIp == null) {
return this.ip;
}
return showIp;
| 7 | 449 | 33 | 482 |
36,032 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SipPlatformRunner.java | SipPlatformRunner | run | class SipPlatformRunner implements CommandLineRunner {
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IPlatformService platformService;
@Autowired
private ISIPCommanderForPlatform sipCommanderForPlatform;
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
} |
// 获取所有启用的平台
List<ParentPlatform> parentPlatforms = storager.queryEnableParentPlatformList(true);
for (ParentPlatform parentPlatform : parentPlatforms) {
ParentPlatformCatch parentPlatformCatchOld = redisCatchStorage.queryPlatformCatchInfo(parentPlatform.getServerGBId());
// 更新缓存
ParentPlatformCatch parentPlatformCatch = new ParentPlatformCatch();
parentPlatformCatch.setParentPlatform(parentPlatform);
parentPlatformCatch.setId(parentPlatform.getServerGBId());
redisCatchStorage.updatePlatformCatchInfo(parentPlatformCatch);
if (parentPlatformCatchOld != null) {
// 取消订阅
try {
sipCommanderForPlatform.unregister(parentPlatform, parentPlatformCatchOld.getSipTransactionInfo(), null, (eventResult)->{
platformService.login(parentPlatform);
});
} catch (Exception e) {
logger.error("[命令发送失败] 国标级联 注销: {}", e.getMessage());
platformService.offline(parentPlatform, true);
continue;
}
}
// 设置所有平台离线
platformService.offline(parentPlatform, false);
}
| 382 | 145 | 318 | 463 |
36,033 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SpringDocConfig.java | SpringDocConfig | springShopOpenApi | class SpringDocConfig {
@Value("${doc.enabled: true}")
private boolean enable;
@Bean
public OpenAPI springShopOpenApi() {<FILL_FUNCTION_BODY>}
/**
* 添加分组
* @return
*/
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("1. 全部")
.packagesToScan("com.genersoft.iot.vmp.vmanager")
.build();
}
@Bean
public GroupedOpenApi publicApi2() {
return GroupedOpenApi.builder()
.group("2. 国标28181")
.packagesToScan("com.genersoft.iot.vmp.vmanager.gb28181")
.build();
}
@Bean
public GroupedOpenApi publicApi3() {
return GroupedOpenApi.builder()
.group("3. 拉流转发")
.packagesToScan("com.genersoft.iot.vmp.vmanager.streamProxy")
.build();
}
@Bean
public GroupedOpenApi publicApi4() {
return GroupedOpenApi.builder()
.group("4. 推流管理")
.packagesToScan("com.genersoft.iot.vmp.vmanager.streamPush")
.build();
}
@Bean
public GroupedOpenApi publicApi5() {
return GroupedOpenApi.builder()
.group("4. 服务管理")
.packagesToScan("com.genersoft.iot.vmp.vmanager.server")
.build();
}
@Bean
public GroupedOpenApi publicApi6() {
return GroupedOpenApi.builder()
.group("5. 用户管理")
.packagesToScan("com.genersoft.iot.vmp.vmanager.user")
.build();
}
} |
Contact contact = new Contact();
contact.setName("pan");
contact.setEmail("648540858@qq.com");
return new OpenAPI()
.components(new Components()
.addSecuritySchemes(JwtUtils.HEADER, new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.bearerFormat("JWT")))
.info(new Info().title("WVP-PRO 接口文档")
.contact(contact)
.description("开箱即用的28181协议视频平台")
.version("v3.1.0")
.license(new License().name("Apache 2.0").url("http://springdoc.org")));
| 266 | 501 | 186 | 687 |
36,034 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/SystemInfoTimerTask.java | SystemInfoTimerTask | execute | class SystemInfoTimerTask {
private Logger logger = LoggerFactory.getLogger(SystemInfoTimerTask.class);
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Scheduled(fixedRate = 2000) //每1秒执行一次
public void execute(){<FILL_FUNCTION_BODY>}
} |
try {
double cpuInfo = SystemInfoUtils.getCpuInfo();
redisCatchStorage.addCpuInfo(cpuInfo);
double memInfo = SystemInfoUtils.getMemInfo();
redisCatchStorage.addMemInfo(memInfo);
Map<String, Double> networkInterfaces = SystemInfoUtils.getNetworkInterfaces();
redisCatchStorage.addNetInfo(networkInterfaces);
List<Map<String, Object>> diskInfo =SystemInfoUtils.getDiskInfo();
redisCatchStorage.addDiskInfo(diskInfo);
} catch (InterruptedException e) {
logger.error("[获取系统信息失败] {}", e.getMessage());
}
| 157 | 95 | 174 | 269 |
36,035 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/ThreadPoolTaskConfig.java | ThreadPoolTaskConfig | taskExecutor | class ThreadPoolTaskConfig {
public static final int cpuNum = Runtime.getRuntime().availableProcessors();
/**
* 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
* 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
* 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝
*/
/**
* 核心线程数(默认线程数)
*/
private static final int corePoolSize = cpuNum;
/**
* 最大线程数
*/
private static final int maxPoolSize = cpuNum*2;
/**
* 允许线程空闲时间(单位:默认为秒)
*/
private static final int keepAliveTime = 30;
/**
* 缓冲队列大小
*/
private static final int queueCapacity = 10000;
/**
* 线程池名前缀
*/
private static final String threadNamePrefix = "wvp-";
/**
*
* @return
*/
@Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
public ThreadPoolTaskExecutor taskExecutor() {<FILL_FUNCTION_BODY>}
} |
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
// CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
| 110 | 380 | 176 | 556 |
36,036 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/VersionInfo.java | VersionInfo | getVersion | class VersionInfo {
@Autowired
GitUtil gitUtil;
public VersionPo getVersion() {<FILL_FUNCTION_BODY>}
} |
VersionPo versionPo = new VersionPo();
versionPo.setGIT_Revision(gitUtil.getGitCommitId());
versionPo.setGIT_BRANCH(gitUtil.getBranch());
versionPo.setGIT_URL(gitUtil.getGitUrl());
versionPo.setBUILD_DATE(gitUtil.getBuildDate());
versionPo.setGIT_Revision_SHORT(gitUtil.getCommitIdShort());
versionPo.setVersion(gitUtil.getBuildVersion());
versionPo.setGIT_DATE(gitUtil.getCommitTime());
return versionPo;
| 82 | 43 | 158 | 201 |
36,037 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/WVPTimerTask.java | WVPTimerTask | execute | class WVPTimerTask {
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Value("${server.port}")
private int serverPort;
@Autowired
private SipConfig sipConfig;
@Scheduled(fixedRate = 2 * 1000) //每3秒执行一次
public void execute(){<FILL_FUNCTION_BODY>}
} |
JSONObject jsonObject = new JSONObject();
jsonObject.put("ip", sipConfig.getIp());
jsonObject.put("port", serverPort);
redisCatchStorage.updateWVPInfo(jsonObject, 3);
| 44 | 112 | 62 | 174 |
36,038 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/exception/SsrcTransactionNotFoundException.java | SsrcTransactionNotFoundException | getMessage | class SsrcTransactionNotFoundException extends Exception{
private String deviceId;
private String channelId;
private String callId;
private String stream;
public SsrcTransactionNotFoundException(String deviceId, String channelId, String callId, String stream) {
this.deviceId = deviceId;
this.channelId = channelId;
this.callId = callId;
this.stream = stream;
}
public String getDeviceId() {
return deviceId;
}
public String getChannelId() {
return channelId;
}
public String getCallId() {
return callId;
}
public String getStream() {
return stream;
}
@Override
public String getMessage() {<FILL_FUNCTION_BODY>}
} |
StringBuffer msg = new StringBuffer();
msg.append(String.format("缓存事务信息未找到,device:%s channel: %s ", deviceId, channelId));
if (callId != null) {
msg.append(",callId: " + callId);
}
if (stream != null) {
msg.append(",stream: " + stream);
}
return msg.toString();
| 110 | 207 | 110 | 317 |
36,039 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/redis/RedisMsgListenConfig.java | RedisMsgListenConfig | container | class RedisMsgListenConfig {
@Autowired
private RedisGpsMsgListener redisGPSMsgListener;
@Autowired
private RedisAlarmMsgListener redisAlarmMsgListener;
@Autowired
private RedisStreamMsgListener redisStreamMsgListener;
@Autowired
private RedisGbPlayMsgListener redisGbPlayMsgListener;
@Autowired
private RedisPushStreamStatusMsgListener redisPushStreamStatusMsgListener;
@Autowired
private RedisPushStreamStatusListMsgListener redisPushStreamListMsgListener;
@Autowired
private RedisPushStreamResponseListener redisPushStreamResponseListener;
@Autowired
private RedisCloseStreamMsgListener redisCloseStreamMsgListener;
@Autowired
private RedisPushStreamCloseResponseListener redisPushStreamCloseResponseListener;
/**
* redis消息监听器容器 可以添加多个监听不同话题的redis监听器,只需要把消息监听器和相应的消息订阅处理器绑定,该消息监听器
* 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
*
* @param connectionFactory
* @return
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {<FILL_FUNCTION_BODY>}
} |
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(redisGPSMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_GPS));
container.addMessageListener(redisAlarmMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_SUBSCRIBE_ALARM_RECEIVE));
container.addMessageListener(redisStreamMsgListener, new PatternTopic(VideoManagerConstants.WVP_MSG_STREAM_CHANGE_PREFIX + "PUSH"));
container.addMessageListener(redisGbPlayMsgListener, new PatternTopic(RedisGbPlayMsgListener.WVP_PUSH_STREAM_KEY));
container.addMessageListener(redisPushStreamStatusMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_PUSH_STREAM_STATUS_CHANGE));
container.addMessageListener(redisPushStreamListMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_PUSH_STREAM_LIST_CHANGE));
container.addMessageListener(redisPushStreamResponseListener, new PatternTopic(VideoManagerConstants.VM_MSG_STREAM_PUSH_RESPONSE));
container.addMessageListener(redisCloseStreamMsgListener, new PatternTopic(VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE));
container.addMessageListener(redisPushStreamCloseResponseListener, new PatternTopic(VideoManagerConstants.VM_MSG_STREAM_PUSH_CLOSE_REQUESTED));
return container;
| 54 | 342 | 432 | 774 |
36,040 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/redis/RedisTemplateConfig.java | RedisTemplateConfig | redisTemplate | class RedisTemplateConfig {
@Bean
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {<FILL_FUNCTION_BODY>}
} |
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
// 使用fastJson序列化
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
// value值的序列化采用fastJsonRedisSerializer
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
| 108 | 51 | 174 | 225 |
36,041 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/AnonymousAuthenticationEntryPoint.java | AnonymousAuthenticationEntryPoint | commence | class AnonymousAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {<FILL_FUNCTION_BODY>}
} |
String jwt = request.getHeader(JwtUtils.getHeader());
JwtUser jwtUser = JwtUtils.verifyToken(jwt);
String username = jwtUser.getUserName();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, jwtUser.getPassword() );
SecurityContextHolder.getContext().setAuthentication(token);
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", ErrorCode.ERROR401.getCode());
jsonObject.put("msg", ErrorCode.ERROR401.getMsg());
String logUri = "api/user/login";
if (request.getRequestURI().contains(logUri)){
jsonObject.put("msg", e.getMessage());
}
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
try {
response.getWriter().print(jsonObject.toJSONString());
} catch (IOException ioException) {
ioException.printStackTrace();
}
| 208 | 55 | 288 | 343 |
36,042 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/DefaultUserDetailsServiceImpl.java | DefaultUserDetailsServiceImpl | loadUserByUsername | class DefaultUserDetailsServiceImpl implements UserDetailsService {
private final static Logger logger = LoggerFactory.getLogger(DefaultUserDetailsServiceImpl.class);
@Autowired
private IUserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<FILL_FUNCTION_BODY>}
} |
if (StringUtils.isBlank(username)) {
logger.info("登录用户:{} 不存在", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
// 查出密码
User user = userService.getUserByUsername(username);
if (user == null) {
logger.info("登录用户:{} 不存在", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
String password = SecurityUtils.encryptPassword(user.getPassword());
user.setPassword(password);
return new LoginUser(user, LocalDateTime.now());
| 159 | 98 | 179 | 277 |
36,043 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/JwtAuthenticationFilter.java | JwtAuthenticationFilter | doFilterInternal | class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private UserSetting userSetting;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>}
} |
// 忽略登录请求的token验证
String requestURI = request.getRequestURI();
if (requestURI.equalsIgnoreCase("/api/user/login")) {
chain.doFilter(request, response);
return;
}
if (!userSetting.isInterfaceAuthentication()) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(null, null, new ArrayList<>() );
SecurityContextHolder.getContext().setAuthentication(token);
chain.doFilter(request, response);
return;
}
String jwt = request.getHeader(JwtUtils.getHeader());
// 这里如果没有jwt,继续往后走,因为后面还有鉴权管理器等去判断是否拥有身份凭证,所以是可以放行的
// 没有jwt相当于匿名访问,若有一些接口是需要权限的,则不能访问这些接口
if (StringUtils.isBlank(jwt)) {
jwt = request.getParameter(JwtUtils.getHeader());
if (StringUtils.isBlank(jwt)) {
jwt = request.getHeader(JwtUtils.getApiKeyHeader());
if (StringUtils.isBlank(jwt)) {
chain.doFilter(request, response);
return;
}
}
}
JwtUser jwtUser = JwtUtils.verifyToken(jwt);
String username = jwtUser.getUserName();
// TODO 处理各个状态
switch (jwtUser.getStatus()){
case EXPIRED:
response.setStatus(400);
chain.doFilter(request, response);
// 异常
return;
case EXCEPTION:
// 过期
response.setStatus(400);
chain.doFilter(request, response);
return;
case EXPIRING_SOON:
// 即将过期
// return;
default:
}
// 构建UsernamePasswordAuthenticationToken,这里密码为null,是因为提供了正确的JWT,实现自动登录
User user = new User();
user.setId(jwtUser.getUserId());
user.setUsername(jwtUser.getUserName());
user.setPassword(jwtUser.getPassword());
Role role = new Role();
role.setId(jwtUser.getRoleId());
user.setRole(role);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, jwtUser.getPassword(), new ArrayList<>() );
SecurityContextHolder.getContext().setAuthentication(token);
chain.doFilter(request, response);
| 694 | 78 | 658 | 736 |
36,044 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java | JwtUtils | verifyToken | class JwtUtils implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
public static final String HEADER = "access-token";
public static final String API_KEY_HEADER = "api-key";
private static final String AUDIENCE = "Audience";
private static final String keyId = "3e79646c4dbc408383a9eed09f2b85ae";
/**
* token过期时间(分钟)
*/
public static final long EXPIRATION_TIME = 30 * 24 * 60;
private static RsaJsonWebKey rsaJsonWebKey;
private static IUserService userService;
private static IUserApiKeyService userApiKeyService;
public static String getApiKeyHeader() {
return API_KEY_HEADER;
}
@Resource
public void setUserService(IUserService userService) {
JwtUtils.userService = userService;
}
@Resource
public void setUserApiKeyService(IUserApiKeyService userApiKeyService) {
JwtUtils.userApiKeyService = userApiKeyService;
}
@Override
public void afterPropertiesSet() {
try {
rsaJsonWebKey = generateRsaJsonWebKey();
} catch (JoseException e) {
logger.error("生成RsaJsonWebKey报错。", e);
}
}
/**
* 创建密钥对
*
* @throws JoseException JoseException
*/
private RsaJsonWebKey generateRsaJsonWebKey() throws JoseException {
RsaJsonWebKey rsaJsonWebKey = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("/jwk.json"), StandardCharsets.UTF_8))) {
String jwkJson = reader.readLine();
JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jwkJson);
List<JsonWebKey> jsonWebKeys = jsonWebKeySet.getJsonWebKeys();
if (!jsonWebKeys.isEmpty()) {
JsonWebKey jsonWebKey = jsonWebKeys.get(0);
if (jsonWebKey instanceof RsaJsonWebKey) {
rsaJsonWebKey = (RsaJsonWebKey) jsonWebKey;
}
}
} catch (Exception e) {
// ignored
}
if (rsaJsonWebKey == null) {
// 生成一个RSA密钥对,该密钥对将用于JWT的签名和验证,包装在JWK中
rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
// 给JWK一个密钥ID
rsaJsonWebKey.setKeyId(keyId);
}
return rsaJsonWebKey;
}
public static String createToken(String username, Long expirationTime, Map<String, Object> extra) {
try {
/*
* “iss” (issuer) 发行人
* “sub” (subject) 主题
* “aud” (audience) 接收方 用户
* “exp” (expiration time) 到期时间
* “nbf” (not before) 在此之前不可用
* “iat” (issued at) jwt的签发时间
*/
JwtClaims claims = new JwtClaims();
claims.setGeneratedJwtId();
claims.setIssuedAtToNow();
// 令牌将过期的时间 分钟
if (expirationTime != null) {
claims.setExpirationTimeMinutesInTheFuture(expirationTime);
}
claims.setNotBeforeMinutesInThePast(0);
claims.setSubject("login");
claims.setAudience(AUDIENCE);
//添加自定义参数,必须是字符串类型
claims.setClaim("userName", username);
if (extra != null) {
extra.forEach(claims::setClaim);
}
//jws
JsonWebSignature jws = new JsonWebSignature();
//签名算法RS256
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
jws.setKeyIdHeaderValue(keyId);
jws.setPayload(claims.toJson());
jws.setKey(rsaJsonWebKey.getPrivateKey());
//get token
return jws.getCompactSerialization();
} catch (JoseException e) {
logger.error("[Token生成失败]: {}", e.getMessage());
}
return null;
}
public static String createToken(String username, Long expirationTime) {
return createToken(username, expirationTime, null);
}
public static String createToken(String username) {
return createToken(username, EXPIRATION_TIME);
}
public static String getHeader() {
return HEADER;
}
public static JwtUser verifyToken(String token) {<FILL_FUNCTION_BODY>}
} |
JwtUser jwtUser = new JwtUser();
try {
JwtConsumer consumer = new JwtConsumerBuilder()
//.setRequireExpirationTime()
//.setMaxFutureValidityInMinutes(5256000)
.setAllowedClockSkewInSeconds(30)
.setRequireSubject()
//.setExpectedIssuer("")
.setExpectedAudience(AUDIENCE)
.setVerificationKey(rsaJsonWebKey.getPublicKey())
.build();
JwtClaims claims = consumer.processToClaims(token);
NumericDate expirationTime = claims.getExpirationTime();
if (expirationTime != null) {
// 判断是否即将过期, 默认剩余时间小于5分钟未即将过期
// 剩余时间 (秒)
long timeRemaining = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8)) - expirationTime.getValue();
if (timeRemaining < 5 * 60) {
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRING_SOON);
} else {
jwtUser.setStatus(JwtUser.TokenStatus.NORMAL);
}
} else {
jwtUser.setStatus(JwtUser.TokenStatus.NORMAL);
}
Long apiKeyId = claims.getClaimValue("apiKeyId", Long.class);
if (apiKeyId != null) {
UserApiKey userApiKey = userApiKeyService.getUserApiKeyById(apiKeyId.intValue());
if (userApiKey == null || !userApiKey.isEnable()) {
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
}
}
String username = (String) claims.getClaimValue("userName");
User user = userService.getUserByUsername(username);
jwtUser.setUserName(username);
jwtUser.setPassword(user.getPassword());
jwtUser.setRoleId(user.getRole().getId());
jwtUser.setUserId(user.getId());
return jwtUser;
} catch (InvalidJwtException e) {
if (e.hasErrorCode(ErrorCodes.EXPIRED)) {
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
} else {
jwtUser.setStatus(JwtUser.TokenStatus.EXCEPTION);
}
return jwtUser;
} catch (Exception e) {
logger.error("[Token解析失败]: {}", e.getMessage());
jwtUser.setStatus(JwtUser.TokenStatus.EXPIRED);
return jwtUser;
}
| 812 | 1,333 | 704 | 2,037 |
36,045 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/SecurityUtils.java | SecurityUtils | login | class SecurityUtils {
/**
* 描述根据账号密码进行调用security进行认证授权 主动调
* 用AuthenticationManager的authenticate方法实现
* 授权成功后将用户信息存入SecurityContext当中
* @param username 用户名
* @param password 密码
* @param authenticationManager 认证授权管理器,
* @see AuthenticationManager
* @return UserInfo 用户信息
*/
public static LoginUser login(String username, String password, AuthenticationManager authenticationManager) throws AuthenticationException {<FILL_FUNCTION_BODY>}
/**
* 获取当前登录的所有认证信息
* @return
*/
public static Authentication getAuthentication(){
SecurityContext context = SecurityContextHolder.getContext();
return context.getAuthentication();
}
/**
* 获取当前登录用户信息
* @return
*/
public static LoginUser getUserInfo(){
Authentication authentication = getAuthentication();
if(authentication!=null){
Object principal = authentication.getPrincipal();
if(principal!=null && !"anonymousUser".equals(principal.toString())){
User user = (User) principal;
return new LoginUser(user, LocalDateTime.now());
}
}
return null;
}
/**
* 获取当前登录用户ID
* @return
*/
public static int getUserId(){
LoginUser user = getUserInfo();
return user.getId();
}
/**
* 生成BCryptPasswordEncoder密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
} |
//使用security框架自带的验证token生成器 也可以自定义。
UsernamePasswordAuthenticationToken token =new UsernamePasswordAuthenticationToken(username,password);
//认证 如果失败,这里会自动异常后返回,所以这里不需要判断返回值是否为空,确定是否登录成功
Authentication authenticate = authenticationManager.authenticate(token);
LoginUser user = (LoginUser) authenticate.getPrincipal();
SecurityContextHolder.getContext().setAuthentication(token);
return user;
| 75 | 475 | 132 | 607 |
36,046 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/conf/security/WebSecurityConfig.java | WebSecurityConfig | configure | class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
@Autowired
private UserSetting userSetting;
@Autowired
private DefaultUserDetailsServiceImpl userDetailsService;
/**
* 登出成功的处理
*/
@Autowired
private LogoutHandler logoutHandler;
/**
* 未登录的处理
*/
@Autowired
private AnonymousAuthenticationEntryPoint anonymousAuthenticationEntryPoint;
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
/**
* 描述: 静态资源放行,这里的放行,是不走 Spring Security 过滤器链
**/
@Override
public void configure(WebSecurity web) {
if (userSetting.isInterfaceAuthentication()) {
ArrayList<String> matchers = new ArrayList<>();
matchers.add("/");
matchers.add("/#/**");
matchers.add("/static/**");
matchers.add("/swagger-ui.html");
matchers.add("/swagger-ui/");
matchers.add("/index.html");
matchers.add("/doc.html");
matchers.add("/webjars/**");
matchers.add("/swagger-resources/**");
matchers.add("/v3/api-docs/**");
matchers.add("/js/**");
matchers.add("/api/device/query/snap/**");
matchers.add("/record_proxy/*/**");
matchers.add("/api/emit");
matchers.add("/favicon.ico");
// 可以直接访问的静态数据
web.ignoring().antMatchers(matchers.toArray(new String[0]));
}
}
/**
* 配置认证方式
*
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {<FILL_FUNCTION_BODY>}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().contentTypeOptions().disable()
.and().cors().configurationSource(configurationSource())
.and().csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// 配置拦截规则
.and()
.authorizeRequests()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(userSetting.getInterfaceAuthenticationExcludes().toArray(new String[0])).permitAll()
.antMatchers("/api/user/login", "/index/hook/**","/index/hook/abl/**", "/swagger-ui/**", "/doc.html").permitAll()
.anyRequest().authenticated()
// 异常处理器
.and()
.exceptionHandling()
.authenticationEntryPoint(anonymousAuthenticationEntryPoint)
.and().logout().logoutUrl("/api/user/logout").permitAll()
.logoutSuccessHandler(logoutHandler)
;
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
CorsConfigurationSource configurationSource() {
// 配置跨域
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setMaxAge(3600L);
if (userSetting.getAllowedOrigins() != null && !userSetting.getAllowedOrigins().isEmpty()) {
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowedOrigins(userSetting.getAllowedOrigins());
}else {
corsConfiguration.setAllowCredentials(false);
corsConfiguration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
}
corsConfiguration.setExposedHeaders(Arrays.asList(JwtUtils.getHeader()));
UrlBasedCorsConfigurationSource url = new UrlBasedCorsConfigurationSource();
url.registerCorsConfiguration("/**", corsConfiguration);
return url;
}
/**
* 描述: 密码加密算法 BCrypt 推荐使用
**/
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 描述: 注入AuthenticationManager管理器
**/
@Override
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
} |
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
// 设置不隐藏 未找到用户异常
provider.setHideUserNotFoundExceptions(true);
// 用户认证service - 查询数据库的逻辑
provider.setUserDetailsService(userDetailsService);
// 设置密码加密算法
provider.setPasswordEncoder(passwordEncoder());
auth.authenticationProvider(provider);
| 79 | 1,186 | 106 | 1,292 |
36,047 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/SipLayer.java | SipLayer | getUdpSipProvider | class SipLayer implements CommandLineRunner {
private final static Logger logger = LoggerFactory.getLogger(SipLayer.class);
@Autowired
private SipConfig sipConfig;
@Autowired
private ISIPProcessorObserver sipProcessorObserver;
@Autowired
private UserSetting userSetting;
private final Map<String, SipProviderImpl> tcpSipProviderMap = new ConcurrentHashMap<>();
private final Map<String, SipProviderImpl> udpSipProviderMap = new ConcurrentHashMap<>();
@Override
public void run(String... args) {
List<String> monitorIps = new ArrayList<>();
// 使用逗号分割多个ip
String separator = ",";
if (sipConfig.getIp().indexOf(separator) > 0) {
String[] split = sipConfig.getIp().split(separator);
monitorIps.addAll(Arrays.asList(split));
}else {
monitorIps.add(sipConfig.getIp());
}
SipFactory.getInstance().setPathName("gov.nist");
if (monitorIps.size() > 0) {
for (String monitorIp : monitorIps) {
addListeningPoint(monitorIp, sipConfig.getPort());
}
if (udpSipProviderMap.size() + tcpSipProviderMap.size() == 0) {
System.exit(1);
}
}
}
private void addListeningPoint(String monitorIp, int port){
SipStackImpl sipStack;
try {
sipStack = (SipStackImpl)SipFactory.getInstance().createSipStack(DefaultProperties.getProperties("GB28181_SIP", userSetting.getSipLog()));
sipStack.setMessageParserFactory(new GbStringMsgParserFactory());
} catch (PeerUnavailableException e) {
logger.error("[SIP SERVER] SIP服务启动失败, 监听地址{}失败,请检查ip是否正确", monitorIp);
return;
}
try {
ListeningPoint tcpListeningPoint = sipStack.createListeningPoint(monitorIp, port, "TCP");
SipProviderImpl tcpSipProvider = (SipProviderImpl)sipStack.createSipProvider(tcpListeningPoint);
tcpSipProvider.setDialogErrorsAutomaticallyHandled();
tcpSipProvider.addSipListener(sipProcessorObserver);
tcpSipProviderMap.put(monitorIp, tcpSipProvider);
logger.info("[SIP SERVER] tcp://{}:{} 启动成功", monitorIp, port);
} catch (TransportNotSupportedException
| TooManyListenersException
| ObjectInUseException
| InvalidArgumentException e) {
logger.error("[SIP SERVER] tcp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确"
, monitorIp, port);
}
try {
ListeningPoint udpListeningPoint = sipStack.createListeningPoint(monitorIp, port, "UDP");
SipProviderImpl udpSipProvider = (SipProviderImpl)sipStack.createSipProvider(udpListeningPoint);
udpSipProvider.addSipListener(sipProcessorObserver);
udpSipProviderMap.put(monitorIp, udpSipProvider);
logger.info("[SIP SERVER] udp://{}:{} 启动成功", monitorIp, port);
} catch (TransportNotSupportedException
| TooManyListenersException
| ObjectInUseException
| InvalidArgumentException e) {
logger.error("[SIP SERVER] udp://{}:{} SIP服务启动失败,请检查端口是否被占用或者ip是否正确"
, monitorIp, port);
}
}
public SipProviderImpl getUdpSipProvider(String ip) {
if (ObjectUtils.isEmpty(ip)) {
return null;
}
return udpSipProviderMap.get(ip);
}
public SipProviderImpl getUdpSipProvider() {<FILL_FUNCTION_BODY>}
public SipProviderImpl getTcpSipProvider() {
if (tcpSipProviderMap.size() != 1) {
return null;
}
return tcpSipProviderMap.values().stream().findFirst().get();
}
public SipProviderImpl getTcpSipProvider(String ip) {
if (ObjectUtils.isEmpty(ip)) {
return null;
}
return tcpSipProviderMap.get(ip);
}
public String getLocalIp(String deviceLocalIp) {
if (!ObjectUtils.isEmpty(deviceLocalIp)) {
return deviceLocalIp;
}
return getUdpSipProvider().getListeningPoint().getIPAddress();
}
} |
if (udpSipProviderMap.size() != 1) {
return null;
}
return udpSipProviderMap.values().stream().findFirst().get();
| 7 | 1,269 | 49 | 1,318 |
36,048 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/auth/DigestServerAuthenticationHelper.java | DigestServerAuthenticationHelper | doAuthenticatePlainTextPassword | class DigestServerAuthenticationHelper {
private Logger logger = LoggerFactory.getLogger(DigestServerAuthenticationHelper.class);
private MessageDigest messageDigest;
public static final String DEFAULT_ALGORITHM = "MD5";
public static final String DEFAULT_SCHEME = "Digest";
/** to hex converter */
private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* Default constructor.
* @throws NoSuchAlgorithmException
*/
public DigestServerAuthenticationHelper()
throws NoSuchAlgorithmException {
messageDigest = MessageDigest.getInstance(DEFAULT_ALGORITHM);
}
public static String toHexString(byte b[]) {
int pos = 0;
char[] c = new char[b.length * 2];
for (int i = 0; i < b.length; i++) {
c[pos++] = toHex[(b[i] >> 4) & 0x0F];
c[pos++] = toHex[b[i] & 0x0f];
}
return new String(c);
}
/**
* Generate the challenge string.
*
* @return a generated nonce.
*/
private String generateNonce() {
long time = Instant.now().toEpochMilli();
Random rand = new Random();
long pad = rand.nextLong();
String nonceString = Long.valueOf(time).toString()
+ Long.valueOf(pad).toString();
byte mdbytes[] = messageDigest.digest(nonceString.getBytes());
return toHexString(mdbytes);
}
public Response generateChallenge(HeaderFactory headerFactory, Response response, String realm) {
try {
WWWAuthenticateHeader proxyAuthenticate = headerFactory
.createWWWAuthenticateHeader(DEFAULT_SCHEME);
proxyAuthenticate.setParameter("realm", realm);
proxyAuthenticate.setParameter("qop", "auth");
proxyAuthenticate.setParameter("nonce", generateNonce());
proxyAuthenticate.setParameter("algorithm", DEFAULT_ALGORITHM);
response.setHeader(proxyAuthenticate);
} catch (Exception ex) {
InternalErrorHandler.handleException(ex);
}
return response;
}
/**
* Authenticate the inbound request.
*
* @param request - the request to authenticate.
* @param hashedPassword -- the MD5 hashed string of username:realm:plaintext password.
*
* @return true if authentication succeded and false otherwise.
*/
public boolean doAuthenticateHashedPassword(Request request, String hashedPassword) {
AuthorizationHeader authHeader = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
if ( authHeader == null ) {
return false;
}
String realm = authHeader.getRealm();
String username = authHeader.getUsername();
if ( username == null || realm == null ) {
return false;
}
String nonce = authHeader.getNonce();
URI uri = authHeader.getURI();
if (uri == null) {
return false;
}
String A2 = request.getMethod().toUpperCase() + ":" + uri.toString();
String HA1 = hashedPassword;
byte[] mdbytes = messageDigest.digest(A2.getBytes());
String HA2 = toHexString(mdbytes);
String cnonce = authHeader.getCNonce();
String KD = HA1 + ":" + nonce;
if (cnonce != null) {
KD += ":" + cnonce;
}
KD += ":" + HA2;
mdbytes = messageDigest.digest(KD.getBytes());
String mdString = toHexString(mdbytes);
String response = authHeader.getResponse();
return mdString.equals(response);
}
/**
* Authenticate the inbound request given plain text password.
*
* @param request - the request to authenticate.
* @param pass -- the plain text password.
*
* @return true if authentication succeded and false otherwise.
*/
public boolean doAuthenticatePlainTextPassword(Request request, String pass) {<FILL_FUNCTION_BODY>}
} |
AuthorizationHeader authHeader = (AuthorizationHeader) request.getHeader(AuthorizationHeader.NAME);
if ( authHeader == null || authHeader.getRealm() == null) {
return false;
}
String realm = authHeader.getRealm().trim();
String username = authHeader.getUsername().trim();
if ( username == null || realm == null ) {
return false;
}
String nonce = authHeader.getNonce();
URI uri = authHeader.getURI();
if (uri == null) {
return false;
}
// qop 保护质量 包含auth(默认的)和auth-int(增加了报文完整性检测)两种策略
String qop = authHeader.getQop();
// 客户端随机数,这是一个不透明的字符串值,由客户端提供,并且客户端和服务器都会使用,以避免用明文文本。
// 这使得双方都可以查验对方的身份,并对消息的完整性提供一些保护
String cnonce = authHeader.getCNonce();
// nonce计数器,是一个16进制的数值,表示同一nonce下客户端发送出请求的数量
int nc = authHeader.getNonceCount();
String ncStr = String.format("%08x", nc).toUpperCase();
// String ncStr = new DecimalFormat("00000000").format(nc);
// String ncStr = new DecimalFormat("00000000").format(Integer.parseInt(nc + "", 16));
String A1 = username + ":" + realm + ":" + pass;
String A2 = request.getMethod().toUpperCase() + ":" + uri.toString();
byte mdbytes[] = messageDigest.digest(A1.getBytes());
String HA1 = toHexString(mdbytes);
logger.debug("A1: " + A1);
logger.debug("A2: " + A2);
mdbytes = messageDigest.digest(A2.getBytes());
String HA2 = toHexString(mdbytes);
logger.debug("HA1: " + HA1);
logger.debug("HA2: " + HA2);
// String cnonce = authHeader.getCNonce();
logger.debug("nonce: " + nonce);
logger.debug("nc: " + ncStr);
logger.debug("cnonce: " + cnonce);
logger.debug("qop: " + qop);
String KD = HA1 + ":" + nonce;
if (qop != null && qop.equalsIgnoreCase("auth") ) {
if (nc != -1) {
KD += ":" + ncStr;
}
if (cnonce != null) {
KD += ":" + cnonce;
}
KD += ":" + qop;
}
KD += ":" + HA2;
logger.debug("KD: " + KD);
mdbytes = messageDigest.digest(KD.getBytes());
String mdString = toHexString(mdbytes);
logger.debug("mdString: " + mdString);
String response = authHeader.getResponse();
logger.debug("response: " + response);
return mdString.equals(response);
| 696 | 1,179 | 864 | 2,043 |
36,052 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/Gb28181Sdp.java | Gb28181Sdp | getInstance | class Gb28181Sdp {
private SessionDescription baseSdb;
private String ssrc;
private String mediaDescription;
public static Gb28181Sdp getInstance(SessionDescription baseSdb, String ssrc, String mediaDescription) {<FILL_FUNCTION_BODY>}
public SessionDescription getBaseSdb() {
return baseSdb;
}
public void setBaseSdb(SessionDescription baseSdb) {
this.baseSdb = baseSdb;
}
public String getSsrc() {
return ssrc;
}
public void setSsrc(String ssrc) {
this.ssrc = ssrc;
}
public String getMediaDescription() {
return mediaDescription;
}
public void setMediaDescription(String mediaDescription) {
this.mediaDescription = mediaDescription;
}
} |
Gb28181Sdp gb28181Sdp = new Gb28181Sdp();
gb28181Sdp.setBaseSdb(baseSdb);
gb28181Sdp.setSsrc(ssrc);
gb28181Sdp.setMediaDescription(mediaDescription);
return gb28181Sdp;
| 50 | 230 | 107 | 337 |
36,053 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/GbSipDate.java | GbSipDate | encode | class GbSipDate extends SIPDate {
/**
*
*/
private static final long serialVersionUID = 1L;
private Calendar javaCal;
public GbSipDate(long timeMillis) {
this.javaCal = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
Date date = new Date(timeMillis);
this.javaCal.setTime(date);
this.wkday = this.javaCal.get(7);
switch(this.wkday) {
case 1:
this.sipWkDay = "Sun";
break;
case 2:
this.sipWkDay = "Mon";
break;
case 3:
this.sipWkDay = "Tue";
break;
case 4:
this.sipWkDay = "Wed";
break;
case 5:
this.sipWkDay = "Thu";
break;
case 6:
this.sipWkDay = "Fri";
break;
case 7:
this.sipWkDay = "Sat";
break;
default:
InternalErrorHandler.handleException("No date map for wkday " + this.wkday);
}
this.day = this.javaCal.get(5);
this.month = this.javaCal.get(2);
switch(this.month) {
case 0:
this.sipMonth = "Jan";
break;
case 1:
this.sipMonth = "Feb";
break;
case 2:
this.sipMonth = "Mar";
break;
case 3:
this.sipMonth = "Apr";
break;
case 4:
this.sipMonth = "May";
break;
case 5:
this.sipMonth = "Jun";
break;
case 6:
this.sipMonth = "Jul";
break;
case 7:
this.sipMonth = "Aug";
break;
case 8:
this.sipMonth = "Sep";
break;
case 9:
this.sipMonth = "Oct";
break;
case 10:
this.sipMonth = "Nov";
break;
case 11:
this.sipMonth = "Dec";
break;
default:
InternalErrorHandler.handleException("No date map for month " + this.month);
}
this.year = this.javaCal.get(1);
this.hour = this.javaCal.get(11);
this.minute = this.javaCal.get(12);
this.second = this.javaCal.get(13);
}
@Override
public StringBuilder encode(StringBuilder var1) {<FILL_FUNCTION_BODY>}
} |
String var2;
if (this.month < 9) {
var2 = "0" + (this.month + 1);
} else {
var2 = "" + (this.month + 1);
}
String var3;
if (this.day < 10) {
var3 = "0" + this.day;
} else {
var3 = "" + this.day;
}
String var4;
if (this.hour < 10) {
var4 = "0" + this.hour;
} else {
var4 = "" + this.hour;
}
String var5;
if (this.minute < 10) {
var5 = "0" + this.minute;
} else {
var5 = "" + this.minute;
}
String var6;
if (this.second < 10) {
var6 = "0" + this.second;
} else {
var6 = "" + this.second;
}
int var8 = this.javaCal.get(14);
String var7;
if (var8 < 10) {
var7 = "00" + var8;
} else if (var8 < 100) {
var7 = "0" + var8;
} else {
var7 = "" + var8;
}
return var1.append(this.year).append("-").append(var2).append("-").append(var3).append("T").append(var4).append(":").append(var5).append(":").append(var6).append(".").append(var7);
| 485 | 752 | 420 | 1,172 |
36,054 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/RecordItem.java | RecordItem | compareTo | class RecordItem implements Comparable<RecordItem>{
@Schema(description = "设备编号")
private String deviceId;
@Schema(description = "名称")
private String name;
@Schema(description = "文件路径名 (可选)")
private String filePath;
@Schema(description = "录像文件大小,单位:Byte(可选)")
private String fileSize;
@Schema(description = "录像地址(可选)")
private String address;
@Schema(description = "录像开始时间(可选)")
private String startTime;
@Schema(description = "录像结束时间(可选)")
private String endTime;
@Schema(description = "保密属性(必选)缺省为0;0:不涉密,1:涉密")
private int secrecy;
@Schema(description = "录像产生类型(可选)time或alarm 或 manua")
private String type;
@Schema(description = "录像触发者ID(可选)")
private String recorderId;
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public int getSecrecy() {
return secrecy;
}
public void setSecrecy(int secrecy) {
this.secrecy = secrecy;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRecorderId() {
return recorderId;
}
public void setRecorderId(String recorderId) {
this.recorderId = recorderId;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
@Override
public int compareTo(@NotNull RecordItem recordItem) {<FILL_FUNCTION_BODY>}
} |
TemporalAccessor startTimeNow = DateUtil.formatter.parse(startTime);
TemporalAccessor startTimeParam = DateUtil.formatter.parse(recordItem.getStartTime());
Instant startTimeParamInstant = Instant.from(startTimeParam);
Instant startTimeNowInstant = Instant.from(startTimeNow);
if (startTimeNowInstant.equals(startTimeParamInstant)) {
return 0;
}else if (Instant.from(startTimeParam).isAfter(Instant.from(startTimeNow)) ) {
return -1;
}else {
return 1;
}
| 23 | 701 | 168 | 869 |
36,056 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/bean/SubscribeHolder.java | SubscribeHolder | putCatalogSubscribe | class SubscribeHolder {
@Autowired
private DynamicTask dynamicTask;
@Autowired
private UserSetting userSetting;
private final String taskOverduePrefix = "subscribe_overdue_";
private static ConcurrentHashMap<String, SubscribeInfo> catalogMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<String, SubscribeInfo> mobilePositionMap = new ConcurrentHashMap<>();
public void putCatalogSubscribe(String platformId, SubscribeInfo subscribeInfo) {<FILL_FUNCTION_BODY>}
public SubscribeInfo getCatalogSubscribe(String platformId) {
return catalogMap.get(platformId);
}
public void removeCatalogSubscribe(String platformId) {
catalogMap.remove(platformId);
String taskOverdueKey = taskOverduePrefix + "catalog_" + platformId;
Runnable runnable = dynamicTask.get(taskOverdueKey);
if (runnable instanceof ISubscribeTask) {
ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
subscribeTask.stop(null);
}
// 添加任务处理订阅过期
dynamicTask.stop(taskOverdueKey);
}
public void putMobilePositionSubscribe(String platformId, SubscribeInfo subscribeInfo) {
mobilePositionMap.put(platformId, subscribeInfo);
String key = VideoManagerConstants.SIP_SUBSCRIBE_PREFIX + userSetting.getServerId() + "MobilePosition_" + platformId;
// 添加任务处理GPS定时推送
dynamicTask.startCron(key, new MobilePositionSubscribeHandlerTask(platformId),
subscribeInfo.getGpsInterval() * 1000);
String taskOverdueKey = taskOverduePrefix + "MobilePosition_" + platformId;
if (subscribeInfo.getExpires() > 0) {
// 添加任务处理订阅过期
dynamicTask.startDelay(taskOverdueKey, () -> {
removeMobilePositionSubscribe(subscribeInfo.getId());
},
subscribeInfo.getExpires() * 1000);
}
}
public SubscribeInfo getMobilePositionSubscribe(String platformId) {
return mobilePositionMap.get(platformId);
}
public void removeMobilePositionSubscribe(String platformId) {
mobilePositionMap.remove(platformId);
String key = VideoManagerConstants.SIP_SUBSCRIBE_PREFIX + userSetting.getServerId() + "MobilePosition_" + platformId;
// 结束任务处理GPS定时推送
dynamicTask.stop(key);
String taskOverdueKey = taskOverduePrefix + "MobilePosition_" + platformId;
Runnable runnable = dynamicTask.get(taskOverdueKey);
if (runnable instanceof ISubscribeTask) {
ISubscribeTask subscribeTask = (ISubscribeTask) runnable;
subscribeTask.stop(null);
}
// 添加任务处理订阅过期
dynamicTask.stop(taskOverdueKey);
}
public List<String> getAllCatalogSubscribePlatform() {
List<String> platforms = new ArrayList<>();
if(catalogMap.size() > 0) {
for (String key : catalogMap.keySet()) {
platforms.add(catalogMap.get(key).getId());
}
}
return platforms;
}
public List<String> getAllMobilePositionSubscribePlatform() {
List<String> platforms = new ArrayList<>();
if(!mobilePositionMap.isEmpty()) {
for (String key : mobilePositionMap.keySet()) {
platforms.add(mobilePositionMap.get(key).getId());
}
}
return platforms;
}
public void removeAllSubscribe(String platformId) {
removeMobilePositionSubscribe(platformId);
removeCatalogSubscribe(platformId);
}
} |
catalogMap.put(platformId, subscribeInfo);
if (subscribeInfo.getExpires() > 0) {
// 添加订阅到期
String taskOverdueKey = taskOverduePrefix + "catalog_" + platformId;
// 添加任务处理订阅过期
dynamicTask.startDelay(taskOverdueKey, () -> removeCatalogSubscribe(subscribeInfo.getId()),
subscribeInfo.getExpires() * 1000);
}
| 117 | 981 | 118 | 1,099 |
36,057 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/conf/DefaultProperties.java | DefaultProperties | getProperties | class DefaultProperties {
public static Properties getProperties(String name, boolean sipLog) {<FILL_FUNCTION_BODY>}
} |
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", name);
// properties.setProperty("javax.sip.IP_ADDRESS", ip);
// 关闭自动会话
properties.setProperty("javax.sip.AUTOMATIC_DIALOG_SUPPORT", "off");
/**
* 完整配置参考 gov.nist.javax.sip.SipStackImpl,需要下载源码
* gov/nist/javax/sip/SipStackImpl.class
* sip消息的解析在 gov.nist.javax.sip.stack.UDPMessageChannel的processIncomingDataPacket方法
*/
// * gov/nist/javax/sip/SipStackImpl.class
// 接收所有notify请求,即使没有订阅
properties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true");
properties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING", "false");
properties.setProperty("gov.nist.javax.sip.CANCEL_CLIENT_TRANSACTION_CHECKED", "true");
// 为_NULL _对话框传递_终止的_事件
properties.setProperty("gov.nist.javax.sip.DELIVER_TERMINATED_EVENT_FOR_NULL_DIALOG", "true");
// 是否自动计算content length的实际长度,默认不计算
properties.setProperty("gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY", "true");
// 会话清理策略
properties.setProperty("gov.nist.javax.sip.RELEASE_REFERENCES_STRATEGY", "Normal");
// 处理由该服务器处理的基于底层TCP的保持生存超时
properties.setProperty("gov.nist.javax.sip.RELIABLE_CONNECTION_KEEP_ALIVE_TIMEOUT", "60");
// 获取实际内容长度,不使用header中的长度信息
properties.setProperty("gov.nist.javax.sip.COMPUTE_CONTENT_LENGTH_FROM_MESSAGE_BODY", "true");
// 线程可重入
properties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true");
// 定义应用程序打算多久审计一次 SIP 堆栈,了解其内部线程的健康状况(该属性指定连续审计之间的时间(以毫秒为单位))
properties.setProperty("gov.nist.javax.sip.THREAD_AUDIT_INTERVAL_IN_MILLISECS", "30000");
// properties.setProperty("gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY", "gov.nist.javax.sip.stack.NioMessageProcessorFactory");
/**
* sip_server_log.log 和 sip_debug_log.log ERROR, INFO, WARNING, OFF, DEBUG, TRACE
*/
Logger logger = LoggerFactory.getLogger(AlarmNotifyMessageHandler.class);
if (sipLog) {
properties.setProperty("gov.nist.javax.sip.STACK_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.StackLoggerImpl");
properties.setProperty("gov.nist.javax.sip.SERVER_LOGGER", "com.genersoft.iot.vmp.gb28181.conf.ServerLoggerImpl");
properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true");
logger.info("[SIP日志]已开启");
}else {
logger.info("[SIP日志]已关闭");
}
return properties;
| 424 | 37 | 1,041 | 1,078 |
36,058 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/conf/ServerLoggerImpl.java | ServerLoggerImpl | setSipStack | class ServerLoggerImpl implements ServerLogger {
private boolean showLog = true;
private SIPTransactionStack sipStack;
protected StackLogger stackLogger;
@Override
public void closeLogFile() {
}
@Override
public void logMessage(SIPMessage message, String from, String to, boolean sender, long time) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender? "发送:目标--->" + from:"接收:来自--->" + to)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logMessage(SIPMessage message, String from, String to, String status, boolean sender, long time) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender? "发送: 目标->" + from :"接收:来自->" + to)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logMessage(SIPMessage message, String from, String to, String status, boolean sender) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender? "发送: 目标->" + from :"接收:来自->" + to)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logException(Exception ex) {
if (!showLog) {
return;
}
this.stackLogger.logException(ex);
}
@Override
public void setStackProperties(Properties stackProperties) {
if (!showLog) {
return;
}
String TRACE_LEVEL = stackProperties.getProperty("gov.nist.javax.sip.TRACE_LEVEL");
if (TRACE_LEVEL != null) {
showLog = true;
}
}
@Override
public void setSipStack(SipStack sipStack) {<FILL_FUNCTION_BODY>}
} |
if (!showLog) {
return;
}
if(sipStack instanceof SIPTransactionStack) {
this.sipStack = (SIPTransactionStack)sipStack;
this.stackLogger = CommonLogger.getLogger(SIPTransactionStack.class);
}
| 82 | 609 | 73 | 682 |
36,059 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/conf/StackLoggerImpl.java | StackLoggerImpl | log | class StackLoggerImpl implements StackLogger {
/**
* 完全限定类名(Fully Qualified Class Name),用于定位日志位置
*/
private static final String FQCN = StackLoggerImpl.class.getName();
/**
* 获取栈中类信息(以便底层日志记录系统能够提取正确的位置信息(方法名、行号))
* @return LocationAwareLogger
*/
private static LocationAwareLogger getLocationAwareLogger() {
return (LocationAwareLogger) LoggerFactory.getLogger(new Throwable().getStackTrace()[4].getClassName());
}
/**
* 封装打印日志的位置信息
* @param level 日志级别
* @param message 日志事件的消息
*/
private static void log(int level, String message) {<FILL_FUNCTION_BODY>}
/**
* 封装打印日志的位置信息
* @param level 日志级别
* @param message 日志事件的消息
*/
private static void log(int level, String message, Throwable throwable) {
LocationAwareLogger locationAwareLogger = getLocationAwareLogger();
locationAwareLogger.log(null, FQCN, level, message, null, throwable);
}
@Override
public void logStackTrace() {
}
@Override
public void logStackTrace(int traceLevel) {
System.out.println("traceLevel: " + traceLevel);
}
@Override
public int getLineCount() {
return 0;
}
@Override
public void logException(Throwable ex) {
}
@Override
public void logDebug(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logDebug(String message, Exception ex) {
log(LocationAwareLogger.INFO_INT, message, ex);
}
@Override
public void logTrace(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logFatalError(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logError(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public boolean isLoggingEnabled() {
return true;
}
@Override
public boolean isLoggingEnabled(int logLevel) {
return true;
}
@Override
public void logError(String message, Exception ex) {
log(LocationAwareLogger.INFO_INT, message, ex);
}
@Override
public void logWarning(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logInfo(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void disableLogging() {
}
@Override
public void enableLogging() {
}
@Override
public void setBuildTimeStamp(String buildTimeStamp) {
}
@Override
public void setStackProperties(Properties stackProperties) {
}
@Override
public String getLoggerName() {
return null;
}
} |
LocationAwareLogger locationAwareLogger = getLocationAwareLogger();
locationAwareLogger.log(null, FQCN, level, message, null, null);
| 9 | 815 | 45 | 860 |
36,060 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/EventPublisher.java | EventPublisher | catalogEventPublish | class EventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
/**
* 设备报警事件
* @param deviceAlarm
*/
public void deviceAlarmEventPublish(DeviceAlarm deviceAlarm) {
AlarmEvent alarmEvent = new AlarmEvent(this);
alarmEvent.setAlarmInfo(deviceAlarm);
applicationEventPublisher.publishEvent(alarmEvent);
}
public void mediaServerOfflineEventPublish(String mediaServerId){
MediaServerOfflineEvent outEvent = new MediaServerOfflineEvent(this);
outEvent.setMediaServerId(mediaServerId);
applicationEventPublisher.publishEvent(outEvent);
}
public void mediaServerOnlineEventPublish(String mediaServerId) {
MediaServerOnlineEvent outEvent = new MediaServerOnlineEvent(this);
outEvent.setMediaServerId(mediaServerId);
applicationEventPublisher.publishEvent(outEvent);
}
public void catalogEventPublish(String platformId, DeviceChannel deviceChannel, String type) {<FILL_FUNCTION_BODY>}
public void requestTimeOut(TimeoutEvent timeoutEvent) {
RequestTimeoutEvent requestTimeoutEvent = new RequestTimeoutEvent(this);
requestTimeoutEvent.setTimeoutEvent(timeoutEvent);
applicationEventPublisher.publishEvent(requestTimeoutEvent);
}
/**
*
* @param platformId
* @param deviceChannels
* @param type
*/
public void catalogEventPublish(String platformId, List<DeviceChannel> deviceChannels, String type) {
CatalogEvent outEvent = new CatalogEvent(this);
List<DeviceChannel> channels = new ArrayList<>();
if (deviceChannels.size() > 1) {
// 数据去重
Set<String> gbIdSet = new HashSet<>();
for (DeviceChannel deviceChannel : deviceChannels) {
if (!gbIdSet.contains(deviceChannel.getChannelId())) {
gbIdSet.add(deviceChannel.getChannelId());
channels.add(deviceChannel);
}
}
}else {
channels = deviceChannels;
}
outEvent.setDeviceChannels(channels);
outEvent.setType(type);
outEvent.setPlatformId(platformId);
applicationEventPublisher.publishEvent(outEvent);
}
public void mobilePositionEventPublish(MobilePosition mobilePosition) {
MobilePositionEvent event = new MobilePositionEvent(this);
event.setMobilePosition(mobilePosition);
applicationEventPublisher.publishEvent(event);
}
public void catalogEventPublishForStream(String platformId, List<GbStream> gbStreams, String type) {
CatalogEvent outEvent = new CatalogEvent(this);
outEvent.setGbStreams(gbStreams);
outEvent.setType(type);
outEvent.setPlatformId(platformId);
applicationEventPublisher.publishEvent(outEvent);
}
public void catalogEventPublishForStream(String platformId, GbStream gbStream, String type) {
List<GbStream> gbStreamList = new ArrayList<>();
gbStreamList.add(gbStream);
catalogEventPublishForStream(platformId, gbStreamList, type);
}
public void recordEndEventPush(RecordInfo recordInfo) {
RecordEndEvent outEvent = new RecordEndEvent(this);
outEvent.setRecordInfo(recordInfo);
applicationEventPublisher.publishEvent(outEvent);
}
} |
List<DeviceChannel> deviceChannelList = new ArrayList<>();
deviceChannelList.add(deviceChannel);
catalogEventPublish(platformId, deviceChannelList, type);
| 7 | 920 | 48 | 968 |
36,061 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/SipSubscribe.java | SipSubscribe | execute | class SipSubscribe {
private final Logger logger = LoggerFactory.getLogger(SipSubscribe.class);
private Map<String, SipSubscribe.Event> errorSubscribes = new ConcurrentHashMap<>();
private Map<String, SipSubscribe.Event> okSubscribes = new ConcurrentHashMap<>();
private Map<String, Instant> okTimeSubscribes = new ConcurrentHashMap<>();
private Map<String, Instant> errorTimeSubscribes = new ConcurrentHashMap<>();
// @Scheduled(cron="*/5 * * * * ?") //每五秒执行一次
// @Scheduled(fixedRate= 100 * 60 * 60 )
@Scheduled(cron="0 0/5 * * * ?") //每5分钟执行一次
public void execute(){<FILL_FUNCTION_BODY>}
public interface Event { void response(EventResult eventResult);
}
/**
*
*/
public enum EventResultType{
// 超时
timeout,
// 回复
response,
// 事务已结束
transactionTerminated,
// 会话已结束
dialogTerminated,
// 设备未找到
deviceNotFoundEvent,
// 消息发送失败
cmdSendFailEvent,
// 消息发送失败
failedToGetPort
}
public static class EventResult<EventObject>{
public int statusCode;
public EventResultType type;
public String msg;
public String callId;
public EventObject event;
public EventResult() {
}
public EventResult(EventObject event) {
this.event = event;
if (event instanceof ResponseEvent) {
ResponseEvent responseEvent = (ResponseEvent)event;
SIPResponse response = (SIPResponse)responseEvent.getResponse();
this.type = EventResultType.response;
if (response != null) {
WarningHeader warningHeader = (WarningHeader)response.getHeader(WarningHeader.NAME);
if (warningHeader != null && !ObjectUtils.isEmpty(warningHeader.getText())) {
this.msg = "";
if (warningHeader.getCode() > 0) {
this.msg += warningHeader.getCode() + ":";
}
if (warningHeader.getAgent() != null) {
this.msg += warningHeader.getCode() + ":";
}
if (warningHeader.getText() != null) {
this.msg += warningHeader.getText();
}
}else {
this.msg = response.getReasonPhrase();
}
this.statusCode = response.getStatusCode();
this.callId = response.getCallIdHeader().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();
}else {
this.callId = ((SIPRequest)timeoutEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId();
}
}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();
}else {
this.callId = ((SIPRequest)transactionTerminatedEvent.getClientTransaction().getRequest()).getCallIdHeader().getCallId();
}
}else if (event instanceof DialogTerminatedEvent) {
DialogTerminatedEvent dialogTerminatedEvent = (DialogTerminatedEvent)event;
this.type = EventResultType.dialogTerminated;
this.msg = "会话已结束";
this.statusCode = -1024;
this.callId = dialogTerminatedEvent.getDialog().getCallId().getCallId();
}else if (event instanceof DeviceNotFoundEvent) {
this.type = EventResultType.deviceNotFoundEvent;
this.msg = "设备未找到";
this.statusCode = -1024;
this.callId = ((DeviceNotFoundEvent) event).getCallId();
}
}
}
public void addErrorSubscribe(String key, SipSubscribe.Event event) {
errorSubscribes.put(key, event);
errorTimeSubscribes.put(key, Instant.now());
}
public void addOkSubscribe(String key, SipSubscribe.Event event) {
okSubscribes.put(key, event);
okTimeSubscribes.put(key, Instant.now());
}
public SipSubscribe.Event getErrorSubscribe(String key) {
return errorSubscribes.get(key);
}
public void removeErrorSubscribe(String key) {
if(key == null){
return;
}
errorSubscribes.remove(key);
errorTimeSubscribes.remove(key);
}
public SipSubscribe.Event getOkSubscribe(String key) {
return okSubscribes.get(key);
}
public void removeOkSubscribe(String key) {
if(key == null){
return;
}
okSubscribes.remove(key);
okTimeSubscribes.remove(key);
}
public int getErrorSubscribesSize(){
return errorSubscribes.size();
}
public int getOkSubscribesSize(){
return okSubscribes.size();
}
} |
logger.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);
}
}
logger.debug("okTimeSubscribes.size:{}",okTimeSubscribes.size());
logger.debug("okSubscribes.size:{}",okSubscribes.size());
logger.debug("errorTimeSubscribes.size:{}",errorTimeSubscribes.size());
logger.debug("errorSubscribes.size:{}",errorSubscribes.size());
| 213 | 1,543 | 294 | 1,837 |
36,062 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/alarm/AlarmEventListener.java | AlarmEventListener | onApplicationEvent | class AlarmEventListener implements ApplicationListener<AlarmEvent> {
private static final Logger logger = LoggerFactory.getLogger(AlarmEventListener.class);
private static final Map<String, PrintWriter> SSE_CACHE = new ConcurrentHashMap<>();
public void addSseEmitter(String browserId, PrintWriter writer) {
SSE_CACHE.put(browserId, writer);
logger.info("SSE 在线数量: {}", SSE_CACHE.size());
}
public void removeSseEmitter(String browserId, PrintWriter writer) {
SSE_CACHE.remove(browserId, writer);
logger.info("SSE 在线数量: {}", SSE_CACHE.size());
}
@Override
public void onApplicationEvent(@NotNull AlarmEvent event) {<FILL_FUNCTION_BODY>}
} |
if (logger.isDebugEnabled()) {
logger.debug("设备报警事件触发, deviceId: {}, {}", event.getAlarmInfo().getDeviceId(), event.getAlarmInfo().getAlarmDescription());
}
String msg = "<strong>设备编号:</strong> <i>" + event.getAlarmInfo().getDeviceId() + "</i>"
+ "<br><strong>通道编号:</strong> <i>" + event.getAlarmInfo().getChannelId() + "</i>"
+ "<br><strong>报警描述:</strong> <i>" + event.getAlarmInfo().getAlarmDescription() + "</i>"
+ "<br><strong>报警时间:</strong> <i>" + event.getAlarmInfo().getAlarmTime() + "</i>";
for (Iterator<Map.Entry<String, PrintWriter>> it = SSE_CACHE.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, PrintWriter> response = it.next();
logger.info("推送到 SSE 连接, 浏览器 ID: {}", response.getKey());
try {
PrintWriter writer = response.getValue();
if (writer.checkError()) {
it.remove();
continue;
}
String sseMsg = "event:message\n" +
"data:" + msg + "\n" +
"\n";
writer.write(sseMsg);
writer.flush();
} catch (Exception e) {
it.remove();
}
}
| 435 | 224 | 413 | 637 |
36,063 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/device/RequestTimeoutEventImpl.java | RequestTimeoutEventImpl | onApplicationEvent | class RequestTimeoutEventImpl implements ApplicationListener<RequestTimeoutEvent> {
@Autowired
private IDeviceService deviceService;
@Override
public void onApplicationEvent(RequestTimeoutEvent event) {<FILL_FUNCTION_BODY>}
} |
ClientTransaction clientTransaction = event.getTimeoutEvent().getClientTransaction();
if (clientTransaction != null) {
Request request = clientTransaction.getRequest();
if (request != null) {
String host = ((SipURI) request.getRequestURI()).getHost();
int port = ((SipURI) request.getRequestURI()).getPort();
Device device = deviceService.getDeviceByHostAndPort(host, port);
if (device == null) {
return;
}
deviceService.offline(device.getDeviceId(), "等待消息超时");
}
}
| 212 | 65 | 152 | 217 |
36,064 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/record/RecordEndEventListener.java | RecordEndEventListener | onApplicationEvent | class RecordEndEventListener implements ApplicationListener<RecordEndEvent> {
private final static Logger logger = LoggerFactory.getLogger(RecordEndEventListener.class);
private Map<String, RecordEndEventHandler> handlerMap = new ConcurrentHashMap<>();
public interface RecordEndEventHandler{
void handler(RecordInfo recordInfo);
}
@Override
public void onApplicationEvent(RecordEndEvent event) {<FILL_FUNCTION_BODY>}
/**
* 添加
* @param device
* @param channelId
* @param recordEndEventHandler
*/
public void addEndEventHandler(String device, String channelId, RecordEndEventHandler recordEndEventHandler) {
logger.info("录像查询事件添加监听,deviceId:{}, channelId: {}", device, channelId);
handlerMap.put(device + channelId, recordEndEventHandler);
}
/**
* 添加
* @param device
* @param channelId
*/
public void delEndEventHandler(String device, String channelId) {
logger.info("录像查询事件移除监听,deviceId:{}, channelId: {}", device, channelId);
handlerMap.remove(device + channelId);
}
} |
String deviceId = event.getRecordInfo().getDeviceId();
String channelId = event.getRecordInfo().getChannelId();
int count = event.getRecordInfo().getCount();
int sumNum = event.getRecordInfo().getSumNum();
logger.info("录像查询完成事件触发,deviceId:{}, channelId: {}, 录像数量{}/{}条", event.getRecordInfo().getDeviceId(),
event.getRecordInfo().getChannelId(), count,sumNum);
if (!handlerMap.isEmpty()) {
RecordEndEventHandler handler = handlerMap.get(deviceId + channelId);
logger.info("录像查询完成事件触发, 发送订阅,deviceId:{}, channelId: {}",
event.getRecordInfo().getDeviceId(), event.getRecordInfo().getChannelId());
if (handler !=null){
handler.handler(event.getRecordInfo());
if (count ==sumNum){
handlerMap.remove(deviceId + channelId);
}
}
}
| 247 | 316 | 261 | 577 |
36,066 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/event/subscribe/mobilePosition/MobilePositionEventLister.java | MobilePositionEventLister | onApplicationEvent | class MobilePositionEventLister implements ApplicationListener<MobilePositionEvent> {
private final static Logger logger = LoggerFactory.getLogger(MobilePositionEventLister.class);
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommanderFroPlatform sipCommanderFroPlatform;
@Autowired
private SubscribeHolder subscribeHolder;
@Override
public void onApplicationEvent(MobilePositionEvent event) {<FILL_FUNCTION_BODY>}
} |
// 获取所用订阅
List<String> platforms = subscribeHolder.getAllMobilePositionSubscribePlatform();
if (platforms.isEmpty()) {
return;
}
List<ParentPlatform> parentPlatformsForGB = storager.queryPlatFormListForGBWithGBId(event.getMobilePosition().getChannelId(), platforms);
for (ParentPlatform platform : parentPlatformsForGB) {
logger.info("[向上级发送MobilePosition] 通道:{},平台:{}, 位置: {}:{}", event.getMobilePosition().getChannelId(),
platform.getServerGBId(), event.getMobilePosition().getLongitude(), event.getMobilePosition().getLatitude());
SubscribeInfo subscribe = subscribeHolder.getMobilePositionSubscribe(platform.getServerGBId());
try {
sipCommanderFroPlatform.sendNotifyMobilePosition(platform, GPSMsgInfo.getInstance(event.getMobilePosition()),
subscribe);
} catch (InvalidArgumentException | ParseException | NoSuchFieldException | SipException |
IllegalAccessException e) {
logger.error("[命令发送失败] 国标级联 Catalog通知: {}", e.getMessage());
}
}
| 271 | 133 | 301 | 434 |
36,067 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/AudioBroadcastManager.java | AudioBroadcastManager | exit | class AudioBroadcastManager {
private final static Logger logger = LoggerFactory.getLogger(AudioBroadcastManager.class);
@Autowired
private SipConfig config;
public static Map<String, AudioBroadcastCatch> data = new ConcurrentHashMap<>();
public void update(AudioBroadcastCatch audioBroadcastCatch) {
if (SipUtils.isFrontEnd(audioBroadcastCatch.getDeviceId())) {
audioBroadcastCatch.setChannelId(audioBroadcastCatch.getDeviceId());
data.put(audioBroadcastCatch.getDeviceId(), audioBroadcastCatch);
}else {
data.put(audioBroadcastCatch.getDeviceId() + audioBroadcastCatch.getChannelId(), audioBroadcastCatch);
}
}
public void del(String deviceId, String channelId) {
if (SipUtils.isFrontEnd(deviceId)) {
data.remove(deviceId);
}else {
data.remove(deviceId + channelId);
}
}
public void delByDeviceId(String deviceId) {
for (String key : data.keySet()) {
if (key.startsWith(deviceId)) {
data.remove(key);
}
}
}
public List<AudioBroadcastCatch> getAll(){
Collection<AudioBroadcastCatch> values = data.values();
return new ArrayList<>(values);
}
public boolean exit(String deviceId, String channelId) {<FILL_FUNCTION_BODY>}
public AudioBroadcastCatch get(String deviceId, String channelId) {
AudioBroadcastCatch audioBroadcastCatch;
if (SipUtils.isFrontEnd(deviceId)) {
audioBroadcastCatch = data.get(deviceId);
}else {
audioBroadcastCatch = data.get(deviceId + channelId);
}
if (audioBroadcastCatch == null) {
Stream<AudioBroadcastCatch> allAudioBroadcastCatchStreamForDevice = data.values().stream().filter(
audioBroadcastCatchItem -> Objects.equals(audioBroadcastCatchItem.getDeviceId(), deviceId));
List<AudioBroadcastCatch> audioBroadcastCatchList = allAudioBroadcastCatchStreamForDevice.collect(Collectors.toList());
if (audioBroadcastCatchList.size() == 1 && Objects.equals(config.getId(), channelId)) {
audioBroadcastCatch = audioBroadcastCatchList.get(0);
}
}
return audioBroadcastCatch;
}
public List<AudioBroadcastCatch> get(String deviceId) {
List<AudioBroadcastCatch> audioBroadcastCatchList= new ArrayList<>();
if (SipUtils.isFrontEnd(deviceId)) {
if (data.get(deviceId) != null) {
audioBroadcastCatchList.add(data.get(deviceId));
}
}else {
for (String key : data.keySet()) {
if (key.startsWith(deviceId)) {
audioBroadcastCatchList.add(data.get(key));
}
}
}
return audioBroadcastCatchList;
}
} |
for (String key : data.keySet()) {
if (SipUtils.isFrontEnd(deviceId)) {
return key.equals(deviceId);
}else {
return key.equals(deviceId + channelId);
}
}
return false;
| 110 | 868 | 72 | 940 |
36,068 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/CatalogDataCatch.java | CatalogDataCatch | timerTask | class CatalogDataCatch {
public static Map<String, CatalogData> data = new ConcurrentHashMap<>();
@Autowired
private IVideoManagerStorage storager;
public void addReady(Device device, int sn ) {
CatalogData catalogData = data.get(device.getDeviceId());
if (catalogData == null || catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end)) {
catalogData = new CatalogData();
catalogData.setChannelList(Collections.synchronizedList(new ArrayList<>()));
catalogData.setDevice(device);
catalogData.setSn(sn);
catalogData.setStatus(CatalogData.CatalogDataStatus.ready);
catalogData.setLastTime(Instant.now());
data.put(device.getDeviceId(), catalogData);
}
}
public void put(String deviceId, int sn, int total, Device device, List<DeviceChannel> deviceChannelList) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
catalogData = new CatalogData();
catalogData.setSn(sn);
catalogData.setTotal(total);
catalogData.setDevice(device);
catalogData.setChannelList(deviceChannelList);
catalogData.setStatus(CatalogData.CatalogDataStatus.runIng);
catalogData.setLastTime(Instant.now());
data.put(deviceId, catalogData);
}else {
// 同一个设备的通道同步请求只考虑一个,其他的直接忽略
if (catalogData.getSn() != sn) {
return;
}
catalogData.setTotal(total);
catalogData.setDevice(device);
catalogData.setStatus(CatalogData.CatalogDataStatus.runIng);
catalogData.getChannelList().addAll(deviceChannelList);
catalogData.setLastTime(Instant.now());
}
}
public List<DeviceChannel> get(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return null;
}
return catalogData.getChannelList();
}
public int getTotal(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return 0;
}
return catalogData.getTotal();
}
public SyncStatus getSyncStatus(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return null;
}
SyncStatus syncStatus = new SyncStatus();
syncStatus.setCurrent(catalogData.getChannelList().size());
syncStatus.setTotal(catalogData.getTotal());
syncStatus.setErrorMsg(catalogData.getErrorMsg());
if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end)) {
syncStatus.setSyncIng(false);
}else {
syncStatus.setSyncIng(true);
}
return syncStatus;
}
public boolean isSyncRunning(String deviceId) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return false;
}
return !catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end);
}
@Scheduled(fixedRate = 5 * 1000) //每5秒执行一次, 发现数据5秒未更新则移除数据并认为数据接收超时
private void timerTask(){<FILL_FUNCTION_BODY>}
public void setChannelSyncEnd(String deviceId, String errorMsg) {
CatalogData catalogData = data.get(deviceId);
if (catalogData == null) {
return;
}
catalogData.setStatus(CatalogData.CatalogDataStatus.end);
catalogData.setErrorMsg(errorMsg);
}
} |
Set<String> keys = data.keySet();
Instant instantBefore5S = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(5));
Instant instantBefore30S = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(30));
for (String deviceId : keys) {
CatalogData catalogData = data.get(deviceId);
if ( catalogData.getLastTime().isBefore(instantBefore5S)) {
// 超过五秒收不到消息任务超时, 只更新这一部分数据, 收到数据与声明的总数一致,则重置通道数据,数据不全则只对收到的数据做更新操作
if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.runIng)) {
if (catalogData.getTotal() == catalogData.getChannelList().size()) {
storager.resetChannels(catalogData.getDevice().getDeviceId(), catalogData.getChannelList());
}else {
storager.updateChannels(catalogData.getDevice().getDeviceId(), catalogData.getChannelList());
}
String errorMsg = "更新成功,共" + catalogData.getTotal() + "条,已更新" + catalogData.getChannelList().size() + "条";
catalogData.setErrorMsg(errorMsg);
if (catalogData.getTotal() != catalogData.getChannelList().size()) {
}
}else if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.ready)) {
String errorMsg = "同步失败,等待回复超时";
catalogData.setErrorMsg(errorMsg);
}
catalogData.setStatus(CatalogData.CatalogDataStatus.end);
}
if (catalogData.getStatus().equals(CatalogData.CatalogDataStatus.end) && catalogData.getLastTime().isBefore(instantBefore30S)) { // 超过三十秒,如果标记为end则删除
data.remove(deviceId);
}
}
| 488 | 1,026 | 523 | 1,549 |
36,069 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/CommonSessionManager.java | CommonSession | add | class CommonSession{
public String session;
public long createTime;
public int timeout;
public CommonCallback<Object> callback;
public CommonCallback<String> timeoutCallback;
}
/**
* 添加回调
* @param sessionId 唯一标识
* @param callback 回调
* @param timeout 超时时间, 单位分钟
*/
public void add(String sessionId, CommonCallback<Object> callback, CommonCallback<String> timeoutCallback,
Integer timeout) {<FILL_FUNCTION_BODY> |
CommonSession commonSession = new CommonSession();
commonSession.session = sessionId;
commonSession.callback = callback;
commonSession.createTime = System.currentTimeMillis();
if (timeoutCallback != null) {
commonSession.timeoutCallback = timeoutCallback;
}
if (timeout != null) {
commonSession.timeout = timeout;
}
callbackMap.put(sessionId, commonSession);
| 124 | 139 | 108 | 247 |
36,070 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/RecordDataCatch.java | RecordDataCatch | put | class RecordDataCatch {
public static Map<String, RecordInfo> data = new ConcurrentHashMap<>();
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private RecordEndEventListener recordEndEventListener;
public int put(String deviceId,String channelId, String sn, int sumNum, List<RecordItem> recordItems) {<FILL_FUNCTION_BODY>}
@Scheduled(fixedRate = 5 * 1000) //每5秒执行一次, 发现数据5秒未更新则移除数据并认为数据接收超时
private void timerTask(){
Set<String> keys = data.keySet();
// 获取五秒前的时刻
Instant instantBefore5S = Instant.now().minusMillis(TimeUnit.SECONDS.toMillis(5));
for (String key : keys) {
RecordInfo recordInfo = data.get(key);
// 超过五秒收不到消息任务超时, 只更新这一部分数据
if ( recordInfo.getLastTime().isBefore(instantBefore5S)) {
// 处理录像数据, 返回给前端
String msgKey = DeferredResultHolder.CALLBACK_CMD_RECORDINFO + recordInfo.getDeviceId() + recordInfo.getSn();
// 对数据进行排序
Collections.sort(recordInfo.getRecordList());
RequestMessage msg = new RequestMessage();
msg.setKey(msgKey);
msg.setData(recordInfo);
deferredResultHolder.invokeAllResult(msg);
recordEndEventListener.delEndEventHandler(recordInfo.getDeviceId(),recordInfo.getChannelId());
data.remove(key);
}
}
}
public boolean isComplete(String deviceId, String sn) {
RecordInfo recordInfo = data.get(deviceId + sn);
return recordInfo != null && recordInfo.getRecordList().size() == recordInfo.getSumNum();
}
public RecordInfo getRecordInfo(String deviceId, String sn) {
return data.get(deviceId + sn);
}
public void remove(String deviceId, String sn) {
data.remove(deviceId + sn);
}
} |
String key = deviceId + sn;
RecordInfo recordInfo = data.get(key);
if (recordInfo == null) {
recordInfo = new RecordInfo();
recordInfo.setDeviceId(deviceId);
recordInfo.setChannelId(channelId);
recordInfo.setSn(sn.trim());
recordInfo.setSumNum(sumNum);
recordInfo.setRecordList(Collections.synchronizedList(new ArrayList<>()));
recordInfo.setLastTime(Instant.now());
recordInfo.getRecordList().addAll(recordItems);
data.put(key, recordInfo);
}else {
// 同一个设备的通道同步请求只考虑一个,其他的直接忽略
if (!Objects.equals(sn.trim(), recordInfo.getSn())) {
return 0;
}
recordInfo.getRecordList().addAll(recordItems);
recordInfo.setLastTime(Instant.now());
}
return recordInfo.getRecordList().size();
| 261 | 561 | 251 | 812 |
36,071 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/SSRCFactory.java | SSRCFactory | initMediaServerSSRC | class SSRCFactory {
/**
* 播流最大并发个数
*/
private static final Integer MAX_STREAM_COUNT = 10000;
/**
* 播流最大并发个数
*/
private static final String SSRC_INFO_KEY = "VMP_SSRC_INFO_";
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private SipConfig sipConfig;
@Autowired
private UserSetting userSetting;
public void initMediaServerSSRC(String mediaServerId, Set<String> usedSet) {<FILL_FUNCTION_BODY>}
/**
* 获取视频预览的SSRC值,第一位固定为0
*
* @return ssrc
*/
public String getPlaySsrc(String mediaServerId) {
return "0" + getSN(mediaServerId);
}
/**
* 获取录像回放的SSRC值,第一位固定为1
*/
public String getPlayBackSsrc(String mediaServerId) {
return "1" + getSN(mediaServerId);
}
/**
* 释放ssrc,主要用完的ssrc一定要释放,否则会耗尽
*
* @param ssrc 需要重置的ssrc
*/
public void releaseSsrc(String mediaServerId, String ssrc) {
if (ssrc == null) {
return;
}
String sn = ssrc.substring(1);
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
redisTemplate.opsForSet().add(redisKey, sn);
}
/**
* 获取后四位数SN,随机数
*/
private String getSN(String mediaServerId) {
String sn = null;
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
Long size = redisTemplate.opsForSet().size(redisKey);
if (size == null || size == 0) {
throw new RuntimeException("ssrc已经用完");
} else {
// 在集合中移除并返回一个随机成员。
sn = (String) redisTemplate.opsForSet().pop(redisKey);
redisTemplate.opsForSet().remove(redisKey, sn);
}
return sn;
}
/**
* 重置一个流媒体服务的所有ssrc
*
* @param mediaServerId 流媒体服务ID
*/
public void reset(String mediaServerId) {
this.initMediaServerSSRC(mediaServerId, null);
}
/**
* 是否已经存在了某个MediaServer的SSRC信息
*
* @param mediaServerId 流媒体服务ID
*/
public boolean hasMediaServerSSRC(String mediaServerId) {
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
return Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
}
} |
String sipDomain = sipConfig.getDomain();
String ssrcPrefix = sipDomain.length() >= 8 ? sipDomain.substring(3, 8) : sipDomain;
String redisKey = SSRC_INFO_KEY + userSetting.getServerId() + "_" + mediaServerId;
List<String> ssrcList = new ArrayList<>();
for (int i = 1; i < MAX_STREAM_COUNT; i++) {
String ssrc = String.format("%s%04d", ssrcPrefix, i);
if (null == usedSet || !usedSet.contains(ssrc)) {
ssrcList.add(ssrc);
}
}
if (redisTemplate.opsForSet().size(redisKey) != null) {
redisTemplate.delete(redisKey);
}
redisTemplate.opsForSet().add(redisKey, ssrcList.toArray(new String[0]));
| 193 | 808 | 243 | 1,051 |
36,072 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/session/VideoStreamSessionManager.java | VideoStreamSessionManager | getSSRC | class VideoStreamSessionManager {
@Autowired
private UserSetting userSetting;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
/**
* 添加一个点播/回放的事务信息
* 后续可以通过流Id/callID
* @param deviceId 设备ID
* @param channelId 通道ID
* @param callId 一次请求的CallID
* @param stream 流名称
* @param mediaServerId 所使用的流媒体ID
* @param response 回复
*/
public void put(String deviceId, String channelId, String callId, String stream, String ssrc, String mediaServerId, SIPResponse response, InviteSessionType type){
SsrcTransaction ssrcTransaction = new SsrcTransaction();
ssrcTransaction.setDeviceId(deviceId);
ssrcTransaction.setChannelId(channelId);
ssrcTransaction.setStream(stream);
ssrcTransaction.setSipTransactionInfo(new SipTransactionInfo(response));
ssrcTransaction.setCallId(callId);
ssrcTransaction.setSsrc(ssrc);
ssrcTransaction.setMediaServerId(mediaServerId);
ssrcTransaction.setType(type);
redisTemplate.opsForValue().set(VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId()
+ ":" + deviceId + ":" + channelId + ":" + callId + ":" + stream, ssrcTransaction);
}
public SsrcTransaction getSsrcTransaction(String deviceId, String channelId, String callId, String stream){
if (ObjectUtils.isEmpty(deviceId)) {
deviceId ="*";
}
if (ObjectUtils.isEmpty(channelId)) {
channelId ="*";
}
if (ObjectUtils.isEmpty(callId)) {
callId ="*";
}
if (ObjectUtils.isEmpty(stream)) {
stream ="*";
}
String key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":" + deviceId + ":" + channelId + ":" + callId+ ":" + stream;
List<Object> scanResult = RedisUtil.scan(redisTemplate, key);
if (scanResult.size() == 0) {
return null;
}
return (SsrcTransaction)redisTemplate.opsForValue().get(scanResult.get(0));
}
public SsrcTransaction getSsrcTransactionByCallId(String callId){
if (ObjectUtils.isEmpty(callId)) {
return null;
}
String key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":*:*:" + callId+ ":*";
List<Object> scanResult = RedisUtil.scan(redisTemplate, key);
if (!scanResult.isEmpty()) {
return (SsrcTransaction)redisTemplate.opsForValue().get(scanResult.get(0));
}else {
key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":*:*:play:*";
scanResult = RedisUtil.scan(redisTemplate, key);
if (scanResult.isEmpty()) {
return null;
}
for (Object keyObj : scanResult) {
SsrcTransaction ssrcTransaction = (SsrcTransaction)redisTemplate.opsForValue().get(keyObj);
if (ssrcTransaction.getSipTransactionInfo() != null &&
ssrcTransaction.getSipTransactionInfo().getCallId().equals(callId)) {
return ssrcTransaction;
}
}
return null;
}
}
public List<SsrcTransaction> getSsrcTransactionForAll(String deviceId, String channelId, String callId, String stream){
if (ObjectUtils.isEmpty(deviceId)) {
deviceId ="*";
}
if (ObjectUtils.isEmpty(channelId)) {
channelId ="*";
}
if (ObjectUtils.isEmpty(callId)) {
callId ="*";
}
if (ObjectUtils.isEmpty(stream)) {
stream ="*";
}
String key = VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":" + deviceId + ":" + channelId + ":" + callId+ ":" + stream;
List<Object> scanResult = RedisUtil.scan(redisTemplate, key);
if (scanResult.size() == 0) {
return null;
}
List<SsrcTransaction> result = new ArrayList<>();
for (Object keyObj : scanResult) {
result.add((SsrcTransaction)redisTemplate.opsForValue().get(keyObj));
}
return result;
}
public String getMediaServerId(String deviceId, String channelId, String stream){
SsrcTransaction ssrcTransaction = getSsrcTransaction(deviceId, channelId, null, stream);
if (ssrcTransaction == null) {
return null;
}
return ssrcTransaction.getMediaServerId();
}
public String getSSRC(String deviceId, String channelId, String stream){<FILL_FUNCTION_BODY>}
public void remove(String deviceId, String channelId, String stream) {
List<SsrcTransaction> ssrcTransactionList = getSsrcTransactionForAll(deviceId, channelId, null, stream);
if (ssrcTransactionList == null || ssrcTransactionList.isEmpty()) {
return;
}
for (SsrcTransaction ssrcTransaction : ssrcTransactionList) {
redisTemplate.delete(VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":"
+ deviceId + ":" + channelId + ":" + ssrcTransaction.getCallId() + ":" + ssrcTransaction.getStream());
}
}
public void removeByCallId(String deviceId, String channelId, String callId) {
SsrcTransaction ssrcTransaction = getSsrcTransaction(deviceId, channelId, callId, null);
if (ssrcTransaction == null ) {
return;
}
redisTemplate.delete(VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX + userSetting.getServerId() + ":"
+ deviceId + ":" + channelId + ":" + ssrcTransaction.getCallId() + ":" + ssrcTransaction.getStream());
}
public List<SsrcTransaction> getAllSsrc() {
List<Object> ssrcTransactionKeys = RedisUtil.scan(redisTemplate, String.format("%s_*_*_*_*", VideoManagerConstants.MEDIA_TRANSACTION_USED_PREFIX+ userSetting.getServerId()));
List<SsrcTransaction> result= new ArrayList<>();
for (Object ssrcTransactionKey : ssrcTransactionKeys) {
String key = (String) ssrcTransactionKey;
SsrcTransaction ssrcTransaction = JsonUtil.redisJsonToObject(redisTemplate, key, SsrcTransaction.class);
result.add(ssrcTransaction);
}
return result;
}
} |
SsrcTransaction ssrcTransaction = getSsrcTransaction(deviceId, channelId, null, stream);
if (ssrcTransaction == null) {
return null;
}
return ssrcTransaction.getSsrc();
| 13 | 1,844 | 58 | 1,902 |
36,073 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/SipRunner.java | SipRunner | run | class SipRunner implements CommandLineRunner {
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private SSRCFactory ssrcFactory;
@Autowired
private UserSetting userSetting;
@Autowired
private IDeviceService deviceService;
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private IPlatformService platformService;
@Autowired
private ISIPCommanderForPlatform commanderForPlatform;
private final static Logger logger = LoggerFactory.getLogger(PlatformServiceImpl.class);
@Override
public void run(String... args) throws Exception {<FILL_FUNCTION_BODY>}
} |
List<Device> deviceList = deviceService.getAllOnlineDevice();
for (Device device : deviceList) {
if (deviceService.expire(device)){
deviceService.offline(device.getDeviceId(), "注册已过期");
}else {
deviceService.online(device, null);
}
}
// 重置cseq计数
redisCatchStorage.resetAllCSEQ();
// 清理redis
// 清理数据库不存在但是redis中存在的数据
List<Device> devicesInDb = deviceService.getAll();
if (devicesInDb.size() == 0) {
redisCatchStorage.removeAllDevice();
}else {
List<Device> devicesInRedis = redisCatchStorage.getAllDevices();
if (devicesInRedis.size() > 0) {
Map<String, Device> deviceMapInDb = new HashMap<>();
devicesInDb.parallelStream().forEach(device -> {
deviceMapInDb.put(device.getDeviceId(), device);
});
devicesInRedis.parallelStream().forEach(device -> {
if (deviceMapInDb.get(device.getDeviceId()) == null) {
redisCatchStorage.removeDevice(device.getDeviceId());
}
});
}
}
// 查找国标推流
List<SendRtpItem> sendRtpItems = redisCatchStorage.queryAllSendRTPServer();
if (sendRtpItems.size() > 0) {
for (SendRtpItem sendRtpItem : sendRtpItems) {
MediaServer mediaServerItem = mediaServerService.getOne(sendRtpItem.getMediaServerId());
redisCatchStorage.deleteSendRTPServer(sendRtpItem.getPlatformId(),sendRtpItem.getChannelId(), sendRtpItem.getCallId(),sendRtpItem.getStream());
if (mediaServerItem != null) {
ssrcFactory.releaseSsrc(sendRtpItem.getMediaServerId(), sendRtpItem.getSsrc());
boolean stopResult = mediaServerService.stopSendRtp(mediaServerItem, sendRtpItem.getApp(), sendRtpItem.getStream(), sendRtpItem.getSsrc());
if (stopResult) {
ParentPlatform platform = platformService.queryPlatformByServerGBId(sendRtpItem.getPlatformId());
if (platform != null) {
try {
commanderForPlatform.streamByeCmd(platform, sendRtpItem.getCallId());
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 国标级联 发送BYE: {}", e.getMessage());
}
}
}
}
}
}
| 888 | 210 | 703 | 913 |
36,074 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/impl/CatalogSubscribeTask.java | CatalogSubscribeTask | run | class CatalogSubscribeTask implements ISubscribeTask {
private final Logger logger = LoggerFactory.getLogger(CatalogSubscribeTask.class);
private Device device;
private final ISIPCommander sipCommander;
private SIPRequest request;
private DynamicTask dynamicTask;
private String taskKey = "catalog-subscribe-timeout";
public CatalogSubscribeTask(Device device, ISIPCommander sipCommander, DynamicTask dynamicTask) {
this.device = device;
this.sipCommander = sipCommander;
this.dynamicTask = dynamicTask;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
@Override
public void stop(CommonCallback<Boolean> callback) {
/**
* dialog 的各个状态
* EARLY-> Early state状态-初始请求发送以后,收到了一个临时响应消息
* CONFIRMED-> Confirmed Dialog状态-已确认
* COMPLETED-> Completed Dialog状态-已完成
* TERMINATED-> Terminated Dialog状态-终止
*/
logger.info("取消目录订阅时dialog状态为{}", DialogState.CONFIRMED);
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
device.setSubscribeCycleForCatalog(0);
try {
sipCommander.catalogSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event;
if (event.getResponse().getRawContent() != null) {
// 成功
logger.info("[取消目录订阅]成功: {}", device.getDeviceId());
}else {
// 成功
logger.info("[取消目录订阅]成功: {}", device.getDeviceId());
}
if (callback != null) {
callback.run(event.getResponse().getRawContent() != null);
}
},eventResult -> {
// 失败
logger.warn("[取消目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 取消目录订阅: {}", e.getMessage());
}
}
} |
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
SIPRequest sipRequest = null;
try {
sipRequest = sipCommander.catalogSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event;
// 成功
logger.info("[目录订阅]成功: {}", device.getDeviceId());
ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME);
try {
this.request.getToHeader().setTag(toHeader.getTag());
} catch (ParseException e) {
logger.info("[目录订阅]成功: 但为request设置ToTag失败");
this.request = null;
}
},eventResult -> {
this.request = null;
// 失败
logger.warn("[目录订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
dynamicTask.startDelay(taskKey, CatalogSubscribeTask.this, 2000);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 目录订阅: {}", e.getMessage());
}
if (sipRequest != null) {
this.request = sipRequest;
}
| 437 | 622 | 365 | 987 |
36,075 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/task/impl/MobilePositionSubscribeTask.java | MobilePositionSubscribeTask | run | class MobilePositionSubscribeTask implements ISubscribeTask {
private final Logger logger = LoggerFactory.getLogger(MobilePositionSubscribeTask.class);
private Device device;
private ISIPCommander sipCommander;
private SIPRequest request;
private DynamicTask dynamicTask;
private String taskKey = "mobile-position-subscribe-timeout";
public MobilePositionSubscribeTask(Device device, ISIPCommander sipCommander, DynamicTask dynamicTask) {
this.device = device;
this.sipCommander = sipCommander;
this.dynamicTask = dynamicTask;
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
@Override
public void stop(CommonCallback<Boolean> callback) {
/**
* dialog 的各个状态
* EARLY-> Early state状态-初始请求发送以后,收到了一个临时响应消息
* CONFIRMED-> Confirmed Dialog状态-已确认
* COMPLETED-> Completed Dialog状态-已完成
* TERMINATED-> Terminated Dialog状态-终止
*/
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
device.setSubscribeCycleForMobilePosition(0);
try {
sipCommander.mobilePositionSubscribe(device, request, eventResult -> {
ResponseEvent event = (ResponseEvent) eventResult.event;
if (event.getResponse().getRawContent() != null) {
// 成功
logger.info("[取消移动位置订阅]成功: {}", device.getDeviceId());
}else {
// 成功
logger.info("[取消移动位置订阅]成功: {}", device.getDeviceId());
}
if (callback != null) {
callback.run(event.getResponse().getRawContent() != null);
}
},eventResult -> {
// 失败
logger.warn("[取消移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 取消移动位置订阅: {}", e.getMessage());
}
}
} |
if (dynamicTask.get(taskKey) != null) {
dynamicTask.stop(taskKey);
}
SIPRequest sipRequest = null;
try {
sipRequest = sipCommander.mobilePositionSubscribe(device, request, eventResult -> {
// 成功
logger.info("[移动位置订阅]成功: {}", device.getDeviceId());
ResponseEvent event = (ResponseEvent) eventResult.event;
ToHeader toHeader = (ToHeader)event.getResponse().getHeader(ToHeader.NAME);
try {
this.request.getToHeader().setTag(toHeader.getTag());
} catch (ParseException e) {
logger.info("[移动位置订阅]成功: 为request设置ToTag失败");
this.request = null;
}
},eventResult -> {
this.request = null;
// 失败
logger.warn("[移动位置订阅]失败,信令发送失败: {}-{} ", device.getDeviceId(), eventResult.msg);
dynamicTask.startDelay(taskKey, MobilePositionSubscribeTask.this, 2000);
});
} catch (InvalidArgumentException | SipException | ParseException e) {
logger.error("[命令发送失败] 移动位置订阅: {}", e.getMessage());
}
if (sipRequest != null) {
this.request = sipRequest;
}
| 437 | 593 | 364 | 957 |
36,076 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/SIPProcessorObserver.java | SIPProcessorObserver | processResponse | class SIPProcessorObserver implements ISIPProcessorObserver {
private final static Logger logger = LoggerFactory.getLogger(SIPProcessorObserver.class);
private static Map<String, ISIPRequestProcessor> requestProcessorMap = new ConcurrentHashMap<>();
private static Map<String, ISIPResponseProcessor> responseProcessorMap = new ConcurrentHashMap<>();
private static ITimeoutProcessor timeoutProcessor;
@Autowired
private SipSubscribe sipSubscribe;
@Autowired
private EventPublisher eventPublisher;
/**
* 添加 request订阅
* @param method 方法名
* @param processor 处理程序
*/
public void addRequestProcessor(String method, ISIPRequestProcessor processor) {
requestProcessorMap.put(method, processor);
}
/**
* 添加 response订阅
* @param method 方法名
* @param processor 处理程序
*/
public void addResponseProcessor(String method, ISIPResponseProcessor processor) {
responseProcessorMap.put(method, processor);
}
/**
* 添加 超时事件订阅
* @param processor 处理程序
*/
public void addTimeoutProcessor(ITimeoutProcessor processor) {
timeoutProcessor = processor;
}
/**
* 分发RequestEvent事件
* @param requestEvent RequestEvent事件
*/
@Override
@Async("taskExecutor")
public void processRequest(RequestEvent requestEvent) {
String method = requestEvent.getRequest().getMethod();
ISIPRequestProcessor sipRequestProcessor = requestProcessorMap.get(method);
if (sipRequestProcessor == null) {
logger.warn("不支持方法{}的request", method);
// TODO 回复错误玛
return;
}
requestProcessorMap.get(method).process(requestEvent);
}
/**
* 分发ResponseEvent事件
* @param responseEvent responseEvent事件
*/
@Override
@Async("taskExecutor")
public void processResponse(ResponseEvent responseEvent) {<FILL_FUNCTION_BODY>}
/**
* 向超时订阅发送消息
* @param timeoutEvent timeoutEvent事件
*/
@Override
public void processTimeout(TimeoutEvent timeoutEvent) {
logger.info("[消息发送超时]");
ClientTransaction clientTransaction = timeoutEvent.getClientTransaction();
if (clientTransaction != null) {
logger.info("[发送错误订阅] clientTransaction != null");
Request request = clientTransaction.getRequest();
if (request != null) {
logger.info("[发送错误订阅] request != null");
CallIdHeader callIdHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
logger.info("[发送错误订阅]");
SipSubscribe.Event subscribe = sipSubscribe.getErrorSubscribe(callIdHeader.getCallId());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(timeoutEvent);
if (subscribe != null){
subscribe.response(eventResult);
}
sipSubscribe.removeOkSubscribe(callIdHeader.getCallId());
sipSubscribe.removeErrorSubscribe(callIdHeader.getCallId());
}
}
}
eventPublisher.requestTimeOut(timeoutEvent);
}
@Override
public void processIOException(IOExceptionEvent exceptionEvent) {
System.out.println("processIOException");
}
@Override
public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
// if (transactionTerminatedEvent.isServerTransaction()) {
// ServerTransaction serverTransaction = transactionTerminatedEvent.getServerTransaction();
// serverTransaction.get
// }
// Transaction transaction = null;
// System.out.println("processTransactionTerminated");
// if (transactionTerminatedEvent.isServerTransaction()) {
// transaction = transactionTerminatedEvent.getServerTransaction();
// }else {
// transaction = transactionTerminatedEvent.getClientTransaction();
// }
//
// System.out.println(transaction.getBranchId());
// System.out.println(transaction.getState());
// System.out.println(transaction.getRequest().getMethod());
// CallIdHeader header = (CallIdHeader)transaction.getRequest().getHeader(CallIdHeader.NAME);
// SipSubscribe.EventResult<TransactionTerminatedEvent> terminatedEventEventResult = new SipSubscribe.EventResult<>(transactionTerminatedEvent);
// sipSubscribe.getErrorSubscribe(header.getCallId()).response(terminatedEventEventResult);
}
@Override
public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
CallIdHeader callId = dialogTerminatedEvent.getDialog().getCallId();
}
} |
Response response = responseEvent.getResponse();
int status = response.getStatusCode();
// Success
if (((status >= Response.OK) && (status < Response.MULTIPLE_CHOICES)) || status == Response.UNAUTHORIZED) {
CSeqHeader cseqHeader = (CSeqHeader) responseEvent.getResponse().getHeader(CSeqHeader.NAME);
String method = cseqHeader.getMethod();
ISIPResponseProcessor sipRequestProcessor = responseProcessorMap.get(method);
if (sipRequestProcessor != null) {
sipRequestProcessor.process(responseEvent);
}
if (status != Response.UNAUTHORIZED && responseEvent.getResponse() != null && sipSubscribe.getOkSubscribesSize() > 0 ) {
CallIdHeader callIdHeader = (CallIdHeader)responseEvent.getResponse().getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
SipSubscribe.Event subscribe = sipSubscribe.getOkSubscribe(callIdHeader.getCallId());
if (subscribe != null) {
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(responseEvent);
sipSubscribe.removeOkSubscribe(callIdHeader.getCallId());
subscribe.response(eventResult);
}
}
}
} else if ((status >= Response.TRYING) && (status < Response.OK)) {
// 增加其它无需回复的响应,如101、180等
} else {
logger.warn("接收到失败的response响应!status:" + status + ",message:" + response.getReasonPhrase());
if (responseEvent.getResponse() != null && sipSubscribe.getErrorSubscribesSize() > 0 ) {
CallIdHeader callIdHeader = (CallIdHeader)responseEvent.getResponse().getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
SipSubscribe.Event subscribe = sipSubscribe.getErrorSubscribe(callIdHeader.getCallId());
if (subscribe != null) {
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(responseEvent);
subscribe.response(eventResult);
sipSubscribe.removeErrorSubscribe(callIdHeader.getCallId());
}
}
}
if (responseEvent.getDialog() != null) {
responseEvent.getDialog().delete();
}
}
| 723 | 1,230 | 629 | 1,859 |
36,077 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/SIPSender.java | SIPSender | transmitRequest | class SIPSender {
private final Logger logger = LoggerFactory.getLogger(SIPSender.class);
@Autowired
private SipLayer sipLayer;
@Autowired
private GitUtil gitUtil;
@Autowired
private SipSubscribe sipSubscribe;
public void transmitRequest(String ip, Message message) throws SipException, ParseException {
transmitRequest(ip, message, null, null);
}
public void transmitRequest(String ip, Message message, SipSubscribe.Event errorEvent) throws SipException, ParseException {
transmitRequest(ip, message, errorEvent, null);
}
public void transmitRequest(String ip, Message message, SipSubscribe.Event errorEvent, SipSubscribe.Event okEvent) throws SipException {<FILL_FUNCTION_BODY>}
public CallIdHeader getNewCallIdHeader(String ip, String transport){
if (ObjectUtils.isEmpty(transport)) {
return sipLayer.getUdpSipProvider().getNewCallId();
}
SipProviderImpl sipProvider;
if (ObjectUtils.isEmpty(ip)) {
sipProvider = transport.equalsIgnoreCase("TCP") ? sipLayer.getTcpSipProvider()
: sipLayer.getUdpSipProvider();
}else {
sipProvider = transport.equalsIgnoreCase("TCP") ? sipLayer.getTcpSipProvider(ip)
: sipLayer.getUdpSipProvider(ip);
}
if (sipProvider == null) {
sipProvider = sipLayer.getUdpSipProvider();
}
if (sipProvider != null) {
return sipProvider.getNewCallId();
}else {
logger.warn("[新建CallIdHeader失败], ip={}, transport={}", ip, transport);
return null;
}
}
} |
ViaHeader viaHeader = (ViaHeader)message.getHeader(ViaHeader.NAME);
String transport = "UDP";
if (viaHeader == null) {
logger.warn("[消息头缺失]: ViaHeader, 使用默认的UDP方式处理数据");
}else {
transport = viaHeader.getTransport();
}
if (message.getHeader(UserAgentHeader.NAME) == null) {
try {
message.addHeader(SipUtils.createUserAgentHeader(gitUtil));
} catch (ParseException e) {
logger.error("添加UserAgentHeader失败", e);
}
}
CallIdHeader callIdHeader = (CallIdHeader) message.getHeader(CallIdHeader.NAME);
// 添加错误订阅
if (errorEvent != null) {
sipSubscribe.addErrorSubscribe(callIdHeader.getCallId(), (eventResult -> {
sipSubscribe.removeErrorSubscribe(eventResult.callId);
sipSubscribe.removeOkSubscribe(eventResult.callId);
errorEvent.response(eventResult);
}));
}
// 添加订阅
if (okEvent != null) {
sipSubscribe.addOkSubscribe(callIdHeader.getCallId(), eventResult -> {
sipSubscribe.removeOkSubscribe(eventResult.callId);
sipSubscribe.removeErrorSubscribe(eventResult.callId);
okEvent.response(eventResult);
});
}
if ("TCP".equals(transport)) {
SipProviderImpl tcpSipProvider = sipLayer.getTcpSipProvider(ip);
if (tcpSipProvider == null) {
logger.error("[发送信息失败] 未找到tcp://{}的监听信息", ip);
return;
}
if (message instanceof Request) {
tcpSipProvider.sendRequest((Request)message);
}else if (message instanceof Response) {
tcpSipProvider.sendResponse((Response)message);
}
} else if ("UDP".equals(transport)) {
SipProviderImpl sipProvider = sipLayer.getUdpSipProvider(ip);
if (sipProvider == null) {
logger.error("[发送信息失败] 未找到udp://{}的监听信息", ip);
return;
}
if (message instanceof Request) {
sipProvider.sendRequest((Request)message);
}else if (message instanceof Response) {
sipProvider.sendResponse((Response)message);
}
}
| 952 | 487 | 652 | 1,139 |
36,078 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/callback/DeferredResultHolder.java | DeferredResultHolder | put | class DeferredResultHolder {
public static final String CALLBACK_CMD_DEVICESTATUS = "CALLBACK_DEVICESTATUS";
public static final String CALLBACK_CMD_DEVICEINFO = "CALLBACK_DEVICEINFO";
public static final String CALLBACK_CMD_DEVICECONTROL = "CALLBACK_DEVICECONTROL";
public static final String CALLBACK_CMD_DEVICECONFIG = "CALLBACK_DEVICECONFIG";
public static final String CALLBACK_CMD_CONFIGDOWNLOAD = "CALLBACK_CONFIGDOWNLOAD";
public static final String CALLBACK_CMD_CATALOG = "CALLBACK_CATALOG";
public static final String CALLBACK_CMD_RECORDINFO = "CALLBACK_RECORDINFO";
public static final String CALLBACK_CMD_PLAY = "CALLBACK_PLAY";
public static final String CALLBACK_CMD_PLAYBACK = "CALLBACK_PLAYBACK";
public static final String CALLBACK_CMD_DOWNLOAD = "CALLBACK_DOWNLOAD";
public static final String CALLBACK_CMD_PROXY = "CALLBACK_PROXY";
public static final String CALLBACK_CMD_STOP = "CALLBACK_STOP";
public static final String UPLOAD_FILE_CHANNEL = "UPLOAD_FILE_CHANNEL";
public static final String CALLBACK_CMD_MOBILE_POSITION = "CALLBACK_CMD_MOBILE_POSITION";
public static final String CALLBACK_CMD_PRESETQUERY = "CALLBACK_PRESETQUERY";
public static final String CALLBACK_CMD_ALARM = "CALLBACK_ALARM";
public static final String CALLBACK_CMD_BROADCAST = "CALLBACK_BROADCAST";
public static final String CALLBACK_CMD_SNAP= "CALLBACK_SNAP";
private Map<String, Map<String, DeferredResultEx>> map = new ConcurrentHashMap<>();
public void put(String key, String id, DeferredResultEx result) {
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null) {
deferredResultMap = new ConcurrentHashMap<>();
map.put(key, deferredResultMap);
}
deferredResultMap.put(id, result);
}
public void put(String key, String id, DeferredResult result) {<FILL_FUNCTION_BODY>}
public DeferredResultEx get(String key, String id) {
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null || ObjectUtils.isEmpty(id)) {
return null;
}
return deferredResultMap.get(id);
}
public Collection<DeferredResultEx> getAllByKey(String key) {
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null) {
return null;
}
return deferredResultMap.values();
}
public boolean exist(String key, String id){
if (key == null) {
return false;
}
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (id == null) {
return deferredResultMap != null;
}else {
return deferredResultMap != null && deferredResultMap.get(id) != null;
}
}
/**
* 释放单个请求
* @param msg
*/
public void invokeResult(RequestMessage msg) {
Map<String, DeferredResultEx> deferredResultMap = map.get(msg.getKey());
if (deferredResultMap == null) {
return;
}
DeferredResultEx result = deferredResultMap.get(msg.getId());
if (result == null) {
return;
}
result.getDeferredResult().setResult(msg.getData());
deferredResultMap.remove(msg.getId());
if (deferredResultMap.size() == 0) {
map.remove(msg.getKey());
}
}
/**
* 释放所有的请求
* @param msg
*/
public void invokeAllResult(RequestMessage msg) {
Map<String, DeferredResultEx> deferredResultMap = map.get(msg.getKey());
if (deferredResultMap == null) {
return;
}
synchronized (this) {
deferredResultMap = map.get(msg.getKey());
if (deferredResultMap == null) {
return;
}
Set<String> ids = deferredResultMap.keySet();
for (String id : ids) {
DeferredResultEx result = deferredResultMap.get(id);
if (result == null) {
return;
}
if (result.getFilter() != null) {
Object handler = result.getFilter().handler(msg.getData());
result.getDeferredResult().setResult(handler);
}else {
result.getDeferredResult().setResult(msg.getData());
}
}
map.remove(msg.getKey());
}
}
} |
Map<String, DeferredResultEx> deferredResultMap = map.get(key);
if (deferredResultMap == null) {
deferredResultMap = new ConcurrentHashMap<>();
map.put(key, deferredResultMap);
}
deferredResultMap.put(id, new DeferredResultEx(result));
| 15 | 1,359 | 90 | 1,449 |
36,084 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/AckRequestProcessor.java | AckRequestProcessor | process | class AckRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final Logger logger = LoggerFactory.getLogger(AckRequestProcessor.class);
private final String method = "ACK";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private UserSetting userSetting;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IDeviceService deviceService;
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private DynamicTask dynamicTask;
@Autowired
private RedisGbPlayMsgListener redisGbPlayMsgListener;
@Autowired
private IPlayService playService;
/**
* 处理 ACK请求
*/
@Override
public void process(RequestEvent evt) {<FILL_FUNCTION_BODY>}
} |
CallIdHeader callIdHeader = (CallIdHeader)evt.getRequest().getHeader(CallIdHeader.NAME);
dynamicTask.stop(callIdHeader.getCallId());
String fromUserId = ((SipURI) ((HeaderAddress) evt.getRequest().getHeader(FromHeader.NAME)).getAddress().getURI()).getUser();
String toUserId = ((SipURI) ((HeaderAddress) evt.getRequest().getHeader(ToHeader.NAME)).getAddress().getURI()).getUser();
logger.info("[收到ACK]: 来自->{}", fromUserId);
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(null, null, null, callIdHeader.getCallId());
if (sendRtpItem == null) {
logger.warn("[收到ACK]:未找到来自{},目标为({})的推流信息",fromUserId, toUserId);
return;
}
// tcp主动时,此时是级联下级平台,在回复200ok时,本地已经请求zlm开启监听,跳过下面步骤
if (sendRtpItem.isTcpActive()) {
logger.info("收到ACK,rtp/{} TCP主动方式后续处理", sendRtpItem.getStream());
return;
}
MediaServer mediaInfo = mediaServerService.getOne(sendRtpItem.getMediaServerId());
logger.info("收到ACK,rtp/{}开始向上级推流, 目标={}:{},SSRC={}, 协议:{}",
sendRtpItem.getStream(),
sendRtpItem.getIp(),
sendRtpItem.getPort(),
sendRtpItem.getSsrc(),
sendRtpItem.isTcp()?(sendRtpItem.isTcpActive()?"TCP主动":"TCP被动"):"UDP"
);
ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(fromUserId);
if (parentPlatform != null) {
if (!userSetting.getServerId().equals(sendRtpItem.getServerId())) {
RequestPushStreamMsg requestPushStreamMsg = RequestPushStreamMsg.getInstance(sendRtpItem);
redisGbPlayMsgListener.sendMsgForStartSendRtpStream(sendRtpItem.getServerId(), requestPushStreamMsg, () -> {
playService.startSendRtpStreamFailHand(sendRtpItem, parentPlatform, callIdHeader);
});
} else {
try {
if (sendRtpItem.isTcpActive()) {
mediaServerService.startSendRtpPassive(mediaInfo, parentPlatform, sendRtpItem, null);
} else {
mediaServerService.startSendRtp(mediaInfo, parentPlatform, sendRtpItem);
}
}catch (ControllerException e) {
logger.error("RTP推流失败: {}", e.getMessage());
playService.startSendRtpStreamFailHand(sendRtpItem, parentPlatform, callIdHeader);
}
}
}else {
Device device = deviceService.getDevice(fromUserId);
if (device == null) {
logger.warn("[收到ACK]:来自{},目标为({})的推流信息为找到流体服务[{}]信息",fromUserId, toUserId, sendRtpItem.getMediaServerId());
return;
}
// 设置为收到ACK后发送语音的设备已经在发送200OK开始发流了
if (!device.isBroadcastPushAfterAck()) {
return;
}
if (mediaInfo == null) {
logger.warn("[收到ACK]:来自{},目标为({})的推流信息为找到流体服务[{}]信息",fromUserId, toUserId, sendRtpItem.getMediaServerId());
return;
}
try {
if (sendRtpItem.isTcpActive()) {
mediaServerService.startSendRtpPassive(mediaInfo, null, sendRtpItem, null);
} else {
mediaServerService.startSendRtp(mediaInfo, null, sendRtpItem);
}
}catch (ControllerException e) {
logger.error("RTP推流失败: {}", e.getMessage());
playService.startSendRtpStreamFailHand(sendRtpItem, null, callIdHeader);
}
}
| 111 | 290 | 1,128 | 1,418 |
36,090 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/SubscribeRequestProcessor.java | SubscribeRequestProcessor | processNotifyCatalogList | class SubscribeRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final Logger logger = LoggerFactory.getLogger(SubscribeRequestProcessor.class);
private final String method = "SUBSCRIBE";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SubscribeHolder subscribeHolder;
@Autowired
private SIPSender sipSender;
@Autowired
private IPlatformService platformService;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
/**
* 处理SUBSCRIBE请求
*
* @param evt 事件
*/
@Override
public void process(RequestEvent evt) {
SIPRequest request = (SIPRequest) evt.getRequest();
try {
Element rootElement = getRootElement(evt);
if (rootElement == null) {
logger.error("处理SUBSCRIBE请求 未获取到消息体{}", evt.getRequest());
return;
}
String cmd = XmlUtil.getText(rootElement, "CmdType");
if (CmdType.MOBILE_POSITION.equals(cmd)) {
processNotifyMobilePosition(request, rootElement);
// } else if (CmdType.ALARM.equals(cmd)) {
// logger.info("接收到Alarm订阅");
// processNotifyAlarm(serverTransaction, rootElement);
} else if (CmdType.CATALOG.equals(cmd)) {
processNotifyCatalogList(request, rootElement);
} else {
logger.info("接收到消息:" + cmd);
Response response = getMessageFactory().createResponse(200, request);
if (response != null) {
ExpiresHeader expireHeader = getHeaderFactory().createExpiresHeader(30);
response.setExpires(expireHeader);
}
logger.info("response : " + response);
sipSender.transmitRequest(request.getLocalAddress().getHostAddress(), response);
}
} catch (ParseException | SipException | InvalidArgumentException | DocumentException e) {
logger.error("未处理的异常 ", e);
}
}
/**
* 处理移动位置订阅消息
*/
private void processNotifyMobilePosition(SIPRequest request, Element rootElement) throws SipException {
if (request == null) {
return;
}
String platformId = SipUtils.getUserIdFromFromHeader(request);
String deviceId = XmlUtil.getText(rootElement, "DeviceID");
ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);
if (platform == null) {
return;
}
String sn = XmlUtil.getText(rootElement, "SN");
logger.info("[回复上级的移动位置订阅请求]: {}", platformId);
StringBuilder resultXml = new StringBuilder(200);
resultXml.append("<?xml version=\"1.0\" ?>\r\n")
.append("<Response>\r\n")
.append("<CmdType>MobilePosition</CmdType>\r\n")
.append("<SN>").append(sn).append("</SN>\r\n")
.append("<DeviceID>").append(deviceId).append("</DeviceID>\r\n")
.append("<Result>OK</Result>\r\n")
.append("</Response>\r\n");
if (subscribeInfo.getExpires() > 0) {
// GPS上报时间间隔
String interval = XmlUtil.getText(rootElement, "Interval");
if (interval == null) {
subscribeInfo.setGpsInterval(5);
}else {
subscribeInfo.setGpsInterval(Integer.parseInt(interval));
}
subscribeInfo.setSn(sn);
}
try {
ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(platformId);
SIPResponse response = responseXmlAck(request, resultXml.toString(), parentPlatform, subscribeInfo.getExpires());
if (subscribeInfo.getExpires() == 0) {
subscribeHolder.removeMobilePositionSubscribe(platformId);
}else {
subscribeInfo.setResponse(response);
subscribeHolder.putMobilePositionSubscribe(platformId, subscribeInfo);
}
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("未处理的异常 ", e);
}
}
private void processNotifyAlarm(RequestEvent evt, Element rootElement) {
}
private void processNotifyCatalogList(SIPRequest request, Element rootElement) throws SipException {<FILL_FUNCTION_BODY>}
} |
if (request == null) {
return;
}
String platformId = SipUtils.getUserIdFromFromHeader(request);
String deviceId = XmlUtil.getText(rootElement, "DeviceID");
ParentPlatform platform = storager.queryParentPlatByServerGBId(platformId);
if (platform == null){
return;
}
SubscribeInfo subscribeInfo = new SubscribeInfo(request, platformId);
String sn = XmlUtil.getText(rootElement, "SN");
logger.info("[回复上级的目录订阅请求]: {}/{}", platformId, deviceId);
StringBuilder resultXml = new StringBuilder(200);
resultXml.append("<?xml version=\"1.0\" ?>\r\n")
.append("<Response>\r\n")
.append("<CmdType>Catalog</CmdType>\r\n")
.append("<SN>").append(sn).append("</SN>\r\n")
.append("<DeviceID>").append(deviceId).append("</DeviceID>\r\n")
.append("<Result>OK</Result>\r\n")
.append("</Response>\r\n");
if (subscribeInfo.getExpires() > 0) {
subscribeHolder.putCatalogSubscribe(platformId, subscribeInfo);
}else if (subscribeInfo.getExpires() == 0) {
subscribeHolder.removeCatalogSubscribe(platformId);
}
try {
ParentPlatform parentPlatform = storager.queryParentPlatByServerGBId(platformId);
SIPResponse response = responseXmlAck(request, resultXml.toString(), parentPlatform, subscribeInfo.getExpires());
if (subscribeInfo.getExpires() == 0) {
subscribeHolder.removeCatalogSubscribe(platformId);
}else {
subscribeInfo.setResponse(response);
subscribeHolder.putCatalogSubscribe(platformId, subscribeInfo);
}
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("未处理的异常 ", e);
}
if (subscribeHolder.getCatalogSubscribe(platformId) == null && platform.isAutoPushChannel()) {
platformService.addSimulatedSubscribeInfo(platform);
}
| 78 | 1,286 | 593 | 1,879 |
36,091 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/info/InfoRequestProcessor.java | InfoRequestProcessor | process | class InfoRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final static Logger logger = LoggerFactory.getLogger(InfoRequestProcessor.class);
private final String method = "INFO";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private IVideoManagerStorage storage;
@Autowired
private SipSubscribe sipSubscribe;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IInviteStreamService inviteStreamService;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommander cmder;
@Autowired
private VideoStreamSessionManager sessionManager;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
@Override
public void process(RequestEvent evt) {<FILL_FUNCTION_BODY>}
} |
logger.debug("接收到消息:" + evt.getRequest());
SIPRequest request = (SIPRequest) evt.getRequest();
String deviceId = SipUtils.getUserIdFromFromHeader(request);
CallIdHeader callIdHeader = request.getCallIdHeader();
// 先从会话内查找
SsrcTransaction ssrcTransaction = sessionManager.getSsrcTransaction(null, null, callIdHeader.getCallId(), null);
// 兼容海康 媒体通知 消息from字段不是设备ID的问题
if (ssrcTransaction != null) {
deviceId = ssrcTransaction.getDeviceId();
}
// 查询设备是否存在
Device device = redisCatchStorage.getDevice(deviceId);
// 查询上级平台是否存在
ParentPlatform parentPlatform = storage.queryParentPlatByServerGBId(deviceId);
try {
if (device != null && parentPlatform != null) {
logger.warn("[重复]平台与设备编号重复:{}", deviceId);
String hostAddress = request.getRemoteAddress().getHostAddress();
int remotePort = request.getRemotePort();
if (device.getHostAddress().equals(hostAddress + ":" + remotePort)) {
parentPlatform = null;
}else {
device = null;
}
}
if (device == null && parentPlatform == null) {
// 不存在则回复404
responseAck(request, Response.NOT_FOUND, "device "+ deviceId +" not found");
logger.warn("[设备未找到 ]: {}", deviceId);
if (sipSubscribe.getErrorSubscribe(callIdHeader.getCallId()) != null){
DeviceNotFoundEvent deviceNotFoundEvent = new DeviceNotFoundEvent(evt.getDialog());
deviceNotFoundEvent.setCallId(callIdHeader.getCallId());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(deviceNotFoundEvent);
sipSubscribe.getErrorSubscribe(callIdHeader.getCallId()).response(eventResult);
};
}else {
ContentTypeHeader header = (ContentTypeHeader)evt.getRequest().getHeader(ContentTypeHeader.NAME);
String contentType = header.getContentType();
String contentSubType = header.getContentSubType();
if ("Application".equalsIgnoreCase(contentType) && "MANSRTSP".equalsIgnoreCase(contentSubType)) {
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(null, null, null, callIdHeader.getCallId());
String streamId = sendRtpItem.getStream();
InviteInfo inviteInfo = inviteStreamService.getInviteInfoByStream(InviteSessionType.PLAYBACK, streamId);
if (null == inviteInfo) {
responseAck(request, Response.NOT_FOUND, "stream " + streamId + " not found");
return;
}
Device device1 = storager.queryVideoDevice(inviteInfo.getDeviceId());
if (inviteInfo.getStreamInfo() != null) {
cmder.playbackControlCmd(device1,inviteInfo.getStreamInfo(),new String(evt.getRequest().getRawContent()),eventResult -> {
// 失败的回复
try {
responseAck(request, eventResult.statusCode, eventResult.msg);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 录像控制: {}", e.getMessage());
}
}, eventResult -> {
// 成功的回复
try {
responseAck(request, eventResult.statusCode);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 录像控制: {}", e.getMessage());
}
});
}
}
}
} catch (SipException e) {
logger.warn("SIP 回复错误", e);
} catch (InvalidArgumentException e) {
logger.warn("参数无效", e);
} catch (ParseException e) {
logger.warn("SIP回复时解析异常", e);
}
| 1,458 | 279 | 1,074 | 1,353 |
36,092 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/MessageHandlerAbstract.java | MessageHandlerAbstract | handForDevice | class MessageHandlerAbstract extends SIPRequestProcessorParent implements IMessageHandler{
private Logger logger = LoggerFactory.getLogger(MessageHandlerAbstract.class);
public Map<String, IMessageHandler> messageHandlerMap = new ConcurrentHashMap<>();
@Autowired
private IVideoManagerStorage storage;
public void addHandler(String cmdType, IMessageHandler messageHandler) {
messageHandlerMap.put(cmdType, messageHandler);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
String cmd = getText(element, "CmdType");
IMessageHandler messageHandler = messageHandlerMap.get(cmd);
if (messageHandler != null) {
messageHandler.handForPlatform(evt, parentPlatform, element);
}
}
} |
String cmd = getText(element, "CmdType");
if (cmd == null) {
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 回复200 OK: {}", e.getMessage());
}
return;
}
IMessageHandler messageHandler = messageHandlerMap.get(cmd);
if (messageHandler != null) {
//两个国标平台互相级联时由于上一步判断导致本该在平台处理的消息 放到了设备的处理逻辑
//所以对目录查询单独做了校验
if(messageHandler instanceof CatalogQueryMessageHandler){
ParentPlatform parentPlatform = storage.queryParentPlatByServerGBId(device.getDeviceId());
messageHandler.handForPlatform(evt, parentPlatform, element);
return;
}
messageHandler.handForDevice(evt, device, element);
}
| 281 | 242 | 257 | 499 |
36,093 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/MessageRequestProcessor.java | MessageRequestProcessor | process | class MessageRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {
private final static Logger logger = LoggerFactory.getLogger(MessageRequestProcessor.class);
private final String method = "MESSAGE";
private static final Map<String, IMessageHandler> messageHandlerMap = new ConcurrentHashMap<>();
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private IVideoManagerStorage storage;
@Autowired
private SipSubscribe sipSubscribe;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private VideoStreamSessionManager sessionManager;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addRequestProcessor(method, this);
}
public void addHandler(String name, IMessageHandler handler) {
messageHandlerMap.put(name, handler);
}
@Override
public void process(RequestEvent evt) {<FILL_FUNCTION_BODY>}
} |
SIPRequest sipRequest = (SIPRequest)evt.getRequest();
// logger.info("接收到消息:" + evt.getRequest());
String deviceId = SipUtils.getUserIdFromFromHeader(evt.getRequest());
CallIdHeader callIdHeader = sipRequest.getCallIdHeader();
// 先从会话内查找
SsrcTransaction ssrcTransaction = sessionManager.getSsrcTransaction(null, null, callIdHeader.getCallId(), null);
// 兼容海康 媒体通知 消息from字段不是设备ID的问题
if (ssrcTransaction != null) {
deviceId = ssrcTransaction.getDeviceId();
}
SIPRequest request = (SIPRequest) evt.getRequest();
// 查询设备是否存在
Device device = redisCatchStorage.getDevice(deviceId);
// 查询上级平台是否存在
ParentPlatform parentPlatform = storage.queryParentPlatByServerGBId(deviceId);
try {
if (device != null && parentPlatform != null) {
String hostAddress = request.getRemoteAddress().getHostAddress();
int remotePort = request.getRemotePort();
if (device.getHostAddress().equals(hostAddress + ":" + remotePort)) {
parentPlatform = null;
}else {
device = null;
}
}
if (device == null && parentPlatform == null) {
// 不存在则回复404
responseAck(request, Response.NOT_FOUND, "device "+ deviceId +" not found");
logger.warn("[设备未找到 ]deviceId: {}, callId: {}", deviceId, callIdHeader.getCallId());
if (sipSubscribe.getErrorSubscribe(callIdHeader.getCallId()) != null){
DeviceNotFoundEvent deviceNotFoundEvent = new DeviceNotFoundEvent(evt.getDialog());
deviceNotFoundEvent.setCallId(callIdHeader.getCallId());
SipSubscribe.EventResult eventResult = new SipSubscribe.EventResult(deviceNotFoundEvent);
sipSubscribe.getErrorSubscribe(callIdHeader.getCallId()).response(eventResult);
}
}else {
Element rootElement;
try {
rootElement = getRootElement(evt);
if (rootElement == null) {
logger.error("处理MESSAGE请求 未获取到消息体{}", evt.getRequest());
responseAck(request, Response.BAD_REQUEST, "content is null");
return;
}
String name = rootElement.getName();
IMessageHandler messageHandler = messageHandlerMap.get(name);
if (messageHandler != null) {
if (device != null) {
messageHandler.handForDevice(evt, device, rootElement);
}else { // 由于上面已经判断都为null则直接返回,所以这里device和parentPlatform必有一个不为null
messageHandler.handForPlatform(evt, parentPlatform, rootElement);
}
}else {
// 不支持的message
// 不存在则回复415
responseAck(request, Response.UNSUPPORTED_MEDIA_TYPE, "Unsupported message type, must Control/Notify/Query/Response");
}
} catch (DocumentException e) {
logger.warn("解析XML消息内容异常", e);
// 不存在则回复404
responseAck(request, Response.BAD_REQUEST, e.getMessage());
}
}
} catch (SipException e) {
logger.warn("SIP 回复错误", e);
} catch (InvalidArgumentException e) {
logger.warn("参数无效", e);
} catch (ParseException e) {
logger.warn("SIP回复时解析异常", e);
}
| 1,269 | 284 | 954 | 1,238 |
36,096 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/notify/cmd/BroadcastNotifyMessageHandler.java | BroadcastNotifyMessageHandler | handForPlatform | class BroadcastNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(BroadcastNotifyMessageHandler.class);
private final static String cmdType = "Broadcast";
@Autowired
private NotifyMessageHandler notifyMessageHandler;
@Autowired
private IVideoManagerStorage storage;
@Autowired
private ISIPCommanderForPlatform commanderForPlatform;
@Autowired
private IMediaServerService mediaServerService;
@Autowired
private IPlayService playService;
@Autowired
private IDeviceService deviceService;
@Autowired
private IPlatformService platformService;
@Autowired
private AudioBroadcastManager audioBroadcastManager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Override
public void afterPropertiesSet() throws Exception {
notifyMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {
}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform platform, Element rootElement) {<FILL_FUNCTION_BODY>}
} |
// 来自上级平台的语音喊话请求
SIPRequest request = (SIPRequest) evt.getRequest();
try {
Element snElement = rootElement.element("SN");
if (snElement == null) {
responseAck(request, Response.BAD_REQUEST, "sn must not null");
return;
}
String sn = snElement.getText();
Element targetIDElement = rootElement.element("TargetID");
if (targetIDElement == null) {
responseAck(request, Response.BAD_REQUEST, "TargetID must not null");
return;
}
String targetId = targetIDElement.getText();
logger.info("[国标级联 语音喊话] platform: {}, channel: {}", platform.getServerGBId(), targetId);
DeviceChannel deviceChannel = storage.queryChannelInParentPlatform(platform.getServerGBId(), targetId);
if (deviceChannel == null) {
logger.warn("[国标级联 语音喊话] 未找到通道 platform: {}, channel: {}", platform.getServerGBId(), targetId);
responseAck(request, Response.NOT_FOUND, "TargetID not found");
return;
}
// 向下级发送语音的喊话请求
Device device = deviceService.getDevice(deviceChannel.getDeviceId());
if (device == null) {
responseAck(request, Response.NOT_FOUND, "device not found");
return;
}
responseAck(request, Response.OK);
// 查看语音通道是否已经建立并且已经在使用
if (playService.audioBroadcastInUse(device, targetId)) {
commanderForPlatform.broadcastResultCmd(platform, deviceChannel, sn, false,null, null);
return;
}
MediaServer mediaServerForMinimumLoad = mediaServerService.getMediaServerForMinimumLoad(null);
commanderForPlatform.broadcastResultCmd(platform, deviceChannel, sn, true, eventResult->{
logger.info("[国标级联] 语音喊话 回复失败 platform: {}, 错误:{}/{}", platform.getServerGBId(), eventResult.statusCode, eventResult.msg);
}, eventResult->{
// 消息发送成功, 向上级发送invite,获取推流
try {
platformService.broadcastInvite(platform, deviceChannel.getChannelId(), mediaServerForMinimumLoad, (hookData)->{
// 上级平台推流成功
AudioBroadcastCatch broadcastCatch = audioBroadcastManager.get(device.getDeviceId(), targetId);
if (broadcastCatch != null ) {
if (playService.audioBroadcastInUse(device, targetId)) {
logger.info("[国标级联] 语音喊话 设备正在使用中 platform: {}, channel: {}",
platform.getServerGBId(), deviceChannel.getChannelId());
// 查看语音通道已经建立且已经占用 回复BYE
platformService.stopBroadcast(platform, deviceChannel, hookData.getStream(), true, hookData.getMediaServer());
}else {
// 查看语音通道已经建立但是未占用
broadcastCatch.setApp(hookData.getApp());
broadcastCatch.setStream(hookData.getStream());
broadcastCatch.setMediaServerItem(hookData.getMediaServer());
audioBroadcastManager.update(broadcastCatch);
// 推流到设备
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(null, targetId, hookData.getStream(), null);
if (sendRtpItem == null) {
logger.warn("[国标级联] 语音喊话 异常,未找到发流信息, channelId: {}, stream: {}", targetId, hookData.getStream());
logger.info("[国标级联] 语音喊话 重新开始,channelId: {}, stream: {}", targetId, hookData.getStream());
try {
playService.audioBroadcastCmd(device, targetId, hookData.getMediaServer(), hookData.getApp(), hookData.getStream(), 60, true, msg -> {
logger.info("[语音喊话] 通道建立成功, device: {}, channel: {}", device.getDeviceId(), targetId);
});
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.info("[消息发送失败] 国标级联 语音喊话 platform: {}", platform.getServerGBId());
}
}else {
// 发流
try {
mediaServerService.startSendRtp(hookData.getMediaServer(),null, sendRtpItem);
}catch (ControllerException e) {
logger.info("[语音喊话] 推流失败, 结果: {}", e.getMessage());
return;
}
logger.info("[语音喊话] 自动推流成功, device: {}, channel: {}", device.getDeviceId(), targetId);
}
}
}else {
try {
playService.audioBroadcastCmd(device, targetId, hookData.getMediaServer(), hookData.getApp(), hookData.getStream(), 60, true, msg -> {
logger.info("[语音喊话] 通道建立成功, device: {}, channel: {}", device.getDeviceId(), targetId);
});
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.info("[消息发送失败] 国标级联 语音喊话 platform: {}", platform.getServerGBId());
}
}
}, eventResultForBroadcastInvite -> {
// 收到错误
logger.info("[国标级联-语音喊话] 与下级通道建立失败 device: {}, channel: {}, 错误:{}/{}", device.getDeviceId(),
targetId, eventResultForBroadcastInvite.statusCode, eventResultForBroadcastInvite.msg);
}, (code, msg)->{
// 超时
logger.info("[国标级联-语音喊话] 与下级通道建立超时 device: {}, channel: {}, 错误:{}/{}", device.getDeviceId(),
targetId, code, msg);
});
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.info("[消息发送失败] 国标级联 语音喊话 invite消息 platform: {}", platform.getServerGBId());
}
});
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.info("[消息发送失败] 国标级联 语音喊话 platform: {}", platform.getServerGBId());
}
| 2,676 | 329 | 1,713 | 2,042 |
36,097 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/notify/cmd/KeepaliveNotifyMessageHandler.java | KeepaliveNotifyMessageHandler | handForDevice | class KeepaliveNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private final Logger logger = LoggerFactory.getLogger(KeepaliveNotifyMessageHandler.class);
private final static String cmdType = "Keepalive";
@Autowired
private NotifyMessageHandler notifyMessageHandler;
@Autowired
private IDeviceService deviceService;
@Autowired
private UserSetting userSetting;
@Autowired
private DynamicTask dynamicTask;
@Override
public void afterPropertiesSet() throws Exception {
notifyMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
// 个别平台保活不回复200OK会判定离线
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 心跳回复: {}", e.getMessage());
}
}
} |
if (device == null) {
// 未注册的设备不做处理
return;
}
SIPRequest request = (SIPRequest) evt.getRequest();
logger.info("[收到心跳] device: {}, callId: {}", device.getDeviceId(), request.getCallIdHeader().getCallId());
// 回复200 OK
try {
responseAck(request, Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 心跳回复: {}", e.getMessage());
}
if (!ObjectUtils.isEmpty(device.getKeepaliveTime()) && DateUtil.getDifferenceForNow(device.getKeepaliveTime()) <= 3000L) {
logger.info("[收到心跳] 心跳发送过于频繁,已忽略 device: {}, callId: {}", device.getDeviceId(), request.getCallIdHeader().getCallId());
return;
}
RemoteAddressInfo remoteAddressInfo = SipUtils.getRemoteAddressFromRequest(request, userSetting.getSipUseSourceIpAsRemoteAddress());
if (!device.getIp().equalsIgnoreCase(remoteAddressInfo.getIp()) || device.getPort() != remoteAddressInfo.getPort()) {
logger.info("[收到心跳] 设备{}地址变化, 远程地址为: {}:{}", device.getDeviceId(), remoteAddressInfo.getIp(), remoteAddressInfo.getPort());
device.setPort(remoteAddressInfo.getPort());
device.setHostAddress(remoteAddressInfo.getIp().concat(":").concat(String.valueOf(remoteAddressInfo.getPort())));
device.setIp(remoteAddressInfo.getIp());
// 设备地址变化会引起目录订阅任务失效,需要重新添加
if (device.getSubscribeCycleForCatalog() > 0) {
deviceService.removeCatalogSubscribe(device, result->{
deviceService.addCatalogSubscribe(device);
});
}
}
if (device.getKeepaliveTime() == null) {
device.setKeepaliveIntervalTime(60);
}else {
long lastTime = DateUtil.yyyy_MM_dd_HH_mm_ssToTimestamp(device.getKeepaliveTime());
if (System.currentTimeMillis()/1000-lastTime > 10) {
device.setKeepaliveIntervalTime(Long.valueOf(System.currentTimeMillis()/1000-lastTime).intValue());
}
}
device.setKeepaliveTime(DateUtil.getNow());
if (device.isOnLine()) {
deviceService.updateDevice(device);
}else {
// 对于已经离线的设备判断他的注册是否已经过期
if (!deviceService.expire(device)){
device.setOnLine(false);
deviceService.online(device, null);
}
}
// 刷新过期任务
String registerExpireTaskKey = VideoManagerConstants.REGISTER_EXPIRE_TASK_KEY_PREFIX + device.getDeviceId();
// 如果三次心跳失败,则设置设备离线
dynamicTask.startDelay(registerExpireTaskKey, ()-> deviceService.offline(device.getDeviceId(), "三次心跳失败"), device.getKeepaliveIntervalTime()*1000*3);
| 643 | 324 | 865 | 1,189 |
36,098 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/notify/cmd/MediaStatusNotifyMessageHandler.java | MediaStatusNotifyMessageHandler | handForDevice | class MediaStatusNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(MediaStatusNotifyMessageHandler.class);
private final String cmdType = "MediaStatus";
@Autowired
private NotifyMessageHandler notifyMessageHandler;
@Autowired
private SIPCommander cmder;
@Autowired
private SIPCommanderFroPlatform sipCommanderFroPlatform;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IVideoManagerStorage storage;
@Autowired
private VideoStreamSessionManager sessionManager;
@Autowired
private HookSubscribe subscribe;
@Autowired
private IInviteStreamService inviteStreamService;
@Autowired
private VideoStreamSessionManager streamSession;
@Override
public void afterPropertiesSet() throws Exception {
notifyMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
}
} |
// 回复200 OK
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 录像流推送完毕,回复200OK: {}", e.getMessage());
}
CallIdHeader callIdHeader = (CallIdHeader)evt.getRequest().getHeader(CallIdHeader.NAME);
String NotifyType =getText(rootElement, "NotifyType");
if ("121".equals(NotifyType)){
logger.info("[录像流]推送完毕,收到关流通知");
SsrcTransaction ssrcTransaction = streamSession.getSsrcTransaction(null, null, callIdHeader.getCallId(), null);
if (ssrcTransaction != null) {
logger.info("[录像流]推送完毕,关流通知, device: {}, channelId: {}", ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId());
InviteInfo inviteInfo = inviteStreamService.getInviteInfo(InviteSessionType.DOWNLOAD, ssrcTransaction.getDeviceId(), ssrcTransaction.getChannelId(), ssrcTransaction.getStream());
if (inviteInfo.getStreamInfo() != null) {
inviteInfo.getStreamInfo().setProgress(1);
inviteStreamService.updateInviteInfo(inviteInfo);
}
try {
cmder.streamByeCmd(device, ssrcTransaction.getChannelId(), null, callIdHeader.getCallId());
} catch (InvalidArgumentException | ParseException | SipException | SsrcTransactionNotFoundException e) {
logger.error("[录像流]推送完毕,收到关流通知, 发送BYE失败 {}", e.getMessage());
}
// 去除监听流注销自动停止下载的监听
Hook hook = Hook.getInstance(HookType.on_media_arrival, "rtp", ssrcTransaction.getStream(), ssrcTransaction.getMediaServerId());
subscribe.removeSubscribe(hook);
// 如果级联播放,需要给上级发送此通知 TODO 多个上级同时观看一个下级 可能存在停错的问题,需要将点播CallId进行上下级绑定
SendRtpItem sendRtpItem = redisCatchStorage.querySendRTPServer(null, ssrcTransaction.getChannelId(), null, null);
if (sendRtpItem != null) {
ParentPlatform parentPlatform = storage.queryParentPlatByServerGBId(sendRtpItem.getPlatformId());
if (parentPlatform == null) {
logger.warn("[级联消息发送]:发送MediaStatus发现上级平台{}不存在", sendRtpItem.getPlatformId());
return;
}
try {
sipCommanderFroPlatform.sendMediaStatusNotify(parentPlatform, sendRtpItem);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 录像播放完毕: {}", e.getMessage());
}
}
}else {
logger.info("[录像流]推送完毕,关流通知, 但是未找到对应的下载信息");
}
}
| 804 | 330 | 835 | 1,165 |
36,099 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/notify/cmd/MobilePositionNotifyMessageHandler.java | MobilePositionNotifyMessageHandler | handForDevice | class MobilePositionNotifyMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(MobilePositionNotifyMessageHandler.class);
private final String cmdType = "MobilePosition";
@Autowired
private NotifyMessageHandler notifyMessageHandler;
@Autowired
private UserSetting userSetting;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IDeviceChannelService deviceChannelService;
@Autowired
private EventPublisher eventPublisher;
private ConcurrentLinkedQueue<SipMsgInfo> taskQueue = new ConcurrentLinkedQueue<>();
@Qualifier("taskExecutor")
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Override
public void afterPropertiesSet() throws Exception {
notifyMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
}
} |
boolean isEmpty = taskQueue.isEmpty();
taskQueue.offer(new SipMsgInfo(evt, device, rootElement));
// 回复200 OK
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 移动位置通知回复: {}", e.getMessage());
}
if (isEmpty) {
taskExecutor.execute(() -> {
while (!taskQueue.isEmpty()) {
SipMsgInfo sipMsgInfo = taskQueue.poll();
try {
Element rootElementAfterCharset = getRootElement(sipMsgInfo.getEvt(), sipMsgInfo.getDevice().getCharset());
if (rootElementAfterCharset == null) {
logger.warn("[移动位置通知] {}处理失败,未识别到信息体", device.getDeviceId());
continue;
}
MobilePosition mobilePosition = new MobilePosition();
mobilePosition.setCreateTime(DateUtil.getNow());
if (!ObjectUtils.isEmpty(sipMsgInfo.getDevice().getName())) {
mobilePosition.setDeviceName(sipMsgInfo.getDevice().getName());
}
mobilePosition.setDeviceId(sipMsgInfo.getDevice().getDeviceId());
mobilePosition.setChannelId(getText(rootElementAfterCharset, "DeviceID"));
String time = getText(rootElementAfterCharset, "Time");
if (ObjectUtils.isEmpty(time)){
mobilePosition.setTime(DateUtil.getNow());
}else {
mobilePosition.setTime(SipUtils.parseTime(time));
}
mobilePosition.setLongitude(Double.parseDouble(getText(rootElementAfterCharset, "Longitude")));
mobilePosition.setLatitude(Double.parseDouble(getText(rootElementAfterCharset, "Latitude")));
if (NumericUtil.isDouble(getText(rootElementAfterCharset, "Speed"))) {
mobilePosition.setSpeed(Double.parseDouble(getText(rootElementAfterCharset, "Speed")));
} else {
mobilePosition.setSpeed(0.0);
}
if (NumericUtil.isDouble(getText(rootElementAfterCharset, "Direction"))) {
mobilePosition.setDirection(Double.parseDouble(getText(rootElementAfterCharset, "Direction")));
} else {
mobilePosition.setDirection(0.0);
}
if (NumericUtil.isDouble(getText(rootElementAfterCharset, "Altitude"))) {
mobilePosition.setAltitude(Double.parseDouble(getText(rootElementAfterCharset, "Altitude")));
} else {
mobilePosition.setAltitude(0.0);
}
mobilePosition.setReportSource("Mobile Position");
// 更新device channel 的经纬度
DeviceChannel deviceChannel = new DeviceChannel();
deviceChannel.setDeviceId(sipMsgInfo.getDevice().getDeviceId());
deviceChannel.setChannelId(mobilePosition.getChannelId());
deviceChannel.setLongitude(mobilePosition.getLongitude());
deviceChannel.setLatitude(mobilePosition.getLatitude());
deviceChannel.setGpsTime(mobilePosition.getTime());
deviceChannel = deviceChannelService.updateGps(deviceChannel, sipMsgInfo.getDevice());
mobilePosition.setLongitudeWgs84(deviceChannel.getLongitudeWgs84());
mobilePosition.setLatitudeWgs84(deviceChannel.getLatitudeWgs84());
mobilePosition.setLongitudeGcj02(deviceChannel.getLongitudeGcj02());
mobilePosition.setLatitudeGcj02(deviceChannel.getLatitudeGcj02());
deviceChannelService.updateChannelGPS(device, deviceChannel, mobilePosition);
} catch (DocumentException e) {
logger.error("未处理的异常 ", e);
} catch (Exception e) {
logger.warn("[移动位置通知] 发现未处理的异常, \r\n{}", evt.getRequest());
logger.error("[移动位置通知] 异常内容: ", e);
}
}
});
}
| 1,645 | 325 | 1,052 | 1,377 |
36,100 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/query/cmd/AlarmQueryMessageHandler.java | AlarmQueryMessageHandler | handForPlatform | class AlarmQueryMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(AlarmQueryMessageHandler.class);
private final String cmdType = "Alarm";
@Autowired
private QueryMessageHandler queryMessageHandler;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommanderFroPlatform cmderFroPlatform;
@Autowired
private SipConfig config;
@Autowired
private EventPublisher publisher;
@Override
public void afterPropertiesSet() throws Exception {
queryMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {
}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {<FILL_FUNCTION_BODY>}
} |
logger.info("不支持alarm查询");
try {
responseAck((SIPRequest) evt.getRequest(), Response.NOT_FOUND, "not support alarm query");
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 alarm查询回复200OK: {}", e.getMessage());
}
| 81 | 249 | 106 | 355 |
36,101 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/query/cmd/CatalogQueryMessageHandler.java | CatalogQueryMessageHandler | handForPlatform | class CatalogQueryMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(CatalogQueryMessageHandler.class);
private final String cmdType = "Catalog";
@Autowired
private QueryMessageHandler queryMessageHandler;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommanderFroPlatform cmderFroPlatform;
@Autowired
private SipConfig config;
@Autowired
private EventPublisher publisher;
@Autowired
private IVideoManagerStorage storage;
@Override
public void afterPropertiesSet() throws Exception {
queryMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {
}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {<FILL_FUNCTION_BODY>}
private DeviceChannel getChannelForPlatform(ParentPlatform platform) {
DeviceChannel deviceChannel = new DeviceChannel();
deviceChannel.setChannelId(platform.getDeviceGBId());
deviceChannel.setName(platform.getName());
deviceChannel.setManufacture("wvp-pro");
deviceChannel.setOwner("wvp-pro");
deviceChannel.setCivilCode(platform.getAdministrativeDivision());
deviceChannel.setAddress("wvp-pro");
deviceChannel.setRegisterWay(0);
deviceChannel.setSecrecy("0");
return deviceChannel;
}
} |
FromHeader fromHeader = (FromHeader) evt.getRequest().getHeader(FromHeader.NAME);
try {
// 回复200 OK
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 目录查询回复200OK: {}", e.getMessage());
}
Element snElement = rootElement.element("SN");
String sn = snElement.getText();
// 准备回复通道信息
List<DeviceChannel> deviceChannelInPlatforms = storager.queryChannelWithCatalog(parentPlatform.getServerGBId());
// 查询关联的直播通道
List<DeviceChannel> gbStreams = storager.queryGbStreamListInPlatform(parentPlatform.getServerGBId());
// 回复目录信息
List<DeviceChannel> catalogs = storager.queryCatalogInPlatform(parentPlatform.getServerGBId());
List<DeviceChannel> allChannels = new ArrayList<>();
// 回复平台
// DeviceChannel deviceChannel = getChannelForPlatform(parentPlatform);
// allChannels.add(deviceChannel);
// 回复目录
if (catalogs.size() > 0) {
allChannels.addAll(catalogs);
}
// 回复级联的通道
if (deviceChannelInPlatforms.size() > 0) {
allChannels.addAll(deviceChannelInPlatforms);
}
// 回复直播的通道
if (gbStreams.size() > 0) {
allChannels.addAll(gbStreams);
}
try {
if (allChannels.size() > 0) {
cmderFroPlatform.catalogQuery(allChannels, parentPlatform, sn, fromHeader.getTag());
}else {
// 回复无通道
cmderFroPlatform.catalogQuery(null, parentPlatform, sn, fromHeader.getTag(), 0);
}
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 目录查询回复: {}", e.getMessage());
}
| 495 | 418 | 582 | 1,000 |
36,102 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/query/cmd/DeviceInfoQueryMessageHandler.java | DeviceInfoQueryMessageHandler | handForPlatform | class DeviceInfoQueryMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(DeviceInfoQueryMessageHandler.class);
private final String cmdType = "DeviceInfo";
@Autowired
private QueryMessageHandler queryMessageHandler;
@Autowired
private SIPCommanderFroPlatform cmderFroPlatform;
@Autowired
private IVideoManagerStorage storager;
@Override
public void afterPropertiesSet() throws Exception {
queryMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {
}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {<FILL_FUNCTION_BODY>}
} |
logger.info("[DeviceInfo查询]消息");
FromHeader fromHeader = (FromHeader) evt.getRequest().getHeader(FromHeader.NAME);
try {
// 回复200 OK
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] DeviceInfo查询回复: {}", e.getMessage());
return;
}
String sn = rootElement.element("SN").getText();
/*根据WVP原有的数据结构,设备和通道是分开放置,设备信息都是存放在设备表里,通道表里的设备信息不可作为真实信息处理
大部分NVR/IPC设备对他的通道信息实现都是返回默认的值没有什么参考价值。NVR/IPC通道我们统一使用设备表的设备信息来作为返回。
我们这里使用查询数据库的方式来实现这个设备信息查询的功能,在其他地方对设备信息更新达到正确的目的。*/
String channelId = getText(rootElement, "DeviceID");
// 查询这是通道id还是设备id
Device device = null;
// 如果id指向平台的国标编号,那么就是查询平台的信息
if (!parentPlatform.getDeviceGBId().equals(channelId)) {
device = storager.queryDeviceInfoByPlatformIdAndChannelId(parentPlatform.getServerGBId(), channelId);
if (device ==null){
logger.error("[平台没有该通道的使用权限]:platformId"+parentPlatform.getServerGBId()+" deviceID:"+channelId);
return;
}
}
try {
cmderFroPlatform.deviceInfoResponse(parentPlatform, device, sn, fromHeader.getTag());
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 DeviceInfo查询回复: {}", e.getMessage());
}
| 346 | 219 | 501 | 720 |
36,103 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/query/cmd/DeviceStatusQueryMessageHandler.java | DeviceStatusQueryMessageHandler | handForPlatform | class DeviceStatusQueryMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(DeviceStatusQueryMessageHandler.class);
private final String cmdType = "DeviceStatus";
@Autowired
private QueryMessageHandler queryMessageHandler;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommanderFroPlatform cmderFroPlatform;
@Autowired
private SipConfig config;
@Autowired
private EventPublisher publisher;
@Override
public void afterPropertiesSet() throws Exception {
queryMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {
}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {<FILL_FUNCTION_BODY>}
} |
logger.info("接收到DeviceStatus查询消息");
FromHeader fromHeader = (FromHeader) evt.getRequest().getHeader(FromHeader.NAME);
// 回复200 OK
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 DeviceStatus查询回复200OK: {}", e.getMessage());
}
String sn = rootElement.element("SN").getText();
String channelId = getText(rootElement, "DeviceID");
DeviceChannel deviceChannel = storager.queryChannelInParentPlatform(parentPlatform.getServerGBId(), channelId);
if (deviceChannel ==null){
logger.error("[平台没有该通道的使用权限]:platformId"+parentPlatform.getServerGBId()+" deviceID:"+channelId);
return;
}
try {
cmderFroPlatform.deviceStatusResponse(parentPlatform,channelId, sn, fromHeader.getTag(),deviceChannel.isStatus());
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 DeviceStatus查询回复: {}", e.getMessage());
}
| 240 | 249 | 333 | 582 |
36,104 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/query/cmd/RecordInfoQueryMessageHandler.java | RecordInfoQueryMessageHandler | handForPlatform | class RecordInfoQueryMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(RecordInfoQueryMessageHandler.class);
private final String cmdType = "RecordInfo";
@Autowired
private QueryMessageHandler queryMessageHandler;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private SIPCommanderFroPlatform cmderFroPlatform;
@Autowired
private SIPCommander commander;
@Autowired
private RecordEndEventListener recordEndEventListener;
@Autowired
private SipConfig config;
@Autowired
private EventPublisher publisher;
@Override
public void afterPropertiesSet() throws Exception {
queryMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {
}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {<FILL_FUNCTION_BODY>}
} |
SIPRequest request = (SIPRequest) evt.getRequest();
Element snElement = rootElement.element("SN");
int sn = Integer.parseInt(snElement.getText());
Element deviceIDElement = rootElement.element("DeviceID");
String channelId = deviceIDElement.getText();
Element startTimeElement = rootElement.element("StartTime");
String startTime = null;
if (startTimeElement != null) {
startTime = startTimeElement.getText();
}
Element endTimeElement = rootElement.element("EndTime");
String endTime = null;
if (endTimeElement != null) {
endTime = endTimeElement.getText();
}
Element secrecyElement = rootElement.element("Secrecy");
int secrecy = 0;
if (secrecyElement != null) {
secrecy = Integer.parseInt(secrecyElement.getText().trim());
}
String type = "all";
Element typeElement = rootElement.element("Type");
if (typeElement != null) {
type = typeElement.getText();
}
// 确认是直播还是国标, 国标直接请求下级,直播请求录像管理服务
List<ChannelSourceInfo> channelSources = storager.getChannelSource(parentPlatform.getServerGBId(), channelId);
if (channelSources.get(0).getCount() > 0) { // 国标
// 向国标设备请求录像数据
Device device = storager.queryVideoDeviceByPlatformIdAndChannelId(parentPlatform.getServerGBId(), channelId);
DeviceChannel deviceChannel = storager.queryChannelInParentPlatform(parentPlatform.getServerGBId(), channelId);
// 接收录像数据
recordEndEventListener.addEndEventHandler(deviceChannel.getDeviceId(), channelId, (recordInfo)->{
try {
logger.info("[国标级联] 录像查询收到数据, 通道: {},准备转发===", channelId);
cmderFroPlatform.recordInfo(deviceChannel, parentPlatform, request.getFromTag(), recordInfo);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 回复录像数据: {}", e.getMessage());
}
});
try {
commander.recordInfoQuery(device, channelId, DateUtil.ISO8601Toyyyy_MM_dd_HH_mm_ss(startTime),
DateUtil.ISO8601Toyyyy_MM_dd_HH_mm_ss(endTime), sn, secrecy, type, (eventResult -> {
// 回复200 OK
try {
responseAck(request, Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 录像查询回复: {}", e.getMessage());
}
}),(eventResult -> {
// 查询失败
try {
responseAck(request, eventResult.statusCode, eventResult.msg);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 录像查询回复: {}", e.getMessage());
}
}));
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 录像查询: {}", e.getMessage());
}
}else if (channelSources.get(1).getCount() > 0) { // 直播流
// TODO
try {
responseAck(request, Response.NOT_IMPLEMENTED); // 回复未实现
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 录像查询: {}", e.getMessage());
}
}else { // 错误的请求
try {
responseAck(request, Response.BAD_REQUEST);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 录像查询: {}", e.getMessage());
}
}
| 1,289 | 282 | 1,058 | 1,340 |
36,105 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/AlarmResponseMessageHandler.java | AlarmResponseMessageHandler | handForDevice | class AlarmResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(AlarmResponseMessageHandler.class);
private final String cmdType = "Alarm";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
}
} |
Element deviceIdElement = rootElement.element("DeviceID");
String channelId = deviceIdElement.getText().toString();
String key = DeferredResultHolder.CALLBACK_CMD_ALARM + device.getDeviceId() + channelId;
JSONObject json = new JSONObject();
XmlUtil.node2Json(rootElement, json);
if (logger.isDebugEnabled()) {
logger.debug(json.toJSONString());
}
RequestMessage msg = new RequestMessage();
msg.setKey(key);
msg.setData(json);
deferredResultHolder.invokeAllResult(msg);
| 129 | 197 | 154 | 351 |
36,106 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/BroadcastResponseMessageHandler.java | BroadcastResponseMessageHandler | handForDevice | class BroadcastResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(BroadcastResponseMessageHandler.class);
private final String cmdType = "Broadcast";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DynamicTask dynamicTask;
@Autowired
private AudioBroadcastManager audioBroadcastManager;
@Autowired
private IPlayService playService;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
}
} |
SIPRequest request = (SIPRequest) evt.getRequest();
try {
String channelId = getText(rootElement, "DeviceID");
if (!audioBroadcastManager.exit(device.getDeviceId(), channelId)) {
// 回复410
responseAck((SIPRequest) evt.getRequest(), Response.GONE);
return;
}
String result = getText(rootElement, "Result");
Element infoElement = rootElement.element("Info");
String reason = null;
if (infoElement != null) {
reason = getText(infoElement, "Reason");
}
logger.info("[语音广播]回复:{}, {}/{}", reason == null? result : result + ": " + reason, device.getDeviceId(), channelId );
// 回复200 OK
responseAck(request, Response.OK);
if (result.equalsIgnoreCase("OK")) {
AudioBroadcastCatch audioBroadcastCatch = audioBroadcastManager.get(device.getDeviceId(), channelId);
audioBroadcastCatch.setStatus(AudioBroadcastCatchStatus.WaiteInvite);
audioBroadcastManager.update(audioBroadcastCatch);
}else {
playService.stopAudioBroadcast(device.getDeviceId(), channelId);
}
} catch (ParseException | SipException | InvalidArgumentException e) {
logger.error("[命令发送失败] 国标级联 语音喊话: {}", e.getMessage());
}
| 415 | 233 | 396 | 629 |
36,107 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/CatalogResponseMessageHandler.java | CatalogResponseMessageHandler | handForDevice | class CatalogResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(CatalogResponseMessageHandler.class);
private final String cmdType = "Catalog";
@Autowired
private ResponseMessageHandler responseMessageHandler;
private final ConcurrentLinkedQueue<HandlerCatchData> taskQueue = new ConcurrentLinkedQueue<>();
@Autowired
private IVideoManagerStorage storager;
@Autowired
private CatalogDataCatch catalogDataCatch;
@Qualifier("taskExecutor")
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
private SipConfig sipConfig;
private AtomicBoolean processing = new AtomicBoolean(false);
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
}
public SyncStatus getChannelSyncProgress(String deviceId) {
if (catalogDataCatch.get(deviceId) == null) {
return null;
} else {
return catalogDataCatch.getSyncStatus(deviceId);
}
}
public boolean isSyncRunning(String deviceId) {
if (catalogDataCatch.get(deviceId) == null) {
return false;
} else {
return catalogDataCatch.isSyncRunning(deviceId);
}
}
public void setChannelSyncReady(Device device, int sn) {
catalogDataCatch.addReady(device, sn);
}
public void setChannelSyncEnd(String deviceId, String errorMsg) {
catalogDataCatch.setChannelSyncEnd(deviceId, errorMsg);
}
} |
taskQueue.offer(new HandlerCatchData(evt, device, element));
// 回复200 OK
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 目录查询回复: {}", e.getMessage());
}
// 已经开启消息处理则跳过
if (processing.compareAndSet(false, true)) {
taskExecutor.execute(() -> {
while (!taskQueue.isEmpty()) {
// 全局异常捕获,保证下一条可以得到处理
try {
HandlerCatchData take = taskQueue.poll();
Element rootElement = null;
try {
rootElement = getRootElement(take.getEvt(), take.getDevice().getCharset());
} catch (DocumentException e) {
logger.error("[xml解析] 失败: ", e);
continue;
}
if (rootElement == null) {
logger.warn("[ 收到通道 ] content cannot be null, {}", evt.getRequest());
continue;
}
Element deviceListElement = rootElement.element("DeviceList");
Element sumNumElement = rootElement.element("SumNum");
Element snElement = rootElement.element("SN");
int sumNum = Integer.parseInt(sumNumElement.getText());
if (sumNum == 0) {
logger.info("[收到通道]设备:{}的: 0个", take.getDevice().getDeviceId());
// 数据已经完整接收
storager.cleanChannelsForDevice(take.getDevice().getDeviceId());
catalogDataCatch.setChannelSyncEnd(take.getDevice().getDeviceId(), null);
} else {
Iterator<Element> deviceListIterator = deviceListElement.elementIterator();
if (deviceListIterator != null) {
List<DeviceChannel> channelList = new ArrayList<>();
List<String> parentChannelIds = new ArrayList<>();
// 遍历DeviceList
while (deviceListIterator.hasNext()) {
Element itemDevice = deviceListIterator.next();
Element channelDeviceElement = itemDevice.element("DeviceID");
if (channelDeviceElement == null) {
continue;
}
DeviceChannel channel = XmlUtil.channelContentHandler(itemDevice, device, null);
if (channel == null) {
logger.info("[收到目录订阅]:但是解析失败 {}", new String(evt.getRequest().getRawContent()));
continue;
}
if (channel.getParentId() != null && channel.getParentId().equals(sipConfig.getId())) {
channel.setParentId(null);
}
SipUtils.updateGps(channel, device.getGeoCoordSys());
channel.setDeviceId(take.getDevice().getDeviceId());
channelList.add(channel);
}
int sn = Integer.parseInt(snElement.getText());
catalogDataCatch.put(take.getDevice().getDeviceId(), sn, sumNum, take.getDevice(), channelList);
logger.info("[收到通道]设备: {} -> {}个,{}/{}", take.getDevice().getDeviceId(), channelList.size(), catalogDataCatch.get(take.getDevice().getDeviceId()) == null ? 0 : catalogDataCatch.get(take.getDevice().getDeviceId()).size(), sumNum);
if (catalogDataCatch.get(take.getDevice().getDeviceId()).size() == sumNum) {
// 数据已经完整接收, 此时可能存在某个设备离线变上线的情况,但是考虑到性能,此处不做处理,
// 目前支持设备通道上线通知时和设备上线时向上级通知
boolean resetChannelsResult = storager.resetChannels(take.getDevice().getDeviceId(), catalogDataCatch.get(take.getDevice().getDeviceId()));
if (!resetChannelsResult) {
String errorMsg = "接收成功,写入失败,共" + sumNum + "条,已接收" + catalogDataCatch.get(take.getDevice().getDeviceId()).size() + "条";
catalogDataCatch.setChannelSyncEnd(take.getDevice().getDeviceId(), errorMsg);
} else {
catalogDataCatch.setChannelSyncEnd(take.getDevice().getDeviceId(), null);
}
}
}
}
} catch (Exception e) {
logger.warn("[收到通道] 发现未处理的异常, \r\n{}", evt.getRequest());
logger.error("[收到通道] 异常内容: ", e);
}
}
processing.set(false);
});
}
| 2,398 | 508 | 1,197 | 1,705 |
36,108 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/ConfigDownloadResponseMessageHandler.java | ConfigDownloadResponseMessageHandler | handForDevice | class ConfigDownloadResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(ConfigDownloadResponseMessageHandler.class);
private final String cmdType = "ConfigDownload";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private EventPublisher publisher;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
// 不会收到上级平台的心跳信息
}
} |
String channelId = getText(element, "DeviceID");
String key = DeferredResultHolder.CALLBACK_CMD_CONFIGDOWNLOAD + device.getDeviceId() + channelId;
try {
// 回复200 OK
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 设备配置查询: {}", e.getMessage());
}
// 此处是对本平台发出DeviceControl指令的应答
JSONObject json = new JSONObject();
XmlUtil.node2Json(element, json);
if (logger.isDebugEnabled()) {
logger.debug(json.toJSONString());
}
RequestMessage msg = new RequestMessage();
msg.setKey(key);
msg.setData(json);
deferredResultHolder.invokeAllResult(msg);
| 204 | 224 | 239 | 463 |
36,109 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/DeviceConfigResponseMessageHandler.java | DeviceConfigResponseMessageHandler | handForDevice | class DeviceConfigResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(DeviceConfigResponseMessageHandler.class);
private final String cmdType = "DeviceConfig";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
}
} |
JSONObject json = new JSONObject();
XmlUtil.node2Json(element, json);
String channelId = getText(element, "DeviceID");
if (logger.isDebugEnabled()) {
logger.debug(json.toJSONString());
}
String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONFIG + device.getDeviceId() + channelId;
RequestMessage msg = new RequestMessage();
msg.setKey(key);
msg.setData(json);
deferredResultHolder.invokeAllResult(msg);
| 119 | 196 | 139 | 335 |
36,110 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/DeviceControlResponseMessageHandler.java | DeviceControlResponseMessageHandler | handForDevice | class DeviceControlResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(DeviceControlResponseMessageHandler.class);
private final String cmdType = "DeviceControl";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
}
} |
// 此处是对本平台发出DeviceControl指令的应答
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 设备控制: {}", e.getMessage());
}
JSONObject json = new JSONObject();
String channelId = getText(element, "DeviceID");
XmlUtil.node2Json(element, json);
if (logger.isDebugEnabled()) {
logger.debug(json.toJSONString());
}
RequestMessage msg = new RequestMessage();
String key = DeferredResultHolder.CALLBACK_CMD_DEVICECONTROL + device.getDeviceId() + channelId;
msg.setKey(key);
msg.setData(json);
deferredResultHolder.invokeAllResult(msg);
| 193 | 196 | 232 | 428 |
36,111 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/DeviceInfoResponseMessageHandler.java | DeviceInfoResponseMessageHandler | handForDevice | class DeviceInfoResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(DeviceInfoResponseMessageHandler.class);
private final String cmdType = "DeviceInfo";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private IDeviceService deviceService;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
}
} |
logger.debug("接收到DeviceInfo应答消息");
// 检查设备是否存在, 不存在则不回复
if (device == null || !device.isOnLine()) {
logger.warn("[接收到DeviceInfo应答消息,但是设备已经离线]:" + (device != null ? device.getDeviceId():"" ));
return;
}
SIPRequest request = (SIPRequest) evt.getRequest();
try {
rootElement = getRootElement(evt, device.getCharset());
if (rootElement == null) {
logger.warn("[ 接收到DeviceInfo应答消息 ] content cannot be null, {}", evt.getRequest());
try {
responseAck((SIPRequest) evt.getRequest(), Response.BAD_REQUEST);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] DeviceInfo应答消息 BAD_REQUEST: {}", e.getMessage());
}
return;
}
Element deviceIdElement = rootElement.element("DeviceID");
String channelId = deviceIdElement.getTextTrim();
String key = DeferredResultHolder.CALLBACK_CMD_DEVICEINFO + device.getDeviceId() + channelId;
device.setName(getText(rootElement, "DeviceName"));
device.setManufacturer(getText(rootElement, "Manufacturer"));
device.setModel(getText(rootElement, "Model"));
device.setFirmware(getText(rootElement, "Firmware"));
if (ObjectUtils.isEmpty(device.getStreamMode())) {
device.setStreamMode("UDP");
}
deviceService.updateDevice(device);
RequestMessage msg = new RequestMessage();
msg.setKey(key);
msg.setData(device);
deferredResultHolder.invokeAllResult(msg);
} catch (DocumentException e) {
throw new RuntimeException(e);
}
try {
// 回复200 OK
responseAck(request, Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] DeviceInfo应答消息 200: {}", e.getMessage());
}
| 600 | 216 | 570 | 786 |
36,112 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/DeviceStatusResponseMessageHandler.java | DeviceStatusResponseMessageHandler | handForDevice | class DeviceStatusResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(DeviceStatusResponseMessageHandler.class);
private final String cmdType = "DeviceStatus";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private IDeviceService deviceService;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
}
} |
logger.info("接收到DeviceStatus应答消息");
// 检查设备是否存在, 不存在则不回复
if (device == null) {
return;
}
// 回复200 OK
try {
responseAck((SIPRequest) evt.getRequest(), Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 设备状态应答回复200OK: {}", e.getMessage());
}
Element deviceIdElement = element.element("DeviceID");
Element onlineElement = element.element("Online");
String channelId = deviceIdElement.getText();
JSONObject json = new JSONObject();
XmlUtil.node2Json(element, json);
if (logger.isDebugEnabled()) {
logger.debug(json.toJSONString());
}
String text = onlineElement.getText();
if ("ONLINE".equalsIgnoreCase(text.trim())) {
deviceService.online(device, null);
}else {
deviceService.offline(device.getDeviceId(), "设备状态查询结果:" + text.trim());
}
RequestMessage msg = new RequestMessage();
msg.setKey(DeferredResultHolder.CALLBACK_CMD_DEVICESTATUS + device.getDeviceId());
msg.setData(json);
deferredResultHolder.invokeAllResult(msg);
| 317 | 237 | 361 | 598 |
36,113 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/MobilePositionResponseMessageHandler.java | MobilePositionResponseMessageHandler | handForDevice | class MobilePositionResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(MobilePositionResponseMessageHandler.class);
private final String cmdType = "MobilePosition";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private UserSetting userSetting;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private IDeviceChannelService deviceChannelService;
@Autowired
private DeferredResultHolder resultHolder;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
}
} |
SIPRequest request = (SIPRequest) evt.getRequest();
try {
rootElement = getRootElement(evt, device.getCharset());
if (rootElement == null) {
logger.warn("[ 移动设备位置数据查询回复 ] content cannot be null, {}", evt.getRequest());
try {
responseAck(request, Response.BAD_REQUEST);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 移动设备位置数据查询 BAD_REQUEST: {}", e.getMessage());
}
return;
}
MobilePosition mobilePosition = new MobilePosition();
mobilePosition.setCreateTime(DateUtil.getNow());
if (!ObjectUtils.isEmpty(device.getName())) {
mobilePosition.setDeviceName(device.getName());
}
mobilePosition.setDeviceId(device.getDeviceId());
mobilePosition.setChannelId(getText(rootElement, "DeviceID"));
//兼容ISO 8601格式时间
String time = getText(rootElement, "Time");
if (ObjectUtils.isEmpty(time)){
mobilePosition.setTime(DateUtil.getNow());
}else {
mobilePosition.setTime(SipUtils.parseTime(time));
}
mobilePosition.setLongitude(Double.parseDouble(getText(rootElement, "Longitude")));
mobilePosition.setLatitude(Double.parseDouble(getText(rootElement, "Latitude")));
if (NumericUtil.isDouble(getText(rootElement, "Speed"))) {
mobilePosition.setSpeed(Double.parseDouble(getText(rootElement, "Speed")));
} else {
mobilePosition.setSpeed(0.0);
}
if (NumericUtil.isDouble(getText(rootElement, "Direction"))) {
mobilePosition.setDirection(Double.parseDouble(getText(rootElement, "Direction")));
} else {
mobilePosition.setDirection(0.0);
}
if (NumericUtil.isDouble(getText(rootElement, "Altitude"))) {
mobilePosition.setAltitude(Double.parseDouble(getText(rootElement, "Altitude")));
} else {
mobilePosition.setAltitude(0.0);
}
mobilePosition.setReportSource("Mobile Position");
// 更新device channel 的经纬度
DeviceChannel deviceChannel = new DeviceChannel();
deviceChannel.setDeviceId(device.getDeviceId());
deviceChannel.setChannelId(mobilePosition.getChannelId());
deviceChannel.setLongitude(mobilePosition.getLongitude());
deviceChannel.setLatitude(mobilePosition.getLatitude());
deviceChannel.setGpsTime(mobilePosition.getTime());
deviceChannel = deviceChannelService.updateGps(deviceChannel, device);
mobilePosition.setLongitudeWgs84(deviceChannel.getLongitudeWgs84());
mobilePosition.setLatitudeWgs84(deviceChannel.getLatitudeWgs84());
mobilePosition.setLongitudeGcj02(deviceChannel.getLongitudeGcj02());
mobilePosition.setLatitudeGcj02(deviceChannel.getLatitudeGcj02());
deviceChannelService.updateChannelGPS(device, deviceChannel, mobilePosition);
String key = DeferredResultHolder.CALLBACK_CMD_MOBILE_POSITION + device.getDeviceId();
RequestMessage msg = new RequestMessage();
msg.setKey(key);
msg.setData(mobilePosition);
resultHolder.invokeAllResult(msg);
//回复 200 OK
try {
responseAck(request, Response.OK);
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 移动设备位置数据查询 200: {}", e.getMessage());
}
} catch (DocumentException e) {
logger.error("未处理的异常 ", e);
}
| 1,033 | 269 | 1,002 | 1,271 |
36,114 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/PresetQueryResponseMessageHandler.java | PresetQueryResponseMessageHandler | handForDevice | class PresetQueryResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private Logger logger = LoggerFactory.getLogger(PresetQueryResponseMessageHandler.class);
private final String cmdType = "PresetQuery";
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element element) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element rootElement) {
}
} |
SIPRequest request = (SIPRequest) evt.getRequest();
try {
Element rootElement = getRootElement(evt, device.getCharset());
if (rootElement == null) {
logger.warn("[ 设备预置位查询应答 ] content cannot be null, {}", evt.getRequest());
try {
responseAck(request, Response.BAD_REQUEST);
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 设备预置位查询应答处理: {}", e.getMessage());
}
return;
}
Element presetListNumElement = rootElement.element("PresetList");
Element snElement = rootElement.element("SN");
//该字段可能为通道或则设备的id
String deviceId = getText(rootElement, "DeviceID");
String key = DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + deviceId;
if (snElement == null || presetListNumElement == null) {
try {
responseAck(request, Response.BAD_REQUEST, "xml error");
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 设备预置位查询应答处理: {}", e.getMessage());
}
return;
}
int sumNum = Integer.parseInt(presetListNumElement.attributeValue("Num"));
List<PresetQuerySipReq> presetQuerySipReqList = new ArrayList<>();
if (sumNum > 0) {
for (Iterator<Element> presetIterator = presetListNumElement.elementIterator(); presetIterator.hasNext(); ) {
Element itemListElement = presetIterator.next();
PresetQuerySipReq presetQuerySipReq = new PresetQuerySipReq();
for (Iterator<Element> itemListIterator = itemListElement.elementIterator(); itemListIterator.hasNext(); ) {
// 遍历item
Element itemOne = itemListIterator.next();
String name = itemOne.getName();
String textTrim = itemOne.getTextTrim();
if ("PresetID".equalsIgnoreCase(name)) {
presetQuerySipReq.setPresetId(textTrim);
} else {
presetQuerySipReq.setPresetName(textTrim);
}
}
presetQuerySipReqList.add(presetQuerySipReq);
}
}
RequestMessage requestMessage = new RequestMessage();
requestMessage.setKey(key);
requestMessage.setData(presetQuerySipReqList);
deferredResultHolder.invokeAllResult(requestMessage);
try {
responseAck(request, Response.OK);
} catch (InvalidArgumentException | ParseException | SipException e) {
logger.error("[命令发送失败] 设备预置位查询应答处理: {}", e.getMessage());
}
} catch (DocumentException e) {
logger.error("[解析xml]失败: ", e);
}
| 1,055 | 202 | 784 | 986 |
36,115 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/request/impl/message/response/cmd/RecordInfoResponseMessageHandler.java | RecordInfoResponseMessageHandler | handForDevice | class RecordInfoResponseMessageHandler extends SIPRequestProcessorParent implements InitializingBean, IMessageHandler {
private final Logger logger = LoggerFactory.getLogger(RecordInfoResponseMessageHandler.class);
private final String cmdType = "RecordInfo";
private ConcurrentLinkedQueue<HandlerCatchData> taskQueue = new ConcurrentLinkedQueue<>();
@Autowired
private ResponseMessageHandler responseMessageHandler;
@Autowired
private DeferredResultHolder deferredResultHolder;
@Autowired
private EventPublisher eventPublisher;
@Qualifier("taskExecutor")
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
private Long recordInfoTtl = 1800L;
@Override
public void afterPropertiesSet() throws Exception {
responseMessageHandler.addHandler(cmdType, this);
}
@Override
public void handForDevice(RequestEvent evt, Device device, Element rootElement) {<FILL_FUNCTION_BODY>}
@Override
public void handForPlatform(RequestEvent evt, ParentPlatform parentPlatform, Element element) {
}
public void releaseRequest(String deviceId, String sn,RecordInfo recordInfo){
String key = DeferredResultHolder.CALLBACK_CMD_RECORDINFO + deviceId + sn;
// 对数据进行排序
if(recordInfo!=null && recordInfo.getRecordList()!=null) {
Collections.sort(recordInfo.getRecordList());
}else{
recordInfo.setRecordList(new ArrayList<>());
}
RequestMessage msg = new RequestMessage();
msg.setKey(key);
msg.setData(recordInfo);
deferredResultHolder.invokeAllResult(msg);
}
} |
try {
// 回复200 OK
responseAck((SIPRequest) evt.getRequest(), Response.OK);
}catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 国标录像: {}", e.getMessage());
}
taskExecutor.execute(()->{
try {
String sn = getText(rootElement, "SN");
String channelId = getText(rootElement, "DeviceID");
RecordInfo recordInfo = new RecordInfo();
recordInfo.setChannelId(channelId);
recordInfo.setDeviceId(device.getDeviceId());
recordInfo.setSn(sn);
recordInfo.setName(getText(rootElement, "Name"));
String sumNumStr = getText(rootElement, "SumNum");
int sumNum = 0;
if (!ObjectUtils.isEmpty(sumNumStr)) {
sumNum = Integer.parseInt(sumNumStr);
}
recordInfo.setSumNum(sumNum);
Element recordListElement = rootElement.element("RecordList");
if (recordListElement == null || sumNum == 0) {
logger.info("无录像数据");
recordInfo.setCount(sumNum);
eventPublisher.recordEndEventPush(recordInfo);
releaseRequest(device.getDeviceId(), sn,recordInfo);
} else {
Iterator<Element> recordListIterator = recordListElement.elementIterator();
if (recordListIterator != null) {
List<RecordItem> recordList = new ArrayList<>();
// 遍历DeviceList
while (recordListIterator.hasNext()) {
Element itemRecord = recordListIterator.next();
Element recordElement = itemRecord.element("DeviceID");
if (recordElement == null) {
logger.info("记录为空,下一个...");
continue;
}
RecordItem record = new RecordItem();
record.setDeviceId(getText(itemRecord, "DeviceID"));
record.setName(getText(itemRecord, "Name"));
record.setFilePath(getText(itemRecord, "FilePath"));
record.setFileSize(getText(itemRecord, "FileSize"));
record.setAddress(getText(itemRecord, "Address"));
String startTimeStr = getText(itemRecord, "StartTime");
record.setStartTime(DateUtil.ISO8601Toyyyy_MM_dd_HH_mm_ss(startTimeStr));
String endTimeStr = getText(itemRecord, "EndTime");
record.setEndTime(DateUtil.ISO8601Toyyyy_MM_dd_HH_mm_ss(endTimeStr));
record.setSecrecy(itemRecord.element("Secrecy") == null ? 0
: Integer.parseInt(getText(itemRecord, "Secrecy")));
record.setType(getText(itemRecord, "Type"));
record.setRecorderId(getText(itemRecord, "RecorderID"));
recordList.add(record);
}
Map<String, String> map = recordList.stream()
.filter(record -> record.getDeviceId() != null)
.collect(Collectors.toMap(record -> record.getStartTime()+ record.getEndTime(), UJson::writeJson));
// 获取任务结果数据
String resKey = VideoManagerConstants.REDIS_RECORD_INFO_RES_PRE + channelId + sn;
redisTemplate.opsForHash().putAll(resKey, map);
redisTemplate.expire(resKey, recordInfoTtl, TimeUnit.SECONDS);
String resCountKey = VideoManagerConstants.REDIS_RECORD_INFO_RES_COUNT_PRE + channelId + sn;
long incr = redisTemplate.opsForValue().increment(resCountKey, map.size());
redisTemplate.expire(resCountKey, recordInfoTtl, TimeUnit.SECONDS);
recordInfo.setRecordList(recordList);
recordInfo.setCount(Math.toIntExact(incr));
eventPublisher.recordEndEventPush(recordInfo);
if (incr < sumNum) {
return;
}
// 已接收完成
List<RecordItem> resList = redisTemplate.opsForHash().entries(resKey).values().stream().map(e -> UJson.readJson(e.toString(), RecordItem.class)).collect(Collectors.toList());
if (resList.size() < sumNum) {
return;
}
recordInfo.setRecordList(resList);
releaseRequest(device.getDeviceId(), sn,recordInfo);
}
}
} catch (Exception e) {
logger.error("[国标录像] 发现未处理的异常, \r\n{}", evt.getRequest());
logger.error("[国标录像] 异常内容: ", e);
}
});
| 2,008 | 464 | 1,233 | 1,697 |
36,116 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/response/impl/InviteResponseProcessor.java | InviteResponseProcessor | process | class InviteResponseProcessor extends SIPResponseProcessorAbstract {
private final static Logger logger = LoggerFactory.getLogger(InviteResponseProcessor.class);
private final String method = "INVITE";
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private SipLayer sipLayer;
@Autowired
private SIPSender sipSender;
@Autowired
private SIPRequestHeaderProvider headerProvider;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addResponseProcessor(method, this);
}
/**
* 处理invite响应
*
* @param evt 响应消息
* @throws ParseException
*/
@Override
public void process(ResponseEvent evt ){<FILL_FUNCTION_BODY>}
} |
logger.debug("接收到消息:" + evt.getResponse());
try {
SIPResponse response = (SIPResponse)evt.getResponse();
int statusCode = response.getStatusCode();
// trying不会回复
if (statusCode == Response.TRYING) {
}
// 成功响应
// 下发ack
if (statusCode == Response.OK) {
ResponseEventExt event = (ResponseEventExt)evt;
String contentString = new String(response.getRawContent());
Gb28181Sdp gb28181Sdp = SipUtils.parseSDP(contentString);
SessionDescription sdp = gb28181Sdp.getBaseSdb();
SipURI requestUri = SipFactory.getInstance().createAddressFactory().createSipURI(sdp.getOrigin().getUsername(), event.getRemoteIpAddress() + ":" + event.getRemotePort());
Request reqAck = headerProvider.createAckRequest(response.getLocalAddress().getHostAddress(), requestUri, response);
logger.info("[回复ack] {}-> {}:{} ", sdp.getOrigin().getUsername(), event.getRemoteIpAddress(), event.getRemotePort());
sipSender.transmitRequest( response.getLocalAddress().getHostAddress(), reqAck);
}
} catch (InvalidArgumentException | ParseException | SipException | SdpParseException e) {
logger.info("[点播回复ACK],异常:", e );
}
| 67 | 223 | 398 | 621 |
36,117 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/response/impl/RegisterResponseProcessor.java | RegisterResponseProcessor | process | class RegisterResponseProcessor extends SIPResponseProcessorAbstract {
private final Logger logger = LoggerFactory.getLogger(RegisterResponseProcessor.class);
private final String method = "REGISTER";
@Autowired
private ISIPCommanderForPlatform sipCommanderForPlatform;
@Autowired
private IVideoManagerStorage storager;
@Autowired
private IRedisCatchStorage redisCatchStorage;
@Autowired
private SIPProcessorObserver sipProcessorObserver;
@Autowired
private SubscribeHolder subscribeHolder;
@Autowired
private IPlatformService platformService;
@Override
public void afterPropertiesSet() throws Exception {
// 添加消息处理的订阅
sipProcessorObserver.addResponseProcessor(method, this);
}
/**
* 处理Register响应
*
* @param evt 事件
*/
@Override
public void process(ResponseEvent evt) {<FILL_FUNCTION_BODY>}
} |
SIPResponse response = (SIPResponse)evt.getResponse();
String callId = response.getCallIdHeader().getCallId();
PlatformRegisterInfo platformRegisterInfo = redisCatchStorage.queryPlatformRegisterInfo(callId);
if (platformRegisterInfo == null) {
logger.info(String.format("[国标级联]未找到callId: %s 的注册/注销平台id", callId ));
return;
}
ParentPlatformCatch parentPlatformCatch = redisCatchStorage.queryPlatformCatchInfo(platformRegisterInfo.getPlatformId());
if (parentPlatformCatch == null) {
logger.warn(String.format("[国标级联]收到注册/注销%S请求,平台:%s,但是平台缓存信息未查询到!!!", response.getStatusCode(),platformRegisterInfo.getPlatformId()));
return;
}
String action = platformRegisterInfo.isRegister() ? "注册" : "注销";
logger.info(String.format("[国标级联]%s %S响应,%s ", action, response.getStatusCode(), platformRegisterInfo.getPlatformId() ));
ParentPlatform parentPlatform = parentPlatformCatch.getParentPlatform();
if (parentPlatform == null) {
logger.warn(String.format("[国标级联]收到 %s %s的%S请求, 但是平台信息未查询到!!!", platformRegisterInfo.getPlatformId(), action, response.getStatusCode()));
return;
}
if (response.getStatusCode() == Response.UNAUTHORIZED) {
WWWAuthenticateHeader www = (WWWAuthenticateHeader)response.getHeader(WWWAuthenticateHeader.NAME);
SipTransactionInfo sipTransactionInfo = new SipTransactionInfo(response);
try {
sipCommanderForPlatform.register(parentPlatform, sipTransactionInfo, www, null, null, platformRegisterInfo.isRegister());
} catch (SipException | InvalidArgumentException | ParseException e) {
logger.error("[命令发送失败] 国标级联 再次注册: {}", e.getMessage());
}
}else if (response.getStatusCode() == Response.OK){
if (platformRegisterInfo.isRegister()) {
SipTransactionInfo sipTransactionInfo = new SipTransactionInfo(response);
platformService.online(parentPlatform, sipTransactionInfo);
}else {
platformService.offline(parentPlatform, true);
}
// 注册/注销成功移除缓存的信息
redisCatchStorage.delPlatformRegisterInfo(callId);
}
| 95 | 242 | 668 | 910 |
36,118 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/transmit/event/timeout/impl/TimeoutProcessorImpl.java | TimeoutProcessorImpl | process | class TimeoutProcessorImpl implements InitializingBean, ITimeoutProcessor {
private Logger logger = LoggerFactory.getLogger(TimeoutProcessorImpl.class);
@Autowired
private SIPProcessorObserver processorObserver;
@Autowired
private SipSubscribe sipSubscribe;
@Override
public void afterPropertiesSet() throws Exception {
processorObserver.addTimeoutProcessor(this);
}
@Override
public void process(TimeoutEvent event) {<FILL_FUNCTION_BODY>}
} |
try {
// TODO Auto-generated method stub
CallIdHeader callIdHeader = event.getClientTransaction().getDialog().getCallId();
String callId = callIdHeader.getCallId();
SipSubscribe.Event errorSubscribe = sipSubscribe.getErrorSubscribe(callId);
SipSubscribe.EventResult<TimeoutEvent> timeoutEventEventResult = new SipSubscribe.EventResult<>(event);
errorSubscribe.response(timeoutEventEventResult);
sipSubscribe.removeErrorSubscribe(callId);
sipSubscribe.removeOkSubscribe(callId);
} catch (Exception e) {
logger.error("[超时事件失败]: {}", e.getMessage());
}
| 161 | 132 | 180 | 312 |
36,120 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/gb28181/utils/NumericUtil.java | NumericUtil | isInteger | class NumericUtil {
private static Logger logger = LoggerFactory.getLogger(NumericUtil.class);
/**
* 判断是否Double格式
* @param str
* @return true/false
*/
public static boolean isDouble(String str) {
try {
Double num2 = Double.valueOf(str);
// logger.debug(num2 + " is a valid numeric string!");
return true;
} catch (Exception e) {
// logger.debug(str + " is an invalid numeric string!");
return false;
}
}
/**
* 判断是否Double格式
* @param str
* @return true/false
*/
public static boolean isInteger(String str) {<FILL_FUNCTION_BODY>}
} |
try {
int num2 = Integer.valueOf(str);
// logger.debug(num2 + " is an integer!");
return true;
} catch (Exception e) {
// logger.debug(str + " is not an integer!");
return false;
}
| 113 | 208 | 77 | 285 |
36,123 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/cmd/JT1078Template.java | JT1078Template | startBackLive | class JT1078Template {
private final Random random = new Random();
private static final String H9101 = "9101";
private static final String H9102 = "9102";
private static final String H9201 = "9201";
private static final String H9202 = "9202";
private static final String H9205 = "9205";
private static final String H0001 = "0001";
private static final String H1205 = "1205";
/**
* 开启直播视频
*
* @param devId 设备号
* @param j9101 开启视频参数
*/
public String startLive(String devId, J9101 j9101, Integer timeOut) {
Cmd cmd = new Cmd.Builder()
.setDevId(devId)
.setPackageNo(randomInt())
.setMsgId(H9101)
.setRespId(H0001)
.setRs(j9101)
.build();
return SessionManager.INSTANCE.request(cmd, timeOut);
}
/**
* 关闭直播视频
*
* @param devId 设备号
* @param j9102 关闭视频参数
*/
public String stopLive(String devId, J9102 j9102, Integer timeOut) {
Cmd cmd = new Cmd.Builder()
.setDevId(devId)
.setPackageNo(randomInt())
.setMsgId(H9102)
.setRespId(H0001)
.setRs(j9102)
.build();
return SessionManager.INSTANCE.request(cmd, timeOut);
}
/**
* 查询音视频列表
*
* @param devId 设备号
* @param j9205 查询音视频列表
*/
public String queryBackTime(String devId, J9205 j9205, Integer timeOut) {
Cmd cmd = new Cmd.Builder()
.setDevId(devId)
.setPackageNo(randomInt())
.setMsgId(H9205)
.setRespId(H1205)
.setRs(j9205)
.build();
return SessionManager.INSTANCE.request(cmd, timeOut);
}
/**
* 开启视频回放
*
* @param devId 设备号
* @param j9201 视频回放参数
*/
public String startBackLive(String devId, J9201 j9201, Integer timeOut) {<FILL_FUNCTION_BODY>}
/**
* 视频回放控制
*
* @param devId 设备号
* @param j9202 控制视频回放参数
*/
public String controlBackLive(String devId, J9202 j9202, Integer timeOut) {
Cmd cmd = new Cmd.Builder()
.setDevId(devId)
.setPackageNo(randomInt())
.setMsgId(H9202)
.setRespId(H0001)
.setRs(j9202)
.build();
return SessionManager.INSTANCE.request(cmd, timeOut);
}
private Long randomInt() {
return (long) random.nextInt(1000) + 1;
}
} |
Cmd cmd = new Cmd.Builder()
.setDevId(devId)
.setPackageNo(randomInt())
.setMsgId(H9201)
.setRespId(H1205)
.setRs(j9201)
.build();
return SessionManager.INSTANCE.request(cmd, timeOut);
| 123 | 934 | 96 | 1,030 |
36,124 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/codec/decode/Jt808Decoder.java | Jt808Decoder | unEscapeAndCheck | class Jt808Decoder extends ByteToMessageDecoder {
private final static Logger log = LoggerFactory.getLogger(Jt808Decoder.class);
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
Session session = ctx.channel().attr(Session.KEY).get();
log.info("> {} hex:{}", session, ByteBufUtil.hexDump(in));
try {
ByteBuf buf = unEscapeAndCheck(in);
Header header = new Header();
header.setMsgId(ByteBufUtil.hexDump(buf.readSlice(2)));
header.setMsgPro(buf.readUnsignedShort());
if (header.is2019Version()) {
header.setVersion(buf.readUnsignedByte());
String devId = ByteBufUtil.hexDump(buf.readSlice(10));
header.setDevId(devId.replaceFirst("^0*", ""));
} else {
header.setDevId(ByteBufUtil.hexDump(buf.readSlice(6)).replaceFirst("^0*", ""));
}
header.setSn(buf.readUnsignedShort());
Re handler = CodecFactory.getHandler(header.getMsgId());
if (handler == null) {
log.error("get msgId is null {}", header.getMsgId());
return;
}
Rs decode = handler.decode(buf, header, session);
if (decode != null) {
out.add(decode);
}
} finally {
in.skipBytes(in.readableBytes());
}
}
/**
* 转义与验证校验码
*
* @param byteBuf 转义Buf
* @return 转义好的数据
*/
public ByteBuf unEscapeAndCheck(ByteBuf byteBuf) throws Exception {<FILL_FUNCTION_BODY>}
private ByteBuf slice0x01(ByteBuf buf, int low, int sign) {
return buf.slice(low, sign - low + 1);
}
private ByteBuf slice0x02(ByteBuf buf, int low, int sign) {
buf.setByte(sign, 0x7e);
return buf.slice(low, sign - low + 1);
}
} |
int low = byteBuf.readerIndex();
int high = byteBuf.writerIndex();
byte checkSum = 0;
int calculationCheckSum = 0;
byte aByte = byteBuf.getByte(high - 2);
byte protocolEscapeFlag7d = 0x7d;
//0x7d转义
byte protocolEscapeFlag01 = 0x01;
//0x7e转义
byte protocolEscapeFlag02 = 0x02;
if (aByte == protocolEscapeFlag7d) {
byte b2 = byteBuf.getByte(high - 1);
if (b2 == protocolEscapeFlag01) {
checkSum = protocolEscapeFlag7d;
} else if (b2 == protocolEscapeFlag02) {
checkSum = 0x7e;
} else {
log.error("转义1异常:{}", ByteBufUtil.hexDump(byteBuf));
throw new Exception("转义错误");
}
high = high - 2;
} else {
high = high - 1;
checkSum = byteBuf.getByte(high);
}
List<ByteBuf> bufList = new ArrayList<>();
int index = low;
while (index < high) {
byte b = byteBuf.getByte(index);
if (b == protocolEscapeFlag7d) {
byte c = byteBuf.getByte(index + 1);
if (c == protocolEscapeFlag01) {
ByteBuf slice = slice0x01(byteBuf, low, index);
bufList.add(slice);
b = protocolEscapeFlag7d;
} else if (c == protocolEscapeFlag02) {
ByteBuf slice = slice0x02(byteBuf, low, index);
bufList.add(slice);
b = 0x7e;
} else {
log.error("转义2异常:{}", ByteBufUtil.hexDump(byteBuf));
throw new Exception("转义错误");
}
index += 2;
low = index;
} else {
index += 1;
}
calculationCheckSum = calculationCheckSum ^ b;
}
if (calculationCheckSum == checkSum) {
if (bufList.size() == 0) {
return byteBuf.slice(low, high);
} else {
bufList.add(byteBuf.slice(low, high - low));
return new CompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, false, bufList.size(), bufList);
}
} else {
log.info("{} 解析校验码:{}--计算校验码:{}", ByteBufUtil.hexDump(byteBuf), checkSum, calculationCheckSum);
throw new Exception("校验码错误!");
}
| 939 | 603 | 706 | 1,309 |
36,125 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/codec/encode/Jt808Encoder.java | Jt808Encoder | encode | class Jt808Encoder extends MessageToByteEncoder<Rs> {
private final static Logger log = LoggerFactory.getLogger(Jt808Encoder.class);
@Override
protected void encode(ChannelHandlerContext ctx, Rs msg, ByteBuf out) throws Exception {<FILL_FUNCTION_BODY>}
} |
Session session = ctx.channel().attr(Session.KEY).get();
ByteBuf encode = Jt808EncoderCmd.encode(msg, session, session.nextSerialNo());
if(encode!=null){
log.info("< {} hex:{}", session, ByteBufUtil.hexDump(encode));
out.writeBytes(encode);
}
| 73 | 88 | 93 | 181 |
36,126 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/codec/encode/Jt808EncoderCmd.java | Jt808EncoderCmd | encode | class Jt808EncoderCmd extends MessageToByteEncoder<Cmd> {
private final static Logger log = LoggerFactory.getLogger(Jt808EncoderCmd.class);
@Override
protected void encode(ChannelHandlerContext ctx, Cmd cmd, ByteBuf out) throws Exception {
Session session = ctx.channel().attr(Session.KEY).get();
Rs msg = cmd.getRs();
ByteBuf encode = encode(msg, session, cmd.getPackageNo().intValue());
if (encode != null) {
log.info("< {} hex:{}", session, ByteBufUtil.hexDump(encode));
out.writeBytes(encode);
}
}
public static ByteBuf encode(Rs msg, Session session, Integer packageNo) {<FILL_FUNCTION_BODY>}
private static final ByteProcessor searcher = value -> !(value == 0x7d || value == 0x7e);
//转义与校验
public static ByteBuf escapeAndCheck0(ByteBuf source) {
sign(source);
int low = source.readerIndex();
int high = source.writerIndex();
LinkedList<ByteBuf> bufList = new LinkedList<>();
int mark, len;
while ((mark = source.forEachByte(low, high - low, searcher)) > 0) {
len = mark + 1 - low;
ByteBuf[] slice = slice(source, low, len);
bufList.add(slice[0]);
bufList.add(slice[1]);
low += len;
}
if (bufList.size() > 0) {
bufList.add(source.slice(low, high - low));
} else {
bufList.add(source);
}
ByteBuf delimiter = Unpooled.buffer(1, 1).writeByte(0x7e).retain();
bufList.addFirst(delimiter);
bufList.addLast(delimiter);
CompositeByteBuf byteBufLs = Unpooled.compositeBuffer(bufList.size());
byteBufLs.addComponents(true, bufList);
return byteBufLs;
}
public static void sign(ByteBuf buf) {
byte checkCode = bcc(buf);
buf.writeByte(checkCode);
}
public static byte bcc(ByteBuf byteBuf) {
byte cs = 0;
while (byteBuf.isReadable())
cs ^= byteBuf.readByte();
byteBuf.resetReaderIndex();
return cs;
}
protected static ByteBuf[] slice(ByteBuf byteBuf, int index, int length) {
byte first = byteBuf.getByte(index + length - 1);
ByteBuf[] byteBufList = new ByteBuf[2];
byteBufList[0] = byteBuf.retainedSlice(index, length);
if (first == 0x7d) {
byteBufList[1] = Unpooled.buffer(1, 1).writeByte(0x01);
} else {
byteBuf.setByte(index + length - 1, 0x7d);
byteBufList[1] = Unpooled.buffer(1, 1).writeByte(0x02);
}
return byteBufList;
}
} |
String id = msg.getClass().getAnnotation(MsgId.class).id();
if (!StringUtils.hasLength(id)) {
log.error("Not find msgId");
return null;
}
ByteBuf byteBuf = Unpooled.buffer();
byteBuf.writeBytes(ByteBufUtil.decodeHexDump(id));
ByteBuf encode = msg.encode();
Header header = msg.getHeader();
if (header == null) {
header = session.getHeader();
}
if (header.is2019Version()) {
// 消息体属性
byteBuf.writeShort(encode.readableBytes() | 1 << 14);
// 版本号
byteBuf.writeByte(header.getVersion());
// 终端手机号
byteBuf.writeBytes(ByteBufUtil.decodeHexDump(Bin.strHexPaddingLeft(header.getDevId(), 20)));
} else {
// 消息体属性
byteBuf.writeShort(encode.readableBytes());
byteBuf.writeBytes(ByteBufUtil.decodeHexDump(Bin.strHexPaddingLeft(header.getDevId(), 12)));
}
// 消息体流水号
byteBuf.writeShort(packageNo);
// 写入消息体
byteBuf.writeBytes(encode);
// 计算校验码,并反转义
byteBuf = escapeAndCheck0(byteBuf);
return byteBuf;
| 344 | 838 | 386 | 1,224 |
36,127 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/codec/netty/Jt808Handler.java | Jt808Handler | userEventTriggered | class Jt808Handler extends ChannelInboundHandlerAdapter {
private final static Logger log = LoggerFactory.getLogger(Jt808Handler.class);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Rs) {
ctx.writeAndFlush(msg);
} else {
ctx.fireChannelRead(msg);
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
Session session = SessionManager.INSTANCE.newSession(channel);
channel.attr(Session.KEY).set(session);
log.info("> Tcp connect {}", session);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
Session session = ctx.channel().attr(Session.KEY).get();
log.info("< Tcp disconnect {}", session);
ctx.close();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
Session session = ctx.channel().attr(Session.KEY).get();
String message = e.getMessage();
if (message.toLowerCase().contains("Connection reset by peer".toLowerCase())) {
log.info("< exception{} {}", session, e.getMessage());
} else {
log.info("< exception{} {}", session, e.getMessage(), e);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {<FILL_FUNCTION_BODY>}
} |
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
IdleState state = event.state();
if (state == IdleState.READER_IDLE || state == IdleState.WRITER_IDLE) {
Session session = ctx.channel().attr(Session.KEY).get();
log.warn("< Proactively disconnect{}", session);
ctx.close();
}
}
| 142 | 398 | 118 | 516 |
36,128 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/codec/netty/TcpServer.java | TcpServer | stop | class TcpServer {
private final static Logger log = LoggerFactory.getLogger(TcpServer.class);
private final Integer port;
private boolean isRunning = false;
private EventLoopGroup bossGroup = null;
private EventLoopGroup workerGroup = null;
private final ByteBuf DECODER_JT808 = Unpooled.wrappedBuffer(new byte[]{0x7e});
public TcpServer(Integer port) {
this.port = port;
}
private void startTcpServer() {
try {
CodecFactory.init();
this.bossGroup = new NioEventLoopGroup();
this.workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.group(bossGroup, workerGroup);
bootstrap.option(NioChannelOption.SO_BACKLOG, 1024)
.option(NioChannelOption.SO_REUSEADDR, true)
.childOption(NioChannelOption.TCP_NODELAY, true)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
public void initChannel(NioSocketChannel channel) {
channel.pipeline()
.addLast(new IdleStateHandler(10, 0, 0, TimeUnit.MINUTES))
.addLast(new DelimiterBasedFrameDecoder(1024 * 2, DECODER_JT808))
.addLast(new Jt808Decoder())
.addLast(new Jt808Encoder())
.addLast(new Jt808EncoderCmd())
.addLast(new Jt808Handler());
}
});
ChannelFuture channelFuture = bootstrap.bind(port).sync();
// 监听设备TCP端口是否启动成功
channelFuture.addListener(future -> {
if (!future.isSuccess()) {
log.error("Binding port:{} fail! cause: {}", port, future.cause().getCause(), future.cause());
}
});
log.info("服务:JT808 Server 启动成功, port:{}", port);
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.warn("服务:JT808 Server 启动异常, port:{},{}", port, e.getMessage(), e);
} finally {
stop();
}
}
/**
* 开启一个新的线程,拉起来Netty
*/
public synchronized void start() {
if (this.isRunning) {
log.warn("服务:JT808 Server 已经启动, port:{}", port);
return;
}
this.isRunning = true;
new Thread(this::startTcpServer).start();
}
public synchronized void stop() {<FILL_FUNCTION_BODY>}
} |
if (!this.isRunning) {
log.warn("服务:JT808 Server 已经停止, port:{}", port);
}
this.isRunning = false;
Future<?> future = this.bossGroup.shutdownGracefully();
if (!future.isSuccess()) {
log.warn("bossGroup 无法正常停止", future.cause());
}
future = this.workerGroup.shutdownGracefully();
if (!future.isSuccess()) {
log.warn("workerGroup 无法正常停止", future.cause());
}
log.warn("服务:JT808 Server 已经停止, port:{}", port);
| 146 | 749 | 167 | 916 |
36,129 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/config/JT1078Controller.java | JT1078Controller | startLive | class JT1078Controller {
@Resource
JT1078Template jt1078Template;
/**
* jt1078Template 调用示例
*/
@GetMapping("/start/live/{deviceId}/{channelId}")
public WVPResult<?> startLive(@PathVariable String deviceId, @PathVariable String channelId) {<FILL_FUNCTION_BODY>}
} |
J9101 j9101 = new J9101();
j9101.setChannel(Integer.valueOf(channelId));
j9101.setIp("192.168.1.1");
j9101.setRate(1);
j9101.setTcpPort(7618);
j9101.setUdpPort(7618);
j9101.setType(0);
// TODO 分配ZLM,获取IP、端口
String s = jt1078Template.startLive(deviceId, j9101, 6);
// TODO 设备响应成功后,封装拉流结果集
WVPResult<String> wvpResult = new WVPResult<>();
wvpResult.setCode(200);
wvpResult.setData(String.format("http://192.168.1.1/rtp/%s_%s.live.mp4", deviceId, channelId));
return wvpResult;
| 137 | 113 | 276 | 389 |
36,130 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/entity/Cmd.java | Builder | toString | class Builder {
String devId;
Long packageNo;
String msgId;
String respId;
Rs rs;
public Builder setDevId(String devId) {
this.devId = devId.replaceFirst("^0*", "");
return this;
}
public Builder setPackageNo(Long packageNo) {
this.packageNo = packageNo;
return this;
}
public Builder setMsgId(String msgId) {
this.msgId = msgId;
return this;
}
public Builder setRespId(String respId) {
this.respId = respId;
return this;
}
public Builder setRs(Rs re) {
this.rs = re;
return this;
}
public Cmd build() {
return new Cmd(this);
}
}
@Override
public String toString() {<FILL_FUNCTION_BODY> |
return "Cmd{" +
"devId='" + devId + '\'' +
", packageNo=" + packageNo +
", msgId='" + msgId + '\'' +
", respId='" + respId + '\'' +
", rs=" + rs +
'}';
| 136 | 251 | 79 | 330 |
36,131 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/factory/CodecFactory.java | CodecFactory | init | class CodecFactory {
private final static Logger log = LoggerFactory.getLogger(CodecFactory.class);
private static Map<String, Class<?>> protocolHash;
public static void init() {<FILL_FUNCTION_BODY>}
public static Re getHandler(String msgId) {
Class<?> aClass = protocolHash.get(msgId);
Object bean = ClassUtil.getBean(aClass);
if (bean instanceof Re) {
return (Re) bean;
}
return null;
}
} |
protocolHash = new HashMap<>();
List<Class<?>> classList = ClassUtil.getClassList("com.genersoft.iot.vmp.jt1078.proc", MsgId.class);
for (Class<?> handlerClass : classList) {
String id = handlerClass.getAnnotation(MsgId.class).id();
protocolHash.put(id, handlerClass);
}
if (log.isDebugEnabled()) {
log.debug("消息ID缓存表 protocolHash:{}", protocolHash);
}
| 109 | 140 | 138 | 278 |
36,132 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/J0001.java | J0001 | decode0 | class J0001 extends Re {
int respNo;
String respId;
int result;
@Override
protected Rs decode0(ByteBuf buf, Header header, Session session) {<FILL_FUNCTION_BODY>}
@Override
protected Rs handler(Header header, Session session) {
SessionManager.INSTANCE.response(header.getDevId(), "0001", (long) respNo, JSON.toJSONString(this));
return null;
}
public int getRespNo() {
return respNo;
}
public String getRespId() {
return respId;
}
public int getResult() {
return result;
}
} |
respNo = buf.readUnsignedShort();
respId = ByteBufUtil.hexDump(buf.readSlice(2));
result = buf.readUnsignedByte();
return null;
| 44 | 185 | 54 | 239 |
36,133 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/J0002.java | J0002 | handler | class J0002 extends Re {
@Override
protected Rs decode0(ByteBuf buf, Header header, Session session) {
return null;
}
@Override
protected Rs handler(Header header, Session session) {<FILL_FUNCTION_BODY>}
} |
J8001 j8001 = new J8001();
j8001.setRespNo(header.getSn());
j8001.setRespId(header.getMsgId());
j8001.setResult(J8001.SUCCESS);
return j8001;
| 50 | 74 | 90 | 164 |
36,134 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/J0100.java | J0100 | decode0 | class J0100 extends Re {
private int provinceId;
private int cityId;
private String makerId;
private String deviceModel;
private String deviceId;
private int plateColor;
private String plateNo;
@Override
protected Rs decode0(ByteBuf buf, Header header, Session session) {<FILL_FUNCTION_BODY>}
@Override
protected Rs handler(Header header, Session session) {
J8100 j8100 = new J8100();
j8100.setRespNo(header.getSn());
j8100.setResult(J8100.SUCCESS);
j8100.setCode("WVP_YYDS");
return j8100;
}
} |
Short version = header.getVersion();
provinceId = buf.readUnsignedShort();
if (version > 1) {
cityId = buf.readUnsignedShort();
// decode as 2019
} else {
int i = buf.readUnsignedShort();
// decode as 2013
}
return null;
| 124 | 211 | 96 | 307 |
36,135 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/J0102.java | J0102 | decode0 | class J0102 extends Re {
@Override
protected Rs decode0(ByteBuf buf, Header header, Session session) {<FILL_FUNCTION_BODY>}
@Override
protected Rs handler(Header header, Session session) {
J8001 j8001 = new J8001();
j8001.setRespNo(header.getSn());
j8001.setRespId(header.getMsgId());
j8001.setResult(J8001.SUCCESS);
return j8001;
}
} |
int lenCode = buf.readUnsignedByte();
// String code = buf.readCharSequence(lenCode, CharsetUtil.UTF_8).toString();
// if 2019 to decode next
return null;
| 50 | 157 | 60 | 217 |
36,136 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/J0200.java | J0200 | handler | class J0200 extends Re {
@Override
protected Rs decode0(ByteBuf buf, Header header, Session session) {
return null;
}
@Override
protected Rs handler(Header header, Session session) {<FILL_FUNCTION_BODY>}
} |
J8001 j8001 = new J8001();
j8001.setRespNo(header.getSn());
j8001.setRespId(header.getMsgId());
j8001.setResult(J8001.SUCCESS);
return j8001;
| 50 | 74 | 90 | 164 |
36,137 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/J1205.java | JRecordItem | toString | class JRecordItem {
// 逻辑通道号
private int channelId;
// 开始时间
private String startTime;
// 结束时间
private String endTime;
// 报警标志
private long warn;
// 音视频资源类型
private int mediaType;
// 码流类型
private int streamType = 1;
// 存储器类型
private int storageType;
// 文件大小
private long size;
public int getChannelId() {
return channelId;
}
public void setChannelId(int channelId) {
this.channelId = channelId;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public long getWarn() {
return warn;
}
public void setWarn(long warn) {
this.warn = warn;
}
public int getMediaType() {
return mediaType;
}
public void setMediaType(int mediaType) {
this.mediaType = mediaType;
}
public int getStreamType() {
return streamType;
}
public void setStreamType(int streamType) {
this.streamType = streamType;
}
public int getStorageType() {
return storageType;
}
public void setStorageType(int storageType) {
this.storageType = storageType;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "JRecordItem{" +
"channelId=" + channelId +
", startTime='" + startTime + '\'' +
", endTime='" + endTime + '\'' +
", warn=" + warn +
", mediaType=" + mediaType +
", streamType=" + streamType +
", storageType=" + storageType +
", size=" + size +
'}';
| 238 | 511 | 107 | 618 |
36,138 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/request/Re.java | Re | decode | class Re {
private final static Logger log = LoggerFactory.getLogger(Re.class);
protected abstract Rs decode0(ByteBuf buf, Header header, Session session);
protected abstract Rs handler(Header header, Session session);
public Rs decode(ByteBuf buf, Header header, Session session) {<FILL_FUNCTION_BODY>}
} |
if (session != null && !StringUtils.hasLength(session.getDevId())) {
session.register(header.getDevId(), (int) header.getVersion(), header);
}
Rs rs = decode0(buf, header, session);
Rs rsHand = handler(header, session);
if (rs == null && rsHand != null) {
rs = rsHand;
} else if (rs != null && rsHand != null) {
log.warn("decode0:{} 与 handler:{} 返回值冲突,采用decode0返回值", rs, rsHand);
}
if (rs != null) {
rs.setHeader(header);
}
return rs;
| 181 | 93 | 193 | 286 |
36,139 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/response/J8001.java | J8001 | encode | class J8001 extends Rs {
public static final Integer SUCCESS = 0;
Integer respNo;
String respId;
Integer result;
@Override
public ByteBuf encode() {<FILL_FUNCTION_BODY>}
public void setRespNo(Integer respNo) {
this.respNo = respNo;
}
public void setRespId(String respId) {
this.respId = respId;
}
public void setResult(Integer result) {
this.result = result;
}
} |
ByteBuf buffer = Unpooled.buffer();
buffer.writeShort(respNo);
buffer.writeBytes(ByteBufUtil.decodeHexDump(respId));
buffer.writeByte(result);
return buffer;
| 49 | 147 | 60 | 207 |
36,140 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/response/J8100.java | J8100 | encode | class J8100 extends Rs {
public static final Integer SUCCESS = 0;
Integer respNo;
Integer result;
String code;
@Override
public ByteBuf encode() {<FILL_FUNCTION_BODY>}
public void setRespNo(Integer respNo) {
this.respNo = respNo;
}
public void setResult(Integer result) {
this.result = result;
}
public void setCode(String code) {
this.code = code;
}
} |
ByteBuf buffer = Unpooled.buffer();
buffer.writeShort(respNo);
buffer.writeByte(result);
buffer.writeCharSequence(code, CharsetUtil.UTF_8);
return buffer;
| 50 | 140 | 57 | 197 |
36,141 | 648540858_wvp-GB28181-pro | wvp-GB28181-pro/src/main/java/com/genersoft/iot/vmp/jt1078/proc/response/J9101.java | J9101 | toString | class J9101 extends Rs {
String ip;
// TCP端口
Integer tcpPort;
// UDP端口
Integer udpPort;
// 逻辑通道号
Integer channel;
// 数据类型
/**
* 0:音视频,1:视频,2:双向对讲,3:监听,4:中心广播,5:透传
*/
Integer type;
// 码流类型
/**
* 0:主码流,1:子码流
*/
Integer rate;
@Override
public ByteBuf encode() {
ByteBuf buffer = Unpooled.buffer();
buffer.writeByte(ip.getBytes().length);
buffer.writeCharSequence(ip, CharsetUtil.UTF_8);
buffer.writeShort(tcpPort);
buffer.writeShort(udpPort);
buffer.writeByte(channel);
buffer.writeByte(type);
buffer.writeByte(rate);
return buffer;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getTcpPort() {
return tcpPort;
}
public void setTcpPort(Integer tcpPort) {
this.tcpPort = tcpPort;
}
public Integer getUdpPort() {
return udpPort;
}
public void setUdpPort(Integer udpPort) {
this.udpPort = udpPort;
}
public Integer getChannel() {
return channel;
}
public void setChannel(Integer channel) {
this.channel = channel;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getRate() {
return rate;
}
public void setRate(Integer rate) {
this.rate = rate;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
} |
return "J9101{" +
"ip='" + ip + '\'' +
", tcpPort=" + tcpPort +
", udpPort=" + udpPort +
", channel=" + channel +
", type=" + type +
", rate=" + rate +
'}';
| 152 | 561 | 86 | 647 |