Commit efa10bcb authored by wangjinjing's avatar wangjinjing

init

parent 60a42fe1
Pipeline #39 failed with stages
......@@ -174,7 +174,10 @@
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
......
package com.cx.cn.cxquartz.bean;
public class PatrolCtrlAlarm {
private String cameraCode;
private String cameraName;
private String time;
private String type;
private String file;
public String getCameraCode() {
return cameraCode;
}
public void setCameraCode(String cameraCode) {
this.cameraCode = cameraCode;
}
public String getCameraName() {
return cameraName;
}
public void setCameraName(String cameraName) {
this.cameraName = cameraName;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
}
package com.cx.cn.cxquartz.bean;
public class PatrolCtrlRecord {
private String cameraCode;
private String cameraName;
private String patrolTime;
private String recordSrc;
private String file;
private String deviceid;
public String getDeviceid() {
return deviceid;
}
public void setDeviceid(String deviceid) {
this.deviceid = deviceid;
}
public String getCameraCode() {
return cameraCode;
}
public void setCameraCode(String cameraCode) {
this.cameraCode = cameraCode;
}
public String getCameraName() {
return cameraName;
}
public void setCameraName(String cameraName) {
this.cameraName = cameraName;
}
public String getPatrolTime() {
return patrolTime;
}
public void setPatrolTime(String patrolTime) {
this.patrolTime = patrolTime;
}
public String getRecordSrc() {
return recordSrc;
}
public void setRecordSrc(String recordSrc) {
this.recordSrc = recordSrc;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
}
package com.cx.cn.cxquartz.bean;
public class PictureTime {
String deviceid;
String lasttime;
public String getDeviceid() {
return deviceid;
}
public void setDeviceid(String deviceid) {
this.deviceid = deviceid;
}
public String getLasttime() {
return lasttime;
}
public void setLasttime(String lasttime) {
this.lasttime = lasttime;
}
}
package com.cx.cn.cxquartz.bean;
public class QuartzTaskInformations {
import java.io.Serializable;
public class QuartzTaskInformations implements Serializable {
private Long id;
private Integer version;
......@@ -39,7 +41,7 @@ public class QuartzTaskInformations {
private String metatype;
private String imgsrc;
private String rtsp;
private String objectType;
private String videoid;
public String getVideoid() {
......@@ -58,12 +60,12 @@ public class QuartzTaskInformations {
this.imgsrc = imgsrc;
}
public String getRtsp() {
return rtsp;
public String getObjectType() {
return objectType;
}
public void setRtsp(String rtsp) {
this.rtsp = rtsp;
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public String getMetatype() {
......
......@@ -73,15 +73,15 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}
@Bean
public JedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName("<server-hostname-here>");
jedisConnectionFactory.setPort(6379);
jedisConnectionFactory.setPassword("<server-password-here>");
jedisConnectionFactory.afterPropertiesSet();
return jedisConnectionFactory;
}
// @Bean
// public JedisConnectionFactory redisConnectionFactory() {
// JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
// jedisConnectionFactory.setHostName("<server-hostname-here>");
// jedisConnectionFactory.setPort(6379);
// jedisConnectionFactory.setPassword("<server-password-here>");
// jedisConnectionFactory.afterPropertiesSet();
// return jedisConnectionFactory;
// }
/**
* 对链表类型的数据操作
*
......
package com.cx.cn.cxquartz.util;
package com.cx.cn.cxquartz.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......
package com.cx.cn.cxquartz.config;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.util.RestUtil;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.Calendar;
import java.util.List;
@Configuration
@EnableScheduling
public class ScheduleTaskConfig {
@Autowired
private SbtdspsrService sbtdspsrService;
@Value("${file.getrtspbyurl}")
private String getrtspbyurl;
RestUtil restUtil=new RestUtil();
// /***
// * 每隔20分钟执行一遍判断rtsp 是否变换
// */
//// @Scheduled(cron = "0 0 2 * * ? ")
// private void statis() {
// //查询所有监控设备,更新rtsp 地址
// List<Sbtdspsr> sbtdpsrList= sbtdspsrService.list();
// //调用decice 端口获得新的rtsp 地址,如果与表里的一样无需更新,不一样则立即更新
// for(Sbtdspsr sbtd:sbtdpsrList)
// {
// restUtil.rtspChangeVlue(sbtd.getSbbh(),sbtd.getSqurllj(),getrtspbyurl);
// }
// }
// @Scheduled(cron = "0 30/5 6-19 * * ?")//每隔5分钟统计当天目前为止的数据
// private void statistoday() {
// //判断是否为空表
// //执行查询存在更新,不存在新增
// log.info("每隔5分钟");
// Integer result= traffFlowService.insertOrUpdatevehicleTodaystatistic();
// log.info("today"+result);
//
// }
}
package com.cx.cn.cxquartz.config;
import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.Properties;
@Configuration //类似xml中的<beans>标签,一般和@bean注解一起使用来配置一个Bean,让Spring来管理它的生命周期
public class SchedulerConfig {
@Bean(name="SchedulerFactory")
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setQuartzProperties(quartzProperties());
return factory;
}
/**
* 加载Quartz配置
*
*/
@Bean
public Properties quartzProperties() throws IOException {
//使用Spring的PropertiesFactoryBean对属性配置文件进行管理
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
Properties properties = propertiesFactoryBean.getObject();
return properties;
}
/**
* 初始化Quartz监听器,让Spring boot启动时初始化Quartz
*
*/
@Bean
public QuartzInitializerListener executorListener() {
return new QuartzInitializerListener();
}
/**
* 通过SchedulerFactoryBean获取Scheduler的实例
*/
@Bean(name="Scheduler")
public Scheduler scheduler() throws IOException {
return schedulerFactoryBean().getScheduler();
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.controller;
import com.cx.cn.cxquartz.bean.QuartzTaskErrors;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskRecordsService;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.util.ResultEnum;
import com.cx.cn.cxquartz.util.ResultUtil;
import com.cx.cn.cxquartz.vo.QuartzTaskRecordsVo;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/video")
public class SbtdspsrController {
private static final Logger logger = LoggerFactory.getLogger(SbtdspsrController.class);
@Autowired
private SbtdspsrService sbtdspsrService;
//
// @RequestMapping(value = "/getSbtdspsrbyrtsp", method = RequestMethod.GET)
// public String addTaskpage() {
// return "addtask";
// }
// @RequestMapping(value = "/list", method = RequestMethod.GET)
// @ResponseBody
// public List<Sbtdspsr> list() {
// return sbtdspsrService.list();
//
// }
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.Code;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Mapper
public interface CodeMapper {
Code selectalarmNum(String keyid);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.Face;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Mapper
public interface FaceMapper {
int insertFace(Face face);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.Pedestrian;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Mapper
public interface PedestrianMapper {
int insertpedestrian(Pedestrian pedestrian);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.PeopleRideBicyc;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Mapper
public interface PeopleridebicycMapper {
int insertPeopleRideBicyc( PeopleRideBicyc peopleridebicyc);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.PictureTime;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
......@@ -32,15 +28,7 @@ public interface QuartzTaskInformationsMapper {
List<QuartzTaskInformations> getUnfrozenTasks(String status);
int insertRecord(PatrolCtrlRecord record);
int insertAlarm(PatrolCtrlAlarm alarm);
List<PictureTime> findLastPicTime();
List< PatrolCtrlRecord> queryCameraCode(List<String> ids);
List<Sbtdspsr> selectByRtsp(String rtsp);
Integer UpdateExecuteParam(Map map);
......
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
@Mapper
public interface SbtdspsrMapper {
List<Sbtdspsr> selectByRtsp( String rtsp);
List<Sbtdspsr> list( );
List<QuartzTaskInformations> selectRecogByRtsp(String rtsp);
int updateRecogByRtsp(Map map);
}
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.Storageserver;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface StorageServerMapper {
List<Storageserver> queryStorageServerAll(Storageserver storageServer);
}
\ No newline at end of file
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.TraffAlarmRecord;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import java.util.List;
import java.util.Map;
@Mapper
public interface TraffAlarmRecordMapper {
int inserTraffAlarmRecord(TraffAlarmRecord traffalarmrecord);
int selectmax();
int updateTraffAlarmRecordUrl(TraffAlarmRecord traffalarmrecord);
List<TraffAlarmRecord> getTraffAlarmRecordByProgress(Map<String, Object> map);
int updateTraffAlarmRecordProcess(TraffAlarmRecord traffalarmrecord);
}
\ No newline at end of file
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.TraffpictureParam;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface TraffPictureMapper {
int inserTraffpicture(TraffpictureParam traffalarmrecord);
int updateTraffpicture(TraffpictureParam traffalarmrecord);
String queryimgpath(TraffpictureParam traffpicture);
String queryimgdataByid(String id);
int updateTraffpicturePushStatus(TraffpictureParam traffpicture );
}
\ No newline at end of file
package com.cx.cn.cxquartz.dao;
import com.cx.cn.cxquartz.vo.Traffic;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wjj
* @since 2021-04-29
*/@Mapper
public interface TrafficMapper {
int insertTraffic(Traffic traffic);
}
package com.cx.cn.cxquartz.job;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class KafkaListener {
@Autowired
private QuartzService quartzService;
private static final Logger logger = LoggerFactory.getLogger(KafkaListener.class);
private AtomicInteger atomicInteger;
public void messageConsumerHandler(String content) {
logger.info("监听到消息:{}", content);
atomicInteger = new AtomicInteger(0);
String id = "";
String taskNo = "";
try {
// message格式 ---------> taskNo:id:executeParameter;
String[] split = ":".split(content);
id = split[1];
taskNo = split[0];
//TODO kafka逻辑
} catch (Exception ex) {
logger.error("");
atomicInteger.incrementAndGet();
quartzService.addTaskErrorRecord(id, taskNo + ":" + ex.getMessage(), CommonUtil.getExceptionDetail(ex));
}
quartzService.updateRecordById(atomicInteger.get(), Long.parseLong(id));
QuartzTaskInformations quartzTaskInformation = new QuartzTaskInformations();
quartzTaskInformation.setId(Long.parseLong(id));
quartzTaskInformation.setLastmodifytime(System.currentTimeMillis());
quartzService.updateTask(quartzTaskInformation);
}
}
package com.cx.cn.cxquartz.job;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.bean.QuartzTaskRecords;
import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.impl.QuartzServiceImpl;
import com.cx.cn.cxquartz.redis.QueueSender;
import com.cx.cn.cxquartz.util.ApplicationContextHolder;
import com.cx.cn.cxquartz.util.CommonUtil;
import com.cx.cn.cxquartz.util.HttpClientUtil;
import com.cx.cn.cxquartz.util.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -27,54 +20,61 @@ public class QuartzMainJobFactory implements Job {
private String czurl;
@Value("${local.fxurl}")
private String fxurl;
// @Autowired
// private QueueSender queueSender;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
atomicInteger = new AtomicInteger(0);
JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
String id = jobDataMap.getString("id");
String taskNo = jobDataMap.getString("taskNo");
String executorNo = jobDataMap.getString("executorNo");
String url = jobDataMap.getString("url");
String executeParameter = jobDataMap.getString("executeParameter");
logger.info("定时任务被执行:taskNo={},executorNo={},url={},executeParameter={}", taskNo, executorNo, url, executeParameter);
QuartzService quartzService = (QuartzServiceImpl) ApplicationContextHolder.getBean("quartzServiceImpl");
QuartzTaskRecords records = null;
QueueSender qeueSender = (QueueSender) ApplicationContextHolder.getBean("queueSender");
try {
//保存定时任务的执行记录
records = quartzService.addTaskRecords(taskNo);
if (null == records || !ResultEnum.INIT.name().equals(records.getTaskstatus())) {
logger.info("taskNo={}保存执行记录失败", taskNo);
return;
}
//if (ResultEnum.HTTP.getMessage().equals(sendType)) {
try {
String result = HttpClientUtil.doPost(taskNo.contains("cz_") ? czurl : fxurl, "text/json", executeParameter);
logger.info("taskNo={},执行结果result{}", taskNo, result);
if (StringUtils.isEmpty(result)) {
throw new RuntimeException("taskNo=" + taskNo + "http方式返回null");
}
} catch (Exception ex) {
logger.error("");
throw ex;
}
// } else if (ResultEnum.KAFKA.getMessage().equals(sendType)) {
//根据事件类型进行通道分配
qeueSender.sendMsg("taskinfo", jobDataMap.get("taskinfo"));
}catch (Exception ex){
logger.error("Scheduler executing error:{}",ex);
}
// String taskNo = jobDataMap.getString("taskNo"); String executorNo = jobDataMap.getString("executorNo");
// String url = jobDataMap.getString("url");
// String executeParameter = jobDataMap.getString("executeParameter");
// logger.info("定时任务被执行:taskNo={},executorNo={},url={},executeParameter={}", taskNo, executorNo, url, executeParameter);
// QuartzService quartzService = (QuartzServiceImpl) ApplicationContextHolder.getBean("quartzServiceImpl");
// QuartzTaskRecords records = null;
// try {
// //保存定时任务的执行记录
// records = quartzService.addTaskRecords(taskNo);
// if (null == records || !ResultEnum.INIT.name().equals(records.getTaskstatus())) {
// logger.info("taskNo={}保存执行记录失败", taskNo);
// return;
// }
//
// //if (ResultEnum.HTTP.getMessage().equals(sendType)) {
// try {
// String message = new StringBuffer(taskNo).append(":").append(id).append(":").append(executeParameter).toString();
// quartzService.sendMessage(message);
// logger.info("taskNo={},sendtype={}推送至kafka成功", taskNo, sendType);
// String result = HttpClientUtil.doPost(taskNo.contains("cz_") ? czurl : fxurl, "text/json", executeParameter);
// logger.info("taskNo={},执行结果result{}", taskNo, result);
// if (StringUtils.isEmpty(result)) {
// throw new RuntimeException("taskNo=" + taskNo + "http方式返回null");
// }
// } catch (Exception ex) {
// logger.error("");
// throw ex;
// }
// }
} catch (Exception ex) {
String exception=CommonUtil.getExceptionDetail(ex);
logger.error(exception);
atomicInteger.incrementAndGet();
quartzService.addTaskErrorRecord(records.getId().toString(), taskNo + ":" + ex.getMessage(), exception);
}
//// } else if (ResultEnum.KAFKA.getMessage().equals(sendType)) {
//// try {
//// String message = new StringBuffer(taskNo).append(":").append(id).append(":").append(executeParameter).toString();
//// quartzService.sendMessage(message);
//// logger.info("taskNo={},sendtype={}推送至kafka成功", taskNo, sendType);
//// } catch (Exception ex) {
//// logger.error("");
//// throw ex;
//// }
//// }
// } catch (Exception ex) {
// String exception=CommonUtil.getExceptionDetail(ex);
// logger.error(exception);
// atomicInteger.incrementAndGet();
// quartzService.addTaskErrorRecord(records.getId().toString(), taskNo + ":" + ex.getMessage(), exception);
// }
// quartzService.updateRecordById(atomicInteger.get(), records.getId());
//QuartzTaskInformations quartzTaskInformation = new QuartzTaskInformations();
//quartzTaskInformation.setId(Long.parseLong(id));
......
package com.cx.cn.cxquartz.job;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
......@@ -12,7 +14,7 @@ import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/websocket/{name}")
public class WebSocket {
private static final Logger logger = LoggerFactory.getLogger(WebSocket.class);
/**
* 与某个客户端的连接对话,需要通过它来给客户端发送消息
*/
......@@ -64,7 +66,7 @@ public class WebSocket {
AppointSending(name, new ObjectMapper().writeValueAsString(map));
}catch (Exception ex)
{
ex.printStackTrace();
logger.error("websocket->OnMessage eror:{}",ex.toString());
}
}
}
......@@ -80,7 +82,7 @@ public class WebSocket {
if (null != webSocketSet.get(name) && null != webSocketSet.get(name).session && null != webSocketSet.get(name).session.getBasicRemote())
webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
logger.error("websocket->GroupSending eror:{}",e.toString());
}
}
}
......@@ -99,7 +101,7 @@ public class WebSocket {
webSocketSet.get(name).session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
logger.error("websocket->AppointSending eror:{}",e.toString());
}
}
}
......
package com.cx.cn.cxquartz.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class OrderProducer implements Producer {
public static final Logger log = LoggerFactory.getLogger(OrderProducer.class);
@Autowired
private RedisTemplate redisTemplate;
public OrderProducer(){
}
@Override
public void produce(String queue,Object message) {
redisTemplate.opsForList().leftPush(queue,message);//消息左入
log.info("添加消息到队列:{}",message.toString());
}
}
package com.cx.cn.cxquartz.redis;
public interface Producer {
void produce(String queue,Object message);
}
package com.cx.cn.cxquartz.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class QueueSender {
@Autowired
private RedisTemplate redisTemplate;
public QueueSender(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void sendMsg(String queue, Object msg) {
redisTemplate.opsForList().leftPush(queue, msg);
}
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.dao.StorageServerMapper;
import com.cx.cn.cxquartz.vo.Storageserver;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class CacheLoadService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Value("${redis.cachekey.ftplist}")
private String ftplistkey;
@Autowired
private StorageServerMapper storageServerMapper;
public boolean loadFtpCache() {
try {
Storageserver server = new Storageserver();
server.setServerstatus(0);//�����õ�
server.setServertype("ftp");
List<Storageserver> storageServers = storageServerMapper.queryStorageServerAll(server);
if (!storageServers.isEmpty() && storageServers.size() > 0) {
stringRedisTemplate.opsForValue().set(ftplistkey, new Gson().toJson(storageServers),60, TimeUnit.SECONDS);
} else {
System.out.println("storageServers.isEmpty");
}
return true;
} catch (Exception e) {
System.out.println(e.toString());
return false;
}
}
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.Code;
/**
* <p>
* 服务类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
public interface CodeService {
Code selectalarmNum(String keyid);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.*;
public interface ExtService {
int insertRecord(PatrolCtrlRecord record);
int insertAlarm(PatrolCtrlAlarm alarm);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.Face;
/**
* <p>
* 服务类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
public interface FaceService {
int insertFace(Face face);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.util.RedisEnum;
import com.cx.cn.cxquartz.vo.Ftp;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class FtpService {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(FtpService.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
private List<Ftp> ftpList;
@Autowired
CacheLoadService cacheLoadService;
@Autowired
public FtpService(StringRedisTemplate stringRedisTemplate) {
// try {
// this.ftpList = getFtpList(stringRedisTemplate.opsForValue().get(RedisEnum.FTPLIST.getValue()));
// }catch (Exception e){
// logger.error("ftpList error:"+e.toString());
// }
}
public Ftp reloadFtp() {
try {
// cacheLoadService.loadFtpCache();
if(null==stringRedisTemplate.opsForValue().get(RedisEnum.FTPLIST.getValue())){
cacheLoadService.loadFtpCache();
}
ftpList = getFtpList(stringRedisTemplate.opsForValue().get(RedisEnum.FTPLIST.getValue()));
}catch (Exception e){
logger.error("ftpListerror:"+e.toString());
}
Long count = null;
try {
count = stringRedisTemplate.opsForValue().increment(RedisEnum.FTPLIST_INDEX.getValue(), 1L);
} catch (Exception e) {
logger.error("redis error" + e.toString());
}
if (count == null) {
count = 0L;
}
long index = count % ftpList.size();
return ftpList.get((int) index);
}
private List<Ftp> getFtpList(String ftpJson) {
try {
JavaType javaType =OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, Map.class);
List<Map> jsonArr = OBJECT_MAPPER.readValue(ftpJson, javaType);
List<Ftp> ftpList = new ArrayList<>();
for (int i = 0; i < jsonArr.size(); i++) {
Ftp ftp = new Ftp();
Map jsonObject = jsonArr.get(i);
ftp.setFtpIp(jsonObject.get("serveip").toString());
ftp.setFtpPort(Integer.parseInt(jsonObject.get("serverport")==null?"21":jsonObject.get("serverport").toString()));
ftp.setFtpUsername(jsonObject.get("serveruser").toString());
ftp.setFtpPassword(jsonObject.get("serverpassword").toString());
ftpList.add(ftp);
}
}catch (Exception ex){
logger.error("ftpListerror:"+ex.toString());
}
return ftpList;
}
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.Pedestrian;
/**
* <p>
* 服务类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
public interface PedestrianService {
int insertpedestrian(Pedestrian pedestrian);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.PeopleRideBicyc;
/**
* <p>
* 服务类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
public interface PeopleridebicycService {
int insertPeopleRideBicyc( PeopleRideBicyc peopleridebicyc);
}
......@@ -41,14 +41,6 @@ public interface QuartzService {
QuartzTaskErrors detailTaskErrors(String recordId);
Integer insertRecord(PatrolCtrlRecord record);
Integer insertAlarm(PatrolCtrlAlarm alarm);
List<PictureTime> findLastPicTime();
List< PatrolCtrlRecord> queryCameraCode(List<String> ids);
List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode);
Integer deletetask(String taskno);
......
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.PictureTime;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import java.util.List;
......@@ -28,13 +25,6 @@ public interface QuartzTaskInformationsService {
Integer updateModifyTimeById(QuartzTaskInformations quartzTaskInformations);
Integer insertRecord(PatrolCtrlRecord record);
Integer insertAlarm(PatrolCtrlAlarm alarm);
List<PictureTime> findLastPicTime();
List< PatrolCtrlRecord> queryCameraCode(List<String> ids);
List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode);
Integer deletetask(String taskno);
......
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import java.util.List;
import java.util.Map;
public interface SbtdspsrService {
List<Sbtdspsr> selectByRtsp(String videoid);
List<QuartzTaskInformations> selectRecogByRtsp(String rtsp);
int updateRecogByRtsp(String rtsp,String devicecode);
List<Sbtdspsr> list();
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.TraffAlarmRecord;
import java.util.List;
import java.util.Map;
public interface TraffAlarmRecordService {
int inserTraffAlarmRecord(TraffAlarmRecord traffalarmrecord);
int selectmax();
int updateTraffAlarmRecordUrl(TraffAlarmRecord record);
int updateTraffAlarmRecordProcess(TraffAlarmRecord recordid);
List<TraffAlarmRecord> getTraffAlarmRecordByProgress(Map<String, Object> map);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.TraffpictureParam;
public interface TraffPictureService {
int inserTraffpicture( TraffpictureParam traffpicture);
int updateTraffpicture( TraffpictureParam traffpicture);
String queryimgpath(TraffpictureParam traffpicture);
String queryimgdataByid(String id);
}
package com.cx.cn.cxquartz.service.quartz;
import com.cx.cn.cxquartz.vo.Traffic;
/**
* <p>
* 服务类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
public interface TrafficService {
int insertTraffic(Traffic traffic);
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.CodeMapper;
import com.cx.cn.cxquartz.service.quartz.CodeService;
import com.cx.cn.cxquartz.vo.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Service
public class CodeServiceImpl implements CodeService {
@Autowired
private CodeMapper codeMapper;
@Override
public Code selectalarmNum(String keyid) {
return codeMapper.selectalarmNum(keyid);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.service.quartz.ExtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExtServiceImpl implements ExtService {
private static final Logger logger = LoggerFactory.getLogger(ExtServiceImpl.class);
@Autowired
private ExtService extService;
@Override
public int insertAlarm(PatrolCtrlAlarm alarm) {
int result = extService.insertAlarm(alarm);
return result;
}
/**
* 新增图片
*
* @param record
* @returnString
*/
@Override
public int insertRecord(PatrolCtrlRecord record) {
int result = extService.insertRecord(record);
return result;
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.FaceMapper;
import com.cx.cn.cxquartz.service.quartz.FaceService;
import com.cx.cn.cxquartz.vo.Face;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Service
public class FaceServiceImpl implements FaceService {
@Autowired
private FaceMapper faceMapper;
@Override
public int insertFace(Face face) {
return faceMapper.insertFace(face);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.PedestrianMapper;
import com.cx.cn.cxquartz.service.quartz.PedestrianService;
import com.cx.cn.cxquartz.vo.Pedestrian;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Service
public class PedestrianServiceImpl implements PedestrianService {
@Autowired
private PedestrianMapper pedestrianMapper;
@Override
public int insertpedestrian(Pedestrian pedestrian) {
return pedestrianMapper.insertpedestrian(pedestrian);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.PeopleridebicycMapper;
import com.cx.cn.cxquartz.service.quartz.PeopleridebicycService;
import com.cx.cn.cxquartz.vo.PeopleRideBicyc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Service
public class PeopleridebicycServiceImpl implements PeopleridebicycService {
@Autowired
private PeopleridebicycMapper peopleridebicycMapper;
@Override
public int insertPeopleRideBicyc(PeopleRideBicyc peopleridebicyc) {
return peopleridebicycMapper.insertPeopleRideBicyc( peopleridebicyc);
}
}
......@@ -7,8 +7,6 @@ import com.cx.cn.cxquartz.service.quartz.QuartzService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskErrorsService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskInformationsService;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskRecordsService;
import com.cx.cn.cxquartz.util.CommonUtil;
import com.cx.cn.cxquartz.util.HttpClientUtil;
import com.cx.cn.cxquartz.util.ResultEnum;
import com.cx.cn.cxquartz.util.ResultUtil;
import com.cx.cn.cxquartz.vo.QuartzTaskRecordsVo;
......@@ -55,10 +53,7 @@ public class QuartzServiceImpl implements QuartzService, InitializingBean {
@Autowired
private SchedulerFactoryBean schedulerBean;
@Value("${local.czurl}")
private String czurl;
@Value("${local.fxurl}")
private String fxurl;
/**
* 列表查询所有定时任务
*
......@@ -179,6 +174,9 @@ public class QuartzServiceImpl implements QuartzService, InitializingBean {
*/
@Override
public void initLoadOnlineTasks() {
//判断是否是分发任务的配置
List<QuartzTaskInformations> unnfrozenTasks = quartzTaskInformationsService.getUnnfrozenTasks(ResultEnum.UNFROZEN.name());
if (CollectionUtils.isEmpty(unnfrozenTasks)) {
logger.info("没有需要初始化加载的定时任务");
......@@ -201,7 +199,7 @@ public class QuartzServiceImpl implements QuartzService, InitializingBean {
*/
@Override
public void afterPropertiesSet() throws Exception {
this.initLoadOnlineTasks();
this.initLoadOnlineTasks();
}
@Override
......@@ -272,16 +270,16 @@ public class QuartzServiceImpl implements QuartzService, InitializingBean {
TriggerKey triggerKey = TriggerKey.triggerKey(quartzTaskInfo.getTaskno(), Scheduler.DEFAULT_GROUP);
JobDetail jobDetail = JobBuilder.newJob(QuartzMainJobFactory.class).withDescription(quartzTaskInfo.getTaskname()).withIdentity(quartzTaskInfo.getTaskno(), Scheduler.DEFAULT_GROUP).build();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("id", quartzTaskInfo.getId().toString());
jobDataMap.put("taskNo", quartzTaskInfo.getTaskno());
jobDataMap.put("executorNo", quartzTaskInfo.getExecutorno());
jobDataMap.put("sendType", quartzTaskInfo.getSendtype());
jobDataMap.put("url", quartzTaskInfo.getUrl());
jobDataMap.put("executeParameter", quartzTaskInfo.getExecuteparamter());
jobDataMap.put("taskinfo", quartzTaskInfo);
// jobDataMap.put("taskNo", quartzTaskInfo.getTaskno());
// jobDataMap.put("executorNo", quartzTaskInfo.getExecutorno());
//// jobDataMap.put("sendType", quartzTaskInfo.getSendtype());
// jobDataMap.put("url", quartzTaskInfo.getUrl());
// jobDataMap.put("executeParameter", quartzTaskInfo.getExecuteparamter());
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzTaskInfo.getSchedulerrule());
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withDescription(quartzTaskInfo.getTaskname()).withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build();
scheduler.scheduleJob(jobDetail, cronTrigger);
logger.info("taskNo={},taskName={},scheduleRule={} load to quartz success!", quartzTaskInfo.getTaskno(), quartzTaskInfo.getTaskname(), quartzTaskInfo.getSchedulerrule());
// logger.info("taskNo={},taskName={},scheduleRule={} load to quartz success!", quartzTaskInfo.getTaskno(), quartzTaskInfo.getTaskname(), quartzTaskInfo.getSchedulerrule());
}
/**
......@@ -309,95 +307,17 @@ public class QuartzServiceImpl implements QuartzService, InitializingBean {
return voList;
}
/**
* 立即运行一次定时任务
*
* @param taskNo
* @return
*/
@Override
public String runTaskRightNow(String taskNo) {
atomicInteger = new AtomicInteger(0);
QuartzTaskInformations quartzTaskInformations = quartzTaskInformationsService.getTaskByTaskNo(taskNo);
if (quartzTaskInformations == null) {
return ResultUtil.success(ResultEnum.NO_DATA.getCode(), ResultEnum.NO_DATA.getMessage());
}
// Long id = quartzTaskInformations.getId();
//String sendType = quartzTaskInformations.getSendtype();
//String executorNo = quartzTaskInformations.getExecutorno();
// String url = quartzTaskInformations.getUrl();
String executeParameter = quartzTaskInformations.getExecuteparamter();
// logger.info("定时任务被执行:taskNo={},executorNo={},sendType={},url={},executeParameter={}", taskNo, executorNo, sendType, url, executeParameter);
QuartzTaskRecords records = null;
try {
//保存定时任务的执行记录
//records = this.addTaskRecords(taskNo);
if (null == records || !ResultEnum.INIT.name().equals(records.getTaskstatus())) {
logger.info("taskNo={}立即运行失--->>保存执行记录失败", taskNo);
return ResultUtil.success(ResultEnum.RUN_NOW_FAIL.getCode(), ResultEnum.RUN_NOW_FAIL.getMessage());
}
// if (ResultEnum.HTTP.getMessage().equals(sendType)) {
try {
HttpClientUtil.doPost(taskNo.contains("cz_") ? czurl : fxurl, "text/json", executeParameter);
logger.info("");
} catch (Exception ex) {
logger.error("");
atomicInteger.incrementAndGet();
throw ex;
}
// } else if (ResultEnum.KAFKA.getMessage().equals(sendType)) {
// try {
// String message = new StringBuffer(taskNo).append(":").append(executeParameter).toString();
// this.sendMessage(message);
// } catch (Exception ex) {
// logger.error("");
// atomicInteger.incrementAndGet();
// throw ex;
// }
// }
} catch (Exception ex) {
logger.error("");
atomicInteger.incrementAndGet();
this.addTaskErrorRecord(records.getId().toString(), taskNo + ":" + ex.getMessage(), CommonUtil.getExceptionDetail(ex));
}
//更改record表的执行状态、最后修改时间、失败个数
// this.updateRecordById(atomicInteger.get(), records.getId());
//更新taskinfo表的最后修改时间
// QuartzTaskInformations quartzTaskInformation = new QuartzTaskInformations();
// quartzTaskInformation.setId(id);
//quartzTaskInformation.setLastmodifytime(System.currentTimeMillis());
// this.updateTask(quartzTaskInformation);
return ResultUtil.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
return null;
}
@Override
public QuartzTaskErrors detailTaskErrors(String recordId) {
return quartzTaskErrorsService.detailTaskErrors(recordId);
}
@Override
public Integer insertRecord(PatrolCtrlRecord record) {
return quartzTaskInformationsService.insertRecord(record);
}
@Override
public Integer insertAlarm(PatrolCtrlAlarm alarm) {
return quartzTaskInformationsService.insertAlarm(alarm);
}
@Override
public List<PictureTime> findLastPicTime() {
return quartzTaskInformationsService.findLastPicTime();
}
@Override
public List< PatrolCtrlRecord> queryCameraCode(List<String> ids){
return quartzTaskInformationsService.queryCameraCode(ids);
}
@Override
public List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode) {
return quartzTaskInformationsService.getTaskSByDeviceCode(devicecode);
......
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.PatrolCtrlAlarm;
import com.cx.cn.cxquartz.bean.PatrolCtrlRecord;
import com.cx.cn.cxquartz.bean.PictureTime;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.dao.QuartzTaskInformationsMapper;
import com.cx.cn.cxquartz.service.quartz.QuartzTaskInformationsService;
......@@ -101,26 +98,6 @@ public class QuartzTaskInformationsServiceImpl implements QuartzTaskInformations
return quartzTaskInformationsMapper.updateByPrimaryKeySelective(quartzTaskInformations);
}
@Override
public Integer insertRecord(PatrolCtrlRecord record) {
return quartzTaskInformationsMapper.insertRecord(record);
}
@Override
public Integer insertAlarm(PatrolCtrlAlarm alarm) {
return quartzTaskInformationsMapper.insertAlarm(alarm);
}
@Override
public List<PictureTime> findLastPicTime() {
return quartzTaskInformationsMapper.findLastPicTime();
}
@Override
public List<PatrolCtrlRecord> queryCameraCode(List<String> ids){
return quartzTaskInformationsMapper.queryCameraCode(ids);
}
@Override
public List<QuartzTaskInformations> getTaskSByDeviceCode(String devicecode) {
......
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.bean.QuartzTaskInformations;
import com.cx.cn.cxquartz.dao.SbtdspsrMapper;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.vo.Sbtdspsr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SbtdspsrImpl implements SbtdspsrService {
@Autowired
private SbtdspsrMapper sbtdspsrMapper;
public List<Sbtdspsr> selectByRtsp(String videoid)
{
return sbtdspsrMapper.selectByRtsp(videoid);
}
@Override
public List<QuartzTaskInformations> selectRecogByRtsp(String rtsp) {
return sbtdspsrMapper.selectRecogByRtsp(rtsp);
}
@Override
public int updateRecogByRtsp(String rtsp, String devicecode) {
Map map =new HashMap();
map.put("rtsp",rtsp);
map.put("devicecode",devicecode);
return sbtdspsrMapper.updateRecogByRtsp(map);
}
@Override
public List<Sbtdspsr> list() {
return sbtdspsrMapper.list();
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class TokenCacheService {
private static final Logger log = LoggerFactory.getLogger(TokenCacheService.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Value("${countryside.eventwrite.token}")
private String qztoken;
@Value("${countryside.eventwrite.expiretoken}")
private String expiretoken;
@Value("${countryside.appid}")
private String appid;
@Value("${countryside.appsecret}")
private String appsecret;
@Value("${countryside.tokenurl}")
private String tokenurl;
public String keepAlive() {
try {
String tokencache = stringRedisTemplate.opsForValue().get(qztoken);
if (tokencache != null) {
//判断是否过期
String datetime=stringRedisTemplate.opsForValue().get(expiretoken);
if( null!=datetime){
//预留1分钟过期时间
Long expireminiseconds =Long.parseLong(datetime);
if(new Date().getTime()<expireminiseconds)
{
return tokencache;
}
}
return loginServer();
} else {
return loginServer();
}
} catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
private String loginServer() {
HttpHeaders headers = getHttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
RestTemplate client = new RestTemplate();
ResponseEntity<String> response = client.getForEntity((tokenurl+"?appid="+appid+"&appsecret="+appsecret),String.class);
return getTokenData(response);
}
private HttpHeaders getHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return headers;
}
private String getTokenData(ResponseEntity<String> response){
try {
if (response != null && response.getBody() != null && response.getBody().contains("code")) {
String ret = response.getBody();
Map map= new ObjectMapper().readValue(ret,Map.class);
if ( null !=map && null!=map.get("obj") &&("0").equals(map.get("code"))) {
Map object= new ObjectMapper().readValue(map.get("obj").toString(),Map.class);
if(null!=object && null!=object.get("accessToken")) {
Long time=Long.parseLong(object.get("expire").toString())-new Date().getTime();
stringRedisTemplate.opsForValue().set(expiretoken,time.toString(),time,TimeUnit.MILLISECONDS);
stringRedisTemplate.opsForValue().set(qztoken, String.valueOf(object.get("accessToken")), time,TimeUnit.MILLISECONDS);
return String.valueOf(object.get("accessToken"));
}
} else {
log.error("getTokenData error :" + response.getBody());
}
} else {
log.error("getTokenData empty...");
}
}catch (Exception e){
System.out.println(e.toString());
log.error(e.getMessage());
}
return null;
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.TraffAlarmRecordMapper;
import com.cx.cn.cxquartz.service.quartz.TraffAlarmRecordService;
import com.cx.cn.cxquartz.vo.TraffAlarmRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class TraffAlarmRecordImpl implements TraffAlarmRecordService {
@Autowired
private TraffAlarmRecordMapper traffAlarmRecordMapper;
public int inserTraffAlarmRecord(TraffAlarmRecord traffalarmrecord){
return traffAlarmRecordMapper.inserTraffAlarmRecord(traffalarmrecord);
}
public int selectmax(){
return traffAlarmRecordMapper.selectmax();
}
public int updateTraffAlarmRecordUrl(TraffAlarmRecord record){
return traffAlarmRecordMapper.updateTraffAlarmRecordUrl(record);
}
public int updateTraffAlarmRecordProcess(TraffAlarmRecord traffalarmrecord){
return traffAlarmRecordMapper.updateTraffAlarmRecordProcess(traffalarmrecord);
}
public List<TraffAlarmRecord> getTraffAlarmRecordByProgress(Map<String, Object> map){
return traffAlarmRecordMapper.getTraffAlarmRecordByProgress( map);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.TrafficMapper;
import com.cx.cn.cxquartz.service.quartz.TrafficService;
import com.cx.cn.cxquartz.vo.Traffic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Service
public class TrafficServiceImpl implements TrafficService {
@Autowired
TrafficMapper trafficMapper;
@Override
public int insertTraffic(Traffic traffic) {
return trafficMapper.insertTraffic(traffic);
}
}
package com.cx.cn.cxquartz.service.quartz.impl;
import com.cx.cn.cxquartz.dao.TraffPictureMapper;
import com.cx.cn.cxquartz.service.quartz.TraffPictureService;
import com.cx.cn.cxquartz.vo.TraffpictureParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author wjj
* @since 2021-04-29
*/
@Service
public class TraffpictureServiceImpl implements TraffPictureService {
@Autowired
private TraffPictureMapper traffPictureMapper;
@Override
public int inserTraffpicture(TraffpictureParam traffpicture) {
return traffPictureMapper.inserTraffpicture(traffpicture);
}
@Override
public int updateTraffpicture(TraffpictureParam traffpicture) {
return traffPictureMapper.updateTraffpicture(traffpicture);
}
@Override
public String queryimgpath(TraffpictureParam traffpicture) {
return traffPictureMapper.queryimgpath(traffpicture);
}
@Override
public String queryimgdataByid(String id) {
return traffPictureMapper.queryimgdataByid(id);
}
}
package com.cx.cn.cxquartz.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class AdminInterceptor implements HandlerInterceptor {
/**
......
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.bean.PictureTime;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
public class CommonUtil {
/**
* 获取具体的异常信息
*
* @param ex
* @return
*/
public static String getExceptionDetail(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
ex.printStackTrace(pw);
return sw.toString();
} finally {
pw.close();
}
}
public static void removeFinishFiles( List<File> jsonFile, List<PictureTime> picturses)
{
if (picturses.size() > 0) {
//根据每个设备最新的时间进行过滤D:\imp\VideoPic\202009021049435991_0\20200906\112004.jpeg
String filetime = "";
for (int i = 0; i < jsonFile.size(); i++) {
String[] str = jsonFile.get(i).getAbsolutePath().split("\\\\");
for (PictureTime pic : picturses) {
filetime = str[str.length - 2] + str[str.length - 1].replace(".jpeg", "");
if (str[str.length - 3].equals(pic.getDeviceid())
&& pic.getLasttime().compareTo(filetime) != -1) {
jsonFile.remove(i--);
}
}
}
}
}
}
......@@ -23,6 +23,7 @@ public class DateUtils {
return formatCurrDateByType(YMDHMS);
}
public static String formatCurrDateYMD(){
return formatCurrDateByType(Y_M_D);
}
......@@ -45,6 +46,14 @@ public class DateUtils {
return DateTime.parse(date,YMDHMS).toDate();
}
public static String parseDateToStrNoSign(String date){
return DateTime.parse(date,YMD_HMS).toString(YMDHMS);
}
public static String parseDateToStrNoSign(Date date){
return new DateTime(date).toString(YMDHMS);
}
public static String getYesterday(int day){
Date date= addDay(new Date(),day);
return new DateTime(date).toString(YMD_HMS);
......
This diff is collapsed.
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.controller.ExtController;
import com.cx.cn.cxquartz.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.TimeUnit;
public class FileTransferManager {
private static CompletionService<String> completionService = new ExecutorCompletionService<String>(ThreadPoolUtil.getPool());
private static CompletionService<String> threadService = new ExecutorCompletionService<String>(ThreadPoolUtil.getPool());
private static final Logger log = LoggerFactory.getLogger(ExtController.class);
/**
* @param ftp
* @param basePath
* @return
* @throws Exception
*/
public static void transferFile(final TraffAlarmRecord traffAlarmRecord, final Ftp ftp, final String basePath) throws Exception {
final Long recordid = traffAlarmRecord.getRecordid();
String fileName = DateUtils.formatCurrDayNoSign() + "_" + recordid + "_img1.jpg";
String ftputl = FTPUtil.getFtpUrl(ftp) + basePath + "/" + fileName;
traffAlarmRecord.setImg1path(ftputl);
completionService.submit(() -> {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(traffAlarmRecord.getImg1urlfrom()).openConnection();
connection.setReadTimeout(2000); //延迟连接
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
InputStream inputStream = connection.getInputStream();
boolean r = FTPUtil.uploadFile(ftp, basePath, fileName, inputStream);
if (r) {
log.info(" ftpupload success:{}", ftputl);
}
} else {
log.error("connection code: " + connection.getResponseCode());
}
} catch (IOException e) {
log.error("ftputl connection error:{}", e.toString());
return "0";
}
return "1";
}
);
}
public static void fetchUrlsFromRecord(TraffAlarmRecord record, Map<String, Object> transferRecord) {
if (record == null || record.getRecordid() == null) {
return;
}
transferRecord.put("recordid", record.getRecordid());
if (record.getImg1path() == null && record.getImg1urlfrom() != null) {
transferRecord.put("img1path", record.getImg1urlfrom());
}
}
public static TraffAlarmRecord traffAlarmRecordUrlUpdate(List<TransferResult> results) throws Exception {
TraffAlarmRecord record = new TraffAlarmRecord();
for (TransferResult result : results) {
record.setRecordid(result.getRecordid());
if (result.getResult()) {
switch (result.getPathvalue()) {
case "img1path":
record.setImg1path(result.getImgpath());
break;
case "videopath":
record.setVideopath(result.getImgpath());
break;
default:
break;
}
}
}
return record;
}
// public static GoalStructureParam getGoalStructureParam(Long[] roiarray, int model, BASE64Encoder base64Encoder, TraffAlarmRecord transferRecord) {
// //获得图片进行分析
// GoalStructureParam param = new GoalStructureParam();
// param.setOutput(new Output(1));
// param.setModel(model);
// param.setApiout("1");////打开1400标准输出,默认可以不填
// List<ImageList> list = new ArrayList<>();
// getImageList("1", roiarray, base64Encoder, list, transferRecord.getImg1path());
// param.setImageList(list);
// return param;
//
// }
public static GoalStructureParam getGoalStructureParam(Long[] roiarray, int model,int format, TraffAlarmRecord transferRecord) {
//获得图片进行分析
GoalStructureParam param = new GoalStructureParam();
Map outmap=new HashMap();
outmap.put("SubClass",1);
param.setOutput(outmap);
param.setModel(model);
param.setApiout("1");////打开1400标准输出,默认可以不填
List<Map> list = new ArrayList<>();
Map imgmap=new HashMap();
imgmap.put("ImageID","1");
imgmap.put("Roi",roiarray);
imgmap.put("apiout","1");
imgmap.put("Format",format);
imgmap.put("Data",transferRecord.getImg1path());
imgmap.put("RoiPadding",0);
imgmap.put("CropObjectImage",1);
imgmap.put("CropObjectImagePadding",20);
imgmap.put("CropObjectImageQuality",100);
list.add(imgmap);
// new ImageList("1", roiarray, format,10, 1, 20, 100, transferRecord.getImg1urlfrom())
// getImageList("1", roiarray,format, list, transferRecord.getImg1urlfrom());
param.setImageList(list);
return param;
}
// private static void getImageList(String id, Long[] roiarray, BASE64Encoder base64Encoder, List<ImageList> list, String img1path) {
// if (null != img1path && !"".equals(img1path)) {
//
// byte[] Img = FTPUtil.getFtpPicBytes(img1path);
// if (Img != null) {
// list.add(new ImageList(id, roiarray, 10, 1, 20, 100, base64Encoder.encode(Img).replaceAll("\r|\n", "")));
//
// }
// }
// }
public static String urlTransToFtp(String url, final Ftp ftp, final String basePath) {
threadService.submit(() -> {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(2000); //延迟连接
connection.setConnectTimeout(3000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
InputStream inputStream = connection.getInputStream();
String pname = DateUtils.formatCurrDayNoSign() + ".jpg";
String ftputl = FTPUtil.getFtpUrl(ftp) + basePath + pname;
boolean r = FTPUtil.uploadFile(ftp, basePath, pname, inputStream);
if (r) {
return ftputl;
}
} else {
log.error("connection code: " + connection.getResponseCode());
}
} catch (IOException e) {
System.out.println(e.toString());
log.error(e.toString());
}
return url;
});
try {
return threadService.poll(10, TimeUnit.SECONDS).get();
} catch (Exception ex) {
return url;
}
}
}
package com.cx.cn.cxquartz.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
public static File uploadToLocal(String path,ByteArrayOutputStream bout, String fileName) {
logger.info("file upload :{}",path+fileName);
DataOutputStream to=null;
try {
File tempFile = new File(path);
if (!tempFile.exists()) {
tempFile.mkdirs();
}
File file= new File(tempFile.getPath() + File.separator + fileName);
if (!file.exists()) {
file.createNewFile();
}
to=new DataOutputStream(new FileOutputStream(file));
bout.writeTo(to);
return file;
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
return null;
} catch (Exception e) {
logger.error(e.toString());
e.printStackTrace();
return null;
} finally {
try {
if(null!=bout)
bout.close();
if(null!=to){
to.close();
}
} catch (IOException e) {
logger.error(e.toString());
e.printStackTrace();
}
}
}
}
package com.cx.cn.cxquartz.util;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtil {
private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
private static final String ENCODING = "UTF-8";
private static final int CONNECTION_TIME_OUT = 3000;
private static final int SO_TIME_OUT = 100000;
private static final boolean STALE_CHECK_ENABLED = true;
private static final boolean TCP_NO_DELAY = true;
private static final int DEFAULT_MAX_CONNECTIONS_PER_HOST = 100;
private static final int MAX_TOTAL_CONNECTIONS = 1000;
private static final HttpConnectionManager connectionManager;
public static final HttpClient client;
static {
HttpConnectionManagerParams params = loadHttpConfFromFile();
connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.setParams(params);
client = new HttpClient(connectionManager);
}
private static HttpConnectionManagerParams loadHttpConfFromFile() {
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setConnectionTimeout(CONNECTION_TIME_OUT);
params.setStaleCheckingEnabled(STALE_CHECK_ENABLED);
params.setTcpNoDelay(TCP_NO_DELAY);
params.setSoTimeout(SO_TIME_OUT);
params.setDefaultMaxConnectionsPerHost(DEFAULT_MAX_CONNECTIONS_PER_HOST);
params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);
params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
return params;
}
/**
* get请求
*
* @param url
* @return
*/
public static String doGet(String url) {
String result = null;
try {
GetMethod getMethod = new GetMethod(url);
client.executeMethod(getMethod);
result = getMethod.getResponseBodyAsString();
} catch (Exception e) {
log.error("httpclient get request url=" + url + ",exception=" + e);
}
return result;
}
public static String doPost(String url, String contentType, String content) throws Exception {
PostMethod method = new PostMethod(url);
method.addRequestHeader("Connection", "Keep-Alive");
method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
try {
method.setRequestEntity(new ByteArrayRequestEntity(content.getBytes(ENCODING)));
method.addRequestHeader("Content-Type", contentType);
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
return null;
}
byte[] ret = method.getResponseBody();
if (ret == null)
return null;
return new String(ret, ENCODING);
} finally {
method.releaseConnection();
}
}
}
package com.cx.cn.cxquartz.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
/**
* JSON工具类
*/
public class JsonUtil {
private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
private final static ObjectMapper objectMapper = new ObjectMapper();
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
static {
// 对象的所有字段全部列入
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
// 取消默认转换timestamps形式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// 忽略空bean转json的错误
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// 统一日期格式
objectMapper.setDateFormat(new SimpleDateFormat(DATE_FORMAT));
// 忽略在json字符串中存在, 但在java对象中不存在对应属性的情况, 防止错误
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static <T> String objToStr(T obj) {
if (null == obj) {
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
log.warn("objToStr error: ", e);
return null;
}
}
public static <T> T strToObj(String str, Class<T> clazz) {
if (StringUtils.isBlank(str) || null == clazz) {
return null;
}
try {
return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
} catch (Exception e) {
log.warn("strToObj error: ", e);
return null;
}
}
public static <T> T strToObj(String str, TypeReference<T> typeReference) {
if (StringUtils.isBlank(str) || null == typeReference) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str,
typeReference));
} catch (Exception e) {
log.error("strToObj error", e);
return null;
}
}
}
package com.cx.cn.cxquartz.util;
import java.io.Serializable;
import java.util.List;
public class Page<T> implements Serializable {
private static final long serialVersionUID = 130050641959720183L;
private List<T> list; //数据集合
private int totalRecord; //总记录数
private int currentPage; //当前页
private int pageSize; //每页大小
private int startIndex;
private int totalPage; //总页数
private int previousPage; //前一页
private int nextPage; //下一页
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = list.size();
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = 10;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = pageSize * (currentPage-1);
}
public void setTotalPage(int totalPage) {
if(this.totalRecord % this.pageSize == 0) {
this.totalPage = this.totalRecord / this.pageSize;
}else {
this.totalPage = this.totalRecord / this.pageSize + 1;
}
}
public void setPreviousPage(int previousPage) {
if(this.totalRecord % this.pageSize == 0) {
this.totalPage = this.totalRecord / this.pageSize;
}else {
this.totalPage = this.totalRecord / this.pageSize + 1;
}
}
public void setNextPage(int nextPage) {
if(this.currentPage + 1 > this.totalPage) {
this.nextPage = this.totalPage;
}else {
this.nextPage = this.currentPage + 1;
}
}
public int getTotalPage() {
return totalPage;
}
public int getPreviousPage() {
return previousPage;
}
public int getNextPage() {
return nextPage;
}
@Override
public String toString() {
return "Page{" +
"list=" + list +
", totalRecord=" + totalRecord +
", currentPage=" + currentPage +
", pageSize=" + pageSize +
", startIndex=" + startIndex +
", totalPage=" + totalPage +
", previousPage=" + previousPage +
", nextPage=" + nextPage +
'}';
}
public Page(List<T> list, int totalRecord, int currentPage) {
this.list = list;
this.totalRecord = totalRecord;
this.currentPage = currentPage;
}
}
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.controller.IndexController;
import com.cx.cn.cxquartz.vo.Location;
import com.cx.cn.cxquartz.vo.Point;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;
import java.util.List;
public class PointUtil {
private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
private static final Logger logger = LoggerFactory.getLogger(PointUtil.class);
public static void getXYWH(List<Point> points, Long[] roiarray){
Map<Integer, Integer> map=new HashMap();
......@@ -42,41 +34,5 @@ public static void getXYWH(List<Point> points, Long[] roiarray){
roiarray[2]=Long.parseLong(String.valueOf(numx.get(1) - numx.get(0)));
roiarray[3]=Long.parseLong(String.valueOf(numy.get(1) - numy.get(0)));
}}
public static ByteArrayOutputStream drawByPoints(InputStream bais,List<Map> detectObjects) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
BufferedImage image = ImageIO.read(bais);
Graphics g = image.getGraphics();
g.setColor(Color.RED);
//遍历所有特征值,画到图片上
int x,y,w,h;
for (Map box : detectObjects) {
if (null != box) {
try {
if (null != box.get("location")) {
x=0;y=0;w=0;h=0;
try {
Location lo =(Location) box.get("location");
logger.info("detectObjects x1,x2,y1,y2==="+lo.toString());
g.drawRect(lo.getX1(),
lo.getY1(),lo.getX2()-lo.getX1(),lo.getY2()-lo.getY1());
}catch (Exception ex){
logger.error("Location Map error:{}", ex.toString());
}
}
} catch (Exception ex) {
logger.error("Location readValue error:{}", ex.toString());
}
}
}
ImageIO.write(image, "JPEG", stream);
return stream;
}catch (Exception ex){
logger.error("Location readValue error:{}", ex.toString());
}
return stream;
}
}
package com.cx.cn.cxquartz.util;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
public class RecursiveGetJsonData {
private static List<Object> list = new ArrayList<Object>(); //公共的的数据池
private String rootDir;//根目录
private List<File> jsonFileList = new ArrayList<File>();//公共的数据区域 找到的文件数据
public List<File> getJsonFileList() {
return jsonFileList;
}
public void setJsonFileList(List<File> jsonFileList) {
this.jsonFileList = jsonFileList;
}
public RecursiveGetJsonData(String rootDir) {
this.setRootDir(rootDir);
}
public RecursiveGetJsonData() { // 空构造方法
}
/**
* rootDir 根目录
* fileNameEndFlag 问价结尾标识
*
* @param rootDir
*/
public void getDataFromFile(String rootDir, final String fileNameEndFlag) {
File rootFile = new File(rootDir);
FileFilter filter = new FileFilter() { //文件后缀过滤
@Override
public boolean accept(File file) {
String fileName = file.getName();
if (fileName != null && fileName != "" && fileName.endsWith(fileNameEndFlag)) {
return true;
}
return false;
}
};
if (rootFile.isDirectory()) { //如果是目录
File[] listFiles = rootFile.listFiles(filter); // 满足条件的文件装入公共数据区
if (null != listFiles && listFiles.length > 0) {
jsonFileList.addAll(Arrays.asList(listFiles)); //Arrays 将数组转化为List集合
}
File[] list = rootFile.listFiles();
if (null != list && list.length > 0) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
getDataFromFile(list[i].getAbsolutePath(), fileNameEndFlag); //递归调用方法
}
}
}
}
}
public String ImageToBase64ByLocal(File file) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
//获取图片路径
in = new FileInputStream(file.getPath());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
return null;
}
return Base64.getEncoder().encodeToString(data);
}
public String getRootDir() {
return rootDir;
}
public void setRootDir(String rootDir) {
this.rootDir = rootDir;
}
public static List<Object> getList() {
return list;
}
public static void setList(List<Object> list) {
RecursiveGetJsonData.list = list;
}
}
package com.cx.cn.cxquartz.util;
/**
* 通用序列枚举类
* @author cp
*/
public enum RedisEnum {
/**
* 支队心跳
*/
DETACHMENT_HEART_BEATS("gs:traff:detachment:heartbeats"),
/**
* FTP List
*/
FTPLIST("gs:traff:global:cache:ftplist"),
/**
* ftp index
*/
FTPLIST_INDEX("gs:traff:global:cache:ftplistindex");
private String value;
RedisEnum(String value){
this.value =value;
}
public String getValue() {
return value;
}
}
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.service.quartz.SbtdspsrService;
import com.cx.cn.cxquartz.vo.TraffAlarmRecord;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RestUtil {
private static final Logger logger = LoggerFactory.getLogger(RestUtil.class);
@Autowired
public RestTemplate restTemplate;
@Autowired
public SbtdspsrService sbtdspsrService;
//
// public String getnewRtspVlue(String devicecode,String getrtspbyurl ){
// String rtspnewvalue="";
// Map<String, String> map = new HashMap<>();
// map.put("deviceCode", devicecode);
// ResponseEntity<String> responseEntity = restTemplate.getForEntity(getrtspbyurl+"?deviceCode={deviceCode}", String.class, map);
// JSONObject json = JSONObject.parseObject(responseEntity.getBody());
// if (null != json.getString("errorCode") && json.getString("errorCode").equals("0")) {
// //返回rtsp 地址
// json = JSONObject.parseObject(json.getString("data"));
// if (null != json.get("rtspUri") && !"".equals(json.get("rtspUri"))) {
// rtspnewvalue = String.valueOf(json.get("rtspUri"));
// if(rtspnewvalue.contains("rtsp")) {
// //更新sbtdspsr 地址
// int result = sbtdspsrService.updateRecogByRtsp(rtspnewvalue, devicecode);
// if (result > 0) {
// logger.info("更新rtsp success");
// } else {
// logger.info("设备" + devicecode + "不存在");
// }
// }
// else {
// logger.info("获取失败");
// }
// }
// }
// return rtspnewvalue;
// }
// public void rtspChangeVlue(String devicecode,String oldrtsp,String getrtspbyurl ){
// String rtspnewvalue="";
// Map<String, String> map = new HashMap<>();
// map.put("deviceCode", devicecode);
// ResponseEntity<String> responseEntity = restTemplate.getForEntity(getrtspbyurl+"?deviceCode={deviceCode}", String.class, map);
// JSONObject json = JSONObject.parseObject(responseEntity.getBody());
// if (null != json.getString("errorCode") && json.getString("errorCode").equals("0")) {
// //返回rtsp 地址
// json = JSONObject.parseObject(json.getString("data"));
// if (null != json.get("rtspUri") && !"".equals(json.get("rtspUri"))) {
// rtspnewvalue = String.valueOf(json.get("rtspUri"));
// //与新获得的rtsp 比较,如果一样则不更新,否则更新
// if(oldrtsp.contains("rtsp") && !oldrtsp.equals(rtspnewvalue)) {
// //更新sbtdspsr 地址
// int result = sbtdspsrService.updateRecogByRtsp(rtspnewvalue, devicecode);
// if (result > 0) {
// logger.info("更新rtsp success");
// } else {
// logger.info("设备" + devicecode + "不存在");
// }
// }
// else {
// logger.info("获取失败");
// }
// }
// }
// }
public String getPicture(List<String> imgUrls, String deviceCode, String rtspurl, TraffAlarmRecord record ) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
Map<String, Object> maps = new HashMap<>();
maps.put("deviceCode", deviceCode);
logger.info("rtspurl:{}",rtspurl);
Map result = restTemplate.getForObject(rtspurl + "?deviceCode={deviceCode}", Map.class, maps);
if(null!=result) {
if (null != result.get("ret") && String.valueOf(result.get("ret")).equals("0")) {
//获得图片地址
imgUrls.add(result.get("url").toString());
record.setImg1urlfrom(result.get("url").toString());
record.setImg1path(result.get("localuri").toString());
return result.get("timestamp").toString();
}
}
return null;
}
//
// public String getSnapshot(List<String> imgUrls, String deviceCode, String rtspurl, TraffAlarmRecord record ) {
// HttpHeaders headers = new HttpHeaders();
// headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
// Map<String, Object> maps = new HashMap<>();
// maps.put("deviceCode", deviceCode);
// logger.info("rtspurl:{}",rtspurl);
// HttpEntity<String> formEntity = new HttpEntity<>(null, headers);
// ResponseEntity<String> exchange = restTemplate.exchange(rtspurl + "?deviceCode={deviceCode}",
// HttpMethod.GET, formEntity, String.class, maps);
// if(null!=exchange.getBody()) {
// JSONObject json = JSONObject.parseObject(exchange.getBody());
// if (null != json.getString("ret") && json.getString("ret").equals("0")) {
// //获得图片地址
// imgUrls.add(json.getString("url"));
// record.setImg1path(json.getString("url"));
// }
// return json.getString("timestamp");
// }
// return null;
// }
/// <summary>
/// 读取远程文件的内容
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static InputStream ReadFromURL(String serverFilePath)
{
try {
HttpURLConnection connection = (HttpURLConnection) new URL(serverFilePath).openConnection();
connection.setReadTimeout(2000); //延迟连接
connection.setConnectTimeout(8000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK || connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
logger.error(e.toString());
}
return null;
}
}
package com.cx.cn.cxquartz.util;
import java.util.concurrent.*;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
public class ThreadPoolUtil {
private static BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(5000);
private static final ExecutorService pool =new ThreadPoolExecutor(10, 30, 2L, TimeUnit.MINUTES,
queue , Executors.defaultThreadFactory(), new CallerRunsPolicy());
private static final ScheduledExecutorService schedulepool = Executors.newScheduledThreadPool(2);
public static ScheduledExecutorService getSchedulePool() {
return schedulepool;
}
public static ExecutorService getPool() {
return pool;
}
public static int getQueueSize(){
return queue.size();
}
public static void executeSchedule(Runnable thread){
getSchedulePool().execute(thread);
}
public static void execute(Runnable thread){
getPool().execute(thread);
}
}
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.vo.TraffAlarmRecord;
/**
* TraffAlarmRecord4��������ͼƬXԴ��ַ
* @author cp
*/
public enum TraffAlarmRecordFromImgEnum implements TraffAlarmRecordImg {
/**
* ����ͼƬ���õ�ַ
*/
IMG0 {
@Override
public void setImg(TraffAlarmRecord traffAlarmRecord, String img) {
traffAlarmRecord.setImg1urlfrom(img);
}
}
}
package com.cx.cn.cxquartz.util;
import com.cx.cn.cxquartz.vo.TraffAlarmRecord;
/**
* TraffAlarmRecordͼƬӿ
* @author cp
*/
public interface TraffAlarmRecordImg {
void setImg(TraffAlarmRecord traffAlarmRecord, String img);
}
package com.cx.cn.cxquartz.util;
import java.util.UUID;
public class UUIDUtils {
/**
* UUID
* @return String32λUUID
*/
public static String createuuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
package com.cx.cn.cxquartz.vo;
import java.io.Serializable;
public class Code implements Serializable {
private String key;
private String name;
private String type;
private String alarmlevel;
private Integer rectifytime ;
private Integer manualchecktime;
private Integer pushchecktime ;
private Integer maxnum;
private Integer alarmnum;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAlarmlevel() {
return alarmlevel;
}
public void setAlarmlevel(String alarmlevel) {
this.alarmlevel = alarmlevel;
}
public Integer getRectifytime() {
return rectifytime;
}
public void setRectifytime(Integer rectifytime) {
this.rectifytime = rectifytime;
}
public Integer getManualchecktime() {
return manualchecktime;
}
public void setManualchecktime(Integer manualchecktime) {
this.manualchecktime = manualchecktime;
}
public Integer getPushchecktime() {
return pushchecktime;
}
public void setPushchecktime(Integer pushchecktime) {
this.pushchecktime = pushchecktime;
}
public Integer getMaxnum() {
return maxnum;
}
public void setMaxnum(Integer maxnum) {
this.maxnum = maxnum;
}
public Integer getAlarmnum() {
return alarmnum;
}
public void setAlarmnum(Integer alarmnum) {
this.alarmnum = alarmnum;
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.vo;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Face {
@JsonIgnore
private Long id;
private String Type;
private FaceBoundingBox FaceBoundingBox;
private HeadBoundingBox HeadBoundingBox;
private String Gender;
private String Age;
private String HasGlasses;
private String HasHat;
private String HasMask;
private String HairStyle;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setType(String Type) {
this.Type = Type;
}
public String getType() {
return Type;
}
public void setFaceBoundingBox(FaceBoundingBox FaceBoundingBox) {
this.FaceBoundingBox = FaceBoundingBox;
}
public FaceBoundingBox getFaceBoundingBox() {
return FaceBoundingBox;
}
public void setHeadBoundingBox(HeadBoundingBox HeadBoundingBox) {
this.HeadBoundingBox = HeadBoundingBox;
}
public HeadBoundingBox getHeadBoundingBox() {
return HeadBoundingBox;
}
public void setGender(String Gender) {
this.Gender = Gender;
}
public String getGender() {
return Gender;
}
public void setAge(String Age) {
this.Age = Age;
}
public String getAge() {
return Age;
}
public void setHasGlasses(String HasGlasses) {
this.HasGlasses = HasGlasses;
}
public String getHasGlasses() {
return HasGlasses;
}
public void setHasHat(String HasHat) {
this.HasHat = HasHat;
}
public String getHasHat() {
return HasHat;
}
public void setHasMask(String HasMask) {
this.HasMask = HasMask;
}
public String getHasMask() {
return HasMask;
}
public void setHairStyle(String HairStyle) {
this.HairStyle = HairStyle;
}
public String getHairStyle() {
return HairStyle;
}
}
/**
* Copyright 2021 json.cn
*/
package com.cx.cn.cxquartz.vo;
public class FaceBoundingBox {
private int x;
private int y;
private int w;
private int h;
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public void setW(int w) {
this.w = w;
}
public int getW() {
return w;
}
public void setH(int h) {
this.h = h;
}
public int getH() {
return h;
}
}
\ No newline at end of file
package com.cx.cn.cxquartz.vo;
import java.util.Date;
public class FileUploadResult {
private String filename;
private String url;
private String localuri;
private long length;
private Date timestamp;
public void setFilename(String filename) {
this.filename = filename;
}
public String getFilename() {
return filename;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
public void setLocaluri(String localuri) {
this.localuri = localuri;
}
public String getLocaluri() {
return localuri;
}
public void setLength(long length) {
this.length = length;
}
public long getLength() {
return length;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public Date getTimestamp() {
return timestamp;
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
/**
* Copyright 2021 json.cn
*/
package com.cx.cn.cxquartz.vo;
import java.util.List;
public class Metadata {
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment