code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package com.zmops.iot.rest.controller;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.web.device.dto.param.DeviceParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 设备日志接口
**/
@RestController
@RequestMapping("/rest/deviceLog")
public class DeviceLogRestController {
/**
* 服务日志分页列表
*
* @return
*/
@PostMapping("/getDeviceByPage")
public Pager<Device> devicePageList(@RequestBody DeviceParam deviceParam) {
return new Pager<>();
}
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/controller/DeviceLogRestController.java
|
Java
|
gpl-3.0
| 798
|
package com.zmops.iot.rest.controller;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.device.dto.param.DeviceParam;
import com.zmops.iot.web.device.dto.param.DeviceParams;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 设备接口
**/
@RestController
@RequestMapping("/rest/device")
public class DeviceRestController {
/**
* 设备分页列表
*
* @return
*/
@PostMapping("/getDeviceByPage")
public Pager<Device> devicePageList(@RequestBody DeviceParam deviceParam) {
return new Pager<>();
}
/**
* 设备列表
*
* @return
*/
@PostMapping("/list")
public ResponseData deviceList(@RequestBody DeviceParams deviceParams) {
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/controller/DeviceRestController.java
|
Java
|
gpl-3.0
| 1,093
|
package com.zmops.iot.rest.controller;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.device.dto.param.DeviceParams;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 登录接口
**/
@RestController
@RequestMapping("/rest/login")
public class LoginRestController {
/**
* 登录
*
* @return
*/
@PostMapping("/list")
public ResponseData deviceList(@RequestBody DeviceParams deviceParams) {
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/controller/LoginRestController.java
|
Java
|
gpl-3.0
| 730
|
package com.zmops.iot.rest.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
*
* 产品接口
**/
@RestController
@RequestMapping("/rest/product")
public class ProductRestController {
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/controller/ProductRestController.java
|
Java
|
gpl-3.0
| 302
|
package com.zmops.iot.rest.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 场景接口
**/
@RestController
@RequestMapping("/rest/scene")
public class SceneRestController {
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/controller/SceneRestController.java
|
Java
|
gpl-3.0
| 302
|
package com.zmops.iot.rest.service;
import org.springframework.stereotype.Service;
/**
* @author yefei
*
* 设备 rest 服务
**/
@Service
public class DeviceRestService {
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/service/DeviceRestService.java
|
Java
|
gpl-3.0
| 181
|
package com.zmops.iot.rest.service;
import org.springframework.stereotype.Service;
/**
* @author yefei
*
* 产品 rest 服务
**/
@Service
public class ProductRestService {
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/service/ProductRestService.java
|
Java
|
gpl-3.0
| 182
|
package com.zmops.iot.rest.service;
import org.springframework.stereotype.Service;
/**
* @author yefei
*
* 场景 rest 服务
**/
@Service
public class SceneRestService {
}
|
2301_81045437/zeus-iot
|
zeus-rest/src/main/java/com/zmops/iot/rest/service/SceneRestService.java
|
Java
|
gpl-3.0
| 180
|
package com.zmops.iot;
import com.dtflys.forest.springboot.annotation.ForestScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.TimeZone;
/**
* @author nantian
* <p>
* ### 宙斯物联网中台 ZEUS-IOT == SpringBoot + Ebean 极简架构
*/
@SpringBootApplication
@ForestScan("com.zmops.zeus.driver.service")
public class IoTApplication {
private final static Logger logger = LoggerFactory.getLogger(IoTApplication.class);
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(IoTApplication.class, args);
logger.info(IoTApplication.class.getSimpleName() + " webapp started successfully!");
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/IoTApplication.java
|
Java
|
gpl-3.0
| 857
|
package com.zmops.iot.config.ebean;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import io.ebean.config.CurrentUserProvider;
import org.springframework.stereotype.Component;
/**
* @author nantian created at 2021/7/30 20:53
* <p>
* 根据当前登录用户 获取 userId,用于 userId 日志记录
*/
@Component
public class CurrentUser implements CurrentUserProvider {
@Override
public Object currentUser() {
return LoginContextHolder.getContext().getUser().getId();
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/ebean/CurrentUser.java
|
Java
|
gpl-3.0
| 515
|
package com.zmops.iot.config.ebean;
import io.ebean.Database;
import io.ebean.DatabaseFactory;
import io.ebean.config.DatabaseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @author nantian created at 2021/7/30 16:50
* <p>
* Ebean Server 配置
*/
@Configuration
public class EbeanServerConfig {
@Autowired
private DataSource dataSource;
@Autowired
private CurrentUser currentUser;
@Bean
public Database createEbeanDatabase() {
DatabaseConfig config = new DatabaseConfig();
config.setName("postgresql");
config.add(new IdSnow());
config.setDefaultServer(true);
config.addPackage("com.zmops.iot.domain");
config.setCurrentUserProvider(currentUser);
config.setDataSource(dataSource);
return DatabaseFactory.create(config);
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/ebean/EbeanServerConfig.java
|
Java
|
gpl-3.0
| 1,003
|
package com.zmops.iot.config.ebean;
import cn.hutool.core.util.IdUtil;
import com.zmops.iot.constant.IdTypeConsts;
import io.ebean.config.IdGenerator;
/**
* @author nantian created at 2021/8/1 18:57
*/
public class IdSnow implements IdGenerator {
@Override
public Object nextValue() {
return IdUtil.getSnowflake().nextId();
}
@Override
public String getName() {
return IdTypeConsts.ID_SNOW;
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/ebean/IdSnow.java
|
Java
|
gpl-3.0
| 441
|
package com.zmops.iot.config.security;
import com.zmops.iot.web.auth.PermissionAop;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* @author nantian created at 2021/7/30 18:28
*/
@Configuration
public class PermissionAopConfig {
/**
* 资源过滤的aop
*
* @author fengshuonan
*/
@Bean
public PermissionAop permissionAop() {
return new PermissionAop();
}
/**
* Spring Security 多线程上下文可以获取 登陆信息
*
* @return MethodInvokingFactoryBean
*/
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);
methodInvokingFactoryBean.setTargetMethod("setStrategyName");
methodInvokingFactoryBean.setArguments(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
return methodInvokingFactoryBean;
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/security/PermissionAopConfig.java
|
Java
|
gpl-3.0
| 1,225
|
package com.zmops.iot.config.security;
import com.zmops.iot.core.auth.entrypoint.JwtAuthenticationEntryPoint;
import com.zmops.iot.core.auth.filter.JwtAuthorizationTokenFilter;
import com.zmops.iot.core.auth.filter.NoneAuthedResources;
import com.zmops.iot.web.sys.service.JwtUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* @author nantian created at 2021/7/29 22:54
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
@Autowired
private JwtAuthorizationTokenFilter authenticationTokenFilter;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(jwtUserDetailsService);
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//csrf关闭
httpSecurity.csrf().disable();
//开启跨域
httpSecurity.cors();
//自定义退出
httpSecurity.logout().disable();
httpSecurity.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
// 全局不创建session
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//放开一些接口的权限校验
for (String notAuthedResource : NoneAuthedResources.BACKEND_RESOURCES) {
httpSecurity.authorizeRequests().antMatchers(notAuthedResource).permitAll();
}
//其他接口都需要权限
httpSecurity.authorizeRequests().anyRequest().authenticated();
//添加自定义的过滤器
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
//disable page caching
httpSecurity.headers().frameOptions().sameOrigin().cacheControl();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.POST, NoneAuthedResources.NO_AUTH_API)
// 静态资源放开过滤
.and().ignoring().antMatchers(HttpMethod.GET,
"/static/**",
"/favicon.ico"
);
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/security/WebSecurityConfig.java
|
Java
|
gpl-3.0
| 3,267
|
package com.zmops.iot.config.web;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
/**
* @author yefei
**/
@Configuration
public class DateformatConfig {
/**
* Date格式化字符串
*/
private static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* DateTime格式化字符串
*/
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* Time格式化字符串
*/
private static final String TIME_FORMAT = "HH:mm:ss";
/**
* 自定义Bean
*
* @return
*/
@Bean
@Primary
public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)))
.serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)))
.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT)))
.deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)))
.deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/web/DateformatConfig.java
|
Java
|
gpl-3.0
| 2,221
|
package com.zmops.iot.config.web;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Properties;
/**
* @author nantian created at 2021/7/30 15:44
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/public/static/");
}
/**
* 验证码 Bean
*
* @return DefaultKaptcha
*/
@Bean
public DefaultKaptcha kaptcha() {
Properties properties = new Properties();
properties.put("kaptcha.border", "no");
properties.put("kaptcha.border.color", "105,179,90");
properties.put("kaptcha.textproducer.font.color", "blue");
properties.put("kaptcha.image.width", "125");
properties.put("kaptcha.image.height", "45");
properties.put("kaptcha.textproducer.font.size", "45");
properties.put("kaptcha.session.key", "code");
properties.put("kaptcha.textproducer.char.length", "4");
properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
Config config = new Config(properties);
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/web/WebConfig.java
|
Java
|
gpl-3.0
| 1,674
|
package com.zmops.iot.config.zbxapi;
import cn.hutool.core.util.NumberUtil;
import com.zmops.zeus.driver.service.ZbxApiInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author nantian created at 2021/8/3 12:03
*/
@Slf4j
@Component
public class ZbxApiInfoValidation implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ZbxApiInfo apiInfo = applicationContext.getBean(ZbxApiInfo.class);
String response = apiInfo.getApiInfo();
int version = NumberUtil.parseInt(response.replaceAll("\\.", ""));
if (version < 540) {
log.error("Zabbix API 当前版本为:{},低于最低支持版本 5.4", response);
int exitCode = SpringApplication.exit(applicationContext, () -> 0);
System.exit(exitCode);
}
}
}
|
2301_81045437/zeus-iot
|
zeus-starter/src/main/java/com/zmops/iot/config/zbxapi/ZbxApiInfoValidation.java
|
Java
|
gpl-3.0
| 1,146
|
package com.zmops.iot.web.alarm.controller;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.alarm.dto.AlarmDto;
import com.zmops.iot.web.alarm.dto.param.AlarmParam;
import com.zmops.iot.web.alarm.service.AlarmService;
import com.zmops.iot.web.auth.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
**/
@RestController
@RequestMapping("/alarm")
public class AlarmController {
@Autowired
AlarmService alarmService;
@Permission(code = "alarmList")
@RequestMapping("/getAlarmByPage")
public Pager<AlarmDto> getAlarmByPage(@RequestBody AlarmParam alarmParam) {
return alarmService.getAlarmByPage(alarmParam);
}
@Permission(code = "alarmList")
@RequestMapping("/acknowledgement")
public ResponseData acknowledgement(@RequestParam String eventId) {
alarmService.acknowledgement(eventId);
return ResponseData.success();
}
@Permission(code = "alarmList")
@RequestMapping("/resolve")
public ResponseData resolve(@RequestParam String eventId) {
alarmService.resolve(eventId);
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/controller/AlarmController.java
|
Java
|
gpl-3.0
| 1,464
|
package com.zmops.iot.web.alarm.controller;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.domain.messages.MailSetting;
import com.zmops.iot.domain.messages.NoticeResult;
import com.zmops.iot.domain.messages.MailParam;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.alarm.service.MailSettingServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
*
**/
@RestController
@RequestMapping("mailSetting")
public class MailSettingController {
@Autowired
MailSettingServiceImpl settingService;
@RequestMapping("get")
public ResponseData get() {
return ResponseData.success(settingService.get());
}
@PostMapping("test")
public ResponseData test(@Validated(MailParam.Test.class) @RequestBody MailParam mailParam) {
NoticeResult test = settingService.test(mailParam);
if(test.getStatus().equals(NoticeResult.NoticeStatus.success)){
return ResponseData.success(test.getMsg());
}else{
return ResponseData.error(test.getMsg());
}
}
@PostMapping("update")
public ResponseData update(@Validated(BaseEntity.Update.class) @RequestBody MailParam mailParam) {
return ResponseData.success(settingService.updateSettings(mailParam.getSettings()));
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/controller/MailSettingController.java
|
Java
|
gpl-3.0
| 1,645
|
package com.zmops.iot.web.alarm.controller;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.alarm.MediaTypeSetting;
import com.zmops.iot.domain.alarm.query.QMediaTypeSetting;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.model.response.SuccessResponseData;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.alarm.service.MediaTypeSettingService;
import io.ebean.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author yefei
**/
@RestController
@RequestMapping("/media/type")
public class MediaTypeSettingController {
@Autowired
MediaTypeSettingService mediaTypeSettingService;
@GetMapping("/list")
public ResponseData list(@RequestParam(value = "type", required = false) String type) {
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
QMediaTypeSetting qMediaTypeSetting = new QMediaTypeSetting();
if (null != tenantId) {
qMediaTypeSetting.tenantId.eq(tenantId);
} else {
qMediaTypeSetting.tenantId.isNull();
}
if (ToolUtil.isNotEmpty(type)) {
qMediaTypeSetting.type.eq(type);
}
return new SuccessResponseData(qMediaTypeSetting.orderBy().id.asc().findList());
}
@PostMapping("update")
public ResponseData update(@RequestBody MediaTypeSetting mediaTypeSetting) {
DB.update(mediaTypeSetting);
return new SuccessResponseData(mediaTypeSetting);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/controller/MediaTypeSettingController.java
|
Java
|
gpl-3.0
| 1,598
|
package com.zmops.iot.web.alarm.controller;
import com.zmops.iot.domain.messages.Messages;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.web.alarm.dto.param.MessageParam;
import com.zmops.iot.web.alarm.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* @author yefei
**/
@RestController
@RequestMapping("/message")
public class MessageController {
@Autowired
MessageService messageService;
/**
* 消息分页列表
*
* @param messageParam
* @return
*/
@RequestMapping("/getMessageByPage")
public Pager getMessageByPage(@RequestBody MessageParam messageParam) {
return messageService.list(messageParam);
}
/**
* 消息详情
*
* @param id
* @return
*/
@RequestMapping("/info")
public Messages info(@RequestParam("id") Integer id) {
return messageService.info(id);
}
/**
* 消息置为已读
*
* @param messageVo
* @return
*/
@RequestMapping("/read")
public List<Integer> read(@RequestBody MessageParam messageVo) {
return messageService.read(messageVo);
}
/**
* 未读消息数
*
* @return
*/
@GetMapping("/num")
public Map<String, Object> unReadNum() {
return messageService.unReadNum();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/controller/MessageController.java
|
Java
|
gpl-3.0
| 1,456
|
package com.zmops.iot.web.alarm.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.zmops.iot.model.cache.filter.CachedValue;
import com.zmops.iot.model.cache.filter.CachedValueFilter;
import com.zmops.iot.model.cache.filter.DicType;
import lombok.Data;
import java.time.LocalDateTime;
/**
* @author yefei
**/
@Data
@JsonSerialize(using = CachedValueFilter.class)
public class AlarmDto {
private Long eventId;
private Long objectId;
private LocalDateTime clock;
private LocalDateTime rClock;
private String name;
private String acknowledged;
@CachedValue(type = DicType.Device, fieldName = "deviceName")
private String deviceId;
@CachedValue(value = "EVENT_LEVEL",fieldName = "severityName")
private String severity;
private String status;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/dto/AlarmDto.java
|
Java
|
gpl-3.0
| 829
|
package com.zmops.iot.web.alarm.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class AlarmParam extends BaseQueryParam {
private String deviceId;
private Long timeFrom;
private Long timeTill;
private String name;
private String statusName;
private Integer severity;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/dto/param/AlarmParam.java
|
Java
|
gpl-3.0
| 377
|
package com.zmops.iot.web.alarm.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
import java.util.List;
/**
* @author yefei
**/
@Data
public class MessageParam extends BaseQueryParam {
private Integer readed;
private List<Integer> ids;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/dto/param/MessageParam.java
|
Java
|
gpl-3.0
| 289
|
package com.zmops.iot.web.alarm.service;
import com.zmops.iot.domain.alarm.AlarmMessage;
import com.zmops.iot.domain.alarm.Problem;
import com.zmops.iot.domain.alarm.query.QProblem;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.product.ProductEvent;
import com.zmops.iot.domain.product.query.QProductEvent;
import com.zmops.iot.media.AlarmCallback;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.alarm.dto.AlarmDto;
import com.zmops.iot.web.alarm.dto.param.AlarmParam;
import com.zmops.iot.web.device.service.DeviceService;
import com.zmops.zeus.driver.service.ZbxProblem;
import io.ebean.PagedList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@Service
public class AlarmService {
@Autowired
Collection<AlarmCallback> alarmCallbacks;
@Autowired
ZbxProblem zbxProblem;
@Autowired
DeviceService deviceService;
private static final String PROBLEM_RESOLVE = "已解决";
public void alarm(Map<String, Object> alarmInfo) {
List<String> deviceIds = (List) alarmInfo.get("hostname");
String eventRuleId = (String) alarmInfo.get("triggerName");
if (ToolUtil.isEmpty(deviceIds) || ToolUtil.isEmpty(eventRuleId)) {
return;
}
List<Device> deviceList = new QDevice().deviceId.in(deviceIds).findList();
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(Long.parseLong(eventRuleId)).findOne();
List<AlarmMessage> alarmMessages = new ArrayList<>();
if (ToolUtil.isNotEmpty(deviceList) && null != productEvent) {
String deviceName = deviceList.parallelStream().map(Device::getName).collect(Collectors.joining(","));
String alarmmessage = "设备:" + deviceName + "发生告警,告警内容:" + productEvent.getEventRuleName();
alarmMessages.add(AlarmMessage.builder().alarmMessage(alarmmessage).build());
alarmCallbacks.forEach(alarmCallback -> {
alarmCallback.doAlarm(alarmMessages, deviceList.get(0).getTenantId());
});
}
}
public void action(Map<String, String> alarmInfo) {
String deviceId = alarmInfo.get("hostname");
String serviceName = alarmInfo.get("serviceName");
if (ToolUtil.isEmpty(deviceId) || ToolUtil.isEmpty(serviceName)) {
return;
}
Device device = new QDevice().deviceId.eq(deviceId).findOne();
List<AlarmMessage> alarmMessages = new ArrayList<>();
if (null != device) {
String alarmmessage = "设备:" + device.getName() + "触发联动服务,服务名称:" + serviceName;
alarmMessages.add(AlarmMessage.builder().alarmMessage(alarmmessage).build());
alarmCallbacks.forEach(alarmCallback -> {
// if (alarmCallback.getType().equals("welink")) {
alarmCallback.doAlarm(alarmMessages, device.getTenantId());
// }
});
}
}
public Pager<AlarmDto> getAlarmByPage(AlarmParam alarmParam) {
QProblem query = buildQproblem(alarmParam);
PagedList<Problem> problemList = query.setFirstRow((alarmParam.getPage() - 1) * alarmParam.getMaxRow())
.setMaxRows(alarmParam.getMaxRow()).findPagedList();
return new Pager<>(formatAlarmList(problemList.getList()), problemList.getTotalCount());
}
public List<AlarmDto> getAlarmList(AlarmParam alarmParam) {
QProblem query = buildQproblem(alarmParam);
return formatAlarmList(query.findList());
}
private QProblem buildQproblem(AlarmParam alarmParam) {
QProblem query = new QProblem();
if (ToolUtil.isNotEmpty(alarmParam.getDeviceId())) {
query.deviceId.eq(alarmParam.getDeviceId());
}
if (ToolUtil.isNotEmpty(alarmParam.getTimeFrom())) {
query.clock.ge(LocalDateTimeUtils.getLDTByMilliSeconds(alarmParam.getTimeFrom() * 1000));
}
if (ToolUtil.isNotEmpty(alarmParam.getTimeTill())) {
query.clock.lt(LocalDateTimeUtils.getLDTByMilliSeconds(alarmParam.getTimeTill() * 1000));
}
if (ToolUtil.isNotEmpty(alarmParam.getStatusName())) {
if (PROBLEM_RESOLVE.equals(alarmParam.getStatusName())) {
query.rClock.isNotNull();
} else {
query.rClock.isNull();
}
}
if (ToolUtil.isNotEmpty(alarmParam.getSeverity())) {
query.severity.eq(alarmParam.getSeverity());
}
query.orderBy().clock.desc();
return query;
}
private List<AlarmDto> formatAlarmList(List<Problem> problemList) {
List<AlarmDto> list = new ArrayList<>();
problemList.forEach(problem -> {
AlarmDto alarmDto = new AlarmDto();
BeanUtils.copyProperties(problem, alarmDto);
alarmDto.setSeverity(problem.getSeverity() + "");
alarmDto.setStatus(problem.getRClock() == null ? "未解决" : "已解决");
alarmDto.setAcknowledged(problem.getAcknowledged() == 0 ? "未确认" : "已确认");
list.add(alarmDto);
});
return list;
}
public void acknowledgement(String eventId) {
zbxProblem.acknowledgement(eventId, 2);
}
public void resolve(String eventId) {
zbxProblem.acknowledgement(eventId, 1);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/service/AlarmService.java
|
Java
|
gpl-3.0
| 5,778
|
package com.zmops.iot.web.alarm.service;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.messages.MailParam;
import com.zmops.iot.domain.messages.MailSetting;
import com.zmops.iot.domain.messages.NoticeResult;
import com.zmops.iot.domain.messages.query.QMailSetting;
import com.zmops.iot.media.mail.MailNotice;
import com.zmops.iot.media.mail.MailSettingService;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author yefei
**/
@Service
@Slf4j
public class MailSettingServiceImpl implements MailSettingService {
@Autowired
MailNotice mailNotice;
private volatile Map<Long, MailSetting> instanceMap = new HashMap<>();
@Override
public MailSetting get() {
return Optional.ofNullable(getOne()).orElse(new MailSetting());
}
private MailSetting getOne() {
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
tenantId = Optional.ofNullable(tenantId).orElse(-1L);
if (instanceMap.get(tenantId) != null) {
return instanceMap.get(tenantId);
}
MailSetting mailSetting = Optional.of(new QMailSetting().findList())
.map(Collection::iterator)
.filter(Iterator::hasNext)
.map(Iterator::next).orElse(null);
if (mailSetting != null) {
instanceMap.put(tenantId, mailSetting);
}
return mailSetting;
}
@Override
public NoticeResult test(MailParam mailParam) {
MailSetting mailSetting = mailParam.getSettings();
NoticeResult noticeResult = mailNotice.test(mailSetting, mailParam.getReceiver());
//updateSettings(noticeResult, mailSetting);
return noticeResult;
}
@Override
public Integer updateSettings(MailSetting mailSetting) {
if (mailSetting.getTls() == null) {
mailSetting.setTls(0);
}
if (mailSetting.getSsl() == null) {
mailSetting.setSsl(0);
}
MailSetting dbSetting = getOne();
if (dbSetting == null) {
DB.insert(mailSetting);
} else {
mailSetting.setId(dbSetting.getId());
DB.update(mailSetting);
}
Long tenantId = Optional.ofNullable(mailSetting.getTenantId()).orElse(-1L);
instanceMap.put(tenantId, mailSetting);
return mailSetting.getId();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/service/MailSettingServiceImpl.java
|
Java
|
gpl-3.0
| 2,533
|
package com.zmops.iot.web.alarm.service;
import org.springframework.stereotype.Service;
/**
* @author yefei
**/
@Service
public class MediaTypeSettingService {
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/service/MediaTypeSettingService.java
|
Java
|
gpl-3.0
| 167
|
package com.zmops.iot.web.alarm.service;
import com.alibaba.fastjson.JSON;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.core.auth.model.LoginUser;
import com.zmops.iot.domain.messages.MessageBody;
import com.zmops.iot.domain.messages.Messages;
import com.zmops.iot.domain.messages.query.QMessages;
import com.zmops.iot.domain.sys.SysUser;
import com.zmops.iot.domain.sys.query.QSysUser;
import com.zmops.iot.message.handler.MessageEventHandler;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.alarm.dto.param.MessageParam;
import io.ebean.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 消息服务
**/
@Service
public class MessageService {
protected final static int sys = 1;
@Autowired
MessageEventHandler messageEventHandler;
/**
* 发送消息
*
* @param body
*/
public void push(MessageBody body) {
Objects.requireNonNull(body.getMsg());
List<Long> tos;
if (!CollectionUtils.isEmpty(body.getTo())) {
tos = body.getTo();
} else {
List<SysUser> userList = new QSysUser().findList();
tos = userList.parallelStream().map(SysUser::getUserId).collect(Collectors.toList());
}
if (body.isPersist()) {
tos.forEach(to -> {
Messages messages = new Messages();
messages.setClassify(sys);
messages.setTitle(body.getMsg());
messages.setUserId(to);
String content = "";
if (ToolUtil.isNotEmpty(body.getBody())) {
content = JSON.toJSONString(body.getBody());
messages.setContent(content);
}
messages.setClock(System.currentTimeMillis() / 1000);
saveMessage(messages);
});
}
body.addBody("classify", sys);
tos.forEach(to -> {
messageEventHandler.sendToUser(to + "", JSON.toJSONString(body));
});
}
/**
* 消息列表
*
* @param messageParam
* @return
*/
public Pager<Messages> list(MessageParam messageParam) {
LoginUser user = LoginContextHolder.getContext().getUser();
QMessages qMessages = new QMessages();
qMessages.userId.eq(user.getId());
if (messageParam.getReaded() != null) {
qMessages.readed.eq(messageParam.getReaded());
}
qMessages.orderBy(" readed asc, clock desc");
List<Messages> list = qMessages.setFirstRow((messageParam.getPage() - 1) * messageParam.getMaxRow())
.setMaxRows(messageParam.getMaxRow()).findList();
return new Pager<>(list, qMessages.findCount());
}
/**
* 读消息
*
* @param messageParam
* @return
*/
public List<Integer> read(MessageParam messageParam) {
LoginUser user = LoginContextHolder.getContext().getUser();
Messages messages = new Messages();
messages.setReaded(1);
QMessages qMessages = new QMessages();
if (!CollectionUtils.isEmpty(messageParam.getIds())) {
qMessages.id.in(messageParam.getIds());
}
qMessages.userId.eq(user.getId());
new QMessages().asUpdate().set("readed", 1).update();
return messageParam.getIds();
}
/**
* 未读消息数
*
* @return
*/
public Map<String, Object> unReadNum() {
LoginUser user = LoginContextHolder.getContext().getUser();
Map<String, Object> map = new HashMap<>();
int count = new QMessages().readed.eq(0).userId.eq(user.getId()).findCount();
map.put("count", count);
return map;
}
/**
* 消息详情
*
* @param id
* @return
*/
public Messages info(Integer id) {
return new QMessages().id.eq(id).findOne();
}
private void saveMessage(Messages messages) {
DB.save(messages);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/alarm/service/MessageService.java
|
Java
|
gpl-3.0
| 4,306
|
package com.zmops.iot.web.analyse.controller;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.analyse.dto.param.HistoryParam;
import com.zmops.iot.web.analyse.service.HistoryService;
import com.zmops.iot.web.auth.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 历史数据
**/
@RestController
@RequestMapping("/history")
public class HistoryController {
@Autowired
HistoryService historyService;
@RequestMapping("/query")
// @Permission(code = "latest")
public Pager<LatestDto> qeuryHistory(@Validated @RequestBody HistoryParam historyParam) {
return historyService.queryHistory(historyParam);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/controller/HistoryController.java
|
Java
|
gpl-3.0
| 1,003
|
package com.zmops.iot.web.analyse.controller;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.analyse.service.HomeService;
import com.zmops.iot.web.analyse.service.ZbxChartsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* @author yefei
* <p>
* 全局概览
**/
@RestController
@RequestMapping("/home")
public class HomeController {
@Autowired
HomeService homeService;
@Autowired
ZbxChartsService zbxChartsService;
/**
* 设备数量统计
*/
@RequestMapping("/deviceNum")
public ResponseData getDeviceNum(@RequestParam("timeFrom") Integer timeFrom, @RequestParam("timeTill") Integer timeTill) {
return ResponseData.success(homeService.getDeviceNum(timeFrom, timeTill));
}
/**
* 告警数量统计
*/
@RequestMapping("/alarmNum")
public ResponseData getAlarmNum(@RequestParam("timeFrom") long timeFrom, @RequestParam("timeTill") long timeTill) {
return ResponseData.success(homeService.getAlarmNum(timeFrom, timeTill));
}
/**
* 服务器取数速率
*
* @return
*/
@RequestMapping("/collectonRate")
public ResponseData collectonRate(@RequestParam("timeFrom") long timeFrom, @RequestParam("timeTill") long timeTill) {
return ResponseData.success(homeService.collectionRate(timeFrom, timeTill));
}
/**
* 事件数量统计
*/
@RequestMapping("/eventNum")
public ResponseData getEventNum(@RequestParam("timeFrom") long timeFrom, @RequestParam("timeTill") long timeTill) {
return ResponseData.success(homeService.getEventNum(timeFrom, timeTill));
}
/**
* 告警TOP统计
*/
@RequestMapping("/alarmTop")
public ResponseData getAlarmTop(@RequestParam("timeFrom") long timeFrom, @RequestParam("timeTill") long timeTill) {
return ResponseData.success(homeService.getAlarmTop(timeFrom, timeTill));
}
/**
* 服务调用统计
*/
@RequestMapping("/serviceExecuteNum")
public ResponseData serviceExecuteNum(@RequestParam("timeFrom") long timeFrom, @RequestParam("timeTill") long timeTill) {
return ResponseData.success(homeService.serviceExecuteNum(timeFrom, timeTill));
}
/**
* 数据量统计
*/
@RequestMapping("/dataLevel")
public ResponseData dataLevel() {
return ResponseData.success(homeService.dataLevel());
}
/**
* 获取 数据图形展示
*
* @param response http响应
* @param from 开始时间
* @param to 结束时间
* @param attrIds 设备属性ID
* @param width 图表宽度
* @param height 图表高度
*/
@RequestMapping("/getCharts")
public void getCookie(HttpServletResponse response,
@RequestParam("from") String from,
@RequestParam("to") String to,
@RequestParam("attrIds") List<Long> attrIds,
@RequestParam("width") String width,
@RequestParam("height") String height) {
zbxChartsService.getCharts(response, from, to, attrIds, width, height);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/controller/HomeController.java
|
Java
|
gpl-3.0
| 3,471
|
package com.zmops.iot.web.analyse.controller;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.analyse.dto.param.LatestParam;
import com.zmops.iot.web.analyse.service.LatestService;
import com.zmops.iot.web.auth.Permission;
import com.zmops.zeus.driver.service.TDEngineRest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 最新数据
**/
@RestController
@RequestMapping("/latest")
public class LatestController {
@Autowired
LatestService latestService;
@Autowired
private TDEngineRest tdEngineRest;
@RequestMapping("/query")
// @Permission(code = "latest")
public Pager<LatestDto> qeuryLatest(@Validated @RequestBody LatestParam latestParam) {
return latestService.qeuryLatest(latestParam);
}
@RequestMapping("/queryMap")
// @Permission(code = "latest")
public ResponseData queryMap(@RequestParam("deviceId") String deviceId) {
return ResponseData.success(latestService.queryMap(deviceId));
}
@RequestMapping("/tdexecutesql")
public ResponseData getTdEngineData(@RequestParam String sql) {
return ResponseData.success(tdEngineRest.executeSql(sql));
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/controller/LatestController.java
|
Java
|
gpl-3.0
| 1,612
|
package com.zmops.iot.web.analyse.controller;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.analyse.service.SelfMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* 自监控
**/
@RestController
@RequestMapping("/monitor/self")
public class SelfMonitorController {
@Autowired
SelfMonitorService selfMonitorService;
@GetMapping("memory")
public ResponseData getMemInfo(){
return ResponseData.success(selfMonitorService.getMemInfo());
}
@GetMapping("cpuLoad")
public ResponseData getCpuInfo(){
return ResponseData.success(selfMonitorService.getCpuLoadInfo());
}
@GetMapping("cpuUtilization")
public ResponseData getCpuUtilization(){
return ResponseData.success(selfMonitorService.getCpuUtilization());
}
@RequestMapping("process")
public ResponseData getProcessInfo(){
return ResponseData.success(selfMonitorService.getProcessInfo());
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/controller/SelfMonitorController.java
|
Java
|
gpl-3.0
| 1,260
|
package com.zmops.iot.web.analyse.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.zmops.iot.model.cache.filter.CachedValue;
import com.zmops.iot.model.cache.filter.CachedValueFilter;
import lombok.Data;
/**
* @author yefei
**/
@Data
@JsonSerialize(using = CachedValueFilter.class)
public class LatestDto {
private String name;
private String itemid;
private Long attrId;
private String key;
private String clock;
private String value;
private String originalValue;
private String change;
private String tags;
@CachedValue(value = "UNITS",fieldName = "unitsName")
private String units;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/dto/LatestDto.java
|
Java
|
gpl-3.0
| 678
|
package com.zmops.iot.web.analyse.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author yefei
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Mapping {
private Integer mappingid;
private Integer valuemapid;
private String value;
private String newvalue;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/dto/Mapping.java
|
Java
|
gpl-3.0
| 374
|
package com.zmops.iot.web.analyse.dto;
import lombok.Data;
import java.util.List;
/**
* @author yefei
**/
@Data
public class ValueMap {
private String valuemapid;
private String name;
private List<Mapping> mappings;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/dto/ValueMap.java
|
Java
|
gpl-3.0
| 237
|
package com.zmops.iot.web.analyse.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author yefei
**/
@Data
public class HistoryParam extends BaseQueryParam {
@NotNull(message = "请选择一个设备再查询")
private String deviceId;
private List<Long> attrIds;
private String timeFrom;
private String timeTill;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/dto/param/HistoryParam.java
|
Java
|
gpl-3.0
| 456
|
package com.zmops.iot.web.analyse.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author yefei
**/
@Data
public class LatestParam extends BaseQueryParam {
@NotNull(message = "请选择一个设备再查询")
private String deviceId;
private List<Long> attrIds;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/dto/param/LatestParam.java
|
Java
|
gpl-3.0
| 396
|
package com.zmops.iot.web.analyse.enums;
import lombok.Getter;
/**
* @author yefei
**/
public enum CpuLoadEnum {
avg1("system.cpu.load[all,avg1]", "cpuLoadAvg1"),
avg5("system.cpu.load[all,avg5]", "cpuLoadAvg5"),
avg15("system.cpu.load[all,avg15]", "cpuLoadAvg15");
@Getter
String code;
@Getter
String message;
CpuLoadEnum(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String status) {
if (status == null) {
return "";
} else {
for (CpuLoadEnum s : CpuLoadEnum.values()) {
if (s.getCode().equals(status)) {
return s.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/enums/CpuLoadEnum.java
|
Java
|
gpl-3.0
| 807
|
package com.zmops.iot.web.analyse.enums;
import lombok.Getter;
/**
* @author yefei
**/
public enum MemoryUtilizationEnum {
utilization("vm.memory.utilization", "memoryUtilization"),
total("vm.memory.size[total]", "memoryTotal"),
available("vm.memory.size[available]", "memoryAvailable");
@Getter
String code;
@Getter
String message;
MemoryUtilizationEnum(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String status) {
if (status == null) {
return "";
} else {
for (MemoryUtilizationEnum s : MemoryUtilizationEnum.values()) {
if (s.getCode().equals(status)) {
return s.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/enums/MemoryUtilizationEnum.java
|
Java
|
gpl-3.0
| 859
|
package com.zmops.iot.web.analyse.enums;
import lombok.Getter;
/**
* @author yefei
**/
public enum ProcessEnum {
num("proc.num", "num"),
run("proc.num[,,run]", "run"),
max("kernel.maxproc", "max");
@Getter
String code;
@Getter
String message;
ProcessEnum(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String status) {
if (status == null) {
return "";
} else {
for (ProcessEnum s : ProcessEnum.values()) {
if (s.getCode().equals(status)) {
return s.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/enums/ProcessEnum.java
|
Java
|
gpl-3.0
| 739
|
package com.zmops.iot.web.analyse.service;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.product.ProductAttribute;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.analyse.dto.Mapping;
import com.zmops.iot.web.analyse.dto.ValueMap;
import com.zmops.iot.web.analyse.dto.param.HistoryParam;
import com.zmops.zeus.driver.service.ZbxHistoryGet;
import com.zmops.zeus.driver.service.ZbxValueMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 历史数据服务
**/
@Service
public class HistoryService {
@Autowired
ZbxHistoryGet zbxHistoryGet;
@Autowired
ZbxValueMap zbxValueMap;
public Pager<LatestDto> queryHistory(HistoryParam historyParam) {
List<LatestDto> latestDtos = queryHistory(historyParam.getDeviceId(), historyParam.getAttrIds(),
dateTransfer(historyParam.getTimeFrom()),
dateTransfer(historyParam.getTimeTill()));
List<LatestDto> collect = latestDtos.stream().skip((historyParam.getPage() - 1) * historyParam.getMaxRow())
.limit(historyParam.getMaxRow()).collect(Collectors.toList());
return new Pager<>(collect, latestDtos.size());
}
private long dateTransfer(String date) {
LocalDateTime now = LocalDateTime.now();
if (ToolUtil.isEmpty(date) || date.equals("now")) {
return LocalDateTimeUtils.getSecondsByTime(now);
}
if (date.startsWith("now-")) {
String value = date.substring(date.indexOf("-") + 1, date.length() - 1);
String unit = date.substring(date.length() - 1);
switch (unit) {
case "m":
return LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.minu(now, Integer.valueOf(value), ChronoUnit.MINUTES));
case "d":
return LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.minu(now, Integer.valueOf(value), ChronoUnit.DAYS));
case "M":
return LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.minu(now, Integer.valueOf(value), ChronoUnit.MONTHS));
case "h":
return LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.minu(now, Integer.valueOf(value), ChronoUnit.HOURS));
case "y":
return LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.minu(now, Integer.valueOf(value), ChronoUnit.YEARS));
default:
return LocalDateTimeUtils.getSecondsByTime(now);
}
} else {
return LocalDateTimeUtils.getSecondsByStr(date);
}
}
public List<LatestDto> queryHistory(String deviceId, List<Long> attrIds, Long timeFrom, Long timeTill) {
//查询出设备
Device one = new QDevice().deviceId.eq(deviceId).findOne();
if (null == one || ToolUtil.isEmpty(one.getZbxId())) {
return Collections.emptyList();
}
//查询设备属性
QProductAttribute query = new QProductAttribute().productId.eq(deviceId);
if (ToolUtil.isNotEmpty(attrIds)) {
query.attrId.in(attrIds);
}
List<ProductAttribute> list = query.findList();
if (ToolUtil.isEmpty(list)) {
return Collections.emptyList();
}
//取出属性对应的ItemID
List<String> zbxIds = list.parallelStream().map(ProductAttribute::getZbxId).collect(Collectors.toList());
Map<String, List<ProductAttribute>> valueTypeMap = list.parallelStream().collect(Collectors.groupingBy(ProductAttribute::getValueType));
Map<String, ProductAttribute> itemIdMap = list.parallelStream().collect(Collectors.toMap(ProductAttribute::getZbxId, o -> o, (a, b) -> a));
List<LatestDto> latestDtos = new ArrayList<>();
if (null == timeFrom) {
timeFrom = LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.getDayStart(LocalDateTime.now()));
}
//根据属性值类型 分组查询历史数据
for (Map.Entry<String, List<ProductAttribute>> map : valueTypeMap.entrySet()) {
latestDtos.addAll(queryHitoryData(one.getZbxId(), zbxIds, 1000, Integer.parseInt(map.getKey()), timeFrom, timeTill));
}
//处理值映射
List<String> valuemapids = list.parallelStream().filter(o -> null != o.getValuemapid()).map(ProductAttribute::getValuemapid).collect(Collectors.toList());
Map<String, List<Mapping>> mappings = new ConcurrentHashMap<>(valuemapids.size());
if (!CollectionUtils.isEmpty(valuemapids)) {
String res = zbxValueMap.valueMapGet(valuemapids.toString());
List<ValueMap> mappingList = JSONObject.parseArray(res, ValueMap.class);
if (!CollectionUtils.isEmpty(mappingList)) {
mappings = mappingList.stream().collect(Collectors.toMap(ValueMap::getValuemapid, ValueMap::getMappings, (a, b) -> a));
}
}
Map<String, List<Mapping>> finalMappings = mappings;
latestDtos.forEach(latestDto -> {
latestDto.setClock(LocalDateTimeUtils.convertTimeToString(Integer.parseInt(latestDto.getClock()), "yyyy-MM-dd HH:mm:ss"));
if (null != itemIdMap.get(latestDto.getItemid())) {
latestDto.setName(itemIdMap.get(latestDto.getItemid()).getName());
latestDto.setAttrId(itemIdMap.get(latestDto.getItemid()).getAttrId());
latestDto.setUnits(itemIdMap.get(latestDto.getItemid()).getUnits());
String valueMapid = itemIdMap.get(latestDto.getItemid()).getValuemapid();
if (null != valueMapid) {
List<Mapping> mappingList = finalMappings.get(valueMapid);
if (!CollectionUtils.isEmpty(mappingList)) {
Map<String, String> mappingMap = mappingList.parallelStream().collect(Collectors.toMap(Mapping::getValue, Mapping::getNewvalue, (a, b) -> a));
latestDto.setValue(mappingMap.get(latestDto.getValue()));
}
}
}
});
return latestDtos;
}
public List<LatestDto> queryHitoryData(String hostId, List<String> itemIds, int hisNum, Integer valueType, Long timeFrom, Long timeTill) {
String res = zbxHistoryGet.historyGet(hostId, itemIds, hisNum, valueType, timeFrom, timeTill);
return JSONObject.parseArray(res, LatestDto.class);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/service/HistoryService.java
|
Java
|
gpl-3.0
| 7,153
|
package com.zmops.iot.web.analyse.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.http.ForestResponse;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.alarm.Problem;
import com.zmops.iot.domain.alarm.query.QProblem;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.DeviceOnlineReport;
import com.zmops.iot.domain.device.EventTriggerRecord;
import com.zmops.iot.domain.device.ServiceExecuteRecord;
import com.zmops.iot.domain.device.query.QDeviceOnlineReport;
import com.zmops.iot.domain.device.query.QEventTriggerRecord;
import com.zmops.iot.domain.device.query.QScenesTriggerRecord;
import com.zmops.iot.domain.device.query.QServiceExecuteRecord;
import com.zmops.iot.domain.product.query.QProduct;
import com.zmops.iot.enums.SeverityEnum;
import com.zmops.iot.enums.ValueType;
import com.zmops.iot.util.DefinitionsUtil;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ParseUtil;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.alarm.dto.AlarmDto;
import com.zmops.iot.web.alarm.dto.param.AlarmParam;
import com.zmops.iot.web.alarm.service.AlarmService;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.device.dto.TaosResponseData;
import com.zmops.iot.web.device.dto.param.DeviceParams;
import com.zmops.iot.web.device.service.DeviceService;
import com.zmops.zeus.driver.entity.ZbxItemInfo;
import com.zmops.zeus.driver.service.TDEngineRest;
import com.zmops.zeus.driver.service.ZbxHost;
import com.zmops.zeus.driver.service.ZbxItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 全局概览服务
**/
@Service
public class HomeService {
@Autowired
private ZbxHost zbxHost;
@Autowired
private ZbxItem zbxItem;
@Autowired
HistoryService historyService;
@Autowired
AlarmService alarmService;
@Autowired
TDEngineRest tdEngineRest;
@Autowired
DeviceService deviceService;
private static String hostId = "";
private static final Map<String, String> ITEM_Map = new ConcurrentHashMap<>(5);
//Zbx 指标取数速率 key
private static final String KEY = "zabbix[wcache,values";
/**
* 服务器取数速率统计
*
* @return
*/
public List<Map<String, Object>> collectionRate(long timeFrom, long timeTill) {
if (ToolUtil.isEmpty(hostId)) {
if (ToolUtil.isEmpty(getZbxServerId())) {
return Collections.emptyList();
}
}
if (ToolUtil.isEmpty(ITEM_Map)) {
if (ToolUtil.isEmpty(getItemMap())) {
return Collections.emptyList();
}
}
List<LatestDto> latestDtos = new ArrayList<>();
ITEM_Map.forEach((key, value) -> {
latestDtos.addAll(historyService.queryHitoryData(hostId, Collections.singletonList(key), 10000, 0, timeFrom, timeTill));
});
latestDtos.forEach(latestDto -> {
latestDto.setClock(LocalDateTimeUtils.convertTimeToString(Integer.parseInt(latestDto.getClock()), "yyyy-MM-dd"));
if (null != ITEM_Map.get(latestDto.getItemid())) {
latestDto.setName(ITEM_Map.get(latestDto.getItemid()));
}
});
Map<String, Map<String, Double>> collect = latestDtos.parallelStream().collect(
Collectors.groupingBy(LatestDto::getName, Collectors.groupingBy(
LatestDto::getClock, Collectors.averagingDouble(o -> Double.parseDouble(o.getValue()))))
);
List<Map<String, Object>> collectList = new ArrayList<>();
collect.forEach((key, value) -> {
Map<String, Object> collectMap = new HashMap<>(2);
List<Map<String, Object>> tmpList = new ArrayList<>();
value.forEach((date, val) -> {
Map<String, Object> valMap = new HashMap<>(2);
valMap.put("date", date);
valMap.put("val", val);
tmpList.add(valMap);
});
List<Map<String, Object>> dataList = tmpList.parallelStream().sorted(
Comparator.comparing(o -> o.get("date").toString())).collect(Collectors.toList());
collectMap.put("name", ValueType.getVal(key));
collectMap.put("data", dataList);
collectList.add(collectMap);
});
return collectList;
}
/**
* 获取服务器 hostid
*
* @return
*/
private String getZbxServerId() {
String response = zbxHost.hostGet("Zabbix server");
List<Map<String, String>> ids = JSON.parseObject(response, List.class);
if (null != ids && ids.size() > 0) {
hostId = ids.get(0).get("hostid");
return hostId;
}
return "";
}
/**
* 获取服务器 取数的ITEM
*
* @return
*/
private Map<String, String> getItemMap() {
String itemList = zbxItem.getItemList(KEY, hostId);
List<ZbxItemInfo> itemInfos = JSONObject.parseArray(itemList, ZbxItemInfo.class);
for (ZbxItemInfo itemInfo : itemInfos) {
ITEM_Map.put(itemInfo.getItemid(), formatName(itemInfo.getName()));
}
return ITEM_Map;
}
/**
* 格式化显示的名称
*/
private static String formatName(String name) {
if (name.length() < 53) {
return "avg";
}
return name.substring(35, name.length() - 18);
}
/**
* 统计设备数量
*
* @return
*/
public Map<String, Object> getDeviceNum(Integer timeFrom, Integer timeTill) {
Map<String, Object> deviceNumMap = new HashMap<>(4);
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
List<Device> list = deviceService.deviceList(new DeviceParams());
deviceNumMap.put("total", list.size());
deviceNumMap.put("disable", (int) list.parallelStream().filter(o -> "DISABLE".equals(o.getStatus())).count());
deviceNumMap.put("online", (int) list.parallelStream().filter(o -> null != o.getOnline() && 1 == o.getOnline()).count());
QProduct qProduct = new QProduct();
if (tenantId != null) {
qProduct.tenantId.eq(tenantId);
}
deviceNumMap.put("product", qProduct.findCount());
QDeviceOnlineReport qDeviceOnlineReport = new QDeviceOnlineReport()
.createTime.ge(LocalDateTimeUtils.convertTimeToString(timeFrom, "yyyy-MM-dd"))
.createTime.lt(LocalDateTimeUtils.convertTimeToString(timeTill, "yyyy-MM-dd"));
if (tenantId != null) {
qDeviceOnlineReport.tenantId.eq(tenantId);
}
List<DeviceOnlineReport> onLineList = qDeviceOnlineReport.findList();
Map<String, Long> collect = onLineList.parallelStream()
.collect(Collectors.groupingBy(DeviceOnlineReport::getCreateTime, Collectors.summingLong(DeviceOnlineReport::getOnline)));
List<Map<String, Object>> trendsList = new ArrayList<>();
collect.forEach((key, value) -> {
Map<String, Object> map = new ConcurrentHashMap<>(2);
map.put("date", key);
map.put("val", value);
trendsList.add(map);
});
List<Map<String, Object>> result = trendsList.parallelStream()
.sorted(Comparator.comparing(o -> o.get("date").toString())).collect(Collectors.toList());
deviceNumMap.put("trends", result);
return deviceNumMap;
}
/**
* 告警数量统计
*
* @return
*/
private static final String[] severity = {"", "信息", "低级", "中级", "高级", "紧急"};
public Map<String, Object> getAlarmNum(long timeFrom, long timeTill) {
List<Problem> alarmList = new QProblem().clock.ge(LocalDateTimeUtils.getLDTBySeconds((int) timeFrom))
.clock.lt(LocalDateTimeUtils.getLDTBySeconds((int) timeTill)).rClock.isNull().orderBy().clock.asc().findList();
Map<String, Object> alarmMap = new ConcurrentHashMap<>(3);
Map<String, Map<String, Long>> initMap = new ConcurrentHashMap<>(5);
for (String s : severity) {
if (ToolUtil.isEmpty(s)) {
continue;
}
initMap.put(s, initMap(timeFrom, timeTill));
}
alarmMap.put("total", alarmList.size());
Collections.reverse(alarmList);
//过滤出指定时间段内的告警 并顺序排序
Map<String, Map<String, Long>> tmpMap = alarmList.parallelStream()
.filter(o -> o.getSeverity() > 0).collect(
Collectors.groupingBy(o -> o.getSeverity() + "", Collectors.groupingBy(
o -> LocalDateTimeUtils.formatTime(o.getClock(), "yyyy-MM-dd"), Collectors.counting())));
List<Map<String, Object>> trendsList = new ArrayList<>();
initMap.forEach((key, value) -> {
Map<String, Object> trendsMap = new ConcurrentHashMap<>(2);
List<Map<String, Object>> list = new ArrayList<>();
value.forEach((date, val) -> {
Map<String, Object> valMap = new ConcurrentHashMap<>(2);
valMap.put("date", date);
valMap.put("val", Optional.ofNullable(tmpMap.get(SeverityEnum.getVal(key))).map(o -> o.get(date)).orElse(val));
list.add(valMap);
});
list.sort(Comparator.comparing(o -> o.get("date").toString()));
trendsMap.put("name", key);
trendsMap.put("data", list);
trendsList.add(trendsMap);
});
alarmMap.put("trends", trendsList);
//今日开始时间
Long timeStart = LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.getDayStart(LocalDateTime.now()));
AlarmParam todayParam = new AlarmParam();
todayParam.setTimeFrom(timeStart);
List<AlarmDto> todayAlarmList = alarmService.getAlarmList(todayParam);
Long todayAlarmNum = todayAlarmList.parallelStream().filter(o -> !o.getSeverity().equals("0")).count();
alarmMap.put("today", todayAlarmNum);
return alarmMap;
}
/**
* 事件数量统计
*/
public Map<String, Object> getEventNum(long timeFrom, long timeTill) {
List<EventTriggerRecord> list = new QEventTriggerRecord().createTime.ge(LocalDateTimeUtils.getLDTBySeconds((int) timeFrom))
.createTime.lt(LocalDateTimeUtils.getLDTBySeconds((int) timeTill)).orderBy().createTime.asc().findList();
Map<String, Object> eventMap = new HashMap<>(3);
if (ToolUtil.isNotEmpty(list)) {
eventMap.put("total", list.size());
Map<String, Long> initMap = initMap(timeFrom, timeTill);
Map<String, Long> tmpMap = list.parallelStream().collect(
Collectors.groupingBy(o -> LocalDateTimeUtils.formatTime(o.getCreateTime(), "yyyy-MM-dd"), Collectors.counting()));
List<Map<String, Object>> trendsList = new ArrayList<>();
initMap.forEach((key, value) -> {
Map<String, Object> valMap = new ConcurrentHashMap<>(2);
valMap.put("date", key);
valMap.put("val", Optional.ofNullable(tmpMap.get(key)).orElse(value));
trendsList.add(valMap);
});
trendsList.sort(Comparator.comparing(o -> o.get("date").toString()));
eventMap.put("trends", trendsList);
}
//今日开始时间
long timeStart = LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.getDayStart(LocalDateTime.now()));
long todayNum = new QEventTriggerRecord().createTime.ge(LocalDateTimeUtils.getLDTBySeconds((int) timeStart)).findCount();
eventMap.put("today", todayNum);
return eventMap;
}
/**
* 告警TOP统计
*/
public List<Map<String, Object>> getAlarmTop(long timeFrom, long timeTill) {
AlarmParam alarmParam = new AlarmParam();
alarmParam.setTimeTill(timeTill);
alarmParam.setTimeFrom(timeFrom);
List<AlarmDto> alarmList = alarmService.getAlarmList(alarmParam);
Map<String, Long> tmpMap = new ConcurrentHashMap<>();
if (ToolUtil.isNotEmpty(alarmList)) {
tmpMap = alarmList.parallelStream().collect(Collectors.groupingBy(AlarmDto::getDeviceId, Collectors.counting()));
}
List<Map<String, Object>> topList = new ArrayList<>();
tmpMap.forEach((key, value) -> {
if (DefinitionsUtil.getDeviceName(key) == null) {
return;
}
Map<String, Object> alarmMap = new ConcurrentHashMap<>(2);
alarmMap.put("name", DefinitionsUtil.getDeviceName(key));
alarmMap.put("value", value);
topList.add(alarmMap);
});
topList.sort(Comparator.comparing(o -> Integer.parseInt(o.get("value").toString())));
topList.subList(0, Math.min(topList.size(), 5));
return topList;
}
/**
* 服务调用统计
*/
public Map<String, Object> serviceExecuteNum(long timeFrom, long timeTill) {
QServiceExecuteRecord query = new QServiceExecuteRecord().createTime.ge(LocalDateTimeUtils.getLDTBySeconds((int) timeFrom))
.createTime.lt(LocalDateTimeUtils.getLDTBySeconds((int) timeTill));
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
if (null != tenantId) {
query.tenantId.eq(tenantId);
}
List<ServiceExecuteRecord> list = query.orderBy().createTime.asc().findList();
Map<String, Object> executeMap = new ConcurrentHashMap<>(3);
if (ToolUtil.isNotEmpty(list)) {
executeMap.put("total", list.size());
Map<String, Long> initMap = initMap(timeFrom, timeTill);
Map<String, Long> tmpMap = list.parallelStream().collect(Collectors.groupingBy(o -> LocalDateTimeUtils.formatTime(o.getCreateTime(),
"yyyy-MM-dd"), Collectors.counting()));
List<Map<String, Object>> trendsList = new ArrayList<>();
initMap.forEach((key, value) -> {
Map<String, Object> valMap = new ConcurrentHashMap<>(2);
valMap.put("date", key);
valMap.put("val", Optional.ofNullable(tmpMap.get(key)).orElse(value));
trendsList.add(valMap);
});
trendsList.sort(Comparator.comparing(o -> o.get("date").toString()));
executeMap.put("trends", trendsList);
}
//今日开始时间
long timeStart = LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.getDayStart(LocalDateTime.now()));
query = new QServiceExecuteRecord().createTime.ge(LocalDateTimeUtils.getLDTBySeconds((int) timeStart));
if (null != tenantId) {
query.tenantId.eq(tenantId);
}
long todayNum = query.findCount();
executeMap.put("today", todayNum);
return executeMap;
}
/**
* 数据量统计
*/
public Map<String, Object> dataLevel() {
Map<String, Object> dataMap = new ConcurrentHashMap<>(4);
dataMap.put("totalRecordNum", ParseUtil.getCommaFormat(getRecordNum() + ""));
dataMap.put("todayRecordNum", ParseUtil.getCommaFormat(getTodayRecordNum(
LocalDateTimeUtils.formatTime(LocalDateTimeUtils.getDayStart(LocalDateTime.now()))) + ""));
QServiceExecuteRecord qServiceExecuteRecord = new QServiceExecuteRecord();
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
if (null != tenantId) {
qServiceExecuteRecord.tenantId.eq(tenantId);
}
int serviceExecuteNum = qServiceExecuteRecord.findCount();
dataMap.put("serviceExecuteNum", ParseUtil.getCommaFormat(serviceExecuteNum + ""));
QScenesTriggerRecord qScenesTriggerRecord = new QScenesTriggerRecord();
if (null != tenantId) {
qScenesTriggerRecord.tenantId.eq(tenantId);
}
int sceneTriggerNum = qScenesTriggerRecord.findCount();
dataMap.put("sceneTriggerNum", ParseUtil.getCommaFormat(sceneTriggerNum + ""));
return dataMap;
}
private int getRecordNum() {
int totalRecord = 0;
String sql = "select count(1) from history";
totalRecord += getRecordNum(sql);
sql = "select count(1) from history_uint";
totalRecord += getRecordNum(sql);
return totalRecord;
}
private int getTodayRecordNum(String time) {
int totalRecord = 0;
String sql = "select count(1) from history where clock>'" + time + "'";
totalRecord += getRecordNum(sql);
sql = "select count(1) from history_uint where clock>'" + time + "'";
totalRecord += getRecordNum(sql);
return totalRecord;
}
private int getRecordNum(String sql) {
ForestResponse<String> res_history = tdEngineRest.executeSql(sql);
if (res_history.isError()) {
return 0;
}
String res = res_history.getContent();
TaosResponseData taosResponseData = JSON.parseObject(res, TaosResponseData.class);
String[][] data_history = taosResponseData.getData();
if (data_history.length > 0) {
return Integer.parseInt(data_history[0][0]);
}
return 0;
}
private Map<String, Long> initMap(long start, long end) {
long l = LocalDateTimeUtils.betweenTwoTime(LocalDateTimeUtils.getLDTBySeconds((int) start), LocalDateTimeUtils.getLDTBySeconds((int) end), ChronoUnit.DAYS);
Map<String, Long> map = new HashMap<>((int) l);
map.put(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.getLDTBySeconds((int) start), "yyyy-MM-dd"), 0L);
for (long i = 1; i <= l; i++) {
map.put(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.plus(LocalDateTimeUtils.getLDTBySeconds((int) start), i, ChronoUnit.DAYS), "yyyy-MM-dd"), 0L);
}
return map;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/service/HomeService.java
|
Java
|
gpl-3.0
| 18,377
|
package com.zmops.iot.web.analyse.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.http.ForestResponse;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.product.ProductAttribute;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ParseUtil;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.analyse.dto.Mapping;
import com.zmops.iot.web.analyse.dto.ValueMap;
import com.zmops.iot.web.analyse.dto.param.LatestParam;
import com.zmops.iot.web.device.dto.TaosResponseData;
import com.zmops.iot.web.init.BasicSettingsInit;
import com.zmops.zeus.driver.service.TDEngineRest;
import com.zmops.zeus.driver.service.ZbxHistoryGet;
import com.zmops.zeus.driver.service.ZbxValueMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 最新数据服务
**/
@Service
public class LatestService {
@Autowired
ZbxHistoryGet zbxHistoryGet;
@Autowired
ZbxValueMap zbxValueMap;
@Autowired
TDEngineRest tdEngineRest;
/**
* 查询最新数据
*
* @param latestParam
* @return
*/
public Pager<LatestDto> qeuryLatest(LatestParam latestParam) {
List<LatestDto> latestDtos = qeuryLatest(latestParam.getDeviceId(), latestParam.getAttrIds());
List<LatestDto> collect = latestDtos.stream().skip((latestParam.getPage() - 1) * latestParam.getMaxRow())
.limit(latestParam.getMaxRow()).collect(Collectors.toList());
return new Pager<>(collect, latestDtos.size());
}
public List<LatestDto> qeuryLatest(String deviceId, List<Long> attrIds) {
//查询出设备
Device one = new QDevice().deviceId.eq(deviceId).findOne();
if (null == one || ToolUtil.isEmpty(one.getZbxId())) {
return Collections.emptyList();
}
//查询设备属性
QProductAttribute query = new QProductAttribute().productId.eq(deviceId);
if (ToolUtil.isNotEmpty(attrIds)) {
query.attrId.in(attrIds);
}
List<ProductAttribute> list = query.findList();
if (ToolUtil.isEmpty(list)) {
return Collections.emptyList();
}
Map<String, List<ProductAttribute>> valueTypeMap = list.parallelStream().collect(Collectors.groupingBy(ProductAttribute::getValueType));
Map<String, ProductAttribute> itemIdMap = list.parallelStream().collect(Collectors.toMap(ProductAttribute::getZbxId, o -> o, (a, b) -> a));
List<LatestDto> latestDtos;
if (checkTDengine()) {
latestDtos = queryLatestFromTD(deviceId, valueTypeMap);
} else {
latestDtos = queryLatestFromZbx(one.getZbxId(), valueTypeMap);
}
//处理值映射
List<String> valuemapids = list.parallelStream().filter(o -> null != o.getValuemapid()).map(ProductAttribute::getValuemapid).collect(Collectors.toList());
Map<String, List<Mapping>> mappings = new ConcurrentHashMap<>(valuemapids.size());
if (!CollectionUtils.isEmpty(valuemapids)) {
String res = zbxValueMap.valueMapGet(valuemapids.toString());
List<ValueMap> mappingList = JSONObject.parseArray(res, ValueMap.class);
if (!CollectionUtils.isEmpty(mappingList)) {
mappings = mappingList.stream().collect(Collectors.toMap(ValueMap::getValuemapid, ValueMap::getMappings, (a, b) -> a));
}
}
Map<String, List<Mapping>> finalMappings = mappings;
latestDtos.forEach(latestDto -> {
// latestDto.setClock(LocalDateTimeUtils.convertTimeToString(Integer.parseInt(latestDto.getClock()), "yyyy-MM-dd HH:mm:ss"));
latestDto.setOriginalValue(latestDto.getValue());
if (null != itemIdMap.get(latestDto.getItemid())) {
latestDto.setName(itemIdMap.get(latestDto.getItemid()).getName());
latestDto.setAttrId(itemIdMap.get(latestDto.getItemid()).getAttrId());
latestDto.setUnits(itemIdMap.get(latestDto.getItemid()).getUnits());
latestDto.setKey(itemIdMap.get(latestDto.getItemid()).getKey());
String valueMapid = itemIdMap.get(latestDto.getItemid()).getValuemapid();
if (null != valueMapid) {
List<Mapping> mappingList = finalMappings.get(valueMapid);
if (!CollectionUtils.isEmpty(mappingList)) {
Map<String, String> mappingMap = mappingList.parallelStream().collect(Collectors.toMap(Mapping::getValue, Mapping::getNewvalue, (a, b) -> a));
latestDto.setValue(mappingMap.get(latestDto.getValue()));
}
}
}
});
return latestDtos;
}
private boolean checkTDengine() {
String sql = String.format("select LAST_ROW(*) from history_uint where deviceid = 'Zabbix server';");
try {
ForestResponse<String> resHistory = tdEngineRest.executeSql(sql);
if (resHistory.isError()) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
//从TDengine取数
public List<LatestDto> queryLatestFromTD(String deviceId, Map<String, List<ProductAttribute>> valueTypeMap) {
List<LatestDto> latestDtos = new ArrayList<>();
//根据属性值类型 分组查询最新数据
for (Map.Entry<String, List<ProductAttribute>> map : valueTypeMap.entrySet()) {
//取出属性对应的ItemID
List<String> itemIds = map.getValue().parallelStream().map(ProductAttribute::getZbxId).collect(Collectors.toList());
latestDtos.addAll(queryLatestFromTD(deviceId, itemIds, Integer.parseInt(map.getKey())));
}
return latestDtos;
}
private List<LatestDto> queryLatestFromTD(String deviceId, List<String> itemIds, int unitType) {
String itemids = "'" + itemIds.parallelStream().collect(Collectors.joining("','")) + "'";
String sql = String.format("select LAST_ROW(*) from %s where deviceid = '%s' and itemid in (%s) group by itemid;", getHistoryTableName(unitType), deviceId, itemids);
ForestResponse<String> resHistory = tdEngineRest.executeSql(sql);
if (resHistory.isError()) {
return Collections.emptyList();
}
String res = resHistory.getContent();
TaosResponseData taosResponseData = JSON.parseObject(res, TaosResponseData.class);
String[][] dataHistory = taosResponseData.getData();
List<LatestDto> latestDtos = new ArrayList<>();
if (dataHistory.length > 0) {
for (String[] data : dataHistory) {
LatestDto latestDto = new LatestDto();
latestDto.setClock(LocalDateTimeUtils.formatTime(LocalDateTimeUtils.dateToStamp(data[0])));
latestDto.setValue(ParseUtil.getFormatFloat(data[1]));
latestDto.setItemid(data[2]);
latestDtos.add(latestDto);
}
}
return latestDtos;
}
private static String getHistoryTableName(int unitType) {
switch (unitType) {
case 0:
return "history";
case 1:
return "history_str";
case 3:
return "history_uint";
case 4:
return "history_text";
default:
throw new UnsupportedOperationException();
}
}
//从Zbx接口取数
private List<LatestDto> queryLatestFromZbx(String zbxId, Map<String, List<ProductAttribute>> valueTypeMap) {
List<LatestDto> latestDtos = new ArrayList<>();
//根据属性值类型 分组查询最新数据
for (Map.Entry<String, List<ProductAttribute>> map : valueTypeMap.entrySet()) {
//取出属性对应的ItemID
List<String> itemIds = map.getValue().parallelStream().map(ProductAttribute::getZbxId).collect(Collectors.toList());
String res = zbxHistoryGet.historyGet(zbxId, itemIds, map.getValue().size(), Integer.parseInt(map.getKey()), null, null);
latestDtos.addAll(JSONObject.parseArray(res, LatestDto.class));
}
//根据itemid去重
latestDtos = latestDtos.parallelStream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(LatestDto::getItemid))),
ArrayList::new)
);
latestDtos.forEach(latestDto -> latestDto.setClock(LocalDateTimeUtils.convertTimeToString(Integer.parseInt(latestDto.getClock()), "yyyy-MM-dd HH:mm:ss")));
return latestDtos;
}
/**
* 取事件属性 最新数据
*
* @return List
*/
public List<LatestDto> queryEventLatest(String hostid, List<String> zbxIds, int valueType) {
//根据属性值类型 查询最新数据
String res = zbxHistoryGet.historyGetWithNoAuth(hostid, zbxIds, 1, valueType, BasicSettingsInit.zbxApiToken);
List<LatestDto> latestDtos = JSONObject.parseArray(res, LatestDto.class);
latestDtos.forEach(latestDto -> {
latestDto.setClock(LocalDateTimeUtils.convertTimeToString(Integer.parseInt(latestDto.getClock()), "yyyy-MM-dd HH:mm:ss"));
latestDto.setOriginalValue(latestDto.getValue());
});
return latestDtos;
}
public Map<String, Object> queryMap(String deviceId) {
List<LatestDto> latestDtos = qeuryLatest(deviceId, Collections.emptyList());
if (ToolUtil.isEmpty(latestDtos)) {
return new HashMap<>(0);
}
return latestDtos.parallelStream().collect(Collectors.toMap(LatestDto::getKey, LatestDto::getValue, (a, b) -> a));
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/service/LatestService.java
|
Java
|
gpl-3.0
| 10,280
|
package com.zmops.iot.web.analyse.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ObjectUtils;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.analyse.enums.CpuLoadEnum;
import com.zmops.iot.web.analyse.enums.MemoryUtilizationEnum;
import com.zmops.iot.web.analyse.enums.ProcessEnum;
import com.zmops.iot.web.product.dto.ZbxTriggerInfo;
import com.zmops.zeus.driver.entity.ZbxItemInfo;
import com.zmops.zeus.driver.service.ZbxHistoryGet;
import com.zmops.zeus.driver.service.ZbxHost;
import com.zmops.zeus.driver.service.ZbxItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@Service
public class SelfMonitorService {
@Autowired
ZbxHistoryGet zbxHistoryGet;
@Autowired
ZbxHost zbxHost;
@Autowired
ZbxItem zbxItem;
@Autowired
HistoryService historyService;
private static Map<String, String> itemMap = new HashMap<>();
private static Map<String, String> hostIdMap = new HashMap<>();
public Map<String, Object> getMemInfo() {
Map<String, Object> resMap = new HashMap<>(3);
getItemValue(getHostId("Zabbix server"), MemoryUtilizationEnum.utilization.getCode(), MemoryUtilizationEnum.utilization.getMessage(), 0, "%", resMap);
getItemValue(getHostId("Zabbix server"), MemoryUtilizationEnum.total.getCode(), MemoryUtilizationEnum.total.getMessage(), 3, "B", resMap);
getItemValue(getHostId("Zabbix server"), MemoryUtilizationEnum.available.getCode(), MemoryUtilizationEnum.available.getMessage(), 3, "B", resMap);
resMap.put("trends", getTrendsData(getHostId("Zabbix server"), itemMap.get(MemoryUtilizationEnum.utilization.getMessage()), 0, "%"));
return resMap;
}
public Map<String, Object> getCpuLoadInfo() {
Map<String, Object> resMap = new HashMap<>(3);
getItemValue(getHostId("Zabbix server"), CpuLoadEnum.avg1.getCode(), CpuLoadEnum.avg1.getMessage(), 0, "%", resMap);
getItemValue(getHostId("Zabbix server"), CpuLoadEnum.avg5.getCode(), CpuLoadEnum.avg5.getMessage(), 0, "%", resMap);
getItemValue(getHostId("Zabbix server"), CpuLoadEnum.avg15.getCode(), CpuLoadEnum.avg15.getMessage(), 0, "%", resMap);
resMap.put("trends", getTrendsData(getHostId("Zabbix server"), itemMap.get(CpuLoadEnum.avg1.getMessage()), 0, "%"));
return resMap;
}
public Map<String, Object> getProcessInfo() {
Map<String, Object> resMap = new HashMap<>(3);
getItemValue(getHostId("Zabbix server"), ProcessEnum.num.getCode(), ProcessEnum.num.getMessage(), 3, "个", resMap);
getItemValue(getHostId("Zabbix server"), ProcessEnum.run.getCode(), ProcessEnum.run.getMessage(), 3, "个", resMap);
getItemValue(getHostId("Zabbix server"), ProcessEnum.max.getCode(), ProcessEnum.max.getMessage(), 3, "个", resMap);
resMap.put("trends", getTrendsData(getHostId("Zabbix server"), itemMap.get(ProcessEnum.run.getMessage()), 3, "个"));
return resMap;
}
public List<Map<String, String>> getCpuUtilization() {
String itemId = getItemId(getHostId("Zabbix server"), "CpuUtilization", "system.cpu.util");
if (ToolUtil.isEmpty(itemId)) {
return Collections.emptyList();
}
return getTrendsData(getHostId("Zabbix server"), itemId, 0, "%");
}
/**
* 获取趋势数据
*
* @param hostId 主机ID
* @param itemId 监控项ID
* @param itemValueType 监控项值类型
* @return
*/
private List<Map<String, String>> getTrendsData(String hostId, String itemId, int itemValueType, String unit) {
long timeTill = LocalDateTimeUtils.getSecondsByTime(LocalDateTime.now());
long timeFrom = LocalDateTimeUtils.getSecondsByTime(LocalDateTimeUtils.minu(LocalDateTime.now(), 1L, ChronoUnit.HOURS));
List<LatestDto> latestDtos = historyService.queryHitoryData(hostId, Collections.singletonList(itemId), 20, itemValueType, timeFrom, timeTill);
return latestDtos.stream().map(o -> {
Map<String, String> tmpMap = new HashMap<>(2);
tmpMap.put("date", LocalDateTimeUtils.convertTimeToString(Integer.parseInt(o.getClock()), "yyyy-MM-dd HH:mm:ss"));
String value = ObjectUtils.convertUnits(o.getValue(), unit);
tmpMap.put("val", value);
return tmpMap;
}).collect(Collectors.toList());
}
/**
* 获取监控项最新值
*
* @param hostId 主机ID
* @param key 监控项key
* @param name 监控项名称
* @param itemValueType 监控项值类型
* @param resMap map
*/
private void getItemValue(String hostId, String key, String name, int itemValueType, String unit, Map<String, Object> resMap) {
String itemId = getItemId(hostId, name, key);
if (ToolUtil.isEmpty(itemId)) {
return;
}
String res = zbxHistoryGet.historyGet(null, Collections.singletonList(itemId), 1, itemValueType, null, null);
List<LatestDto> latestDtos = JSONObject.parseArray(res, LatestDto.class);
if (ToolUtil.isNotEmpty(latestDtos)) {
String value = ObjectUtils.convertUnits(latestDtos.get(0).getValue(), unit);
resMap.put(name, value);
}
}
/**
* 从缓存取 hostId
*
* @param host 主机名称
* @return hostId
*/
private String getHostId(String host) {
String hostId = hostIdMap.get(host);
if (ToolUtil.isEmpty(hostId)) {
hostId = getHostIdByName(host);
hostIdMap.put(host, hostId);
}
return hostId;
}
/**
* 从Zbx取 hostId
*
* @param host 主机名称
* @return hostId
*/
private String getHostIdByName(String host) {
String s = zbxHost.hostGet(host);
List<ZbxTriggerInfo.Host> hosts = JSON.parseArray(s, ZbxTriggerInfo.Host.class);
if (ToolUtil.isNotEmpty(hosts)) {
return hosts.get(0).getHostid();
}
return "";
}
/**
* 从缓存取 itemId
*
* @param hostId 主机ID
* @param name 监控项名称
* @param key 监控项key
* @return itemId
*/
private String getItemId(String hostId, String name, String key) {
String itemId = itemMap.get(name);
if (ToolUtil.isEmpty(itemId)) {
itemId = getItemIdByName(hostId, key);
itemMap.put(name, itemId);
}
return itemId;
}
/**
* 从Zbx取 itemId
*
* @param hostId 主机ID
* @param key 监控项key
* @return itemId
*/
private String getItemIdByName(String hostId, String key) {
if (ToolUtil.isEmpty(key) || ToolUtil.isEmpty(hostId)) {
return "";
}
String item = zbxItem.getItemList(key, hostId);
List<ZbxItemInfo> itemInfos = JSON.parseArray(item, ZbxItemInfo.class);
if (ToolUtil.isNotEmpty(itemInfos)) {
return itemInfos.get(0).getItemid();
}
return "";
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/service/SelfMonitorService.java
|
Java
|
gpl-3.0
| 7,524
|
package com.zmops.iot.web.analyse.service;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ToolUtil;
import com.zmops.zeus.driver.entity.ZbxItemInfo;
import com.zmops.zeus.driver.service.ZbxItem;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
/**
* @author yefei
* <p>
* 全局概览服务
**/
@Service
public class ZbxChartsService {
@Value("${forest.variables.zbxServerIp}")
private String zbxServerIp;
@Value("${forest.variables.zbxServerPort}")
private String zbxServerPort;
private static String COOKIE = "";
private static LocalDateTime COOKIE_TIME;
@Autowired
ZbxItem zbxItem;
/**
* 获取 数据图形展示
*
* @param response http响应
* @param from 开始时间
* @param to 结束时间
* @param attrIds 设备属性ID
* @param width 图表宽度
* @param height 图表高度
*/
public void getCharts(HttpServletResponse response,
String from, String to,
List<Long> attrIds, String width, String height) {
OutputStream out = null;
if (ToolUtil.isEmpty(COOKIE) ||
LocalDateTimeUtils.betweenTwoTime(COOKIE_TIME, LocalDateTime.now(), ChronoUnit.DAYS) >= 30) {
getCookie();
}
List<String> itemids = getItemIds(attrIds);
if (!validItemInfo(itemids)) {
try {
ClassPathResource classPathResource = new ClassPathResource("/nodata.jpg");
InputStream inputStream = classPathResource.getInputStream();
response.setContentType("image/jpeg");
out = response.getOutputStream();
out.write(toByteArray(inputStream));
out.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://" + zbxServerIp + ":" + zbxServerPort
+ "/zabbix/chart.php?type=0&profileIdx=web.item.graph.filter");
NameValuePair[] nameValuePairs = new NameValuePair[itemids.size() + 4];
nameValuePairs[0] = new NameValuePair("from", from);
nameValuePairs[1] = new NameValuePair("to", to);
nameValuePairs[2] = new NameValuePair("width", width);
nameValuePairs[3] = new NameValuePair("height", height);
for (int index = 0; index < itemids.size(); index++) {
nameValuePairs[4 + index] = new NameValuePair("itemids[" + index + "]", itemids.get(index));
}
postMethod.setRequestBody(nameValuePairs);
postMethod.setRequestHeader("Content_Type", "application/json-rpc");
postMethod.setRequestHeader("Cookie", COOKIE);
try {
client.executeMethod(postMethod);
InputStream responseBody = postMethod.getResponseBodyAsStream();
response.setContentType("image/jpeg");
out = response.getOutputStream();
out.write(toByteArray(responseBody));
out.flush();
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean validItemInfo(List<String> itemids) {
if (ToolUtil.isEmpty(itemids)) {
return false;
}
List<ZbxItemInfo> itemInfos = JSONObject.parseArray(zbxItem.getItemInfo(itemids.toString(), null), ZbxItemInfo.class);
if (ToolUtil.isEmpty(itemInfos)) {
return false;
}
return true;
}
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
private List<String> getItemIds(List<Long> attrIds) {
return new QProductAttribute().select(QProductAttribute.alias().zbxId).attrId.in(attrIds).zbxId.isNotNull().findSingleAttributeList();
}
/**
* 用户访客 获取cookie
*/
private void getCookie() {
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://" + zbxServerIp + ":" + zbxServerPort + "/zabbix/index.php");
//TODO 使用了一个只读权限的访客用户
NameValuePair namePair = new NameValuePair("name", "cookie");
NameValuePair pwdPair = new NameValuePair("password", "cookie");
NameValuePair autologinPair = new NameValuePair("autologin", "1");
NameValuePair enterPair = new NameValuePair("enter", "Sign in");
postMethod.setRequestBody(new NameValuePair[]{namePair, pwdPair, autologinPair, enterPair});
postMethod.setRequestHeader("Content_Type", "application/json");
try {
client.executeMethod(postMethod);
} catch (IOException ioException) {
ioException.printStackTrace();
}
COOKIE = postMethod.getResponseHeader("Set-Cookie").getValue();
COOKIE_TIME = LocalDateTime.now();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/analyse/service/ZbxChartsService.java
|
Java
|
gpl-3.0
| 6,398
|
package com.zmops.iot.web.auth;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.zmops.iot.constant.ConstantsContext;
import com.zmops.iot.core.auth.cache.SessionManager;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.core.auth.exception.AuthException;
import com.zmops.iot.core.auth.exception.enums.AuthExceptionEnum;
import com.zmops.iot.core.auth.jwt.JwtTokenUtil;
import com.zmops.iot.core.auth.jwt.payload.JwtPayLoad;
import com.zmops.iot.core.auth.model.LoginUser;
import com.zmops.iot.core.util.HttpContext;
import com.zmops.iot.core.util.SaltUtil;
import com.zmops.iot.domain.sys.SysUser;
import com.zmops.iot.domain.sys.query.QSysUser;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.message.handler.MessageEventHandler;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.web.constant.state.ManagerStatus;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.log.LogManager;
import com.zmops.iot.web.log.factory.LogTaskFactory;
import com.zmops.iot.web.sys.dto.LoginUserDto;
import com.zmops.iot.web.sys.factory.UserFactory;
import com.zmops.zeus.driver.service.ZbxUser;
import io.ebean.DB;
import io.ebean.SqlRow;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.zmops.iot.constant.ConstantsContext.getJwtSecretExpireSec;
import static com.zmops.iot.constant.ConstantsContext.getTokenHeaderName;
import static com.zmops.iot.core.util.HttpContext.getIp;
@Service
@Transactional(readOnly = true)
public class AuthService {
@Autowired
private SessionManager sessionManager;
@Autowired
private ZbxUser zbxUser;
@Autowired
MessageEventHandler messageEventHandler;
/**
* 用户名 和 密码 登陆
*
* @param username 用户名
* @param password 密码
* @return
*/
public LoginUserDto login(String username, String password) {
SysUser user = new QSysUser().account.eq(username).findOne();
// 账号不存在
if (null == user) {
throw new AuthException(AuthExceptionEnum.NOT_EXIST_ERROR);
}
// 账号被冻结
if (!user.getStatus().equals(ManagerStatus.OK.getCode())) {
throw new AuthException(AuthExceptionEnum.ACCOUNT_FREEZE_ERROR);
}
//验证账号密码是否正确
try {
password = new String(Hex.decodeHex(password));
} catch (DecoderException e) {
throw new AuthException(AuthExceptionEnum.USERNAME_PWD_ERROR);
}
String requestMd5 = SaltUtil.md5Encrypt(password, user.getSalt());
String dbMd5 = user.getPassword();
if (dbMd5 == null || !dbMd5.equalsIgnoreCase(requestMd5)) {
throw new AuthException(AuthExceptionEnum.USERNAME_PWD_ERROR);
}
int i = DB.sqlUpdate("update sys_user set zbx_token = :token where account = :account")
.setParameter("token", zbxUser.userLogin(username, password))
.setParameter("account", username)
.execute();
if (i == 0) {
throw new ServiceException(BizExceptionEnum.ZBX_TOKEN_SAVE_ERROR);
}
//单点登录
if (CommonStatus.ENABLE.getCode().equals(ConstantsContext.getConstntsMap().get("ZEUS_SIGN_IN"))) {
messageEventHandler.sendDisconnectMsg(user.getUserId() + "");
}
return LoginUserDto.buildLoginUser(user, login(user));
}
/**
* 用户名 登陆
*
* @param user 用户
* @return
*/
public String login(SysUser user) {
//记录登录日志
LogManager.me().executeLog(LogTaskFactory.loginLog(user.getUserId(), getIp(), user.getTenantId()));
//TODO key的作用
JwtPayLoad payLoad = new JwtPayLoad(user.getUserId(), user.getAccount(), "xxxx");
//创建token
String token = JwtTokenUtil.generateToken(payLoad);
//创建登录会话
sessionManager.createSession(token, user(user.getAccount()));
//创建cookie
addLoginCookie(token);
return token;
}
/**
* 写入 登陆 Cookie
*
* @param token
*/
public void addLoginCookie(String token) {
//创建cookie
Cookie authorization = new Cookie(getTokenHeaderName(), token);
authorization.setMaxAge(getJwtSecretExpireSec().intValue());
authorization.setHttpOnly(true);
authorization.setPath("/");
HttpServletResponse response = HttpContext.getResponse();
response.addCookie(authorization);
}
public void logout() {
String token = LoginContextHolder.getContext().getToken();
logout(token);
}
public void logout(String token) {
//记录退出日志
LoginUser loginUser = LoginContextHolder.getContext().getUser();
LogManager.me().executeLog(LogTaskFactory.exitLog(loginUser.getId(), getIp(), loginUser.getTenantId()));
//删除Auth相关cookies
Cookie[] cookies = HttpContext.getRequest().getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
String tokenHeader = getTokenHeaderName();
if (tokenHeader.equalsIgnoreCase(cookie.getName())) {
Cookie temp = new Cookie(cookie.getName(), "");
temp.setMaxAge(0);
temp.setPath("/");
HttpContext.getResponse().addCookie(temp);
}
}
}
//删除会话
sessionManager.removeSession(token);
}
public LoginUser user(String account) {
SysUser user = new QSysUser().account.eq(account).findOne();
LoginUser loginUser = UserFactory.createLoginUser(user);
// //用户角色数组
Long[] roleArray = Convert.toLongArray(user.getRoleId());
//
// //如果角色是空就直接返回
// if (roleArray == null || roleArray.length == 0) {
// return loginUser;
// }
// //获取用户角色列表
List<Long> roleList = new ArrayList<>();
// List<String> roleNameList = new ArrayList<>();
// List<String> roleTipList = new ArrayList<>();
for (Long roleId : roleArray) {
roleList.add(roleId);
// roleNameList.add(ConstantFactory.me().getSingleRoleName(roleId));
// roleTipList.add(ConstantFactory.me().getSingleRoleTip(roleId));
}
loginUser.setRoleList(roleList);
// loginUser.setRoleNames(roleNameList);
// loginUser.setRoleTips(roleTipList);
//
// //根据角色获取系统的类型
// List<String> systemTypes = this.menuMapper.getMenusTypesByRoleIds(roleList);
//
// //通过字典编码
// List<Map<String, Object>> dictsByCodes = dictService.getDictsByCodes(systemTypes);
// loginUser.setSystemTypes(dictsByCodes);
//
// //设置权限列表
// Set<String> permissionSet = new HashSet<>();
// for (Long roleId : roleList) {
// List<String> permissions = this.findPermissionsByRoleId(roleId);
// if (permissions != null) {
// for (String permission : permissions) {
// if (ToolUtil.isNotEmpty(permission)) {
// permissionSet.add(permission);
// }
// }
// }
// }
// loginUser.setPermissions(permissionSet);
//
// //如果开启了多租户功能,则设置当前登录用户的租户标识
// if (ConstantsContext.getTenantOpen()) {
// String tenantCode = TenantCodeHolder.get();
// String dataBaseName = DataBaseNameHolder.get();
// if (ToolUtil.isNotEmpty(tenantCode) && ToolUtil.isNotEmpty(dataBaseName)) {
// loginUser.setTenantCode(tenantCode);
// loginUser.setTenantDataSourceName(dataBaseName);
// }
//
// //注意,这里remove不代表所有情况,在aop remove
// TenantCodeHolder.remove();
// DataBaseNameHolder.remove();
// }
return loginUser;
}
public List<String> findPermissionsByRoleId(Long roleId) {
// return menuMapper.getResUrlsByRoleId(roleId);
return Collections.emptyList();
}
public boolean check(String[] roleNames) {
LoginUser user = LoginContextHolder.getContext().getUser();
if (null == user) {
return false;
}
ArrayList<String> objects = CollectionUtil.newArrayList(roleNames);
String join = CollectionUtil.join(objects, ",");
if (LoginContextHolder.getContext().hasAnyRoles(join)) {
return true;
}
return false;
}
public boolean checkAll(String code) {
HttpServletRequest request = HttpContext.getRequest();
LoginUser user = LoginContextHolder.getContext().getUser();
if (null == user) {
return false;
}
String sql = "select * from sys_menu where code = :code and menu_id in (SELECT menu_id from sys_role_menu where role_id = :roleId)";
List<SqlRow> list = DB.sqlQuery(sql).setParameter("code", code).setParameter("roleId", user.getRoleList().get(0)).findList();
if (list.size() > 0) {
return true;
}
return false;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/auth/AuthService.java
|
Java
|
gpl-3.0
| 9,887
|
package com.zmops.iot.web.auth;
import com.zmops.iot.constant.ConstantsContext;
import com.zmops.iot.core.auth.context.LoginContext;
import com.zmops.iot.core.auth.exception.AuthException;
import com.zmops.iot.core.auth.exception.enums.AuthExceptionEnum;
import com.zmops.iot.core.auth.model.LoginUser;
import com.zmops.iot.core.auth.util.TokenUtil;
import com.zmops.iot.web.init.BasicSettingsInit;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
/**
* 用户登录上下文
*
* @author fengshuonan
*/
@Component
public class LoginContextSpringSecutiryImpl implements LoginContext {
@Override
public LoginUser getUser() {
if (null == SecurityContextHolder.getContext().getAuthentication()) {
//默认 Admin
return new LoginUser(1L, BasicSettingsInit.zbxApiToken);
}
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String) {
throw new AuthException(AuthExceptionEnum.NOT_LOGIN_ERROR);
} else {
return (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
@Override
public String getToken() {
return TokenUtil.getToken();
}
@Override
public String getZbxToken() {
return null;
}
@Override
public boolean hasLogin() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
} else {
if (authentication instanceof AnonymousAuthenticationToken) {
return false;
} else {
return true;
}
}
}
@Override
public Long getUserId() {
return getUser().getId();
}
@Override
public boolean hasRole(String roleName) {
return getUser().getRoleTips().contains(roleName);
}
@Override
public boolean hasAnyRoles(String roleNames) {
boolean hasAnyRole = false;
if (this.hasLogin() && roleNames != null && roleNames.length() > 0) {
for (String role : roleNames.split(",")) {
if (hasRole(role.trim())) {
hasAnyRole = true;
break;
}
}
}
return hasAnyRole;
}
@Override
public boolean hasPermission(String permission) {
return getUser().getPermissions().contains(permission);
}
@Override
public boolean isAdmin() {
// List<Long> roleList = getUser().getRoleList();
// if(roleList != null){
// for (Long integer : roleList) {
// String singleRoleTip = ConstantFactory.me().getSingleRoleTip(integer);
// if (singleRoleTip.equals(Const.ADMIN_NAME)) {
// return true;
// }
// }
// }
return false;
}
@Override
public boolean oauth2Flag() {
String account = getUser().getAccount();
if (account.startsWith(ConstantsContext.getOAuth2UserPrefix())) {
return true;
} else {
return false;
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/auth/LoginContextSpringSecutiryImpl.java
|
Java
|
gpl-3.0
| 3,391
|
package com.zmops.iot.web.auth;
import java.lang.annotation.*;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Permission {
/**
* <p>角色英文名称</p>
* <p>使用注解时加上这个值表示限制只有某个角色的才可以访问对应的资源</p>
* <p>常用在某些资源限制只有超级管理员角色才可访问</p>
*/
String[] value() default {};
/**
* 操作code
*
* @return
*/
String code();
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/auth/Permission.java
|
Java
|
gpl-3.0
| 524
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.web.auth;
import com.zmops.iot.core.auth.exception.PermissionException;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import java.lang.reflect.Method;
/**
* 权限检查的aop
*
* @author fengshuonan
*/
@Aspect
@Order(200)
public class PermissionAop {
@Autowired
private AuthService authService;
@Pointcut(value = "@annotation(com.zmops.iot.web.auth.Permission)")
private void cutPermission() {
}
@Around("cutPermission()")
public Object doPermission(ProceedingJoinPoint point) throws Throwable {
MethodSignature ms = (MethodSignature) point.getSignature();
Method method = ms.getMethod();
Permission permission = method.getAnnotation(Permission.class);
String[] permissions = permission.value();
String code = permission.code();
if (permissions.length == 0 && StringUtils.isNotBlank(code)) {
//检查全体角色
boolean result = authService.checkAll(code);
if (result) {
return point.proceed();
} else {
throw new PermissionException();
}
} else {
//检查指定角色
boolean result = authService.check(permissions);
if (result) {
return point.proceed();
} else {
throw new PermissionException();
}
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/auth/PermissionAop.java
|
Java
|
gpl-3.0
| 2,410
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.web.constant;
/**
* 系统常量
*
* @author fengshuonan
*/
public interface Const {
/**
* 管理员角色的名字
*/
String ADMIN_NAME = "root";
/**
* 管理员id
*/
Long ADMIN_ID = 1L;
/**
* 超级管理员角色id
*/
Long ADMIN_ROLE_ID = 1L;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/constant/Const.java
|
Java
|
gpl-3.0
| 984
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.web.constant.state;
/**
* 业务是否成功的日志记录
*
* @author fengshuonan
*/
public enum LogSucceed {
SUCCESS("成功"),
FAIL("失败");
String message;
LogSucceed(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/constant/state/LogSucceed.java
|
Java
|
gpl-3.0
| 1,077
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.web.constant.state;
/**
* 日志类型
*
* @author fengshuonan
*/
public enum LogType {
LOGIN("登录日志"),
LOGIN_FAIL("登录失败日志"),
EXIT("退出日志"),
EXCEPTION("异常日志"),
BUSSINESS("业务日志");
String message;
LogType(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/constant/state/LogType.java
|
Java
|
gpl-3.0
| 1,160
|
/**
* Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zmops.iot.web.constant.state;
import lombok.Getter;
/**
* 管理员的状态
*
* @author fengshuonan
*/
@Getter
public enum ManagerStatus {
OK("ENABLE", "启用"), FREEZED("LOCKED", "冻结"), DELETED("DELETED", "被删除");
String code;
String message;
ManagerStatus(String code, String message) {
this.code = code;
this.message = message;
}
public static String getDescription(String value) {
if (value == null) {
return "";
} else {
for (ManagerStatus ms : ManagerStatus.values()) {
if (ms.getCode().equals(value)) {
return ms.getMessage();
}
}
return "";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/constant/state/ManagerStatus.java
|
Java
|
gpl-3.0
| 1,407
|
package com.zmops.iot.web.device.controller;
import com.zmops.iot.domain.device.ApiParam;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.proxy.Proxy;
import com.zmops.iot.domain.proxy.query.QProxy;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.zeus.driver.entity.ItemParam;
import com.zmops.zeus.driver.entity.SendParam;
import com.zmops.zeus.driver.service.ZbxConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* @author yefei
**/
@RequestMapping("/device/api")
@RestController
public class DeviceApiController {
@Autowired
ZbxConfig zbxConfig;
//@Value("${forest.variables.zeusServerIp}")
private String IOT_SERVER_IP = "127.0.0.1";
@RequestMapping("/sendData")
public ResponseData sendData(@Validated @RequestBody ApiParam apiParam) {
Device device = new QDevice().deviceId.eq(apiParam.getDeviceId()).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
if (null != device.getProxyId()) {
Proxy proxy = new QProxy().id.eq(device.getProxyId()).findOne();
IOT_SERVER_IP = proxy.getAddress();
}
List<ItemParam> valueList = new ArrayList<>();
if (ToolUtil.isNotEmpty(apiParam.getParams())) {
apiParam.getParams().forEach(params -> {
if (ToolUtil.isEmpty(params.getDeviceAttrKey()) || ToolUtil.isEmpty(params.getDeviceAttrValue())) {
return;
}
ItemParam itemParam = new ItemParam();
itemParam.setHost(apiParam.getDeviceId());
itemParam.setClock(LocalDateTimeUtils.getSecondsByTime(LocalDateTime.now()));
itemParam.setKey(params.getDeviceAttrKey());
itemParam.setValue(params.getDeviceAttrValue());
valueList.add(itemParam);
});
}
if (ToolUtil.isEmpty(valueList)) {
throw new ServiceException(BizExceptionEnum.ZBX_DEVICE_API_HASNOT_KEY);
}
SendParam sendParam = new SendParam();
sendParam.setParams(valueList);
zbxConfig.sendData(IOT_SERVER_IP, sendParam);
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceApiController.java
|
Java
|
gpl-3.0
| 2,849
|
package com.zmops.iot.web.device.controller;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.auth.Permission;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.device.dto.param.DeviceParam;
import com.zmops.iot.web.device.dto.param.DeviceParams;
import com.zmops.iot.web.device.service.DeviceService;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.product.dto.ProductTag;
import com.zmops.iot.web.product.dto.ValueMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
* @author nantian created at 2021/8/2 2:05
* <p>
* 设备管理
*/
@RestController
@RequestMapping("/device")
public class DeviceController {
@Autowired
DeviceService deviceService;
/**
* 设备分页列表
*
* @return
*/
@Permission(code = "dev_list")
@PostMapping("/getDeviceByPage")
public Pager<DeviceDto> devicePageList(@RequestBody DeviceParam deviceParam) {
return deviceService.devicePageList(deviceParam);
}
/**
* 设备列表
*
* @return
*/
@Permission(code = "dev_list")
@PostMapping("/list")
public ResponseData deviceList(@RequestBody DeviceParams deviceParams) {
return ResponseData.success(deviceService.deviceList(deviceParams));
}
/**
* 设备创建
*/
@Permission(code = "dev_add")
@RequestMapping("/create")
public ResponseData create(@Validated(BaseEntity.Create.class) @RequestBody DeviceDto deviceDto) {
if (ToolUtil.validDeviceName(deviceDto.getName())) {
throw new ServiceException(BizExceptionEnum.DEVICE_NAME_HAS_INCOREECT_CHARACTER);
}
int count = new QDevice().name.eq(deviceDto.getName()).findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.DEVICE_EXISTS);
}
if (ToolUtil.isNotEmpty(deviceDto.getDeviceId())) {
count = new QDevice().deviceId.eq(deviceDto.getDeviceId()).findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.DEVICE_ID_EXISTS);
}
} else {
deviceDto.setDeviceId(IdUtil.getSnowflake().nextId() + "");
}
deviceDto.setEdit("false");
deviceService.checkProductExist(deviceDto);
String deviceId = deviceService.create(deviceDto);
deviceDto.setDeviceId(deviceId);
return ResponseData.success(deviceDto);
}
/**
* 设备创建
*/
@Permission(code = "dev_update")
@RequestMapping("/update")
public ResponseData update(@Validated(BaseEntity.Update.class) @RequestBody DeviceDto deviceDto) {
if (ToolUtil.validDeviceName(deviceDto.getName())) {
throw new ServiceException(BizExceptionEnum.DEVICE_NAME_HAS_INCOREECT_CHARACTER);
}
int count = new QDevice().deviceId.ne(deviceDto.getDeviceId()).name.eq(deviceDto.getName()).findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.DEVICE_EXISTS);
}
deviceDto.setEdit("true");
deviceService.checkProductExist(deviceDto);
deviceService.update(deviceDto);
return ResponseData.success(deviceDto);
}
/**
* 设备删除
*/
@Permission(code = "dev_delete")
@RequestMapping("/delete")
public ResponseData delete(@Validated(BaseEntity.Delete.class) @RequestBody DeviceDto deviceDto) {
return ResponseData.success(deviceService.delete(deviceDto));
}
/**
* 设备启用、禁用
*/
@Permission(code = "dev_update")
@RequestMapping("/status/update")
public ResponseData status(@Validated(BaseEntity.Status.class) @RequestBody DeviceDto deviceDto) {
Device device = new QDevice().deviceId.eq(deviceDto.getDeviceId()).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
deviceService.status(deviceDto.getStatus(), deviceDto.getDeviceId(), device.getZbxId());
return ResponseData.success();
}
/**
* 设备详情
*/
@Permission(code = "dev_detail")
@GetMapping("/detail")
public ResponseData prodDetail(@RequestParam("deviceId") String deviceId) {
return ResponseData.success(deviceService.deviceDetail(deviceId));
}
/**
* 设备标签列表
*/
@Permission(code = "dev")
@GetMapping("/tag/list")
public ResponseData prodTagList(@RequestParam("deviceId") String deviceId) {
return ResponseData.success(deviceService.deviceTagList(deviceId));
}
/**
* 设备值映射列表
*/
@Permission(code = "dev")
@GetMapping("/valueMap/list")
public ResponseData valueMapList(@RequestParam("deviceId") String deviceId) {
return ResponseData.success(deviceService.valueMapList(deviceId));
}
/**
* 设备创建修改 TAG
*
* @return
*/
@Permission(code = "dev")
@PostMapping("/tag/update")
public ResponseData deviceTagCreate(@RequestBody @Valid ProductTag productTag) {
String deviceId = productTag.getProductId();
Device device = new QDevice().deviceId.eq(deviceId).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
deviceService.deviceTagCreate(productTag, device.getZbxId());
return ResponseData.success(productTag);
}
/**
* 设备创建值映射
*
* @param valueMap
* @return
*/
@Permission(code = "dev")
@PostMapping("/valueMap/update")
public ResponseData prodValueMapCreate(@RequestBody @Validated(BaseEntity.Create.class) ValueMap valueMap) {
Device device = new QDevice().deviceId.eq(valueMap.getProductId()).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
String response;
if (ToolUtil.isEmpty(valueMap.getValuemapid())) {
response = deviceService.valueMapCreate(device.getZbxId(), valueMap.getValueMapName(), valueMap.getValueMaps());
} else {
response = deviceService.valueMapUpdate(device.getZbxId(), valueMap.getValueMapName(), valueMap.getValueMaps(), valueMap.getValuemapid());
}
return ResponseData.success(JSONObject.parseObject(response).getJSONArray("valuemapids").get(0));
}
/**
* 删除 设备值映射
*
* @param valueMap
* @return
*/
@Permission(code = "dev")
@PostMapping("/valueMap/delete")
public ResponseData prodValueMapDelete(@RequestBody @Validated(BaseEntity.Delete.class) ValueMap valueMap) {
String response = deviceService.valueMapDelete(valueMap.getValuemapid());
return ResponseData.success(JSONObject.parseObject(response).getJSONArray("valuemapids").get(0));
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceController.java
|
Java
|
gpl-3.0
| 7,432
|
package com.zmops.iot.web.device.controller;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.domain.product.ProductEvent;
import com.zmops.iot.domain.product.ProductEventRelation;
import com.zmops.iot.domain.product.query.QProductEvent;
import com.zmops.iot.domain.product.query.QProductEventExpression;
import com.zmops.iot.domain.product.query.QProductEventRelation;
import com.zmops.iot.domain.product.query.QProductEventService;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.enums.InheritStatus;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceEventRule;
import com.zmops.iot.web.device.service.DeviceEventRuleService;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.zeus.driver.service.ZbxTrigger;
import io.ebean.DB;
import io.ebean.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 设备告警规则
**/
@RestController
@RequestMapping("/device/event/trigger")
public class DeviceEventTriggerController {
@Autowired
DeviceEventRuleService deviceEventRuleService;
@Autowired
private ZbxTrigger zbxTrigger;
private static final String ALARM_TAG_NAME = "__alarm__";
private static final String EXECUTE_TAG_NAME = "__execute__";
private static final String EVENT_TAG_NAME = "__event__";
private static final String EVENT_TYPE_NAME = "事件";
/**
* 触发器 详情
*
* @param eventRuleId
* @return
*/
@GetMapping("/detail")
public ResponseData detail(@RequestParam("eventRuleId") long eventRuleId, @RequestParam("deviceId") String deviceId) {
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(eventRuleId).findOne();
if (null == productEvent) {
throw new ServiceException(BizExceptionEnum.EVENT_NOT_EXISTS);
}
return ResponseData.success(deviceEventRuleService.detail(productEvent, eventRuleId, deviceId));
}
/**
* 创建 触发器
*
* @param eventRule 触发器规则
* @return 触发器ID
*/
@Transactional
@PostMapping("/create")
public ResponseData createDeviceEventRule(@RequestBody @Validated(value = BaseEntity.Create.class)
DeviceEventRule eventRule) {
//检查是否有重复动作服务
deviceEventRuleService.checkService(eventRule.getDeviceServices());
Long eventRuleId = IdUtil.getSnowflake().nextId(); // ruleId, trigger name
deviceEventRuleService.createDeviceEventRule(eventRuleId, eventRule);
//step 1: 先创建 zbx 触发器
String expression = eventRule.getExpList()
.stream().map(Object::toString).collect(Collectors.joining(" " + eventRule.getExpLogic() + " "));
//step 2: zbx 保存触发器
String[] triggerIds = deviceEventRuleService.createZbxTrigger(eventRuleId + "", expression, eventRule.getEventLevel());
//step 4: zbx 触发器创建 Tag
Map<String, String> tags = new ConcurrentHashMap<>(3);
if (ToolUtil.isNotEmpty(eventRule.getTags())) {
tags = eventRule.getTags().stream()
.collect(Collectors.toMap(DeviceEventRule.Tag::getTag, DeviceEventRule.Tag::getValue, (k1, k2) -> k2));
}
if (!tags.containsKey(ALARM_TAG_NAME)) {
tags.put(ALARM_TAG_NAME, "{HOST.HOST}");
}
if (ToolUtil.isNotEmpty(eventRule.getDeviceServices()) && !tags.containsKey(EXECUTE_TAG_NAME)) {
tags.put(EXECUTE_TAG_NAME, eventRuleId + "");
}
// Optional<DeviceEventRule.Expression> any = eventRule.getExpList().parallelStream().filter(o -> EVENT_TYPE_NAME.equals(o.getProductAttrType())).findAny();
// if (any.isPresent()) {
// tags.put(EVENT_TAG_NAME, eventRuleId + "");
// }
for (String triggerId : triggerIds) {
zbxTrigger.triggerTagCreate(triggerId, tags);
}
//step 5: 更新 zbxId
deviceEventRuleService.updateProductEventRuleZbxId(eventRuleId, triggerIds);
// 返回触发器ID
return ResponseData.success(eventRuleId);
}
/**
* 修改 触发器状态
*
* @param eventRule 触发器规则
* @return 触发器ID
*/
@PostMapping("/status")
public ResponseData updateProductEventStatus(@RequestBody @Validated(value = BaseEntity.Status.class) DeviceEventRule eventRule) {
DB.update(ProductEventRelation.class).where().eq("eventRuleId", eventRule.getEventRuleId()).eq("relationId", eventRule.getDeviceId()).asUpdate()
.set("status", eventRule.getStatus()).update();
ProductEventRelation productEventRelation = new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId())
.relationId.eq(eventRule.getDeviceId()).findOne();
if (null != productEventRelation && null != productEventRelation.getZbxId()) {
zbxTrigger.triggerStatusUpdate(productEventRelation.getZbxId(), eventRule.getStatus().equals(CommonStatus.ENABLE.getCode()) ? "0" : "1");
}
return ResponseData.success();
}
/**
* 修改 触发器
*
* @param eventRule 触发器规则
* @return 触发器ID
*/
@Transactional
@PostMapping("/update")
public ResponseData updateDeviceEventRule(@RequestBody @Validated(value = BaseEntity.Update.class) DeviceEventRule eventRule) {
int count = new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId())
.findCount();
if (count == 0) {
throw new ServiceException(BizExceptionEnum.EVENT_NOT_EXISTS);
}
//检查是否有重复动作服务
deviceEventRuleService.checkService(eventRule.getDeviceServices());
//来自产品的告警规则 只能修改备注
count = new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).inherit.eq(InheritStatus.YES.getCode())
.findCount();
if (count > 0) {
DB.update(ProductEventRelation.class).where().eq("eventRuleId", eventRule.getEventRuleId()).eq("relationId", eventRule.getDeviceId())
.asUpdate().set("remark", eventRule.getRemark()).update();
return ResponseData.success(eventRule.getEventRuleId());
}
//step 1: 删除原有的 关联关系
deviceEventRuleService.updateDeviceEventRule(eventRule.getEventRuleId(), eventRule);
//step 1: 先创建 zbx 触发器
String expression = eventRule.getExpList()
.stream().map(Object::toString).collect(Collectors.joining(" " + eventRule.getExpLogic() + " "));
//step 2: zbx 保存触发器
String[] triggerIds = deviceEventRuleService.updateZbxTrigger(eventRule.getZbxId(), expression, eventRule.getEventLevel());
//step 4: zbx 触发器创建 Tag
Map<String, String> tags = eventRule.getTags().stream()
.collect(Collectors.toMap(DeviceEventRule.Tag::getTag, DeviceEventRule.Tag::getValue, (k1, k2) -> k2));
if (ToolUtil.isEmpty(tags)) {
tags = new HashMap<>(2);
}
if (!tags.containsKey(ALARM_TAG_NAME)) {
tags.put(ALARM_TAG_NAME, "{HOST.HOST}");
}
if (ToolUtil.isNotEmpty(eventRule.getDeviceServices()) && !tags.containsKey(EXECUTE_TAG_NAME)) {
tags.put(EXECUTE_TAG_NAME, eventRule.getEventRuleId() + "");
}
// Optional<DeviceEventRule.Expression> any = eventRule.getExpList().parallelStream().filter(o -> EVENT_TYPE_NAME.equals(o.getProductAttrType())).findAny();
// if (any.isPresent()) {
// tags.put(EVENT_TAG_NAME, eventRule.getEventRuleId() + "");
// }
for (String triggerId : triggerIds) {
zbxTrigger.triggerTagCreate(triggerId, tags);
}
//step 5: 更新 zbxId 反写
deviceEventRuleService.updateProductEventRuleZbxId(eventRule.getEventRuleId(), triggerIds);
// 返回触发器ID
return ResponseData.success(eventRule.getEventRuleId());
}
/**
* 删除 触发器
*
* @param eventRule 触发器规则
* @return 触发器ID
*/
@Transactional
@PostMapping("/delete")
public ResponseData deleteProductEventRule(@RequestBody @Validated(value = BaseEntity.Delete.class) DeviceEventRule eventRule) {
ProductEventRelation productEventRelation = new QProductEventRelation().relationId.eq(eventRule.getDeviceId())
.eventRuleId.eq(eventRule.getEventRuleId()).findOne();
if (productEventRelation != null && InheritStatus.YES.getCode().equals(productEventRelation.getInherit())) {
throw new ServiceException(BizExceptionEnum.EVENT_PRODUCT_CANNOT_DELETE);
}
//step 01:删除 zbx触发器
if (productEventRelation != null && ToolUtil.isNotEmpty(productEventRelation.getZbxId())) {
List<DeviceEventRuleService.Triggers> triggers = JSONObject.parseArray(
zbxTrigger.triggerGet(productEventRelation.getZbxId()), DeviceEventRuleService.Triggers.class);
if (ToolUtil.isNotEmpty(triggers)) {
zbxTrigger.triggerDelete(productEventRelation.getZbxId());
}
}
//step 1:删除 与设备的关联
new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).delete();
//step 2:删除 关联的执行服务
new QProductEventService().eventRuleId.eq(eventRule.getEventRuleId()).delete();
//step 3:删除 关联的表达式
new QProductEventExpression().eventRuleId.eq(eventRule.getEventRuleId()).delete();
//step 4:删除 触发器
new QProductEvent().eventRuleId.eq(eventRule.getEventRuleId()).delete();
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceEventTriggerController.java
|
Java
|
gpl-3.0
| 10,408
|
package com.zmops.iot.web.device.controller;
import com.zmops.iot.core.log.BussinessLog;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.domain.device.DeviceGroup;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.device.dto.DeviceGroupDto;
import com.zmops.iot.web.device.dto.param.DeviceGroupParam;
import com.zmops.iot.web.device.service.DeviceGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
* @author nantian created at 2021/8/2 2:06
* <p>
* 设备分组管理
*/
@RestController
@RequestMapping("/deviceGroup")
public class DeviceGroupController {
@Autowired
DeviceGroupService deviceGroupService;
/**
* 设备组分页列表
*
* @return
*/
@PostMapping("/getDeviceGrpByPage")
public Pager<DeviceGroupDto> getDeviceGrpByPage(@RequestBody DeviceGroupParam devGroupParam) {
return deviceGroupService.deviceGroupPageList(devGroupParam);
}
/**
* 设备组列表
*
* @return
*/
@PostMapping("/list")
public ResponseData deviceGroupList(@RequestBody DeviceGroupParam devGroupParam) {
return ResponseData.success(deviceGroupService.deviceGroupList(devGroupParam));
}
/**
* 创建设备组
*
* @return
*/
@PostMapping("/create")
@BussinessLog(value = "创建设备组")
public ResponseData createDeviceGroup(@Validated(BaseEntity.Create.class) @RequestBody DeviceGroupParam deviceGroupDto) {
return ResponseData.success(deviceGroupService.createDeviceGroup(deviceGroupDto));
}
/**
* 更新设备组
*
* @return
*/
@PostMapping("/update")
@BussinessLog(value = "更新设备组")
public ResponseData updateDeviceGroup(@Validated(BaseEntity.Update.class) @RequestBody DeviceGroupParam deviceGroupDto) {
return ResponseData.success(deviceGroupService.updateDeviceGroup(deviceGroupDto));
}
/**
* 删除设备组
*
* @return
*/
@PostMapping("/delete")
@BussinessLog(value = "删除设备组")
public ResponseData deleteDeviceGroup(@Validated(BaseEntity.Delete.class) @RequestBody DeviceGroupParam deviceGroupParam) {
deviceGroupService.deleteDeviceGroup(deviceGroupParam);
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceGroupController.java
|
Java
|
gpl-3.0
| 2,708
|
package com.zmops.iot.web.device.controller;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.device.dto.DeviceLogDto;
import com.zmops.iot.web.device.dto.param.DeviceLogParam;
import com.zmops.iot.web.device.service.DeviceLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
**/
@RestController
@RequestMapping("/device/log")
public class DeviceLogController {
@Autowired
DeviceLogService deviceLogService;
@RequestMapping("list")
public ResponseData list(@RequestParam(value = "deviceId") String deviceId,
@RequestParam(value = "logType", required = false) String logType,
@RequestParam(value = "timeFrom", required = false) Long timeFrom,
@RequestParam(value = "timeTill", required = false) Long timeTill) {
return ResponseData.success(deviceLogService.list(deviceId, logType, timeFrom, timeTill));
}
@RequestMapping("getLogByPage")
public Pager<DeviceLogDto> getLogByPage(@RequestBody DeviceLogParam deviceLogParam) {
return deviceLogService.getLogByPage(deviceLogParam);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceLogController.java
|
Java
|
gpl-3.0
| 1,478
|
package com.zmops.iot.web.device.controller;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.domain.product.ProductAttribute;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.device.service.DeviceModelService;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.product.dto.ProductAttr;
import com.zmops.iot.web.product.dto.ProductAttrDto;
import com.zmops.iot.web.product.dto.param.ProductAttrParam;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
* <p>
* 设备属性
*/
@RestController
@RequestMapping("/device/model")
public class DeviceModelController {
@Autowired
private DeviceModelService deviceModelService;
//依赖属性类型
private static final String ATTR_SOURCE_DEPEND = "18";
/**
* 设备物模型 分页列表
*
* @return ResponseData
*/
@RequestMapping("/getAttrTrapperByPage")
public Pager<ProductAttrDto> prodModelAttributeList(@Validated(BaseEntity.Get.class) @RequestBody ProductAttrParam productAttr) {
return deviceModelService.prodModelAttributeList(productAttr);
}
/**
* 设备物模型 列表
*
* @return ResponseData
*/
@RequestMapping("/list")
public ResponseData list(@RequestBody ProductAttrParam productAttr) {
return ResponseData.success(deviceModelService.list(productAttr));
}
/**
* 设备物模型 详情
*
* @return ResponseData
*/
@RequestMapping("/detail")
public ResponseData detail(@RequestParam(value = "attrId") Long attrId) {
return ResponseData.success(deviceModelService.detail(attrId));
}
/**
* 创建 设备物模型
*
* @return ResponseData
*/
@RequestMapping("/attr/trapper/create")
public ResponseData prodModelAttributeCreate(@RequestBody @Validated(BaseEntity.Create.class) ProductAttr productAttr) {
int i = new QProductAttribute().productId.eq(productAttr.getProductId()).key.eq(productAttr.getKey()).findCount();
if (i > 0) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_KEY_EXISTS);
}
if (ATTR_SOURCE_DEPEND.equals(productAttr.getSource())) {
if (productAttr.getDepAttrId() == null) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_DEPTED_NULL);
}
ProductAttribute productAttribute = new QProductAttribute().attrId.eq(productAttr.getDepAttrId()).findOne();
if (null == productAttribute) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_DEPTED_NOT_EXIST);
}
productAttr.setMasterItemId(productAttribute.getZbxId());
}
Long attrId = IdUtil.getSnowflake().nextId();
productAttr.setAttrId(attrId);
String response = deviceModelService.createTrapperItem(productAttr);
String zbxId = JSON.parseObject(response, TemplateIds.class).getItemids()[0];
deviceModelService.createProductAttr(productAttr, zbxId);
return ResponseData.success(productAttr);
}
/**
* 修改 设备物模型
*
* @return ResponseData
*/
@RequestMapping("/attr/trapper/update")
public ResponseData prodModelAttributeUpdate(@RequestBody @Validated(BaseEntity.Update.class) ProductAttr productAttr) {
int i = new QProductAttribute().productId.eq(productAttr.getProductId()).key.eq(productAttr.getKey())
.attrId.ne(productAttr.getAttrId()).findCount();
if (i > 0) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_KEY_EXISTS);
}
if (ATTR_SOURCE_DEPEND.equals(productAttr.getSource())) {
if (productAttr.getDepAttrId() == null) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_DEPTED_NULL);
}
ProductAttribute productAttribute = new QProductAttribute().attrId.eq(productAttr.getDepAttrId()).findOne();
if (null == productAttribute) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_DEPTED_NOT_EXIST);
}
productAttr.setMasterItemId(productAttribute.getZbxId());
}
return ResponseData.success(deviceModelService.updateTrapperItem(productAttr));
}
/**
* 删除 设备物模型 属性
*
* @return ResponseData
*/
@RequestMapping("/attr/trapper/delete")
public ResponseData prodModelAttributeDelete(@RequestBody @Validated(BaseEntity.Delete.class) ProductAttr productAttr) {
deviceModelService.deleteTrapperItem(productAttr);
return ResponseData.success();
}
@Data
static class TemplateIds {
private String[] itemids;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceModelController.java
|
Java
|
gpl-3.0
| 5,351
|
package com.zmops.iot.web.device.controller;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.web.device.dto.ServiceExecuteDto;
import com.zmops.iot.web.device.service.DeviceSvrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yefei
**/
@RestController
@CrossOrigin
@RequestMapping("/device/service")
public class DeviceServiceController {
@Autowired
DeviceSvrService deviceSvrService;
@RequestMapping("/execute")
public ResponseData execute(@Validated @RequestBody ServiceExecuteDto serviceExecuteDto) {
deviceSvrService.execute(serviceExecuteDto.getDeviceId(), serviceExecuteDto.getServiceId(), serviceExecuteDto.getServiceParams());
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/DeviceServiceController.java
|
Java
|
gpl-3.0
| 1,077
|
package com.zmops.iot.web.device.controller;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.domain.product.ProductEvent;
import com.zmops.iot.domain.product.ProductEventRelation;
import com.zmops.iot.domain.product.query.*;
import com.zmops.iot.domain.schedule.Task;
import com.zmops.iot.domain.schedule.query.QTask;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.model.response.ResponseData;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.MultipleDeviceEventDto;
import com.zmops.iot.web.device.dto.MultipleDeviceEventRule;
import com.zmops.iot.web.device.dto.param.MultipleDeviceEventParm;
import com.zmops.iot.web.device.service.MultipleDeviceEventRuleService;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.zeus.driver.service.ZbxTrigger;
import io.ebean.DB;
import io.ebean.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static com.zmops.iot.web.device.service.MultipleDeviceEventRuleService.*;
/**
* @author yefei
* <p>
* 设备 场景 联动
**/
@RestController
@RequestMapping("/multiple/device/event/trigger")
public class MultipleDeviceEventTriggerController {
@Autowired
MultipleDeviceEventRuleService multipleDeviceEventRuleService;
@Autowired
private ZbxTrigger zbxTrigger;
/**
* 场景 分页列表
*
* @param eventParm
* @return
*/
@PostMapping("/getEventByPage")
public Pager<MultipleDeviceEventDto> getEventByPage(@RequestBody MultipleDeviceEventParm eventParm) {
return multipleDeviceEventRuleService.getEventByPage(eventParm);
}
/**
* 场景 列表
*
* @param eventParm
* @return
*/
@PostMapping("/list")
public ResponseData list(@RequestBody MultipleDeviceEventParm eventParm) {
return ResponseData.success(multipleDeviceEventRuleService.list(eventParm));
}
/**
* 设备联动 详情
*
* @param eventRuleId
* @return
*/
@GetMapping("/detail")
public ResponseData detail(@RequestParam("eventRuleId") long eventRuleId) {
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(eventRuleId).findOne();
if (null == productEvent) {
throw new ServiceException(BizExceptionEnum.EVENT_NOT_EXISTS);
}
return ResponseData.success(multipleDeviceEventRuleService.detail(productEvent, eventRuleId));
}
/**
* 创建 设备联动
*
* @param eventRule 设备联动规则
* @return 设备联动ID
*/
@Transactional
@PostMapping("/create")
public ResponseData createDeviceEventRule(@RequestBody @Validated(value = BaseEntity.Create.class)
MultipleDeviceEventRule eventRule) {
int count = new QProductEvent().eventRuleName.eq(eventRule.getEventRuleName()).classify.eq("1").findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.SCENE_EXISTED);
}
multipleDeviceEventRuleService.checkParam(eventRule);
Long eventRuleId = IdUtil.getSnowflake().nextId();
eventRule.setEventRuleId(eventRuleId);
multipleDeviceEventRuleService.createDeviceEventRule(eventRule);
if (TRIGGER_TYPE_CONDITION == eventRule.getTriggerType()) {
//step 1: 先创建 zbx 触发器
String expression = eventRule.getExpList()
.stream().map(Object::toString).collect(Collectors.joining(" " + eventRule.getExpLogic() + " "));
//时间区间表达式
if (ToolUtil.isNotEmpty(eventRule.getTimeIntervals())) {
String timeExpression = eventRule.getTimeIntervals().parallelStream().map(Objects::toString).collect(Collectors.joining(" or "));
expression = "(" + expression + ") and (" + timeExpression + ")";
}
//step 2: zbx 保存触发器
String[] triggerIds = multipleDeviceEventRuleService.createZbxTrigger(eventRuleId + "", expression, eventRule.getEventLevel());
//step 4: zbx 触发器创建 Tag
Map<String, String> tags = new ConcurrentHashMap<>(1);
if (ToolUtil.isNotEmpty(eventRule.getTags())) {
tags = eventRule.getTags().stream()
.collect(Collectors.toMap(MultipleDeviceEventRule.Tag::getTag, MultipleDeviceEventRule.Tag::getValue, (k1, k2) -> k2));
}
if (ToolUtil.isNotEmpty(eventRule.getDeviceServices()) && !tags.containsKey(SCENE_TAG_NAME)) {
tags.put(SCENE_TAG_NAME, eventRuleId + "");
}
for (String triggerId : triggerIds) {
zbxTrigger.triggerTagCreate(triggerId, tags);
}
//step 5: 更新 zbxId
multipleDeviceEventRuleService.updateProductEventRuleZbxId(eventRuleId, triggerIds);
}
// 返回触发器ID
return ResponseData.success(eventRuleId);
}
/**
* 修改 设备联动 状态
*
* @param eventRule 设备联动规则
*/
@PostMapping("/status")
public ResponseData updateProductEventStatus(@RequestBody @Validated(value = BaseEntity.Status.class) MultipleDeviceEventRule eventRule) {
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(eventRule.getEventRuleId()).findOne();
if (null == productEvent) {
throw new ServiceException(BizExceptionEnum.SCENE_NOT_EXISTS);
}
if (TRIGGER_TYPE_SCHEDULE == productEvent.getTriggerType()) {
DB.update(Task.class).where().eq("taskId", productEvent.getTaskId()).asUpdate()
.set("triggerStatus", eventRule.getStatus()).update();
} else {
DB.update(ProductEventRelation.class).where().eq("eventRuleId", eventRule.getEventRuleId()).asUpdate()
.set("status", eventRule.getStatus()).update();
ProductEventRelation productEventRelation = new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).findOne();
if (null != productEventRelation && null != productEventRelation.getZbxId()) {
zbxTrigger.triggerStatusUpdate(productEventRelation.getZbxId(), eventRule.getStatus().equals(CommonStatus.ENABLE.getCode()) ? "0" : "1");
}
}
return ResponseData.success();
}
/**
* 修改 设备联动
*
* @param eventRule 设备联动规则
* @return 设备联动ID
*/
@Transactional
@PostMapping("/update")
public ResponseData updateDeviceEventRule(@RequestBody @Validated(value = BaseEntity.Update.class) MultipleDeviceEventRule eventRule) {
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(eventRule.getEventRuleId())
.findOne();
if (null == productEvent) {
throw new ServiceException(BizExceptionEnum.EVENT_NOT_EXISTS);
}
int count = new QProductEvent().eventRuleName.eq(eventRule.getEventRuleName()).eventRuleId.ne(eventRule.getEventRuleId()).classify.eq("1").findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.SCENE_EXISTED);
}
//检查参数
multipleDeviceEventRuleService.checkParam(eventRule);
//step 1: 删除原有的 关联关系 并重新建立 关联关系
ProductEventRelation productEventRelation = new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).setMaxRows(1).findOne();
eventRule.setTaskId(productEvent.getTaskId());
if (null != productEventRelation) {
eventRule.setZbxId(productEventRelation.getZbxId());
}
multipleDeviceEventRuleService.updateDeviceEventRule(eventRule);
if (TRIGGER_TYPE_CONDITION == eventRule.getTriggerType()) {
//step 1: 先创建 zbx 触发器
String expression = eventRule.getExpList()
.stream().map(Object::toString).collect(Collectors.joining(" " + eventRule.getExpLogic() + " "));
//时间区间表达式
if (ToolUtil.isNotEmpty(eventRule.getTimeIntervals())) {
String timeExpression = eventRule.getTimeIntervals().parallelStream().map(Objects::toString).collect(Collectors.joining(" or "));
expression = "(" + expression + ") and (" + timeExpression + ")";
}
//step 2: zbx 保存触发器
String[] triggerIds = multipleDeviceEventRuleService.createZbxTrigger(eventRule.getEventRuleId() + "", expression, eventRule.getEventLevel());
//step 4: zbx 触发器创建 Tag
Map<String, String> tags = new ConcurrentHashMap<>(1);
if (ToolUtil.isNotEmpty(eventRule.getTags())) {
tags = eventRule.getTags().stream()
.collect(Collectors.toMap(MultipleDeviceEventRule.Tag::getTag, MultipleDeviceEventRule.Tag::getValue, (k1, k2) -> k2));
}
if (ToolUtil.isNotEmpty(eventRule.getDeviceServices()) && !tags.containsKey(SCENE_TAG_NAME)) {
tags.put(SCENE_TAG_NAME, eventRule.getEventRuleId() + "");
}
for (String triggerId : triggerIds) {
zbxTrigger.triggerTagCreate(triggerId, tags);
}
//step 5: 更新 zbxId 反写
multipleDeviceEventRuleService.updateProductEventRuleZbxId(eventRule.getEventRuleId(), triggerIds);
}
// 返回触发器ID
return ResponseData.success(eventRule.getEventRuleId());
}
/**
* 删除 设备联动
*
* @param eventRule 设备联动规则
*/
@Transactional
@PostMapping("/delete")
public ResponseData deleteProductEventRule(@RequestBody @Validated(value = BaseEntity.Delete.class) MultipleDeviceEventRule eventRule) {
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(eventRule.getEventRuleId()).findOne();
if (null == productEvent) {
throw new ServiceException(BizExceptionEnum.SCENE_NOT_EXISTS);
}
if (TRIGGER_TYPE_CONDITION == eventRule.getTriggerType()) {
List<ProductEventRelation> productEventRelationList = new QProductEventRelation()
.eventRuleId.eq(eventRule.getEventRuleId()).findList();
//step 01:删除 zbx触发器
if (ToolUtil.isNotEmpty(productEventRelationList) && ToolUtil.isNotEmpty(productEventRelationList.get(0).getZbxId())) {
List<MultipleDeviceEventRuleService.Triggers> triggers = JSONObject.parseArray(
zbxTrigger.triggerGet(productEventRelationList.get(0).getZbxId()), MultipleDeviceEventRuleService.Triggers.class);
if (ToolUtil.isNotEmpty(triggers)) {
zbxTrigger.triggerDelete(productEventRelationList.get(0).getZbxId());
}
}
//step 1:删除 与设备的关联
new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).delete();
//step 2:删除 关联的表达式
new QProductEventExpression().eventRuleId.eq(eventRule.getEventRuleId()).delete();
//step 3:删除 关联的时间表达式
new QProductEventTimeInterval().eventRuleId.eq(eventRule.getEventRuleId()).delete();
} else {
//step 1:删除 定时器
new QTask().id.eq(productEvent.getTaskId()).delete();
}
//step 3:删除 关联的执行服务
new QProductEventService().eventRuleId.eq(eventRule.getEventRuleId()).delete();
//step 4:删除 触发器
new QProductEvent().eventRuleId.eq(eventRule.getEventRuleId()).delete();
return ResponseData.success();
}
@RequestMapping("/execute")
public ResponseData execute(@RequestParam("eventRuleId") Long eventRuleId) {
int count = new QProductEvent().eventRuleId.eq(eventRuleId).classify.eq("1").findCount();
if (count <= 0) {
throw new ServiceException(BizExceptionEnum.SCENE_NOT_EXISTS);
}
multipleDeviceEventRuleService.execute(eventRuleId, "手动", LoginContextHolder.getContext().getUser().getId());
return ResponseData.success();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/controller/MultipleDeviceEventTriggerController.java
|
Java
|
gpl-3.0
| 12,808
|
package com.zmops.iot.web.device.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.model.cache.filter.CachedValue;
import com.zmops.iot.model.cache.filter.CachedValueFilter;
import com.zmops.iot.model.cache.filter.DicType;
import com.zmops.zeus.driver.entity.Interface;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author yefei
**/
@Data
@JsonSerialize(using = CachedValueFilter.class)
public class DeviceDto {
@NotBlank(groups = {BaseEntity.Update.class, BaseEntity.Delete.class, BaseEntity.Status.class})
private String deviceId;
private String edit;
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String name;
@NotNull(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private Long productId;
private String productName;
@NotEmpty(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private List<Long> deviceGroupIds;
@CachedValue(value = "STATUS", fieldName = "statusName")
@NotBlank(groups = {BaseEntity.Status.class})
private String status;
@CachedValue(value = "DEVICE_TYPE", fieldName = "typeName")
private String type;
private String remark;
@CachedValue(type = DicType.Tenant, fieldName = "tenantName")
private Long tenantId;
private LocalDateTime createTime;
private LocalDateTime updateTime;
@CachedValue(type = DicType.SysUserName, fieldName = "createUserName")
private Long createUser;
@CachedValue(type = DicType.SysUserName, fieldName = "updateUserName")
private Long updateUser;
private Long oldProductId;
private String zbxId;
private String groupIds;
private String groupName;
private String addr;
private String position;
private Integer online;
private Long proxyId;
private Interface deviceInterface;
private LocalDateTime latestOnline;
private String productCode;
private String method;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/DeviceDto.java
|
Java
|
gpl-3.0
| 2,193
|
package com.zmops.iot.web.device.dto;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class DeviceEventRelationDto {
private Long id;
private Long eventRuleId;
private String relationId;
private String zbxId;
private String inherit;
private String status;
private String remark;
private String triggerDevice;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/DeviceEventRelationDto.java
|
Java
|
gpl-3.0
| 356
|
package com.zmops.iot.web.device.dto;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.util.ToolUtil;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author nantian created at 2021/9/14 14:47
* <p>
* 告警规则
*/
@Getter
@Setter
public class DeviceEventRule {
@NotNull(groups = {BaseEntity.Update.class, BaseEntity.Delete.class, BaseEntity.Status.class})
private Long eventRuleId;
@NotNull(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private Byte eventNotify; // 0 否 1 是,默认 1
// 告警规则名称
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String eventRuleName;
// 告警规则级别
@NotNull(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private Byte eventLevel;
// 表达式列表
@Valid
@NotEmpty(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private List<Expression> expList;
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String expLogic; // and or
private String remark;
private List<DeviceService> deviceServices;
private List<Tag> tags;
@NotNull(groups = BaseEntity.Update.class)
private String zbxId;
@NotBlank(groups = {BaseEntity.Status.class, BaseEntity.Delete.class})
private String deviceId;
@NotBlank(groups = BaseEntity.Status.class)
private String status;
private String classify = "0";
@Data
public static class Tag {
@Max(20)
private String tag;
@Max(50)
private String value;
}
@Getter
@Setter
// 告警表达式 构成
public static class Expression {
private Long eventExpId;
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String function; // last avg max min sum change nodata
private String scope; // s m h T
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String condition; // > < = <> >= <=
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String value;
@NotNull(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String productAttrKey; // 产品属性 Key
private String deviceId; // 设备ID
private String unit;
private Long productAttrId;
private String productAttrType;
private String attrValueType;
private String period;
@Override
public String toString() {
StringBuilder expression = new StringBuilder();
expression.append(function);
expression.append("(/");
expression.append(deviceId);
expression.append("/");
expression.append(productAttrKey);
if (StringUtils.isNotBlank(scope)) {
expression.append(", ");
expression.append(scope);
}
expression.append(") ").append(condition).append(" ").append(ToolUtil.addQuotes(value));
return expression.toString();
}
}
@Setter
@Getter
public static class DeviceService {
private String deviceId;
private String executeDeviceId;
private Long serviceId;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/DeviceEventRule.java
|
Java
|
gpl-3.0
| 3,643
|
package com.zmops.iot.web.device.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.zmops.iot.model.cache.filter.CachedValue;
import com.zmops.iot.model.cache.filter.CachedValueFilter;
import com.zmops.iot.model.cache.filter.DicType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
/**
* 设备组传输bean
*
* @author yefei
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonSerialize(using = CachedValueFilter.class)
public class DeviceGroupDto {
private Long deviceGroupId;
private String name;
private String remark;
@CachedValue(type = DicType.Tenant, fieldName = "tenantName")
private Long tenantId;
@CachedValue(type = DicType.SysUserName, fieldName = "createUserName")
private Long createUser;
@CachedValue(type = DicType.SysUserName, fieldName = "updateUserName")
private Long updateUser;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/DeviceGroupDto.java
|
Java
|
gpl-3.0
| 1,077
|
package com.zmops.iot.web.device.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.zmops.iot.model.cache.filter.CachedValue;
import com.zmops.iot.model.cache.filter.CachedValueFilter;
import com.zmops.iot.model.cache.filter.DicType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author yefei
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonSerialize(using = CachedValueFilter.class)
public class DeviceLogDto {
private String logType;
private String triggerTime;
private String content;
@CachedValue(type = DicType.Device, fieldName = "deviceName")
private String deviceId;
@CachedValue(value = "EVENT_LEVEL", fieldName = "severityName")
private String severity;
private String param;
private String status;
private String triggerType;
private String triggerBody;
private String key;
private Long eventRuleId;
private Long userId;
private List<DeviceRelationDto> triggerDevice;
private List<DeviceRelationDto> executeDevice;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/DeviceLogDto.java
|
Java
|
gpl-3.0
| 1,150
|
package com.zmops.iot.web.device.dto;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class DeviceRelationDto {
private String deviceId;
private String name;
private Long eventRuleId;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/DeviceRelationDto.java
|
Java
|
gpl-3.0
| 215
|
package com.zmops.iot.web.device.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.zmops.iot.domain.product.ProductEventExpression;
import com.zmops.iot.domain.product.ProductEventService;
import com.zmops.iot.domain.product.ProductEventTimeInterval;
import com.zmops.iot.model.cache.filter.CachedValue;
import com.zmops.iot.model.cache.filter.CachedValueFilter;
import com.zmops.iot.model.cache.filter.DicType;
import lombok.Data;
import java.util.List;
/**
* @author yefei
**/
@Data
@JsonSerialize(using = CachedValueFilter.class)
public class MultipleDeviceEventDto {
private Long eventRuleId;
private Byte eventNotify;
private String eventRuleName;
@CachedValue(value = "EVENT_LEVEL", fieldName = "eventLevelName")
private String eventLevel;
@CachedValue(value = "STATUS", fieldName = "statusName")
private String status;
private String inherit;
private String remark;
private String classify;
private String expLogic;
@CachedValue(type = DicType.SysUserName, fieldName = "createUserName")
private Long createUser;
private String createTime;
@CachedValue(type = DicType.SysUserName, fieldName = "updateUserName")
private Long updateUser;
private String updateTime;
private String triggerDevice;
private String executeDevice;
@CachedValue(type = DicType.Tenant, fieldName = "tenantName")
private Long tenantId;
private Integer taskId;
@CachedValue(value = "triggerType", fieldName = "triggerTypeName")
private String triggerType;
private String scheduleConf;
private List<ProductEventExpression> expList;
private List<ProductEventService> deviceServices;
private List<MultipleDeviceEventRule.Tag> tags;
private List<ProductEventTimeInterval> timeExpList;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/MultipleDeviceEventDto.java
|
Java
|
gpl-3.0
| 1,831
|
package com.zmops.iot.web.device.dto;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.util.ToolUtil;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author nantian created at 2021/9/14 14:47
* <p>
* 告警规则
*/
@Getter
@Setter
public class MultipleDeviceEventRule {
@NotNull(groups = {BaseEntity.Update.class, BaseEntity.Delete.class, BaseEntity.Status.class})
private Long eventRuleId;
private Byte eventNotify = 0;
// 名称
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String eventRuleName;
private Byte eventLevel = 1;
// 表达式列表
private List<Expression> expList;
private String expLogic = "and"; // and or
private String remark;
@NotEmpty(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private List<DeviceService> deviceServices;
private List<Tag> tags;
private String zbxId;
private String deviceId;
@NotBlank(groups = BaseEntity.Status.class)
private String status;
private String classify = "1";
private Long tenantId;
private String scheduleConf;
@NotNull
private Integer triggerType = 0;
private Integer taskId;
private List<TimeInterval> timeIntervals;
@Data
public static class Tag {
@Max(20)
private String tag;
@Max(50)
private String value;
}
@Getter
@Setter
// 告警表达式 构成
public static class Expression {
private Long eventExpId;
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String function; // last avg max min sum change nodata
private String scope; // s m h T
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String condition; // > < = <> >= <=
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String value;
@NotNull(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String productAttrKey; // 产品属性 Key
private String deviceId; // 设备ID
private String unit;
private Long productAttrId;
private String productAttrType;
private String attrValueType;
private String period;
@Override
public String toString() {
StringBuilder expression = new StringBuilder();
expression.append(function);
expression.append("(/");
expression.append(deviceId);
expression.append("/");
expression.append(productAttrKey);
if (StringUtils.isNotBlank(scope)) {
expression.append(", ");
expression.append(scope);
}
expression.append(") ").append(condition).append(" ").append(ToolUtil.addQuotes(value));
return expression.toString();
}
}
@Setter
@Getter
public static class DeviceService {
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private String executeDeviceId;
@NotBlank(groups = {BaseEntity.Create.class, BaseEntity.Update.class})
private Long serviceId;
}
@Getter
@Setter
public static class TimeInterval {
private String dayOfWeeks;
private String startTime;
private String endTime;
@Override
public String toString() {
String weekExpression = "";
if (ToolUtil.isNotEmpty(dayOfWeeks)) {
weekExpression = Arrays.asList(dayOfWeeks.split(",")).parallelStream().map(day -> "dayofweek()=" + day).collect(Collectors.joining(" or "));
}
if (ToolUtil.isNotEmpty(weekExpression)) {
return "((" + weekExpression + ") and time()>= " + startTime + " and " + " time()< " + endTime + " )";
}
return "(time()>= " + startTime + " and " + " time()< " + endTime + " )";
}
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/MultipleDeviceEventRule.java
|
Java
|
gpl-3.0
| 4,363
|
package com.zmops.iot.web.device.dto;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class MultipleDeviceServiceDto {
private Long eventRuleId;
private String executeDevice;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/MultipleDeviceServiceDto.java
|
Java
|
gpl-3.0
| 202
|
package com.zmops.iot.web.device.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author yefei
**/
@Data
public class ServiceExecuteDto {
@NotBlank
private String deviceId;
@NotNull
private Long serviceId;
private List<ServiceParam> serviceParams;
@Data
public static class ServiceParam {
@NotBlank
private String key;
@NotBlank
private String value;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/ServiceExecuteDto.java
|
Java
|
gpl-3.0
| 526
|
package com.zmops.iot.web.device.dto;
import lombok.Data;
/**
* @author nantian created at 2021/8/2 16:59
*/
@Data
public class TaosResponseData {
private String status;
private String[] head;
private String[][] column_meta;
private String[][] data;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/TaosResponseData.java
|
Java
|
gpl-3.0
| 279
|
package com.zmops.iot.web.device.dto.param;
import com.zmops.iot.domain.BaseEntity;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* 设备组参数
*
* @author yefei
*/
@Data
public class DeviceGroupParam extends BaseQueryParam {
@NotNull(groups = BaseEntity.Update.class)
private Long deviceGroupId;
@NotBlank(groups = {BaseEntity.Update.class, BaseEntity.Create.class})
private String name;
private String remark;
@NotNull(groups = BaseEntity.Delete.class)
private List<Long> deviceGroupIds;
private Long tenantId;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/param/DeviceGroupParam.java
|
Java
|
gpl-3.0
| 710
|
package com.zmops.iot.web.device.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class DeviceLogParam extends BaseQueryParam {
private String logType;
private String deviceId;
private String content;
private Long timeFrom;
private Long timeTill;
private String triggerType;
private Long triggerUser;
private Long eventRuleId;
private String triggerDeviceId;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/param/DeviceLogParam.java
|
Java
|
gpl-3.0
| 485
|
package com.zmops.iot.web.device.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
/**
* @author yefei
**/
@Data
public class DeviceParam extends BaseQueryParam {
private String name;
private Long productId;
private Long deviceGroupId;
private String prodType;
private String tag;
private String tagVal;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/param/DeviceParam.java
|
Java
|
gpl-3.0
| 377
|
package com.zmops.iot.web.device.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
import java.util.List;
/**
* @author yefei
**/
@Data
public class DeviceParams extends BaseQueryParam {
private String name;
private String deviceId;
private List<Long> productIds;
private List<Long> deviceGroupIds;
private List<Long> prodTypes;
private String tag;
private String tagVal;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/param/DeviceParams.java
|
Java
|
gpl-3.0
| 450
|
package com.zmops.iot.web.device.dto.param;
import com.zmops.iot.web.sys.dto.param.BaseQueryParam;
import lombok.Data;
import java.util.List;
/**
* @author yefei
**/
@Data
public class MultipleDeviceEventParm extends BaseQueryParam {
private String eventRuleName;
private List<String> deviceIds;
private List<Long> deviceGrpIds;
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/dto/param/MultipleDeviceEventParm.java
|
Java
|
gpl-3.0
| 352
|
package com.zmops.iot.web.device.schedule;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.DeviceOnlineReport;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.util.LocalDateTimeUtils;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@EnableScheduling
@Component
@Slf4j
public class DeviceOnlineReprotSchedule {
@Scheduled(cron = "0 59 23 1/1 * ? ")
public void report() {
log.info("开始查询设备在线情况");
//统计出 当前 设备在线情况
List<Device> deviceList = new QDevice().findList();
Map<Long, Map<Integer, Long>> onLinemap = deviceList.parallelStream()
.collect(Collectors.groupingBy(o -> Optional.ofNullable(o.getTenantId()).orElse(0L), Collectors.groupingBy(o -> Optional.ofNullable(o.getOnline()).orElse(0), Collectors.counting())));
List<DeviceOnlineReport> list = new ArrayList<>();
AtomicLong onLine = new AtomicLong();
AtomicLong offLine = new AtomicLong();
onLinemap.forEach((key, val) -> {
onLine.addAndGet(Optional.ofNullable(val.get(1)).orElse(0L));
offLine.addAndGet(Optional.ofNullable(val.get(0)).orElse(0L));
if (key == 0) {
return;
}
list.add(DeviceOnlineReport.builder().tenantId(key)
.createTime(LocalDateTimeUtils.formatTimeDate(LocalDateTime.now()))
.online(Optional.ofNullable(val.get(1)).orElse(0L))
.offline(Optional.ofNullable(val.get(0)).orElse(0L)).build());
});
list.add(DeviceOnlineReport.builder()
.createTime(LocalDateTimeUtils.formatTimeDate(LocalDateTime.now()))
.online(onLine.get())
.offline(offLine.get()).build());
//插入 在线情况表
DB.saveAll(list);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/schedule/DeviceOnlineReprotSchedule.java
|
Java
|
gpl-3.0
| 2,357
|
package com.zmops.iot.web.device.schedule;
import com.alibaba.fastjson.JSON;
import com.dtflys.forest.http.ForestResponse;
import com.zmops.iot.domain.device.Tag;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.device.query.QTag;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.TaosResponseData;
import com.zmops.zeus.driver.service.TDEngineRest;
import com.zmops.zeus.driver.service.ZbxItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@EnableScheduling
@Component
@Slf4j
public class SyncTaosTagSchedule {
@Autowired
ZbxItem zbxItem;
@Autowired
TDEngineRest tdEngineRest;
@Scheduled(cron = "0 55 23 1/1 * ? ")
// @Scheduled(cron = "0 0/1 * * * ? ")
public void sync() {
List<String> deviceIds = new QDevice().select(QDevice.alias().deviceId).findSingleAttributeList();
List<Tag> tagList = new QTag().sid.in(deviceIds).findList();
if (ToolUtil.isEmpty(tagList)) {
return;
}
Map<String, List<Tag>> tagMap = tagList.parallelStream().collect(Collectors.groupingBy(Tag::getSid));
ForestResponse<String> res_history = tdEngineRest.executeSql("DESCRIBE history;");
if (res_history.isError()) {
return;
}
String describe = res_history.getContent();
TaosResponseData taosResponseData = JSON.parseObject(describe, TaosResponseData.class);
String[][] data = taosResponseData.getData();
List<String> taosTagNames = new ArrayList<>();
for (String[] datum : data) {
if (ToolUtil.isNotEmpty(datum[3]) && "TAG".equals(datum[3])) {
taosTagNames.add(datum[0]);
}
}
if (ToolUtil.isEmpty(taosTagNames)) {
return;
}
List<String> tagNames = tagList.parallelStream().map(Tag::getTag).collect(Collectors.toList());
//新增taos没有的标签
addTaosTag(tagNames, taosTagNames);
//删除taos标签
delTaosTag(taosTagNames, tagNames);
//更新子表 标签值
tagMap.forEach((deviceId, tags) -> {
//根据deviceId 找到 设备下所有itemId
List<String> itemIds = new QProductAttribute().select(QProductAttribute.alias().zbxId).productId.eq(deviceId).zbxId.isNotNull().findSingleAttributeList();
if (ToolUtil.isEmpty(itemIds)) {
return;
}
itemIds.forEach(itemId -> {
tags.forEach(tag -> {
tdEngineRest.executeSql("ALTER TABLE h_" + itemId + " SET TAG " + tag.getTag() + "='" + tag.getValue() + "'");
});
});
});
}
private void delTaosTag(List<String> list1, List<String> list2) {
list1.removeAll(list2);
if (ToolUtil.isEmpty(list1)) {
return;
}
list1.forEach(tagName -> {
if ("deviceid".equals(tagName) || "itemid".equals(tagName)) {
return;
}
tdEngineRest.executeSql("ALTER STABLE history_uint DROP TAG '" + tagName + "'");
tdEngineRest.executeSql("ALTER STABLE history DROP TAG '" + tagName + "'");
});
}
private void addTaosTag(List<String> list1, List<String> list2) {
list1.removeAll(list2);
if (ToolUtil.isEmpty(list1)) {
return;
}
list1.forEach(tagName -> {
tdEngineRest.executeSql("ALTER STABLE history_uint ADD TAG " + tagName + " NCHAR(16)");
tdEngineRest.executeSql("ALTER STABLE history ADD TAG " + tagName + " NCHAR(16)");
});
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/schedule/SyncTaosTagSchedule.java
|
Java
|
gpl-3.0
| 4,073
|
package com.zmops.iot.web.device.service;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceDeleteEvent;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import com.zmops.iot.web.event.applicationEvent.dto.DeviceDeleteEventData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
@Component
@EnableAsync
public class DeviceEventPublisher {
@Autowired
ApplicationEventPublisher publisher;
@Async
public void DeviceSaveEventPublish(DeviceDto deviceDto) {
publisher.publishEvent(new DeviceSaveEvent(this, deviceDto));
}
public void DeviceDeleteEventPublish(String deviceId, String zbxId) {
publisher.publishEvent(new DeviceDeleteEvent(this, DeviceDeleteEventData.builder().deviceId(deviceId).zbxId(zbxId).build()));
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceEventPublisher.java
|
Java
|
gpl-3.0
| 1,074
|
package com.zmops.iot.web.device.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.product.ProductEvent;
import com.zmops.iot.domain.product.ProductEventExpression;
import com.zmops.iot.domain.product.ProductEventRelation;
import com.zmops.iot.domain.product.query.QProductEventExpression;
import com.zmops.iot.domain.product.query.QProductEventRelation;
import com.zmops.iot.domain.product.query.QProductEventService;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.enums.InheritStatus;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceEventRule;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.product.dto.ProductEventRuleDto;
import com.zmops.iot.web.product.service.ProductEventRuleService;
import com.zmops.zeus.driver.service.ZbxTrigger;
import io.ebean.DB;
import io.ebean.annotation.Transactional;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@Service
public class DeviceEventRuleService {
@Autowired
private ZbxTrigger zbxTrigger;
@Autowired
ProductEventRuleService productEventRuleService;
/**
* 保存触发器
*
* @param eventRuleId 触发器ID
* @param eventRule 告警规则
*/
@Transactional(rollbackFor = Exception.class)
public void createDeviceEventRule(Long eventRuleId, DeviceEventRule eventRule) {
// step 1: 保存产品告警规则
ProductEvent event = initEventRule(eventRule);
event.setEventRuleId(eventRuleId);
DB.save(event);
//step 2: 保存 表达式,方便回显
List<ProductEventExpression> expList = new ArrayList<>();
eventRule.getExpList().forEach(i -> {
ProductEventExpression exp = initEventExpression(i);
exp.setEventRuleId(eventRuleId);
expList.add(exp);
});
DB.saveAll(expList);
//step 3: 保存触发器 调用 动作服务
if (null != eventRule.getDeviceServices() && !eventRule.getDeviceServices().isEmpty()) {
List<String> deviceIds = eventRule.getExpList().parallelStream().map(DeviceEventRule.Expression::getDeviceId).distinct().collect(Collectors.toList());
deviceIds.forEach(deviceId -> {
eventRule.getDeviceServices().forEach(i -> {
DB.sqlUpdate("insert into product_event_service(event_rule_id, device_id,execute_device_id, service_id) " +
"values (:eventRuleId, :deviceId,:executeDeviceId, :serviceId)")
.setParameter("eventRuleId", eventRuleId)
.setParameter("deviceId", deviceId)
.setParameter("executeDeviceId", i.getExecuteDeviceId())
.setParameter("serviceId", i.getServiceId())
.execute();
});
});
}
//step 4: 保存关联关系
List<String> relationIds = eventRule.getExpList().parallelStream().map(DeviceEventRule.Expression::getDeviceId).distinct().collect(Collectors.toList());
if (ToolUtil.isEmpty(relationIds)) {
throw new ServiceException(BizExceptionEnum.EVENT_HAS_NOT_DEVICE);
}
List<ProductEventRelation> productEventRelationList = new ArrayList<>();
relationIds.forEach(relationId -> {
ProductEventRelation productEventRelation = new ProductEventRelation();
productEventRelation.setEventRuleId(eventRuleId);
productEventRelation.setRelationId(relationId);
productEventRelation.setInherit(InheritStatus.NO.getCode());
productEventRelation.setStatus(CommonStatus.ENABLE.getCode());
productEventRelation.setRemark(eventRule.getRemark());
productEventRelationList.add(productEventRelation);
});
DB.saveAll(productEventRelationList);
//更新缓存
productEventRuleService.updateProductEvent();
}
@Transactional(rollbackFor = Exception.class)
public void updateDeviceEventRule(Long eventRuleId, DeviceEventRule eventRule) {
//step 1: 函数表达式
DB.sqlUpdate("delete from product_event_expression where event_rule_id = :eventRuleId")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.execute();
//step 2: 删除服务方法调用
DB.sqlUpdate("delete from product_event_service where event_rule_id = :eventRuleId")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.execute();
// 删除和所有设备的关联关系
new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).delete();
// step 3: 保存产品告警规则
ProductEvent event = initEventRule(eventRule);
event.setEventRuleId(eventRuleId);
event.update();
//step 4: 保存 表达式,方便回显
List<ProductEventExpression> expList = new ArrayList<>();
eventRule.getExpList().forEach(i -> {
ProductEventExpression exp = initEventExpression(i);
exp.setEventRuleId(eventRuleId);
expList.add(exp);
});
DB.saveAll(expList);
//step 5: 保存触发器 调用 本产品方法
if (null != eventRule.getDeviceServices() && !eventRule.getDeviceServices().isEmpty()) {
List<String> deviceIds = eventRule.getExpList().parallelStream().map(DeviceEventRule.Expression::getDeviceId).distinct().collect(Collectors.toList());
deviceIds.forEach(deviceId -> {
eventRule.getDeviceServices().forEach(i -> {
DB.sqlUpdate("insert into product_event_service(event_rule_id, device_id,execute_device_id, service_id) values (:eventRuleId, :deviceId,:executeDeviceId, :serviceId)")
.setParameter("eventRuleId", eventRuleId)
.setParameter("deviceId", deviceId)
.setParameter("executeDeviceId", i.getExecuteDeviceId())
.setParameter("serviceId", i.getServiceId())
.execute();
});
});
}
// step 6: 保存关联关系
List<String> relationIds = eventRule.getExpList().parallelStream().map(DeviceEventRule.Expression::getDeviceId).distinct().collect(Collectors.toList());
if (ToolUtil.isEmpty(relationIds)) {
throw new ServiceException(BizExceptionEnum.EVENT_HAS_NOT_DEVICE);
}
List<ProductEventRelation> productEventRelationList = new ArrayList<>();
relationIds.forEach(relationId -> {
ProductEventRelation productEventRelation = new ProductEventRelation();
productEventRelation.setEventRuleId(eventRuleId);
productEventRelation.setRelationId(relationId);
productEventRelation.setStatus(CommonStatus.ENABLE.getCode());
productEventRelation.setRemark(eventRule.getRemark());
productEventRelationList.add(productEventRelation);
});
DB.saveAll(productEventRelationList);
//更新缓存
productEventRuleService.updateProductEvent();
}
private ProductEvent initEventRule(DeviceEventRule eventRule) {
ProductEvent event = new ProductEvent();
event.setEventLevel(eventRule.getEventLevel().toString());
event.setExpLogic(eventRule.getExpLogic());
event.setEventNotify(eventRule.getEventNotify().toString());
event.setClassify(eventRule.getClassify());
event.setEventRuleName(eventRule.getEventRuleName());
return event;
}
private ProductEventExpression initEventExpression(DeviceEventRule.Expression exp) {
ProductEventExpression eventExpression = new ProductEventExpression();
eventExpression.setEventExpId(exp.getEventExpId());
eventExpression.setCondition(exp.getCondition());
eventExpression.setFunction(exp.getFunction());
eventExpression.setScope(exp.getScope());
eventExpression.setValue(exp.getValue());
eventExpression.setDeviceId(exp.getDeviceId());
eventExpression.setProductAttrKey(exp.getProductAttrKey());
eventExpression.setProductAttrId(exp.getProductAttrId());
eventExpression.setProductAttrType(exp.getProductAttrType());
eventExpression.setPeriod(exp.getPeriod());
eventExpression.setUnit(exp.getUnit());
eventExpression.setAttrValueType(exp.getAttrValueType());
return eventExpression;
}
/**
* 更新 触发器规则 zbxId
*
* @param triggerId 规则ID
* @param zbxId triggerId
*/
public void updateProductEventRuleZbxId(Long triggerId, String[] zbxId) {
// List<Triggers> triggers = JSONObject.parseArray(zbxTrigger.triggerGet(Arrays.toString(zbxId)), Triggers.class);
//
// Map<String, String> map = triggers.parallelStream().collect(Collectors.toMap(o -> o.hosts.get(0).host, Triggers::getTriggerid));
//
// List<ProductEventRelation> productEventRelationList = new QProductEventRelation().eventRuleId.eq(triggerId).findList();
// productEventRelationList.forEach(productEventRelation -> {
// if (null != map.get(productEventRelation.getRelationId())) {
DB.update(ProductEventRelation.class).where().eq("eventRuleId", triggerId)
.asUpdate().set("zbxId", zbxId[0]).update();
// }
// });
}
/**
* 获取产品事件规则详情
*
* @param productEvent
* @param eventRuleId
* @param deviceId
* @return
*/
public ProductEventRuleDto detail(ProductEvent productEvent, long eventRuleId, String deviceId) {
ProductEventRuleDto productEventRuleDto = new ProductEventRuleDto();
ToolUtil.copyProperties(productEvent, productEventRuleDto);
List<ProductEventExpression> expList = new QProductEventExpression().eventRuleId.eq(eventRuleId).findList();
expList.forEach(productEventExpression -> {
if (ToolUtil.isEmpty(productEventExpression.getDeviceId())) {
productEventExpression.setDeviceId(deviceId);
}
});
productEventRuleDto.setExpList(expList);
productEventRuleDto.setDeviceServices(new QProductEventService().eventRuleId.eq(eventRuleId).deviceId.eq(deviceId).findList());
ProductEventRelation productEventRelation = new QProductEventRelation().relationId.eq(deviceId).eventRuleId.eq(eventRuleId).findOne();
productEventRuleDto.setStatus(productEventRelation.getStatus());
productEventRuleDto.setRemark(productEventRelation.getRemark());
productEventRuleDto.setInherit(productEventRelation.getInherit());
if (InheritStatus.YES.getCode().equals(productEventRelation.getInherit())) {
ProductEventRelation one = new QProductEventRelation().eventRuleId.eq(eventRuleId).inherit.eq(InheritStatus.NO.getCode()).findOne();
productEventRuleDto.setInheritProductId(one.getRelationId());
}
if (null != productEventRelation) {
JSONArray triggerInfo = JSONObject.parseArray(zbxTrigger.triggerAndTagsGet(productEventRelation.getZbxId()));
List<ProductEventRuleDto.Tag> tagList = JSONObject.parseArray(triggerInfo.getJSONObject(0).getString("tags"), ProductEventRuleDto.Tag.class);
productEventRuleDto.setZbxId(productEventRelation.getZbxId());
productEventRuleDto.setTags(tagList.stream()
.filter(s -> !s.getTag().equals("__execute__") && !s.getTag().equals("__alarm__") && !s.getTag().equals("__event__"))
.collect(Collectors.toList()));
}
return productEventRuleDto;
}
/**
* 创建 触发器
*
* @param triggerName 触发器名称
* @param expression 表达式
* @param level 告警等级
* @return 触发器ID
*/
public String[] createZbxTrigger(String triggerName, String expression, Byte level) {
String res = zbxTrigger.triggerCreate(triggerName, expression, level,0);
return JSON.parseObject(res, TriggerIds.class).getTriggerids();
}
/**
* 更新 触发器
*
* @param triggerId
* @param expression
* @param level
* @return
*/
public String[] updateZbxTrigger(String triggerId, String expression, Byte level) {
String res = zbxTrigger.triggerUpdate(triggerId, expression, level);
return JSON.parseObject(res, TriggerIds.class).getTriggerids();
}
/**
* 检查动作服务是否重复
*
* @param deviceServices
*/
public void checkService(List<DeviceEventRule.DeviceService> deviceServices) {
if (ToolUtil.isEmpty(deviceServices)) {
return;
}
long count = deviceServices.parallelStream().map(DeviceEventRule.DeviceService::getServiceId).distinct().count();
if (count < deviceServices.size()) {
throw new ServiceException(BizExceptionEnum.SERVICE_HAS_DUPLICATE);
}
}
@Data
static class TriggerIds {
private String[] triggerids;
}
@Data
public static class Triggers {
private String triggerid;
private String description;
private List<Hosts> hosts;
}
@Data
public static class Hosts {
private String hostid;
private String host;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceEventRuleService.java
|
Java
|
gpl-3.0
| 13,856
|
package com.zmops.iot.web.device.service;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.core.auth.model.LoginUser;
import com.zmops.iot.domain.device.DeviceGroup;
import com.zmops.iot.domain.device.query.QDeviceGroup;
import com.zmops.iot.domain.device.query.QDevicesGroups;
import com.zmops.iot.domain.device.query.QSysUserGrpDevGrp;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceGroupDto;
import com.zmops.iot.web.device.dto.param.DeviceGroupParam;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.zeus.driver.entity.ZbxHostGrpInfo;
import com.zmops.zeus.driver.service.ZbxHostGroup;
import io.ebean.DB;
import io.ebean.PagedList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@Service
public class DeviceGroupService {
@Autowired
private ZbxHostGroup zbxHostGroup;
/**
* 设备组分页列表
*
* @param devGroupParam
* @return
*/
public Pager<DeviceGroupDto> deviceGroupPageList(DeviceGroupParam devGroupParam) {
List<Long> devGroupIds = getDevGroupIds();
if (ToolUtil.isEmpty(devGroupIds)) {
return new Pager<>();
}
QDeviceGroup qDeviceGroup = new QDeviceGroup();
qDeviceGroup.deviceGroupId.in(devGroupIds);
if (ToolUtil.isNotEmpty(devGroupParam.getName())) {
qDeviceGroup.name.contains(devGroupParam.getName());
}
qDeviceGroup.order().createTime.desc()
.setFirstRow((devGroupParam.getPage() - 1) * devGroupParam.getMaxRow())
.setMaxRows(devGroupParam.getMaxRow());
PagedList<DeviceGroup> pagedList = qDeviceGroup.orderBy(" create_time desc").findPagedList();
List<DeviceGroupDto> deviceGroupDtos = ToolUtil.convertBean(pagedList.getList(), DeviceGroupDto.class);
return new Pager<>(deviceGroupDtos, pagedList.getTotalCount());
}
/**
* 设备组列表
*
* @param devGroupParam
* @return
*/
public List<DeviceGroup> deviceGroupList(DeviceGroupParam devGroupParam) {
List<Long> devGroupIds = getDevGroupIds();
if (ToolUtil.isEmpty(devGroupIds)) {
return Collections.emptyList();
}
QDeviceGroup qDeviceGroup = new QDeviceGroup();
qDeviceGroup.deviceGroupId.in(devGroupIds);
if (ToolUtil.isNotEmpty(devGroupParam.getName())) {
qDeviceGroup.name.contains(devGroupParam.getName());
}
return qDeviceGroup.findList();
}
/**
* 获取当前登录用户绑定的主机组ID
*
* @return
*/
public List<Long> getDevGroupIds() {
LoginUser user = LoginContextHolder.getContext().getUser();
Long curUserGrpId = user.getUserGroupId();
Long tenantId = user.getTenantId();
List<Long> devGroupIds = new ArrayList<>();
if (null != curUserGrpId) {
devGroupIds = new QSysUserGrpDevGrp().select(QSysUserGrpDevGrp.alias().deviceGroupId).userGroupId.eq(curUserGrpId).findSingleAttributeList();
}
if (ToolUtil.isEmpty(devGroupIds) && null != curUserGrpId) {
QDeviceGroup qDeviceGroup = new QDeviceGroup().select(QDeviceGroup.alias().deviceGroupId);
if (null != tenantId) {
qDeviceGroup.tenantId.eq(tenantId);
}
devGroupIds = qDeviceGroup.findSingleAttributeList();
}
return devGroupIds;
}
/**
* 添加设备組
*/
public DeviceGroup createDeviceGroup(DeviceGroupParam deviceGroup) {
// 判断设备组是否重复
checkByGroupName(deviceGroup.getName(), -1L, deviceGroup.getTenantId());
//获取ID
long devGrpId = IdUtil.getSnowflake().nextId();
// 先在ZBX 添加主机组
DeviceGroup newDeviceGroup = new DeviceGroup();
BeanUtils.copyProperties(deviceGroup, newDeviceGroup);
newDeviceGroup.setDeviceGroupId(devGrpId);
//回填 ZBX主机组ID
JSONObject result = JSONObject.parseObject(zbxHostGroup.hostGroupCreate(String.valueOf(devGrpId)));
JSONArray grpids = result.getJSONArray("groupids");
newDeviceGroup.setZbxId(grpids.get(0).toString());
DB.save(newDeviceGroup);
return newDeviceGroup;
}
/**
* 修改设备组
*
* @param deviceGroup
* @return DeviceGroup
*/
public DeviceGroup updateDeviceGroup(DeviceGroupParam deviceGroup) {
// 判断设备组是否重复
checkByGroupName(deviceGroup.getName(), deviceGroup.getDeviceGroupId(), deviceGroup.getTenantId());
DeviceGroup newDeviceGroup = new DeviceGroup();
BeanUtils.copyProperties(deviceGroup, newDeviceGroup);
DB.update(newDeviceGroup);
return newDeviceGroup;
}
/**
* 根据GroupName userGroupId检查用户组是否已存在
*
* @param groupName
*/
private void checkByGroupName(String groupName, long deviceGroupId, Long tenantId) {
int count;
if (deviceGroupId >= 0) {
count = new QDeviceGroup().name.equalTo(groupName).tenantId.eq(tenantId).deviceGroupId.ne(deviceGroupId).findCount();
} else {
count = new QDeviceGroup().name.equalTo(groupName).tenantId.eq(tenantId).findCount();
}
if (count > 0) {
throw new ServiceException(BizExceptionEnum.DEVICEGROUP_HAS_EXIST);
}
}
/**
* 删除设备组
*
* @param deviceGroupParam
*/
@Transactional(rollbackFor = Exception.class)
public void deleteDeviceGroup(DeviceGroupParam deviceGroupParam) {
List<DeviceGroup> list = new QDeviceGroup().deviceGroupId.in(deviceGroupParam.getDeviceGroupIds()).findList();
if (ToolUtil.isEmpty(list)) {
throw new ServiceException(BizExceptionEnum.DEVICEGROUP_NOT_EXIST);
}
//检查是否关联设备
int count = new QDevicesGroups().deviceGroupId.in(deviceGroupParam.getDeviceGroupIds()).findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.DEVICEGROUP_HAS_BIND_DEVICE);
}
//删除ZBX中主机组
List<String> zbxHostGrpIds = list.parallelStream().map(DeviceGroup::getZbxId).collect(Collectors.toList());
if (ToolUtil.isNotEmpty(zbxHostGrpIds)) {
List<ZbxHostGrpInfo> zbxHostGrpInfos = JSONObject.parseArray(zbxHostGroup.getHostGroup(zbxHostGrpIds.toString()), ZbxHostGrpInfo.class);
if (ToolUtil.isNotEmpty(zbxHostGrpInfos)) {
zbxHostGroup.hostGroupDelete(zbxHostGrpInfos.parallelStream().map(ZbxHostGrpInfo::getGroupid).collect(Collectors.toList()));
}
}
// 删除 与用户组关联
new QSysUserGrpDevGrp().deviceGroupId.in(deviceGroupParam.getDeviceGroupIds()).delete();
new QDeviceGroup().deviceGroupId.in(deviceGroupParam.getDeviceGroupIds()).delete();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceGroupService.java
|
Java
|
gpl-3.0
| 7,523
|
package com.zmops.iot.web.device.service;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.device.EventTriggerRecord;
import com.zmops.iot.domain.device.ScenesTriggerRecord;
import com.zmops.iot.domain.device.ServiceExecuteRecord;
import com.zmops.iot.domain.device.query.QEventTriggerRecord;
import com.zmops.iot.domain.device.query.QScenesTriggerRecord;
import com.zmops.iot.domain.device.query.QServiceExecuteRecord;
import com.zmops.iot.domain.product.query.QProductEventRelation;
import com.zmops.iot.domain.product.query.QProductEventService;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.DefinitionsUtil;
import com.zmops.iot.util.LocalDateTimeUtils;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.alarm.dto.AlarmDto;
import com.zmops.iot.web.alarm.dto.param.AlarmParam;
import com.zmops.iot.web.alarm.service.AlarmService;
import com.zmops.iot.web.device.dto.DeviceLogDto;
import com.zmops.iot.web.device.dto.DeviceRelationDto;
import com.zmops.iot.web.device.dto.param.DeviceLogParam;
import com.zmops.iot.web.event.applicationEvent.DeviceSceneLogEvent;
import com.zmops.iot.web.event.applicationEvent.DeviceServiceLogEvent;
import com.zmops.iot.web.event.applicationEvent.dto.LogEventData;
import io.ebean.DB;
import io.ebean.PagedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@Service
public class DeviceLogService {
private static final String LOG_TYPE_ALARM = "告警日志";
private static final String LOG_TYPE_EVENT = "事件日志";
private static final String LOG_TYPE_SERVICE = "服务日志";
private static final String LOG_TYPE_SCENES = "联动日志";
@Autowired
AlarmService alarmService;
@Autowired
ApplicationEventPublisher publisher;
public List<DeviceLogDto> list(String deviceId, String logType, Long timeFrom, Long timeTill) {
List<DeviceLogDto> deviceLogDtoList = new ArrayList<>();
if (ToolUtil.isEmpty(logType) || (ToolUtil.isNotEmpty(logType) && LOG_TYPE_ALARM.equals(logType))) {
AlarmParam alarmParam = new AlarmParam();
alarmParam.setDeviceId(deviceId);
alarmParam.setTimeFrom(timeFrom);
alarmParam.setTimeTill(timeTill);
List<AlarmDto> alarmList = alarmService.getAlarmList(alarmParam);
if (ToolUtil.isNotEmpty(alarmList)) {
alarmList.forEach(alarm -> {
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_ALARM).content(alarm.getName())
.triggerTime(LocalDateTimeUtils.formatTime(alarm.getClock()))
.status(null == alarm.getRClock() ? "未解决" : "已解决").build());
});
}
}
if (ToolUtil.isEmpty(logType) || (ToolUtil.isNotEmpty(logType) && LOG_TYPE_EVENT.equals(logType))) {
QEventTriggerRecord query = new QEventTriggerRecord().deviceId.eq(deviceId);
if (null != timeFrom) {
query.createTime.ge(LocalDateTimeUtils.getLDTByMilliSeconds(timeFrom * 1000));
}
if (null != timeTill) {
query.createTime.lt(LocalDateTimeUtils.getLDTByMilliSeconds(timeTill * 1000));
}
List<EventTriggerRecord> list = query.findList();
if (ToolUtil.isNotEmpty(list)) {
list.forEach(service -> {
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_EVENT).content(service.getEventName())
.triggerTime(LocalDateTimeUtils.formatTime(service.getCreateTime()))
.param(service.getEventName()).build());
});
}
}
if (ToolUtil.isEmpty(logType) || (ToolUtil.isNotEmpty(logType) && LOG_TYPE_SERVICE.equals(logType))) {
QServiceExecuteRecord query = new QServiceExecuteRecord().deviceId.eq(deviceId);
if (null != timeFrom) {
query.createTime.ge(LocalDateTimeUtils.getLDTByMilliSeconds(timeFrom * 1000));
}
if (null != timeTill) {
query.createTime.lt(LocalDateTimeUtils.getLDTByMilliSeconds(timeTill * 1000));
}
List<ServiceExecuteRecord> list = query.findList();
if (ToolUtil.isNotEmpty(list)) {
list.forEach(service -> {
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_SERVICE).content(service.getServiceName())
.triggerTime(LocalDateTimeUtils.formatTime(service.getCreateTime()))
.param(service.getParam()).build());
});
}
}
deviceLogDtoList.sort(Comparator.comparing(DeviceLogDto::getTriggerTime));
return deviceLogDtoList;
}
public Pager<DeviceLogDto> getLogByPage(DeviceLogParam deviceLogParam) {
String logType = deviceLogParam.getLogType();
if (ToolUtil.isNotEmpty(logType) && LOG_TYPE_SERVICE.equals(logType)) {
return getServiceLog(deviceLogParam);
} else if (ToolUtil.isNotEmpty(logType) && LOG_TYPE_SCENES.equals(logType)) {
return getScenesLog(deviceLogParam);
} else {
return getEventLog(deviceLogParam);
}
}
/**
* 告警日志
*
* @param deviceId
* @param timeFrom
* @param timeTill
* @param content
* @return
*/
private List<DeviceLogDto> getAlarmLog(String deviceId, Long timeFrom, Long timeTill, String content) {
List<DeviceLogDto> deviceLogDtoList = new ArrayList<>();
AlarmParam alarmParam = new AlarmParam();
if (ToolUtil.isNotEmpty(deviceId)) {
alarmParam.setDeviceId(deviceId);
}
alarmParam.setTimeFrom(timeFrom);
alarmParam.setTimeTill(timeTill);
List<AlarmDto> alarmList = alarmService.getAlarmList(alarmParam);
if (ToolUtil.isNotEmpty(alarmList)) {
alarmList.forEach(alarm -> {
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_ALARM).content(alarm.getName())
.triggerTime(LocalDateTimeUtils.formatTime(alarm.getClock()))
.status(null == alarm.getRClock() ? "未解决" : "已解决").severity(alarm.getSeverity())
.deviceId(alarm.getDeviceId()).build());
});
}
return deviceLogDtoList;
}
/**
* 事件日志
*
* @param deviceLogParam
* @return
*/
private Pager<DeviceLogDto> getEventLog(DeviceLogParam deviceLogParam) {
List<DeviceLogDto> deviceLogDtoList = new ArrayList<>();
QEventTriggerRecord query = new QEventTriggerRecord();
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
if (null != tenantId) {
query.tenantId.eq(tenantId);
}
if (ToolUtil.isNotEmpty(deviceLogParam.getDeviceId())) {
query.deviceId.eq(deviceLogParam.getDeviceId());
}
if (ToolUtil.isNotEmpty(deviceLogParam.getContent())) {
query.eventName.eq(deviceLogParam.getContent());
}
if (null != deviceLogParam.getTimeFrom()) {
query.createTime.ge(LocalDateTimeUtils.getLDTByMilliSeconds(deviceLogParam.getTimeFrom()));
}
if (null != deviceLogParam.getTimeTill()) {
query.createTime.lt(LocalDateTimeUtils.getLDTByMilliSeconds(deviceLogParam.getTimeTill()));
}
query.orderBy().createTime.desc();
PagedList<EventTriggerRecord> pagedList = query.setFirstRow((deviceLogParam.getPage() - 1) * deviceLogParam.getMaxRow())
.setMaxRows(deviceLogParam.getMaxRow()).findPagedList();
if (ToolUtil.isNotEmpty(pagedList.getList())) {
pagedList.getList().forEach(service -> {
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_EVENT).content(service.getEventName())
.triggerTime(LocalDateTimeUtils.formatTime(service.getCreateTime())).deviceId(service.getDeviceId())
.key(service.getKey())
.param(service.getEventValue()).build());
});
}
return new Pager<>(deviceLogDtoList, pagedList.getTotalCount());
}
/**
* 服务日志
*
* @param deviceLogParam
* @return
*/
private Pager<DeviceLogDto> getServiceLog(DeviceLogParam deviceLogParam) {
List<DeviceLogDto> deviceLogDtoList = new ArrayList<>();
QServiceExecuteRecord query = new QServiceExecuteRecord();
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
if (null != tenantId) {
query.tenantId.eq(tenantId);
}
if (ToolUtil.isNotEmpty(deviceLogParam.getDeviceId())) {
query.deviceId.eq(deviceLogParam.getDeviceId());
}
if (ToolUtil.isNotEmpty(deviceLogParam.getContent())) {
query.serviceName.eq(deviceLogParam.getContent());
}
if (ToolUtil.isNotEmpty(deviceLogParam.getTriggerType())) {
query.executeType.eq(deviceLogParam.getTriggerType());
}
if (ToolUtil.isNotEmpty(deviceLogParam.getTriggerUser())) {
query.executeUser.eq(deviceLogParam.getTriggerUser());
}
if (ToolUtil.isNotEmpty(deviceLogParam.getEventRuleId())) {
query.executeRuleId.eq(deviceLogParam.getEventRuleId());
}
if (null != deviceLogParam.getTimeFrom()) {
query.createTime.ge(LocalDateTimeUtils.getLDTByMilliSeconds(deviceLogParam.getTimeFrom()));
}
if (null != deviceLogParam.getTimeTill()) {
query.createTime.lt(LocalDateTimeUtils.getLDTByMilliSeconds(deviceLogParam.getTimeTill()));
}
query.orderBy().createTime.desc();
PagedList<ServiceExecuteRecord> pagedList = query.setFirstRow((deviceLogParam.getPage() - 1) * deviceLogParam.getMaxRow())
.setMaxRows(deviceLogParam.getMaxRow()).findPagedList();
if (ToolUtil.isNotEmpty(pagedList.getList())) {
pagedList.getList().forEach(service -> {
String triggerBody = null != service.getExecuteUser() ?
DefinitionsUtil.getSysUserName(service.getExecuteUser()) : DefinitionsUtil.getTriggerName(service.getExecuteRuleId());
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_SERVICE).content(service.getServiceName()).eventRuleId(service.getExecuteRuleId())
.triggerTime(LocalDateTimeUtils.formatTime(service.getCreateTime())).deviceId(service.getDeviceId()).userId(service.getExecuteUser())
.param(service.getParam()).triggerType(service.getExecuteType()).triggerBody(triggerBody).build());
});
}
return new Pager<>(deviceLogDtoList, pagedList.getTotalCount());
}
/**
* 场景日志
*
* @param deviceLogParam
* @return
*/
private Pager<DeviceLogDto> getScenesLog(DeviceLogParam deviceLogParam) {
List<DeviceLogDto> deviceLogDtoList = new ArrayList<>();
QScenesTriggerRecord query = new QScenesTriggerRecord();
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
if (null != tenantId) {
query.tenantId.eq(tenantId);
}
if (null != deviceLogParam.getEventRuleId()) {
query.ruleId.eq(deviceLogParam.getEventRuleId());
}
if (ToolUtil.isNotEmpty(deviceLogParam.getTriggerType())) {
query.triggerType.eq(deviceLogParam.getTriggerType());
}
if (null != deviceLogParam.getTriggerUser()) {
query.triggerUser.eq(deviceLogParam.getTriggerUser());
}
if (null != deviceLogParam.getTimeFrom()) {
query.createTime.ge(LocalDateTimeUtils.getLDTByMilliSeconds(deviceLogParam.getTimeFrom()));
}
if (null != deviceLogParam.getTimeTill()) {
query.createTime.lt(LocalDateTimeUtils.getLDTByMilliSeconds(deviceLogParam.getTimeTill()));
}
if (ToolUtil.isNotEmpty(deviceLogParam.getTriggerDeviceId())) {
List<Long> triggerRuleIds = new QProductEventRelation().select(QProductEventRelation.alias().eventRuleId).relationId.eq(deviceLogParam.getTriggerDeviceId()).findSingleAttributeList();
if (ToolUtil.isEmpty(triggerRuleIds)) {
return new Pager<>(Collections.emptyList(), 0);
}
query.ruleId.in(triggerRuleIds);
}
if (ToolUtil.isNotEmpty(deviceLogParam.getDeviceId())) {
List<Long> executeRuleIds = new QProductEventService().select(QProductEventService.alias().eventRuleId).executeDeviceId.eq(deviceLogParam.getDeviceId()).findSingleAttributeList();
if (ToolUtil.isEmpty(executeRuleIds)) {
return new Pager<>(Collections.emptyList(), 0);
}
query.ruleId.in(executeRuleIds);
}
query.orderBy().createTime.desc();
PagedList<ScenesTriggerRecord> pagedList = query.setFirstRow((deviceLogParam.getPage() - 1) * deviceLogParam.getMaxRow())
.setMaxRows(deviceLogParam.getMaxRow()).findPagedList();
if (ToolUtil.isEmpty(pagedList.getList())) {
return new Pager<>(deviceLogDtoList, pagedList.getTotalCount());
}
//关联触发设备
List<Long> eventRuleIds = pagedList.getList().parallelStream().map(ScenesTriggerRecord::getRuleId).collect(Collectors.toList());
String sql = "select distinct d.device_id,d.name,p.event_rule_id from product_event_relation p LEFT JOIN device d on d.device_id = p.relation_id where p.event_rule_id in (:eventRuleIds)";
List<DeviceRelationDto> triggerDeviceDtos = DB.findDto(DeviceRelationDto.class, sql).setParameter("eventRuleIds", eventRuleIds).findList();
Map<Long, List<DeviceRelationDto>> triggerDeviceMap = triggerDeviceDtos.parallelStream()
.collect(Collectors.groupingBy(DeviceRelationDto::getEventRuleId));
//关联 执行设备
sql = "select distinct d.device_id,d.name,p.event_rule_id from product_event_service p LEFT JOIN device d on d.device_id = p.execute_device_id where p.event_rule_id in (:eventRuleIds)";
List<DeviceRelationDto> executeDeviceDtos = DB.findDto(DeviceRelationDto.class, sql).setParameter("eventRuleIds", eventRuleIds).findList();
Map<Long, List<DeviceRelationDto>> executeDeviceMap = executeDeviceDtos.parallelStream()
.collect(Collectors.groupingBy(DeviceRelationDto::getEventRuleId));
pagedList.getList().forEach(service -> {
deviceLogDtoList.add(DeviceLogDto.builder().logType(LOG_TYPE_SCENES).content(service.getRuleName()).eventRuleId(service.getRuleId())
.triggerTime(LocalDateTimeUtils.formatTime(service.getCreateTime())).triggerType(service.getTriggerType())
.triggerBody(Optional.ofNullable(service.getTriggerUser()).map(DefinitionsUtil::getSysUserName).orElse("-"))
.triggerDevice(triggerDeviceMap.get(service.getRuleId())).executeDevice(executeDeviceMap.get(service.getRuleId()))
.build());
});
return new Pager<>(deviceLogDtoList, pagedList.getTotalCount());
}
/**
* 记录场景日志
*/
public void recordSceneLog(Long eventRuleId, String type, Long userId) {
publisher.publishEvent(new DeviceServiceLogEvent(this, LogEventData.builder().eventRuleId(eventRuleId).triggerType("自动".equals(type) ? "场景联动" : type).triggerUser(userId).build()));
publisher.publishEvent(new DeviceSceneLogEvent(this, LogEventData.builder().eventRuleId(eventRuleId).triggerType(type).triggerUser(userId).build()));
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceLogService.java
|
Java
|
gpl-3.0
| 16,120
|
package com.zmops.iot.web.device.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.product.ProductAttribute;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.domain.product.query.QProductEventExpression;
import com.zmops.iot.enums.CommonTimeUnit;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.analyse.dto.LatestDto;
import com.zmops.iot.web.analyse.service.LatestService;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.product.dto.ProductAttr;
import com.zmops.iot.web.product.dto.ProductAttrDto;
import com.zmops.iot.web.product.dto.ProductTag;
import com.zmops.iot.web.product.dto.param.ProductAttrParam;
import com.zmops.zeus.driver.entity.Interface;
import com.zmops.zeus.driver.entity.ZbxItemInfo;
import com.zmops.zeus.driver.entity.ZbxProcessingStep;
import com.zmops.zeus.driver.service.ZbxInterface;
import com.zmops.zeus.driver.service.ZbxItem;
import io.ebean.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 设备物模型服务
**/
@Service
public class DeviceModelService {
@Autowired
private ZbxItem zbxItem;
@Autowired
LatestService latestService;
@Autowired
ZbxInterface zbxInterface;
private static final String ATTR_SOURCE_AGENT = "0";
/**
* 设备属性分页列表
*
* @param productAttr
* @return
*/
public Pager<ProductAttrDto> prodModelAttributeList(ProductAttrParam productAttr) {
QProductAttribute qProductAttribute = new QProductAttribute();
qProductAttribute.productId.eq(productAttr.getProdId());
if (ToolUtil.isNotEmpty(productAttr.getAttrName())) {
qProductAttribute.name.contains(productAttr.getAttrName());
}
if (ToolUtil.isNotEmpty(productAttr.getKey())) {
qProductAttribute.key.contains(productAttr.getKey());
}
List<ProductAttrDto> pagedList = qProductAttribute.setFirstRow((productAttr.getPage() - 1) * productAttr.getMaxRow())
.setMaxRows(productAttr.getMaxRow()).orderBy(" create_time desc").asDto(ProductAttrDto.class).findList();
if (ToolUtil.isEmpty(pagedList)) {
return new Pager<>();
}
//查询最新数据
List<Long> attrIds = pagedList.parallelStream().map(ProductAttrDto::getAttrId).collect(Collectors.toList());
List<LatestDto> latestDtos = latestService.qeuryLatest(productAttr.getProdId(), attrIds);
Map<Long, LatestDto> map = latestDtos.parallelStream().distinct().collect(Collectors.toMap(LatestDto::getAttrId, o -> o, (a, b) -> b));
//查询zbx item 信息
List<String> zbxIds = pagedList.parallelStream().map(ProductAttrDto::getZbxId).collect(Collectors.toList());
String itemInfo = zbxItem.getItemInfo(zbxIds.toString(), null);
List<ZbxItemInfo> itemInfos = JSONObject.parseArray(itemInfo, ZbxItemInfo.class);
Map<String, String> errorMap = itemInfos.parallelStream().collect(Collectors.toMap(ZbxItemInfo::getItemid, o -> Optional.ofNullable(o.getError()).orElse("")));
pagedList.forEach(productAttrDto -> {
if (null != map.get(productAttrDto.getAttrId())) {
productAttrDto.setClock(map.get(productAttrDto.getAttrId()).getClock());
productAttrDto.setValue(map.get(productAttrDto.getAttrId()).getValue());
String delayName = "";
if (null != productAttrDto.getDelay()) {
delayName = productAttrDto.getDelay() + CommonTimeUnit.getDescription(productAttrDto.getUnit());
}
productAttrDto.setOriginalValue(map.get(productAttrDto.getAttrId()).getOriginalValue());
productAttrDto.setDelayName(delayName);
}
if (null != errorMap.get(productAttrDto.getZbxId())) {
productAttrDto.setError(errorMap.get(productAttrDto.getZbxId()));
}
});
int count = qProductAttribute.findCount();
return new Pager<>(pagedList, count);
}
/**
* 设备属性列表
*
* @param productAttr
* @return
*/
public List<ProductAttrDto> list(ProductAttrParam productAttr) {
QProductAttribute qProductAttribute = new QProductAttribute();
if (null != productAttr.getProdId()) {
qProductAttribute.productId.eq(productAttr.getProdId());
}
if (ToolUtil.isNotEmpty(productAttr.getAttrName())) {
qProductAttribute.name.contains(productAttr.getAttrName());
}
if (ToolUtil.isNotEmpty(productAttr.getKey())) {
qProductAttribute.key.contains(productAttr.getKey());
}
List<ProductAttribute> list = qProductAttribute.findList();
return ToolUtil.convertBean(list, ProductAttrDto.class);
// StringBuilder sql = new StringBuilder("select * from product_attribute where 1=1");
// if (null != productAttr.getProdId()) {
// sql.append(" and product_id = :productId");
// }
// if (ToolUtil.isNotEmpty(productAttr.getAttrName())) {
// sql.append(" and name like :attrName");
// }
// if (ToolUtil.isNotEmpty(productAttr.getKey())) {
// sql.append(" and key like :key");
// }
// sql.append(" order by create_time desc");
// DtoQuery<ProductAttrDto> dto = DB.findDto(ProductAttrDto.class, sql.toString());
//
// if (null != productAttr.getProdId()) {
// dto.setParameter("productId", productAttr.getProdId());
// }
// if (ToolUtil.isNotEmpty(productAttr.getAttrName())) {
// dto.setParameter("attrName", "%" + productAttr.getAttrName() + "%");
// }
// if (ToolUtil.isNotEmpty(productAttr.getKey())) {
// dto.setParameter("key", "%" + productAttr.getKey() + "%");
// }
//
// return dto.findList();
}
/**
* 设备属性详情
*
* @param attrId
* @return
*/
public ProductAttrDto detail(Long attrId) {
ProductAttrDto attr = new QProductAttribute().attrId.eq(attrId).asDto(ProductAttrDto.class).findOne();
if (attr == null || ToolUtil.isEmpty(attr.getZbxId())) {
return attr;
}
JSONArray itemInfo = JSONObject.parseArray(zbxItem.getItemInfo(attr.getZbxId(), null));
if (itemInfo.size() == 0) {
return attr;
}
attr.setTags(JSONObject.parseArray(itemInfo.getJSONObject(0).getString("tags"), ProductTag.Tag.class));
attr.setProcessStepList(formatProcessStep(itemInfo.getJSONObject(0).getString("preprocessing")));
// String valuemap = itemInfo.getJSONObject(0).getString("valuemap");
// if (ToolUtil.isNotEmpty(valuemap) && !"[]".equals(valuemap)) {
// attr.setValuemapid(JSONObject.parseObject(valuemap).getString("valuemapid"));
// }
return attr;
}
private List<ProductAttr.ProcessingStep> formatProcessStep(String preprocessing) {
if (ToolUtil.isEmpty(preprocessing)) {
return Collections.emptyList();
}
List<ProductAttr.ProcessingStep> processingSteps = new ArrayList<>();
JSONArray jsonArray = JSONObject.parseArray(preprocessing);
for (Object object : jsonArray) {
ProductAttr.ProcessingStep processingStep = new ProductAttr.ProcessingStep();
processingStep.setType(((JSONObject) object).getString("type"));
processingStep.setParams(((JSONObject) object).getString("params").split("\\n"));
processingSteps.add(processingStep);
}
return processingSteps;
}
/**
* 创建 设备物模型
*
* @param productAttr 产品属性DTO
*/
public void createProductAttr(ProductAttr productAttr, String zbxId) {
ProductAttribute productAttribute = new ProductAttribute();
buildProdAttribute(productAttribute, productAttr);
productAttribute.setZbxId(zbxId);
productAttribute.save();
}
private ProductAttribute buildProdAttribute(ProductAttribute prodAttribute, ProductAttr productAttr) {
if (null == prodAttribute.getTemplateId()) {
prodAttribute.setName(productAttr.getAttrName());
prodAttribute.setKey(productAttr.getKey());
prodAttribute.setSource(productAttr.getSource());
prodAttribute.setUnits(productAttr.getUnits());
prodAttribute.setDepAttrId(productAttr.getDepAttrId());
prodAttribute.setValueType(productAttr.getValueType());
prodAttribute.setDelay(productAttr.getDelay());
prodAttribute.setUnit(productAttr.getUnit());
prodAttribute.setValuemapid(productAttr.getValuemapid());
}
prodAttribute.setProductId(productAttr.getProductId());
prodAttribute.setRemark(productAttr.getRemark());
prodAttribute.setAttrId(productAttr.getAttrId());
return prodAttribute;
}
/**
* 创建 Trapper 类型 ITEM
*
* @param productAttr 属性
* @return String
*/
public String createTrapperItem(ProductAttr productAttr) {
String itemName = productAttr.getAttrId() + "";
Device device = new QDevice().deviceId.eq(productAttr.getProductId()).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
String hostId = device.getZbxId();
List<ZbxProcessingStep> processingSteps = new ArrayList<>();
if (ToolUtil.isNotEmpty(productAttr.getProcessStepList())) {
productAttr.getProcessStepList().forEach(i -> {
ZbxProcessingStep step = new ZbxProcessingStep();
step.setType(i.getType());
step.setParams(i.getParams().replaceAll("\n","").replaceAll("\"", "\\\\\\\\\""));
processingSteps.add(step);
});
}
Map<String, String> tagMap = new HashMap<>();
if (ToolUtil.isNotEmpty(productAttr.getTags())) {
tagMap = productAttr.getTags().stream()
.collect(Collectors.toMap(ProductTag.Tag::getTag, ProductTag.Tag::getValue, (k1, k2) -> k2));
}
String delay = "";
if (null != productAttr.getDelay()) {
delay = productAttr.getDelay() + productAttr.getUnit();
}
String interfaceid = null;
if (ATTR_SOURCE_AGENT.equals(productAttr.getSource())) {
String interfaceInfo = zbxInterface.hostinterfaceGet(device.getZbxId());
List<Interface> interfaces = JSONObject.parseArray(interfaceInfo, Interface.class);
if (ToolUtil.isNotEmpty(interfaces)) {
interfaceid = interfaces.get(0).getInterfaceid();
}
}
return zbxItem.createTrapperItem(itemName, productAttr.getKey(),
hostId, productAttr.getSource(), delay, productAttr.getMasterItemId(), productAttr.getValueType(), productAttr.getUnits(), processingSteps, productAttr.getValuemapid(), tagMap, interfaceid);
}
/**
* 修改 Trapper 类型 ITEM
*
* @param productAttr 属性
* @return String
*/
public ProductAttr updateTrapperItem(ProductAttr productAttr) {
ProductAttribute productAttribute = new QProductAttribute().attrId.eq(productAttr.getAttrId()).findOne();
buildProdAttribute(productAttribute, productAttr);
Device device = new QDevice().deviceId.eq(productAttr.getProductId()).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
String hostId = device.getZbxId();
List<ZbxProcessingStep> processingSteps = new ArrayList<>();
if (ToolUtil.isNotEmpty(productAttr.getProcessStepList())) {
productAttr.getProcessStepList().forEach(i -> {
ZbxProcessingStep step = new ZbxProcessingStep();
step.setType(i.getType());
step.setParams(i.getParams().replaceAll("\n","").replaceAll("\"", "\\\\\\\\\""));
processingSteps.add(step);
});
}
Map<String, String> tagMap = new HashMap<>();
if (ToolUtil.isNotEmpty(productAttr.getTags())) {
tagMap = productAttr.getTags().stream()
.collect(Collectors.toMap(ProductTag.Tag::getTag, ProductTag.Tag::getValue, (k1, k2) -> k2));
}
String delay = "";
if (null != productAttr.getDelay()) {
delay = productAttr.getDelay() + productAttr.getUnit();
}
String interfaceid = null;
if (ATTR_SOURCE_AGENT.equals(productAttr.getSource())) {
String interfaceInfo = zbxInterface.hostinterfaceGet(device.getZbxId());
List<Interface> interfaces = JSONObject.parseArray(interfaceInfo, Interface.class);
if (ToolUtil.isNotEmpty(interfaces)) {
interfaceid = interfaces.get(0).getInterfaceid();
}
}
zbxItem.updateTrapperItem(productAttribute.getZbxId(), productAttr.getAttrId() + "", productAttr.getKey(),
hostId, productAttr.getSource(), delay, productAttr.getMasterItemId(), productAttr.getValueType(), productAttr.getUnits(), processingSteps, productAttr.getValuemapid(), tagMap, interfaceid);
DB.update(productAttribute);
return productAttr;
}
/**
* 删称 Trapper 类型 ITEM
*
* @param productAttr 属性
* @return String
*/
public void deleteTrapperItem(ProductAttr productAttr) {
//检查是否有属性依赖
int count = new QProductAttribute().depAttrId.in(productAttr.getAttrIds()).findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.PRODUCT_ATTR_DEPTED);
}
//检查属性是否被告警规则引入
count = new QProductEventExpression().productAttrId.in(productAttr.getAttrIds()).findCount();
if (count > 0) {
throw new ServiceException(BizExceptionEnum.PRODUCT_EVENT_HASDEPTED);
}
List<String> zbxIds = new QProductAttribute().select(QProductAttribute.alias().zbxId).attrId.in(productAttr.getAttrIds()).zbxId.isNotNull().findSingleAttributeList();
//删除zbx item
if (ToolUtil.isNotEmpty(zbxIds)) {
List<ZbxItemInfo> itemInfos = JSONObject.parseArray(zbxItem.getItemInfo(zbxIds.toString(), null), ZbxItemInfo.class);
if (ToolUtil.isNotEmpty(itemInfos)) {
zbxItem.deleteTrapperItem(itemInfos.parallelStream().map(ZbxItemInfo::getItemid).collect(Collectors.toList()));
}
}
//删除 属性
new QProductAttribute().attrId.in(productAttr.getAttrIds()).delete();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceModelService.java
|
Java
|
gpl-3.0
| 15,213
|
package com.zmops.iot.web.device.service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.Tag;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.device.query.QDevicesGroups;
import com.zmops.iot.domain.device.query.QTag;
import com.zmops.iot.domain.product.Product;
import com.zmops.iot.domain.product.query.QProduct;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.DefinitionsUtil;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.device.dto.param.DeviceParam;
import com.zmops.iot.web.device.dto.param.DeviceParams;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.product.dto.ProductTag;
import com.zmops.zeus.driver.entity.Interface;
import com.zmops.zeus.driver.service.ZbxHost;
import com.zmops.zeus.driver.service.ZbxInterface;
import com.zmops.zeus.driver.service.ZbxValueMap;
import io.ebean.DB;
import io.ebean.DtoQuery;
import io.ebean.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author yefei
**/
@Service
public class DeviceService implements CommandLineRunner {
@Autowired
private ZbxHost zbxHost;
@Autowired
private ZbxValueMap zbxValueMap;
@Autowired
DeviceGroupService deviceGroupService;
@Autowired
ZbxInterface zbxInterface;
@Autowired
DeviceEventPublisher deviceEventPublisher;
/**
* 设备列表
*
* @param deviceParams
* @return
*/
public List<Device> deviceList(DeviceParams deviceParams) {
List<String> deviceIds = getDeviceIds();
if (ToolUtil.isEmpty(deviceIds)) {
return Collections.emptyList();
}
QDevice qDevice = new QDevice();
qDevice.deviceId.in(deviceIds);
if (ToolUtil.isNotEmpty(deviceParams.getName())) {
qDevice.name.contains(deviceParams.getName());
}
if (ToolUtil.isNotEmpty(deviceParams.getDeviceId())) {
qDevice.deviceId.eq(deviceParams.getDeviceId());
}
if (ToolUtil.isNotEmpty(deviceParams.getProductIds())) {
qDevice.productId.in(deviceParams.getProductIds());
}
if (ToolUtil.isEmpty(deviceParams.getProductIds()) && ToolUtil.isNotEmpty(deviceParams.getProdTypes())) {
List<Long> productIdList = new QProduct().select(QProduct.Alias.productId).groupId.in(
deviceParams.getProdTypes()).findSingleAttributeList();
qDevice.productId.in(productIdList);
}
if (ToolUtil.isNotEmpty(deviceParams.getDeviceGroupIds())) {
List<String> deviceList = new QDevicesGroups().select(QDevicesGroups.Alias.deviceId).deviceGroupId.in(
deviceParams.getDeviceGroupIds()).findSingleAttributeList();
qDevice.deviceId.in(deviceList);
}
return qDevice.findList();
}
/**
* 获取当前用户 绑定的设备ID
*
* @return
*/
public List<String> getDeviceIds() {
List<Long> devGroupIds = deviceGroupService.getDevGroupIds();
return new QDevicesGroups().select(QDevicesGroups.alias().deviceId).deviceGroupId.in(devGroupIds)
.findSingleAttributeList();
}
/**
* 设备分页列表
*
* @param deviceParam
* @return
*/
public Pager<DeviceDto> devicePageList(DeviceParam deviceParam) {
//根据当前用户所属用户组 取出绑定的主机组
List<Long> devGroupIds = deviceGroupService.getDevGroupIds();
if (ToolUtil.isEmpty(devGroupIds)) {
return new Pager<>();
}
//组装查询SQL
StringBuilder sql = generateBaseSql();
sql.append(" where 1=1");
//根据标签过滤
List<Long> sids = new ArrayList<>();
if (ToolUtil.isNotEmpty(deviceParam.getTag())) {
QTag qTag = new QTag().select(QTag.Alias.sid).templateId.isNull();
qTag.tag.contains(deviceParam.getTag());
if (ToolUtil.isNotEmpty(deviceParam.getTagVal())) {
qTag.value.contains(deviceParam.getTagVal());
}
sids = qTag.findSingleAttributeList();
if (ToolUtil.isNotEmpty(sids)) {
sql.append(" and d.device_id in ( :deviceIds )");
}
}
if (ToolUtil.isNotEmpty(deviceParam.getProdType())) {
sql.append(" and d.type = :prodType ");
}
if (ToolUtil.isNotEmpty(deviceParam.getProductId())) {
sql.append(" and d.product_id = :prodId ");
}
if (ToolUtil.isNotEmpty(deviceParam.getName())) {
sql.append(" and d.name like :name ");
}
//用于查询总记录数
Query<Device> count = DB.findNative(Device.class, sql.toString());
sql.append(" order by d.create_time desc ");
DtoQuery<DeviceDto> dto = DB.findDto(DeviceDto.class, sql.toString());
if (ToolUtil.isNotEmpty(sids)) {
dto.setParameter("deviceIds", sids);
count.setParameter("deviceIds", sids);
}
if (null != deviceParam.getDeviceGroupId()) {
dto.setParameter("deviceGroupId", deviceParam.getDeviceGroupId() + "");
count.setParameter("deviceGroupId", deviceParam.getDeviceGroupId() + "");
}
if (ToolUtil.isNotEmpty(deviceParam.getProdType())) {
dto.setParameter("prodType", deviceParam.getProdType());
count.setParameter("prodType", deviceParam.getProdType());
}
if (ToolUtil.isNotEmpty(deviceParam.getProductId())) {
dto.setParameter("prodId", deviceParam.getProductId());
count.setParameter("prodId", deviceParam.getProductId());
}
if (ToolUtil.isNotEmpty(deviceParam.getName())) {
dto.setParameter("name", "%" + deviceParam.getName() + "%");
count.setParameter("name", "%" + deviceParam.getName() + "%");
}
if (null != deviceParam.getDeviceGroupId()) {
if (devGroupIds.contains(deviceParam.getDeviceGroupId())) {
dto.setParameter("deviceGroupIds", deviceParam.getDeviceGroupId());
count.setParameter("deviceGroupIds", deviceParam.getDeviceGroupId());
} else {
return new Pager<>();
}
} else {
dto.setParameter("deviceGroupIds", devGroupIds);
count.setParameter("deviceGroupIds", devGroupIds);
}
List<DeviceDto> list = dto.setFirstRow((deviceParam.getPage() - 1) * deviceParam.getMaxRow())
.setMaxRows(deviceParam.getMaxRow()).findList();
return new Pager<>(list, count.findCount());
}
private StringBuilder generateBaseSql() {
return new StringBuilder("SELECT " +
" d.device_id," +
" d.NAME, " +
" d.product_id, " +
" d.status, " +
" d.remark, " +
" d.create_time, " +
" d.create_user, " +
" d.update_time, " +
" d.update_user, " +
" d.TYPE, " +
" d.addr, " +
" d.position, " +
" d.online," +
" d.zbx_id," +
" d.latest_online," +
" d.tenant_id," +
" d.proxy_id," +
" P.NAME product_name, " +
" P.product_code product_code, " +
" ds.group_name, " +
" ds.groupIds," +
" m.method " +
"FROM " +
" device d ")
.append(" LEFT JOIN product P ON P.product_id = d.product_id ")
.append(" INNER JOIN ( " +
" SELECT " +
" d.device_id, " +
" array_to_string( ARRAY_AGG ( dg.NAME ), ',' ) group_name, " +
" array_to_string( ARRAY_AGG ( dg.device_group_id ), ',' ) groupIds " +
" FROM " +
" device d " +
" LEFT JOIN devices_groups dgs ON dgs.device_id = d.device_id " +
" LEFT JOIN device_group dg ON dg.device_group_id = dgs.device_group_id " +
" where dg.device_group_id in (:deviceGroupIds) " +
" GROUP BY d.device_id " +
" ) ds ON ds.device_id = d.device_id ")
.append(" left join device_service_method m on m.device_id = d.device_id ");
}
/**
* 设备创建
*
* @param deviceDto
* @return
*/
public String create(DeviceDto deviceDto) {
Device device = new Device();
ToolUtil.copyProperties(deviceDto, device);
device.setStatus(CommonStatus.ENABLE.getCode());
DB.insert(device);
deviceEventPublisher.DeviceSaveEventPublish(deviceDto);
updateDeviceNameCache(deviceDto.getDeviceId(), deviceDto.getName());
return deviceDto.getDeviceId();
}
/**
* 设备修改
*
* @param deviceDto
* @return
*/
public String update(DeviceDto deviceDto) {
Device device = new QDevice().deviceId.eq(deviceDto.getDeviceId()).findOne();
if (null == device) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
ToolUtil.copyProperties(deviceDto, device);
deviceDto.setOldProductId(device.getProductId());
deviceDto.setZbxId(device.getZbxId());
DB.update(device);
deviceEventPublisher.DeviceSaveEventPublish(deviceDto);
updateDeviceNameCache(deviceDto.getDeviceId(), deviceDto.getName());
return deviceDto.getDeviceId();
}
/**
* 检查产品是否存在 并把赋值type
*
* @param deviceDto
*/
public void checkProductExist(DeviceDto deviceDto) {
Product product = new QProduct().productId.eq(deviceDto.getProductId()).findOne();
if (null == product) {
throw new ServiceException(BizExceptionEnum.PRODUCT_NOT_EXISTS);
}
deviceDto.setType(product.getType());
}
public String delete(DeviceDto deviceDto) {
Device device = new QDevice().deviceId.eq(deviceDto.getDeviceId()).findOne();
if (null == device) {
return deviceDto.getDeviceId();
}
String zbxId = device.getZbxId();
deviceEventPublisher.DeviceDeleteEventPublish(device.getDeviceId(), zbxId);
//更新设备名称缓存
removeDeviceNameCache(deviceDto.getDeviceId());
return deviceDto.getDeviceId();
}
/**
* 设备标签修改
*
* @param productTag
* @param zbxId
*/
public void deviceTagCreate(ProductTag productTag, String zbxId) {
if (ToolUtil.isEmpty(productTag.getProductTag())) {
return;
}
//先删除 之前的标签
new QTag().sid.eq(productTag.getProductId()).delete();
List<Tag> tags = new ArrayList<>();
for (ProductTag.Tag tag : productTag.getProductTag()) {
tags.add(Tag.builder().sid(productTag.getProductId()).tag(tag.getTag()).value(tag.getValue()).build());
}
DB.saveAll(tags);
if (ToolUtil.isEmpty(zbxId)) {
return;
}
//同步到Zbx
List<Tag> list = new QTag().sid.eq(productTag.getProductId()).findList();
Map<String, String> tagMap = new HashMap<>(list.size());
for (Tag tag : list) {
tagMap.put(tag.getTag(), tag.getValue());
}
//保存
zbxHost.hostTagUpdate(zbxId, tagMap);
}
/**
* 创建产品 值映射
*
* @param hostid 产品模板ID
* @param valueMapName 名称
* @param valueMaps KV
* @return
*/
public String valueMapCreate(String hostid, String valueMapName, Map<String, String> valueMaps) {
return zbxValueMap.valueMapCreate(hostid, valueMapName, valueMaps);
}
/**
* 修改 产品值映射
*
* @param hostid 产品模板ID
* @param valueMapName 名称
* @param valueMaps KV
* @param valueMapId 映射ID
* @return
*/
public String valueMapUpdate(String hostid, String valueMapName, Map<String, String> valueMaps, String valueMapId) {
return zbxValueMap.valueMapUpdate(hostid, valueMapName, valueMaps, valueMapId);
}
/**
* 删除值映射
*
* @param valueMapId 值映射ID
* @return String
*/
public String valueMapDelete(String valueMapId) {
return zbxValueMap.valueMapDelete(valueMapId);
}
/**
* 设备详情
*
* @param deviceId
* @return
*/
public DeviceDto deviceDetail(String deviceId) {
List<Long> devGroupIds = deviceGroupService.getDevGroupIds();
if (ToolUtil.isEmpty(devGroupIds)) {
return new DeviceDto();
}
StringBuilder sql = generateBaseSql();
sql.append(" where d.device_id=:deviceId");
DeviceDto deviceDto = DB.findDto(DeviceDto.class, sql.toString()).setParameter("deviceId", deviceId)
.setParameter("deviceGroupIds", devGroupIds).findOne();
if (deviceDto == null) {
throw new ServiceException(BizExceptionEnum.DEVICE_NOT_EXISTS);
}
if (ToolUtil.isEmpty(deviceDto.getZbxId())) {
return deviceDto;
}
String interfaceInfo = zbxInterface.hostinterfaceGet(deviceDto.getZbxId());
List<Interface> interfaces = JSONObject.parseArray(interfaceInfo, Interface.class);
if (ToolUtil.isNotEmpty(interfaces)) {
deviceDto.setDeviceInterface(interfaces.get(0));
}
return deviceDto;
}
/**
* 设备标签列表
*
* @param deviceId
* @return
*/
public List<Tag> deviceTagList(String deviceId) {
QTag tag = QTag.alias();
return new QTag().select(tag.id, tag.sid, tag.tag, tag.value).sid.eq(deviceId).findList();
}
/**
* 设备值映射列表
*
* @param deviceId
* @return
*/
public JSONArray valueMapList(String deviceId) {
JSONArray zbxTemplateInfo = getZbxHostInfo(deviceId);
if (zbxTemplateInfo.size() == 0) {
return new JSONArray();
}
//查询ZBX valueMap
return JSONObject.parseArray(zbxTemplateInfo.getJSONObject(0).getString("valuemaps"));
}
private JSONArray getZbxHostInfo(String deviceId) {
String zbxId = new QDevice().select(QDevice.alias().zbxId).deviceId.eq(deviceId).findSingleAttribute();
if (null == zbxId) {
return new JSONArray();
}
return JSONObject.parseArray(zbxHost.hostDetail(zbxId));
}
/**
* 修改设备状态
*
* @param status
* @param deviceId
* @return
*/
public void status(String status, String deviceId, String zbxId) {
if (ToolUtil.isNotEmpty(zbxId)) {
zbxHost.hostStatusUpdate(zbxId, "ENABLE".equals(status) ? "0" : "1");
}
DB.update(Device.class).where().eq("device_id", deviceId).asUpdate().set("status", status).setNull("online")
.update();
}
/**
* 更新设备名称缓存
*/
private void updateDeviceCache() {
List<Device> deviceList = new QDevice().select(QDevice.Alias.deviceId, QDevice.Alias.name).findList();
Map<String, String> map = deviceList.parallelStream()
.collect(Collectors.toMap(Device::getDeviceId, Device::getName, (a, b) -> a));
DefinitionsUtil.updateDeviceCache(map);
}
/**
* 更新设备名称缓存
*/
private void updateDeviceNameCache(String deviceId, String name) {
Map<String, String> all = DefinitionsUtil.getDeviceCache().getAll();
all.put(deviceId, name);
DefinitionsUtil.updateDeviceCache(all);
}
/**
* 更新设备名称缓存
*/
private void removeDeviceNameCache(String deviceId) {
Map<String, String> all = DefinitionsUtil.getDeviceCache().getAll();
all.remove(deviceId);
DefinitionsUtil.updateDeviceCache(all);
}
@Override
public void run(String... args) throws Exception {
updateDeviceCache();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceService.java
|
Java
|
gpl-3.0
| 16,784
|
package com.zmops.iot.web.device.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.Forest;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.ServiceExecuteRecord;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.product.ProductService;
import com.zmops.iot.domain.product.ProductServiceParam;
import com.zmops.iot.domain.product.query.QProductService;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.util.DefinitionsUtil;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.ServiceExecuteDto.ServiceParam;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import io.ebean.DB;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 设备服务
**/
@Service
public class DeviceSvrService {
/**
* 执行指定设备的某个服务
*
* @param deviceId 设备ID
* @param serviceId 服务ID
*/
public void execute(String deviceId, Long serviceId, List<ServiceParam> serviceParams) {
//封装执行参数
List<Map<String, Object>> body = new ArrayList<>();
Map<String, Object> map = new ConcurrentHashMap<>(2);
map.put("device", deviceId);
List<Map<String, Object>> serviceList = new ArrayList<>();
Map<String, Object> serviceMap = new ConcurrentHashMap<>(2);
ProductService productService = new QProductService().id.eq(serviceId).findOne();
if (null == productService) {
throw new ServiceException(BizExceptionEnum.SERVICE_NOT_EXISTS);
}
serviceMap.put("name", productService.getName());
List<ProductServiceParam> paramList = DefinitionsUtil.getServiceParam(serviceId);
Map<String, String> paramStr = null;
if (ToolUtil.isNotEmpty(paramList)) {
paramStr = paramList.parallelStream().filter(o -> deviceId.equals(o.getDeviceId())).collect(Collectors.toMap(ProductServiceParam::getKey, ProductServiceParam::getValue, (a, b) -> a));
if (ToolUtil.isNotEmpty(serviceParams)) {
Map<String, String> userParam = serviceParams.parallelStream().collect(Collectors.toMap(ServiceParam::getKey, ServiceParam::getValue, (a, b) -> a));
for (Map.Entry<String, String> param : paramStr.entrySet()) {
if (userParam.get(param.getKey()) != null) {
param.setValue(userParam.get(param.getKey()));
}
}
}
serviceMap.put("param", paramStr);
}
serviceList.add(serviceMap);
map.put("service", serviceList);
body.add(map);
//下发命令 执行
Forest.post("/device/action/exec").host("127.0.0.1").port(12800).contentTypeJson().addBody(JSON.toJSON(body)).execute();
//记录服务日志
ServiceExecuteRecord serviceExecuteRecord = new ServiceExecuteRecord();
serviceExecuteRecord.setDeviceId(deviceId);
if (ToolUtil.isNotEmpty(paramStr)) {
serviceExecuteRecord.setParam(JSONObject.toJSONString(paramStr));
}
serviceExecuteRecord.setServiceName(DefinitionsUtil.getServiceName(serviceId));
Device device = new QDevice().deviceId.eq(deviceId).findOne();
if (null != device) {
serviceExecuteRecord.setTenantId(device.getTenantId());
}
serviceExecuteRecord.setCreateTime(LocalDateTime.now());
serviceExecuteRecord.setExecuteType("手动");
serviceExecuteRecord.setExecuteUser(LoginContextHolder.getContext().getUserId());
DB.insert(serviceExecuteRecord);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/DeviceSvrService.java
|
Java
|
gpl-3.0
| 3,970
|
package com.zmops.iot.web.device.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.Forest;
import com.zmops.iot.core.auth.context.LoginContextHolder;
import com.zmops.iot.domain.device.query.QDevicesGroups;
import com.zmops.iot.domain.product.*;
import com.zmops.iot.domain.product.query.*;
import com.zmops.iot.domain.schedule.Task;
import com.zmops.iot.domain.schedule.query.QTask;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.enums.InheritStatus;
import com.zmops.iot.model.exception.ServiceException;
import com.zmops.iot.model.page.Pager;
import com.zmops.iot.util.DefinitionsUtil;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceEventRelationDto;
import com.zmops.iot.web.device.dto.MultipleDeviceEventDto;
import com.zmops.iot.web.device.dto.MultipleDeviceEventRule;
import com.zmops.iot.web.device.dto.MultipleDeviceServiceDto;
import com.zmops.iot.web.device.dto.param.MultipleDeviceEventParm;
import com.zmops.iot.web.exception.enums.BizExceptionEnum;
import com.zmops.iot.web.task.dto.TaskDto;
import com.zmops.iot.web.task.service.TaskService;
import com.zmops.zeus.driver.service.ZbxTrigger;
import io.ebean.DB;
import io.ebean.annotation.Transactional;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* @author yefei
*
* 设备 场景 联动 服务
**/
@Service
public class MultipleDeviceEventRuleService {
@Autowired
private ZbxTrigger zbxTrigger;
private static final String EVENT_CLASSIFY = "1";
public static final int TRIGGER_TYPE_SCHEDULE = 1;
public static final int TRIGGER_TYPE_CONDITION = 0;
public static final String SCENE_TAG_NAME = "__scene__";
@Autowired
TaskService taskService;
@Autowired
DeviceLogService deviceLogService;
/**
* 场景列表
*
* @param eventParam
* @return
*/
public List<MultipleDeviceEventDto> list(MultipleDeviceEventParm eventParam) {
QProductEvent query = new QProductEvent();
if (ToolUtil.isNotEmpty(eventParam.getEventRuleName())) {
query.eventRuleName.contains(eventParam.getEventRuleName());
}
if (LoginContextHolder.getContext().getUser().getTenantId() != null) {
query.tenantId.eq(LoginContextHolder.getContext().getUser().getTenantId());
}
query.classify.eq(EVENT_CLASSIFY);
return query.orderBy(" create_time desc").asDto(MultipleDeviceEventDto.class).findList();
}
/**
* 设备联动 分页列表
*
* @param eventParam 查询参数
* @return MultipleDeviceEventDto
*/
public Pager<MultipleDeviceEventDto> getEventByPage(MultipleDeviceEventParm eventParam) {
QProductEvent query = new QProductEvent();
Long tenantId = LoginContextHolder.getContext().getUser().getTenantId();
if (null != tenantId) {
query.tenantId.eq(tenantId);
}
if (ToolUtil.isNotEmpty(eventParam.getEventRuleName())) {
query.eventRuleName.contains(eventParam.getEventRuleName());
}
if (ToolUtil.isNotEmpty(eventParam.getDeviceIds())) {
List<Long> eventIds = new QProductEventService().select(QProductEventService.alias().eventRuleId).executeDeviceId.isNotNull().executeDeviceId.in(eventParam.getDeviceIds()).findSingleAttributeList();
query.eventRuleId.in(eventIds);
} else if (ToolUtil.isNotEmpty(eventParam.getDeviceGrpIds())) {
List<String> deviceIds = new QDevicesGroups().select(QDevicesGroups.alias().deviceId).deviceId.isNotNull().deviceGroupId.in(eventParam.getDeviceGrpIds()).findSingleAttributeList();
List<Long> eventIds = new QProductEventService().select(QProductEventService.alias().eventRuleId).executeDeviceId.isNotNull().executeDeviceId.in(deviceIds).findSingleAttributeList();
query.eventRuleId.in(eventIds);
}
query.classify.eq(EVENT_CLASSIFY);
List<MultipleDeviceEventDto> list = query.setFirstRow((eventParam.getPage() - 1) * eventParam.getMaxRow())
.setMaxRows(eventParam.getMaxRow()).orderBy(" create_time desc").asDto(MultipleDeviceEventDto.class).findList();
if (ToolUtil.isEmpty(list)) {
return new Pager<>(list, 0);
}
//关联状态 备注 触发设备
List<Long> eventRuleIds = list.parallelStream().map(MultipleDeviceEventDto::getEventRuleId).collect(Collectors.toList());
String sql = "SELECT " +
" pr.event_rule_id, " +
" array_to_string( ARRAY_AGG ( d.NAME ), ',' ) triggerDevice, " +
" pr.status," +
" pr.remark " +
"FROM " +
" product_event_relation pr " +
" LEFT JOIN device d ON pr.relation_id = d.device_id " +
"WHERE " +
" pr.event_rule_id IN (:eventRuleIds) " +
"GROUP BY " +
" pr.event_rule_id,pr.status,pr.remark";
List<DeviceEventRelationDto> deviceEventRelationDtos = DB.findDto(DeviceEventRelationDto.class, sql).setParameter("eventRuleIds", eventRuleIds).findList();
Map<Long, DeviceEventRelationDto> productEventRelationMap = deviceEventRelationDtos.parallelStream()
.collect(Collectors.toConcurrentMap(DeviceEventRelationDto::getEventRuleId, o -> o));
//关联 执行设备
sql = "SELECT " +
" ps.event_rule_id, " +
" array_to_string( ARRAY_AGG ( d.NAME ), ',' ) executeDevice " +
"FROM " +
" product_event_service ps " +
" LEFT JOIN device d ON ps.execute_device_id = d.device_id " +
"WHERE " +
" ps.event_rule_id IN (:eventRuleIds) " +
"GROUP BY " +
" ps.event_rule_id";
List<MultipleDeviceServiceDto> deviceServiceDtos = DB.findDto(MultipleDeviceServiceDto.class, sql).setParameter("eventRuleIds", eventRuleIds).findList();
Map<Long, MultipleDeviceServiceDto> deviceServiceMap = deviceServiceDtos.parallelStream()
.collect(Collectors.toConcurrentMap(MultipleDeviceServiceDto::getEventRuleId, o -> o));
list.forEach(productEventDto -> {
DeviceEventRelationDto deviceEventRelationDto = productEventRelationMap.get(productEventDto.getEventRuleId());
if (null != deviceEventRelationDto) {
String status = deviceEventRelationDto.getStatus();
String remark = deviceEventRelationDto.getRemark();
String triggerDevice = deviceEventRelationDto.getTriggerDevice();
productEventDto.setStatus(status);
productEventDto.setRemark(remark);
productEventDto.setTriggerDevice(triggerDevice);
}
MultipleDeviceServiceDto deviceServiceDto = deviceServiceMap.get(productEventDto.getEventRuleId());
if (null != deviceServiceDto) {
productEventDto.setExecuteDevice(deviceServiceDto.getExecuteDevice());
}
});
return new Pager<>(list, query.findCount());
}
private String generateExecuteParam(MultipleDeviceEventRule eventRule) {
Map<String, Object> param = new HashMap<>(2);
param.put("eventRuleId", eventRule.getEventRuleId());
List<Map<String, Object>> list = new ArrayList<>();
Map<String, List<MultipleDeviceEventRule.DeviceService>> collect = eventRule.getDeviceServices().parallelStream().collect(Collectors.groupingBy(MultipleDeviceEventRule.DeviceService::getExecuteDeviceId));
collect.forEach((key, value) -> {
Map<String, Object> map = new ConcurrentHashMap<>(2);
map.put("device", key);
List<Map<String, Object>> serviceList = new ArrayList<>();
value.forEach(val -> {
Map<String, Object> serviceMap = new ConcurrentHashMap<>(2);
serviceMap.put("name", DefinitionsUtil.getServiceName(val.getServiceId()));
List<ProductServiceParam> paramList = DefinitionsUtil.getServiceParam(val.getServiceId());
if (ToolUtil.isNotEmpty(paramList)) {
serviceMap.put("param", paramList.parallelStream().filter(o->key.equals(o.getDeviceId())).collect(Collectors.toMap(ProductServiceParam::getKey, ProductServiceParam::getValue, (a, b) -> a)));
}
serviceList.add(serviceMap);
});
map.put("service", serviceList);
list.add(map);
});
param.put("executeParam", list);
return JSON.toJSONString(param);
}
/**
* 保存设备联动
*
* @param eventRule 设备联动规则
*/
@Transactional(rollbackFor = Exception.class)
public void createDeviceEventRule(MultipleDeviceEventRule eventRule) {
//setp 0: 创建任务
Integer taskId = null;
if (eventRule.getTriggerType() == TRIGGER_TYPE_SCHEDULE) {
TaskDto taskDto = new TaskDto();
taskDto.setScheduleConf(eventRule.getScheduleConf());
taskDto.setExecutorParam(generateExecuteParam(eventRule));
taskDto.setRemark(eventRule.getRemark());
taskId = taskService.createTask(taskDto);
}
// step 1: 保存产品告警规则
ProductEvent event = initEventRule(eventRule);
event.setEventRuleId(eventRule.getEventRuleId());
event.setTaskId(taskId);
DB.save(event);
//step 2: 保存 表达式,方便回显
if (TRIGGER_TYPE_CONDITION == eventRule.getTriggerType()) {
List<ProductEventExpression> expList = new ArrayList<>();
eventRule.getExpList().forEach(i -> {
ProductEventExpression exp = initEventExpression(i);
exp.setEventRuleId(eventRule.getEventRuleId());
expList.add(exp);
});
DB.saveAll(expList);
//step 3: 保存关联关系
List<String> relationIds = eventRule.getExpList().parallelStream().map(MultipleDeviceEventRule.Expression::getDeviceId).distinct().collect(Collectors.toList());
if (ToolUtil.isEmpty(relationIds)) {
throw new ServiceException(BizExceptionEnum.EVENT_HAS_NOT_DEVICE);
}
List<ProductEventRelation> productEventRelationList = new ArrayList<>();
relationIds.forEach(relationId -> {
ProductEventRelation productEventRelation = new ProductEventRelation();
productEventRelation.setEventRuleId(eventRule.getEventRuleId());
productEventRelation.setRelationId(relationId);
productEventRelation.setInherit(InheritStatus.NO.getCode());
productEventRelation.setStatus(CommonStatus.ENABLE.getCode());
productEventRelation.setRemark(eventRule.getRemark());
productEventRelationList.add(productEventRelation);
});
DB.saveAll(productEventRelationList);
//step 4: 保存时间区间
if (ToolUtil.isNotEmpty(eventRule.getTimeIntervals())) {
List<ProductEventTimeInterval> timeExpList = new ArrayList<>();
eventRule.getTimeIntervals().forEach(i -> {
ProductEventTimeInterval timeExp = new ProductEventTimeInterval();
timeExp.setEventRuleId(eventRule.getEventRuleId());
timeExp.setStartTime(i.getStartTime());
timeExp.setEndTime(i.getEndTime());
timeExp.setDayOfWeeks(i.getDayOfWeeks());
timeExpList.add(timeExp);
});
DB.insertAll(timeExpList);
}
}
//step 5: 保存触发器 调用 本产品方法
if (null != eventRule.getDeviceServices() && !eventRule.getDeviceServices().isEmpty()) {
eventRule.getDeviceServices().forEach(i -> {
DB.sqlUpdate("insert into product_event_service(event_rule_id, execute_device_id, service_id) " +
"values (:eventRuleId, :executeDeviceId, :serviceId)")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.setParameter("executeDeviceId", i.getExecuteDeviceId())
.setParameter("serviceId", i.getServiceId())
.execute();
});
}
}
@Transactional(rollbackFor = Exception.class)
public void updateDeviceEventRule(MultipleDeviceEventRule eventRule) {
//setp 0: 创建任务
if (TRIGGER_TYPE_SCHEDULE == eventRule.getTriggerType()) {
TaskDto taskDto = new TaskDto();
taskDto.setScheduleConf(eventRule.getScheduleConf());
taskDto.setExecutorParam(generateExecuteParam(eventRule));
taskDto.setRemark(eventRule.getRemark());
if (ToolUtil.isEmpty(eventRule.getTaskId())) {
int taskId = taskService.createTask(taskDto);
eventRule.setTaskId(taskId);
} else {
taskDto.setId(eventRule.getTaskId());
taskService.updateTask(taskDto);
}
}
//setp 1: 删除zbx触发器
if (ToolUtil.isNotEmpty(eventRule.getZbxId())) {
zbxTrigger.triggerDelete(eventRule.getZbxId());
}
//step 2: 删除函数表达式
DB.sqlUpdate("delete from product_event_expression where event_rule_id = :eventRuleId")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.execute();
//step 3: 删除服务方法调用
DB.sqlUpdate("delete from product_event_service where event_rule_id = :eventRuleId")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.execute();
//step : 删除时间区间函数表达式
DB.sqlUpdate("delete from product_event_time_interval where event_rule_id = :eventRuleId")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.execute();
// 删除和所有设备的关联关系
new QProductEventRelation().eventRuleId.eq(eventRule.getEventRuleId()).delete();
// step 4: 保存产品告警规则
ProductEvent event = initEventRule(eventRule);
event.setEventRuleId(eventRule.getEventRuleId());
event.setTaskId(eventRule.getTaskId());
event.update();
//step 5: 保存 表达式,方便回显
if (TRIGGER_TYPE_CONDITION == eventRule.getTriggerType()) {
List<ProductEventExpression> expList = new ArrayList<>();
eventRule.getExpList().forEach(i -> {
ProductEventExpression exp = initEventExpression(i);
exp.setEventExpId(i.getEventExpId());
exp.setEventRuleId(eventRule.getEventRuleId());
expList.add(exp);
});
DB.saveAll(expList);
// step 6: 保存关联关系
List<String> relationIds = eventRule.getExpList().parallelStream().map(MultipleDeviceEventRule.Expression::getDeviceId).distinct().collect(Collectors.toList());
if (ToolUtil.isEmpty(relationIds)) {
throw new ServiceException(BizExceptionEnum.EVENT_HAS_NOT_DEVICE);
}
List<ProductEventRelation> productEventRelationList = new ArrayList<>();
relationIds.forEach(relationId -> {
ProductEventRelation productEventRelation = new ProductEventRelation();
productEventRelation.setEventRuleId(eventRule.getEventRuleId());
productEventRelation.setRelationId(relationId);
productEventRelation.setStatus(CommonStatus.ENABLE.getCode());
productEventRelation.setRemark(eventRule.getRemark());
productEventRelationList.add(productEventRelation);
});
DB.saveAll(productEventRelationList);
//step 7: 保存时间区间
if (ToolUtil.isNotEmpty(eventRule.getTimeIntervals())) {
List<ProductEventTimeInterval> timeExpList = new ArrayList<>();
eventRule.getTimeIntervals().forEach(i -> {
ProductEventTimeInterval timeExp = new ProductEventTimeInterval();
timeExp.setEventRuleId(eventRule.getEventRuleId());
timeExp.setStartTime(i.getStartTime());
timeExp.setEndTime(i.getEndTime());
timeExp.setDayOfWeeks(i.getDayOfWeeks());
timeExpList.add(timeExp);
});
DB.insertAll(timeExpList);
}
}
//step 8: 保存触发器 调用 本产品方法
if (null != eventRule.getDeviceServices() && !eventRule.getDeviceServices().isEmpty()) {
eventRule.getDeviceServices().forEach(i -> {
DB.sqlUpdate("insert into product_event_service(event_rule_id,execute_device_id, service_id) values (:eventRuleId, :executeDeviceId, :serviceId)")
.setParameter("eventRuleId", eventRule.getEventRuleId())
.setParameter("executeDeviceId", i.getExecuteDeviceId())
.setParameter("serviceId", i.getServiceId())
.execute();
});
}
}
private ProductEvent initEventRule(MultipleDeviceEventRule eventRule) {
ProductEvent event = new ProductEvent();
event.setEventLevel(eventRule.getEventLevel().toString());
event.setExpLogic(eventRule.getExpLogic());
event.setEventNotify(eventRule.getEventNotify().toString());
event.setClassify(eventRule.getClassify());
event.setEventRuleName(eventRule.getEventRuleName());
event.setTenantId(eventRule.getTenantId());
event.setStatus(CommonStatus.ENABLE.getCode());
event.setRemark(eventRule.getRemark());
event.setTriggerType(eventRule.getTriggerType());
return event;
}
private ProductEventExpression initEventExpression(MultipleDeviceEventRule.Expression exp) {
ProductEventExpression eventExpression = new ProductEventExpression();
eventExpression.setCondition(exp.getCondition());
eventExpression.setFunction(exp.getFunction());
eventExpression.setScope(exp.getScope());
eventExpression.setValue(exp.getValue());
eventExpression.setDeviceId(exp.getDeviceId());
eventExpression.setProductAttrKey(exp.getProductAttrKey());
eventExpression.setProductAttrId(exp.getProductAttrId());
eventExpression.setProductAttrType(exp.getProductAttrType());
eventExpression.setPeriod(exp.getPeriod());
eventExpression.setUnit(exp.getUnit());
eventExpression.setAttrValueType(exp.getAttrValueType());
return eventExpression;
}
/**
* 更新 设备联动规则 zbxId
*
* @param triggerId 设备联动ID
* @param zbxId triggerId
*/
public void updateProductEventRuleZbxId(Long triggerId, String[] zbxId) {
DB.update(ProductEventRelation.class).where().eq("eventRuleId", triggerId)
.asUpdate().set("zbxId", zbxId[0]).update();
}
/**
* 获取设备联动详情
*
* @param productEvent
* @param eventRuleId
* @return
*/
public MultipleDeviceEventDto detail(ProductEvent productEvent, long eventRuleId) {
MultipleDeviceEventDto multipleDeviceEventDto = new MultipleDeviceEventDto();
ToolUtil.copyProperties(productEvent, multipleDeviceEventDto);
multipleDeviceEventDto.setDeviceServices(new QProductEventService().eventRuleId.eq(eventRuleId).findList());
if (TRIGGER_TYPE_CONDITION == productEvent.getTriggerType()) {
List<ProductEventExpression> expList = new QProductEventExpression().eventRuleId.eq(eventRuleId).findList();
multipleDeviceEventDto.setExpList(expList);
List<ProductEventTimeInterval> timeExpList = new QProductEventTimeInterval().eventRuleId.eq(eventRuleId).findList();
multipleDeviceEventDto.setTimeExpList(timeExpList);
ProductEventRelation productEventRelation = new QProductEventRelation().eventRuleId.eq(eventRuleId).setMaxRows(1).findOne();
if (null == productEventRelation) {
return multipleDeviceEventDto;
}
multipleDeviceEventDto.setStatus(productEventRelation.getStatus());
multipleDeviceEventDto.setRemark(productEventRelation.getRemark());
multipleDeviceEventDto.setInherit(productEventRelation.getInherit());
JSONArray triggerInfo = JSONObject.parseArray(zbxTrigger.triggerAndTagsGet(productEventRelation.getZbxId()));
List<MultipleDeviceEventRule.Tag> tagList = JSONObject.parseArray(triggerInfo.getJSONObject(0).getString("tags"), MultipleDeviceEventRule.Tag.class);
multipleDeviceEventDto.setTags(tagList.stream()
.filter(s -> !s.getTag().equals(SCENE_TAG_NAME))
.collect(Collectors.toList()));
} else {
Task task = new QTask().id.eq(productEvent.getTaskId()).findOne();
multipleDeviceEventDto.setScheduleConf(Optional.ofNullable(task).map(Task::getScheduleConf).orElse(""));
multipleDeviceEventDto.setExpList(Collections.emptyList());
multipleDeviceEventDto.setTimeExpList(Collections.emptyList());
}
return multipleDeviceEventDto;
}
/**
* 创建 设备联动
*
* @param triggerName 设备联动名称
* @param expression 表达式
* @return 触发器ID
*/
public String[] createZbxTrigger(String triggerName, String expression, Byte level) {
String res = zbxTrigger.executeTriggerCreate(triggerName, expression, level);
return JSON.parseObject(res, TriggerIds.class).getTriggerids();
}
/**
* 更新 设备联动
*
* @param triggerId
* @param expression
* @param level
* @return
*/
public String[] updateZbxTrigger(String triggerId, String expression, Byte level) {
String res = zbxTrigger.triggerUpdate(triggerId, expression, level);
return JSON.parseObject(res, TriggerIds.class).getTriggerids();
}
/**
* 执行动作服务
*
* @param eventRuleId 场景ID
* @param type 执行方式
* @param userId 执行人
*/
public void execute(Long eventRuleId, String type, Long userId) {
//先异步 执行记录日志
deviceLogService.recordSceneLog(eventRuleId, type, userId);
//根据场景ID 找出需要执行的服务
List<ProductEventService> productEventServiceList = new QProductEventService().eventRuleId.eq(eventRuleId)
.deviceId.isNull().findList();
Map<String, List<ProductEventService>> deviceServiceMap = productEventServiceList.parallelStream().collect(Collectors.groupingBy(ProductEventService::getExecuteDeviceId));
//封装执行的参数
List<Map<String, Object>> body = new ArrayList<>();
deviceServiceMap.forEach((key, value) -> {
Map<String, Object> map = new ConcurrentHashMap<>();
map.put("device", key);
List<Map<String, Object>> serviceList = new ArrayList<>();
value.forEach(val -> {
Map<String, Object> serviceMap = new ConcurrentHashMap<>();
serviceMap.put("name", DefinitionsUtil.getServiceName(val.getServiceId()));
List<ProductServiceParam> paramList = DefinitionsUtil.getServiceParam(val.getServiceId());
if (ToolUtil.isNotEmpty(paramList)) {
serviceMap.put("param", paramList.parallelStream().filter(o->key.equals(o.getDeviceId())).collect(Collectors.toMap(ProductServiceParam::getKey, ProductServiceParam::getValue, (a, b) -> a)));
}
serviceList.add(serviceMap);
});
map.put("service", serviceList);
body.add(map);
});
//提交IOT SERVER执行命令下发
Forest.post("/device/action/exec").host("127.0.0.1").port(12800).contentTypeJson().addBody(JSON.toJSON(body)).execute();
}
/**
* 场景 参数 检查
*
* @param eventRule
*/
public void checkParam(MultipleDeviceEventRule eventRule) {
if (eventRule.getTriggerType() == 0) {
if (ToolUtil.isEmpty(eventRule.getExpList())) {
throw new ServiceException(BizExceptionEnum.SCENE_EXPRESSION_NOT_EXISTS);
}
} else {
if (ToolUtil.isEmpty(eventRule.getScheduleConf())) {
throw new ServiceException(BizExceptionEnum.TASK_NOT_SCHEDULE_CONF);
}
if (!ToolUtil.validCron(eventRule.getScheduleConf())) {
throw new ServiceException(BizExceptionEnum.TASK_SCHEDULE_CONF_NOT_MATCH);
}
}
// long count = eventRule.getDeviceServices().parallelStream().map(MultipleDeviceEventRule.DeviceService::getServiceId).distinct().count();
long count = eventRule.getDeviceServices().parallelStream().map(o-> (o.getExecuteDeviceId()+o.getServiceId()).hashCode()).distinct().count();
if (count < eventRule.getDeviceServices().size()) {
throw new ServiceException(BizExceptionEnum.SERVICE_HAS_DUPLICATE);
}
}
@Data
static class TriggerIds {
private String[] triggerids;
}
@Data
public static class Triggers {
private String triggerid;
private String description;
private List<Hosts> hosts;
}
@Data
static class Hosts {
private String hostid;
private String host;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/MultipleDeviceEventRuleService.java
|
Java
|
gpl-3.0
| 26,204
|
package com.zmops.iot.web.device.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.Forest;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.event.applicationEvent.SceneEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author yefei
* <p>
* 定时 触发场景 处理
**/
@Slf4j
@Component
@EnableAsync
public class SceneScheduleProcessor {
@Autowired
DeviceLogService deviceLogService;
@EventListener(classes = {SceneEvent.class})
@Async
public void subscribe(SceneEvent event) {
log.info("子线程接收异步事件 - {},String类型", event.getEventData().getExecuteParam());
if (ToolUtil.isEmpty(event.getEventData().getExecuteParam())) {
return;
}
Map<String, Object> eventMap = JSONObject.parseObject(event.getEventData().getExecuteParam(), Map.class);
Long eventRuleId = Long.parseLong(eventMap.get("eventRuleId").toString());
//记录日志
deviceLogService.recordSceneLog(eventRuleId, "自动", null);
//提交IOT SERVER 下发命令
Forest.post("/device/action/exec").host("127.0.0.1").port(12800).contentTypeJson().addBody(JSON.toJSON(eventMap.get("executeParam"))).execute();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/SceneScheduleProcessor.java
|
Java
|
gpl-3.0
| 1,587
|
package com.zmops.iot.web.device.service.event;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.device.query.QDevicesGroups;
import com.zmops.iot.domain.device.query.QTag;
import com.zmops.iot.domain.product.query.*;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.event.applicationEvent.DeviceDeleteEvent;
import com.zmops.zeus.driver.service.ZbxHost;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.util.Collections;
@Slf4j
@Component
@EnableAsync
public class DeleteDeviceEventHandler {
@Autowired
private ZbxHost zbxHost;
@Async
@EventListener(classes = {DeviceDeleteEvent.class})
public void onApplicationEvent(DeviceDeleteEvent event) {
String deviceId = event.getEventData().getDeviceId();
String zbxId = event.getEventData().getZbxId();
new QTag().sid.eq(deviceId).delete();
new QProductAttribute().productId.eq(deviceId).delete();
new QDevicesGroups().deviceId.eq(deviceId).delete();
if (ToolUtil.isNotEmpty(zbxId)) {
JSONArray jsonArray = JSONObject.parseArray(zbxHost.hostDetail(zbxId));
if (jsonArray.size() > 0) {
zbxHost.hostDelete(Collections.singletonList(zbxId));
}
}
new QProductStatusFunctionRelation().relationId.eq(deviceId).delete();
new QProductServiceRelation().relationId.eq(deviceId).delete();
new QProductEventRelation().relationId.eq(deviceId).delete();
new QProductEventService().deviceId.eq(deviceId).delete();
new QProductServiceParam().deviceId.eq(deviceId).delete();
// new QDeviceServiceMethod().deviceId.eq(deviceId).delete();
new QDevice().deviceId.eq(deviceId).delete();
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/DeleteDeviceEventHandler.java
|
Java
|
gpl-3.0
| 2,118
|
package com.zmops.iot.web.device.service.event;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author yefei
* <p>
* 处理设备服务下发 方法
*/
@Slf4j
@Component
@Order(1)
public class SaveActionMethodEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 2:SaveActionMethodWorker----DEVICEID:{}…………", event.getEventData().getDeviceId());
// if (null == event.getEventData()) {
// return;
// }
// DeviceDto deviceDto = event.getEventData();
// if (ToolUtil.isEmpty(deviceDto.getMethod())) {
// return;
// }
//
// //保存设备服务下发 执行方法
// DeviceServiceMethod deviceServiceMethod = new DeviceServiceMethod();
// deviceServiceMethod.setDeviceId(deviceDto.getDeviceId());
// deviceServiceMethod.setMethod(deviceDto.getMethod());
//
// DB.save(deviceServiceMethod);
// log.debug("step 2:SaveActionMethodWorker----DEVICEID:{} complete…………", deviceDto.getDeviceId());
return;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/SaveActionMethodEventHandler.java
|
Java
|
gpl-3.0
| 1,353
|
package com.zmops.iot.web.device.service.event;
import cn.hutool.core.util.IdUtil;
import com.zmops.iot.domain.product.ProductAttribute;
import com.zmops.iot.domain.product.ProductAttributeEvent;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.domain.product.query.QProductAttributeEvent;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author yefei
* <p>
* 设备属性处理步骤
*/
@Slf4j
@Component
@Order(1)
public class SaveAttributeEventHandler implements ApplicationListener<DeviceSaveEvent> {
private static final String ATTR_TYPE_RELY = "18";
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 3:saveAttributeWorker----DEVICEID:{}…………", event.getEventData().getDeviceId());
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
String deviceId = deviceDto.getDeviceId();
if (ToolUtil.isNotEmpty(deviceDto.getEdit()) && "true".equals(deviceDto.getEdit())) {
//修改
//没有修改关联的产品 不做处理
if (deviceDto.getProductId().equals(deviceDto.getOldProductId())) {
return;
}
new QProductAttribute().productId.eq(deviceId).templateId.isNotNull().delete();
new QProductAttributeEvent().productId.eq(deviceId).templateId.isNotNull().delete();
}
//属性
List<ProductAttribute> productAttributeList = new QProductAttribute().productId.eq(
deviceDto.getProductId() + "").orderBy(" source::int ").findList();
List<ProductAttribute> newProductAttributeList = new ArrayList<>();
/**
* 处理依赖属性用
* 遍历属性时 attrKeyMap保存 继承的属性ID 对应的 key
* attrIdMap 保存 key 对应的 新的属性ID
*/
Map<Long, String> attrKeyMap = new ConcurrentHashMap<>(productAttributeList.size());
Map<String, Long> attrIdMap = new ConcurrentHashMap<>(productAttributeList.size());
for (ProductAttribute productAttribute : productAttributeList) {
ProductAttribute newProductAttrbute = new ProductAttribute();
ToolUtil.copyProperties(productAttribute, newProductAttrbute);
newProductAttrbute.setTemplateId(productAttribute.getAttrId());
newProductAttrbute.setZbxId("");
Long attrId = IdUtil.getSnowflake().nextId();
newProductAttrbute.setAttrId(attrId);
newProductAttrbute.setProductId(deviceId);
//处理依赖属性
if (ATTR_TYPE_RELY.equals(productAttribute.getSource())) {
String key = attrKeyMap.get(productAttribute.getDepAttrId());
if (ToolUtil.isNotEmpty(key)) {
Long deptAttrId = attrIdMap.get(key);
newProductAttrbute.setDepAttrId(deptAttrId);
}
} else {
attrKeyMap.put(productAttribute.getAttrId(), productAttribute.getKey());
attrIdMap.put(productAttribute.getKey(), attrId);
}
newProductAttributeList.add(newProductAttrbute);
}
DB.saveAll(newProductAttributeList);
//属性事件
List<ProductAttributeEvent> productAttributeEventList = new QProductAttributeEvent().productId.eq(
deviceDto.getProductId() + "").findList();
List<ProductAttributeEvent> newProductAttributeEventList = new ArrayList<>();
for (ProductAttributeEvent productAttributeEvent : productAttributeEventList) {
ProductAttributeEvent newProductAttrbuteEvent = new ProductAttributeEvent();
ToolUtil.copyProperties(productAttributeEvent, newProductAttrbuteEvent);
newProductAttrbuteEvent.setTemplateId(productAttributeEvent.getAttrId());
newProductAttrbuteEvent.setZbxId("");
newProductAttrbuteEvent.setAttrId(IdUtil.getSnowflake().nextId());
newProductAttrbuteEvent.setProductId(deviceId);
newProductAttributeEventList.add(newProductAttrbuteEvent);
}
DB.saveAll(newProductAttributeEventList);
log.debug("step 3:saveAttributeWorker----DEVICEID:{} complete…………", deviceDto.getDeviceId());
return;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/SaveAttributeEventHandler.java
|
Java
|
gpl-3.0
| 4,802
|
package com.zmops.iot.web.device.service.event;
import com.zmops.iot.domain.device.DevicesGroups;
import com.zmops.iot.domain.device.query.QDevicesGroups;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author yefei
* <p>
* 处理设备与设备组关系处理步骤
*/
@Slf4j
@Component
@Order(1)
public class SaveDeviceGrpEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 4:SaveDeviceGrpWorker----DEVICEID:{}…………", event.getEventData().getDeviceId());
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
//修改模式 先清空关联关系
if (null != deviceDto.getDeviceId()) {
new QDevicesGroups().deviceId.eq(deviceDto.getDeviceId()).delete();
}
//保存设备与设备组关系
List<DevicesGroups> devicesGroupsList = new ArrayList<>();
for (Long deviceGroupId : deviceDto.getDeviceGroupIds()) {
devicesGroupsList.add(
DevicesGroups.builder().deviceId(deviceDto.getDeviceId()).deviceGroupId(deviceGroupId).build());
}
DB.saveAll(devicesGroupsList);
log.debug("step 4:SaveDeviceGrpWorker----DEVICEID:{} complate…………", deviceDto.getDeviceId());
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/SaveDeviceGrpEventHandler.java
|
Java
|
gpl-3.0
| 1,716
|
package com.zmops.iot.web.device.service.event;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.product.ProductEventRelation;
import com.zmops.iot.domain.product.ProductStatusFunctionRelation;
import com.zmops.iot.domain.product.query.*;
import com.zmops.iot.enums.CommonStatus;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import com.zmops.iot.web.product.dto.ZbxTriggerInfo;
import com.zmops.iot.web.product.service.ProductEventRuleService;
import com.zmops.zeus.driver.service.ZbxTrigger;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 其它处理步骤
*/
@Slf4j
@Component
@Order(2)
public class SaveOtherEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Autowired
ZbxTrigger zbxTrigger;
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 6:SaveOtherWorker----DEVICEID:{}…………", event.getEventData().getDeviceId());
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
String deviceId = deviceDto.getDeviceId();
if (ToolUtil.isNotEmpty(deviceDto.getEdit()) && "true".equals(deviceDto.getEdit())) {
//修改
//没有修改关联的产品 不做处理
if (deviceDto.getProductId().equals(deviceDto.getOldProductId())) {
return;
}
//删除服务关联
new QProductServiceRelation().relationId.eq(deviceId).delete();
//删除服务参数
new QProductServiceParam().deviceId.eq(deviceId).delete();
//删除 上下线规则关联
new QProductStatusFunctionRelation().relationId.eq(deviceId).delete();
//删除 告警规则关联
new QProductEventRelation().relationId.eq(deviceId).delete();
//删除 告警执行动作关联
new QProductEventService().deviceId.eq(deviceId).delete();
}
//服务关联
DB.sqlUpdate(
"insert into product_service_relation (relation_id,service_id,inherit) SELECT :deviceId,service_id,1 from product_service_relation where relation_id=:relationId")
.setParameter("deviceId", deviceId).setParameter("relationId", deviceDto.getProductId() + "").execute();
//服务参数
DB.sqlUpdate(
"insert into product_service_param (device_id,service_id,key,name,value,remark) SELECT :deviceId,service_id,key,name,value,remark from product_service_param where device_id=:relationId")
.setParameter("deviceId", deviceId).setParameter("relationId", deviceDto.getProductId() + "").execute();
//上下线规则关联
ProductStatusFunctionRelation relation = new QProductStatusFunctionRelation().relationId.eq(
deviceDto.getProductId() + "").findOne();
if (null != relation) {
String triggerRes = zbxTrigger.triggerGetByName(relation.getRuleId() + "");
List<ZbxTriggerInfo> zbxTriggerInfoList = JSONObject.parseArray(triggerRes, ZbxTriggerInfo.class);
Map<String, String> hostTriggerMap = zbxTriggerInfoList.parallelStream()
.filter(o -> o.getTags().parallelStream().anyMatch(t -> "__offline__".equals(t.getTag())))
.collect(Collectors.toMap(o -> o.getHosts().get(0).getHost(), ZbxTriggerInfo::getTriggerid, (a, b) -> a));
Map<String, String> hostRecoveryTriggerMap = zbxTriggerInfoList.parallelStream()
.filter(o -> o.getTags().parallelStream().anyMatch(t -> "__online__".equals(t.getTag())))
.collect(Collectors.toMap(o -> o.getHosts().get(0).getHost(), ZbxTriggerInfo::getTriggerid, (a, b) -> a));
String zbxId = Optional.ofNullable(hostTriggerMap.get(deviceDto.getDeviceId())).orElse("");
String zbxIdRecovery = Optional.ofNullable(hostRecoveryTriggerMap.get(deviceDto.getDeviceId())).orElse("");
DB.sqlUpdate(
"insert into product_status_function_relation (relation_id,rule_id,inherit,zbx_id,zbx_id_recovery) SELECT :deviceId,rule_id,1,:zbxId,:zbxIdRecovery from product_status_function_relation where relation_id=:relationId")
.setParameter("deviceId", deviceId).setParameter("relationId", deviceDto.getProductId() + "")
.setParameter("zbxId", zbxId)
.setParameter("zbxIdRecovery", zbxIdRecovery).execute();
}
//告警规则关联 并 回填zbx triggerId
List<ProductEventRuleService.Triggers> triggers = JSONObject.parseArray(zbxTrigger.triggerGetByHost(deviceId),
ProductEventRuleService.Triggers.class);
Map<String, String> map = triggers.parallelStream().collect(
Collectors.toMap(ProductEventRuleService.Triggers::getDescription,
ProductEventRuleService.Triggers::getTriggerid, (a, b) -> a));
List<ProductEventRelation> productEventRelationList = new QProductEventRelation().status.eq(
CommonStatus.ENABLE.getCode()).relationId.eq(deviceDto.getProductId() + "").findList();
List<ProductEventRelation> newRelationList = new ArrayList<>();
for (ProductEventRelation productEventRelation : productEventRelationList) {
ProductEventRelation newEventRelation = new ProductEventRelation();
newEventRelation.setRelationId(deviceId);
newEventRelation.setInherit("1");
newEventRelation.setZbxId(map.get(productEventRelation.getEventRuleId() + ""));
newEventRelation.setRemark(productEventRelation.getRemark());
newEventRelation.setStatus(productEventRelation.getStatus());
newEventRelation.setEventRuleId(productEventRelation.getEventRuleId());
newRelationList.add(newEventRelation);
}
DB.saveAll(newRelationList);
//告警执行动作关联
DB.sqlUpdate(
"insert into product_event_service (service_id,device_id,execute_device_id,event_rule_id) SELECT service_id,:deviceId,:executeDeviceId,event_rule_id from product_event_service where device_id=:relationId")
.setParameter("deviceId", deviceId).setParameter("executeDeviceId", deviceId)
.setParameter("relationId", deviceDto.getProductId() + "").execute();
log.debug("step 6:SaveOtherWorker----DEVICEID:{} complate…………", deviceDto.getDeviceId());
return;
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/SaveOtherEventHandler.java
|
Java
|
gpl-3.0
| 7,059
|
package com.zmops.iot.web.device.service.event;
import com.zmops.iot.domain.device.query.QTag;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author yefei
* <p>
* 设备标签处理步骤
*/
@Slf4j
@Component
@Order(2)
public class SaveTagEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 5:SaveTagWorker----DEVICEID:{}…………", event.getEventData().getDeviceId());
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
String deviceId = deviceDto.getDeviceId();
if (ToolUtil.isNotEmpty(deviceDto.getEdit()) && "true".equals(deviceDto.getEdit())) {
//修改
//没有修改关联的产品 不做处理
if (deviceDto.getProductId().equals(deviceDto.getOldProductId())) {
return;
}
new QTag().sid.eq(deviceId).delete();
}
//继承产品中的标签
DB.sqlUpdate(
"insert into tag (sid,tag,value,template_id) SELECT :deviceId,tag,value,id template_id from tag where sid=:sid")
.setParameter("deviceId", deviceId).setParameter("sid", deviceDto.getProductId() + "").execute();
log.debug("step 5:SaveTagWorker----DEVICEID:{} complete", deviceDto.getDeviceId());
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/SaveTagEventHandler.java
|
Java
|
gpl-3.0
| 1,743
|
package com.zmops.iot.web.device.service.event;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.constant.ConstantsContext;
import com.zmops.iot.domain.device.query.QDeviceGroup;
import com.zmops.iot.domain.product.query.QProduct;
import com.zmops.iot.domain.proxy.query.QProxy;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import com.zmops.zeus.driver.service.ZbxHost;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
import static com.zmops.iot.web.init.DeviceSatusScriptInit.GLOBAL_HOST_GROUP_CODE;
/**
* @author yefei
* <p>
* 保存至zbx
*/
@Slf4j
@Component
@Order(0)
public class SaveZbxHostEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Autowired
ZbxHost zbxHost;
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("事件step 1:SaveZbxHostWorker----DEVICEID:{}…………", event.getEventData().getDeviceId());
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
//设备ID 作为zbx HOST name
String host = deviceDto.getDeviceId();
//取出 设备对应的 zbx主机组ID,模板ID
List<String> hostGrpIds = new QDeviceGroup().select(QDeviceGroup.alias().zbxId).deviceGroupId.in(
deviceDto.getDeviceGroupIds()).findSingleAttributeList();
log.debug("step 1-1:SaveZbxHostWorker----hostGrpIds:{}…………", hostGrpIds.toString());
String templateId = new QProduct().select(QProduct.alias().zbxId).productId.eq(deviceDto.getProductId())
.findSingleAttribute();
log.debug("step 1-2:SaveZbxHostWorker----templateId:{}…………", templateId);
hostGrpIds.add(ConstantsContext.getConstntsMap().get(GLOBAL_HOST_GROUP_CODE).toString());
log.debug("step 1-3:SaveZbxHostWorker----hostGrpIds:{}…………", hostGrpIds.toString());
//保存 zbx主机
String result = "";
Long proxyId = deviceDto.getProxyId();
String zbxProxyId = null;
if (null != proxyId) {
zbxProxyId = new QProxy().select(QProxy.alias().zbxId).id.eq(proxyId).findSingleAttribute();
}
log.debug("step 1-4:SaveZbxHostWorker----zbxProxyId:{}…………", zbxProxyId);
if (ToolUtil.isNotEmpty(deviceDto.getZbxId())) {
result = zbxHost.hostUpdate(deviceDto.getZbxId(), hostGrpIds, templateId, zbxProxyId,
deviceDto.getDeviceInterface());
} else {
result = zbxHost.hostCreate(host, hostGrpIds, templateId, zbxProxyId, deviceDto.getDeviceInterface());
}
String hostid = JSONObject.parseObject(result).getJSONArray("hostids").getString(0);
deviceDto.setZbxId(hostid);
log.debug("step 1:SaveZbxHostWorker----DEVICEID:{} complete,hostid:{}", deviceDto.getDeviceId(), hostid);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/SaveZbxHostEventHandler.java
|
Java
|
gpl-3.0
| 3,205
|
package com.zmops.iot.web.device.service.event;
import com.zmops.iot.domain.device.ScenesTriggerRecord;
import com.zmops.iot.domain.product.ProductEvent;
import com.zmops.iot.domain.product.query.QProductEvent;
import com.zmops.iot.web.event.applicationEvent.DeviceSceneLogEvent;
import com.zmops.iot.web.event.applicationEvent.dto.LogEventData;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Slf4j
@Component
@EnableAsync
public class ScenesLogEventHandler {
@Async
@EventListener(classes = {DeviceSceneLogEvent.class})
public void onApplicationEvent(DeviceSceneLogEvent event) {
log.debug("insert into ScenesLogWorker…………");
LogEventData eventData = event.getEventData();
long eventRuleId = eventData.getEventRuleId();
String triggerType = eventData.getTriggerType();
Long triggerUser = eventData.getTriggerUser();
ProductEvent productEvent = new QProductEvent().eventRuleId.eq(eventRuleId).findOne();
if (productEvent == null) {
return;
}
ScenesTriggerRecord scenesTriggerRecord = new ScenesTriggerRecord();
scenesTriggerRecord.setRuleId(eventRuleId);
scenesTriggerRecord.setRuleName(productEvent.getEventRuleName());
scenesTriggerRecord.setCreateTime(LocalDateTime.now());
scenesTriggerRecord.setTenantId(productEvent.getTenantId());
scenesTriggerRecord.setTriggerType(triggerType);
scenesTriggerRecord.setTriggerUser(triggerUser);
DB.save(scenesTriggerRecord);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/ScenesLogEventHandler.java
|
Java
|
gpl-3.0
| 1,805
|
package com.zmops.iot.web.device.service.event;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.domain.device.ServiceExecuteRecord;
import com.zmops.iot.domain.device.query.QDevice;
import com.zmops.iot.domain.product.ProductEventService;
import com.zmops.iot.domain.product.ProductService;
import com.zmops.iot.domain.product.ProductServiceParam;
import com.zmops.iot.domain.product.query.QProductEventService;
import com.zmops.iot.domain.product.query.QProductService;
import com.zmops.iot.util.DefinitionsUtil;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.event.applicationEvent.DeviceSceneLogEvent;
import com.zmops.iot.web.event.applicationEvent.dto.LogEventData;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
@Component
@EnableAsync
public class ServiceLogEventHandler {
@Async
@EventListener(classes = {DeviceSceneLogEvent.class})
public void onApplicationEvent(DeviceSceneLogEvent event) {
log.debug("insert into service log…………");
LogEventData eventData = event.getEventData();
long eventRuleId = eventData.getEventRuleId();
String executeType = eventData.getTriggerType();
Long executeUser = eventData.getTriggerUser();
List<ProductEventService> productEventServiceList = new QProductEventService().eventRuleId.eq(eventRuleId).findList();
List<Long> serviceIds = productEventServiceList.parallelStream().map(ProductEventService::getServiceId).collect(Collectors.toList());
List<ProductService> productServiceList = new QProductService().id.in(serviceIds).findList();
Map<Long, ProductService> productServiceMap = productServiceList.parallelStream().collect(Collectors.toMap(ProductService::getId, o -> o, (a, b) -> a));
List<String> deviceIds = productEventServiceList.parallelStream().map(ProductEventService::getExecuteDeviceId).collect(Collectors.toList());
List<Device> deviceList = new QDevice().deviceId.in(deviceIds).tenantId.isNotNull().findList();
Map<String, Long> deviceIdMap = deviceList.parallelStream().collect(Collectors.toMap(Device::getDeviceId, Device::getTenantId, (a, b) -> a));
List<ServiceExecuteRecord> serviceExecuteRecordList = new ArrayList<>();
productEventServiceList.forEach(productEventService -> {
ServiceExecuteRecord serviceExecuteRecord = new ServiceExecuteRecord();
serviceExecuteRecord.setDeviceId(productEventService.getExecuteDeviceId());
List<ProductServiceParam> paramList = DefinitionsUtil.getServiceParam(productEventService.getServiceId());
if (ToolUtil.isNotEmpty(paramList)) {
serviceExecuteRecord.setParam(JSONObject.toJSONString(paramList.parallelStream().collect(Collectors.toMap(ProductServiceParam::getKey, ProductServiceParam::getValue, (a, b) -> a))));
}
serviceExecuteRecord.setServiceName(Optional.ofNullable(productServiceMap.get(productEventService.getServiceId())).map(ProductService::getName).orElse(""));
if (deviceIdMap.get(productEventService.getExecuteDeviceId()) != null) {
serviceExecuteRecord.setTenantId(deviceIdMap.get(productEventService.getExecuteDeviceId()));
}
serviceExecuteRecord.setCreateTime(LocalDateTime.now());
serviceExecuteRecord.setExecuteRuleId(eventRuleId);
serviceExecuteRecord.setExecuteType(executeType);
serviceExecuteRecord.setExecuteUser(executeUser);
serviceExecuteRecordList.add(serviceExecuteRecord);
});
DB.saveAll(serviceExecuteRecordList);
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/ServiceLogEventHandler.java
|
Java
|
gpl-3.0
| 4,077
|
package com.zmops.iot.web.device.service.event;
import com.alibaba.fastjson.JSONObject;
import com.zmops.iot.domain.product.ProductAttribute;
import com.zmops.iot.domain.product.ProductAttributeEvent;
import com.zmops.iot.domain.product.query.QProductAttribute;
import com.zmops.iot.domain.product.query.QProductAttributeEvent;
import com.zmops.iot.util.ToolUtil;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import com.zmops.zeus.driver.entity.ZbxItemInfo;
import com.zmops.zeus.driver.service.ZbxItem;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author yefei
* <p>
* 更新设备属性中ZBXID
*/
@Slf4j
@Component
@Order(2)
public class UpdateAttrZbxIdEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Autowired
ZbxItem zbxItem;
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 7:resolve Attr zbxID async----deviceid: {} …………", event.getEventData().getDeviceId());
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
String deviceId = deviceDto.getDeviceId();
if (ToolUtil.isNotEmpty(deviceDto.getEdit()) && "true".equals(deviceDto.getEdit())) {
//修改
//没有修改关联的产品 不做处理
if (deviceDto.getProductId().equals(deviceDto.getOldProductId())) {
return;
}
}
//取出 ZBX hostid
//根据hostid 取出监控项
List<ZbxItemInfo> itemInfos = JSONObject.parseArray(zbxItem.getItemInfo(null, deviceDto.getZbxId()),
ZbxItemInfo.class);
if (ToolUtil.isEmpty(itemInfos)) {
return;
}
Map<String, ZbxItemInfo> itemMap = itemInfos.parallelStream()
.collect(Collectors.toMap(ZbxItemInfo::getName, o -> o, (a, b) -> a));
//取出继承的属性 并塞入对应的 itemId
List<ProductAttribute> productAttributeList = new QProductAttribute().productId.eq(deviceId).findList();
for (ProductAttribute productAttribute : productAttributeList) {
productAttribute.setZbxId(itemMap.get(productAttribute.getTemplateId() + "").getItemid());
}
DB.updateAll(productAttributeList);
//取出继承的属性事件 并塞入对应的 itemId
List<ProductAttributeEvent> productAttributeEventList = new QProductAttributeEvent().productId.eq(deviceId)
.findList();
for (ProductAttributeEvent productAttributeEvent : productAttributeEventList) {
productAttributeEvent.setZbxId(itemMap.get(productAttributeEvent.getTemplateId() + "").getItemid());
}
DB.updateAll(productAttributeEventList);
log.debug("step 7:resolve Attr zbxID async----deviceid: {} complete", deviceDto.getDeviceId());
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/UpdateAttrZbxIdEventHandler.java
|
Java
|
gpl-3.0
| 3,247
|
package com.zmops.iot.web.device.service.event;
import com.zmops.iot.domain.device.Device;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import io.ebean.DB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author yefei
* <p>
* 更新设备中zbxID
*/
@Slf4j
@Component
@Order(2)
public class UpdateDeviceZbxIdEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
log.debug("step 8:resolve zbxID async----DEVICEID:{}, HOSTID:{}…………", deviceDto.getDeviceId(),
deviceDto.getZbxId());
DB.update(Device.class).where().eq("deviceId", deviceDto.getDeviceId()).asUpdate()
.set("zbxId", deviceDto.getZbxId()).update();
log.debug("step 8:resolve zbxID async----DEVICEID:{}, HOSTID:{} 完成", deviceDto.getDeviceId(),
deviceDto.getZbxId());
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/UpdateDeviceZbxIdEventHandler.java
|
Java
|
gpl-3.0
| 1,256
|
package com.zmops.iot.web.device.service.event;
import com.zmops.iot.domain.device.Tag;
import com.zmops.iot.domain.device.query.QTag;
import com.zmops.iot.web.device.dto.DeviceDto;
import com.zmops.iot.web.event.applicationEvent.DeviceSaveEvent;
import com.zmops.zeus.driver.service.ZbxHost;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author yefei
* <p>
* 同步设备标签到zbx
*/
@Slf4j
@Component
@Order(2)
public class UpdateZbxTagEventHandler implements ApplicationListener<DeviceSaveEvent> {
@Autowired
ZbxHost zbxHost;
@Override
public void onApplicationEvent(DeviceSaveEvent event) {
log.debug("step 9: UpdateZbxTagWorker ……");
if (null == event.getEventData()) {
return;
}
DeviceDto deviceDto = event.getEventData();
//查询出本地tag
List<Tag> list = new QTag().sid.eq(deviceDto.getDeviceId()).findList();
Map<String, String> tagMap = new HashMap<>(list.size());
for (Tag tag : list) {
tagMap.put(tag.getTag(), tag.getValue());
}
//保存
zbxHost.hostTagUpdate(deviceDto.getZbxId(), tagMap);
log.debug("step 9:resolve zbxID async----DEVICEID:{}, HOSTID:{} 完成", deviceDto.getDeviceId(),
deviceDto.getZbxId());
}
}
|
2301_81045437/zeus-iot
|
zeus-webapp/src/main/java/com/zmops/iot/web/device/service/event/UpdateZbxTagEventHandler.java
|
Java
|
gpl-3.0
| 1,594
|