Commit ced377e6 authored by 李振振's avatar 李振振

代码提交

parent 425bc885
kind: pipeline
name: dev
trigger:
branch:
- dev
clone:
disable: true
volumes:
- name: docker-sock
host:
path: /var/run/docker.sock
##--------------------------------流水线⬇-------------------------------##
steps:
- name: fetch
image: registry.cn-qingdao.aliyuncs.com/wod/devops-git:1.0
- name: s3-cache
image: registry.cn-qingdao.aliyuncs.com/wod/devops-s3-cache:1.0
settings:
restore: true
mount:
- .repository
endpoint: http://cache.wodcloud.com
access_key:
from_secret: ACCESS_KEY_MINIO
secret_key:
from_secret: SECRET_KEY_MINIO
- name: build
image: hub.wodcloud.com/xinchuang/mvn3.8-jdk8:v2.0
commands:
- mvn clean install -Dmaven.test.skip=true
- name: s3-cache-build
image: registry.cn-qingdao.aliyuncs.com/wod/devops-s3-cache:1.0
settings:
rebuild: true
hash: pom.xml
mount:
- .repository
endpoint: http://cache.wodcloud.com
access_key:
from_secret: ACCESS_KEY_MINIO
secret_key:
from_secret: SECRET_KEY_MINIO
- name: docker-amd64
image: registry.cn-qingdao.aliyuncs.com/wod/devops-docker:1.0
volumes:
- name: docker-sock
path: /var/run/docker.sock
settings:
base: hub.wodcloud.com/base/jdk:8-amd64
dockerfile: .beagle/dockerfile
repo: haidian/sdk-golden-api
version: "v1.0.0"
channel: amd64
args: "TARGETOS=linux,TARGETARCH=amd64"
registry: hub.wodcloud.com
registry_user:
from_secret: REGISTRY_USER
registry_password:
from_secret: REGISTRY_PASSWORD
- name: docker-arm64
image: registry.cn-qingdao.aliyuncs.com/wod/devops-docker:1.0
volumes:
- name: docker-sock
path: /var/run/docker.sock
settings:
base: hub.wodcloud.com/xinchuang/sdt-cryptohi-mmj:v1.0.0-arm64
dockerfile: .beagle/dockerfile
repo: haidian/sdk-golden-api
version: "v1.0.0"
channel: arm64
args: "TARGETOS=linux,TARGETARCH=arm64"
registry: hub.wodcloud.com
registry_user:
from_secret: REGISTRY_USER
registry_password:
from_secret: REGISTRY_PASSWORD
- name: docker-arch
image: registry.cn-qingdao.aliyuncs.com/wod/devops-docker-manifest:v1.2.3
settings:
platforms: linux/amd64,linux/arm64
template: hub.wodcloud.com/haidian/sdk-golden-api:v1.0.0-ARCH
target: hub.wodcloud.com/haidian/sdk-golden-api:v1.0.0
username:
from_secret: REGISTRY_USER
password:
from_secret: REGISTRY_PASSWORD
---
kind: secret
name: REGISTRY_USER
get:
name: REGISTRY_USER
path: devops-secrets
---
kind: secret
name: REGISTRY_PASSWORD
get:
name: REGISTRY_PASSWORD
path: devops-secrets
---
kind: secret
name: KUBERNETES_SERVER
get:
name: KUBERNETES_SERVER
path: devops-secrets
---
kind: secret
name: KUBERNETES_TOKEN
get:
name: KUBERNETES_TOKEN
path: devops-secrets
---
kind: secret
name: ACCESS_KEY_MINIO
get:
name: ACCESS_KEY_MINIO
path: devops-secrets
---
kind: secret
name: SECRET_KEY_MINIO
get:
name: SECRET_KEY_MINIO
path: devops-secrets
\ No newline at end of file
ARG BASE
FROM ${BASE}
ARG AUTHOR
ARG VERSION
LABEL maintainer=${AUTHOR} version=${VERSION}
RUN echo "Asia/Shanghai" > /etc/timezone
COPY ./target/sdt-kangdun-api-1.0.0.jar /app/sdt-kangdun-api-1.0.0.jar
ENTRYPOINT ["java","-jar","/app/sdt-kangdun-api-1.0.0.jar"]
# 断网重连超时时间,单位毫秒
rtdb.connect.retry.timeout=5000
---
kind: ConfigMap
apiVersion: v1
metadata:
name: extends-sdk-golden-api-config
data:
GOLDEN_IP: '10.253.1.97'
GOLDEN_PORT: '6327'
GOLDEN_USER: 'sa'
GOLDEN_PASSWORD: 'golden'
---
kind: Deployment
apiVersion: apps/v1
metadata:
name: beagle-extends-sdk-golden-api
labels:
app: beagle-extends-sdk-golden-api
spec:
replicas: 1
selector:
matchLabels:
app: beagle-extends-sdk-golden-api
template:
metadata:
labels:
app: beagle-extends-sdk-golden-api
spec:
containers:
- name: beagle-extends-sdk-golden-api
image: hub.wodcloud.com/xinchuang/sdt-cryptohi-api:v1.0.0-amd64
imagePullPolicy: Always
resources:
limits:
cpu: 1
memory: 2Gi
requests:
cpu: 0.1
memory: 256Mi
ports:
- containerPort: 8080
name: http
volumeMounts:
- name: localtime
mountPath: /etc/localtime
envFrom:
- configMapRef:
name: xc-sdt-cryptohi-api-config-dev
volumes:
- name: localtime
hostPath:
path: /etc/localtime
---
kind: Service
apiVersion: v1
metadata:
name: beagle-extends-sdk-golden-api
spec:
selector:
app: beagle-extends-sdk-golden-api
ports:
- name: beagle-extends-sdk-golden-api
port: 80
targetPort: 8080
---
kind: IngressRoute
apiVersion: bcc.bd-apaas.com/v1alpha1
metadata:
name: beagle-extends-sdk-golden-api
spec:
entryPoints:
- websecure
routes:
- kind: Rule
match: Host(`xc-cloud.dev.wodcloud.com`) && PathPrefix(`/sdk/golden/api`)
services:
- name: beagle-extends-sdk-golden-api
port: 80
tls:
certResolver: default
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.beagle.sdt.kangdun</groupId>
<artifactId>sdt-kangdun-api</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>sdt-kangdun-api</name>
<properties>
<java.version>8</java.version>
<alibaba.fastjson.version>2.0.40</alibaba.fastjson.version>
<knife4j.version>3.0.3</knife4j.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/net.java.dev.jna/jna -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.5.2</version>
<systemPath>${pom.basedir}/lib/rtdb-java-sdk-3.0.48.jar</systemPath>
<scope>system</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<!-- <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<systemPath>${pom.basedir}/lib/log4j-1.2.17.jar</systemPath>
<scope>system</scope>
</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!--springboot web项目核心包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--springboot aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--springboot 配置类-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--参数校验器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- json工具包-->
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${alibaba.fastjson.version}</version>
</dependency>
<!--接口文档-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<!--热启动-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.15</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.yaml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.xlsx</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>${project.basedir}/lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
<includes>
<include>**/*.jar</include>
</includes>
</resource>
</resources>
</build>
</project>
package com.beagle.base;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author wuwanli
*/
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableScheduling
public class BaseApplication {
public static void main(String[] args) {
SpringApplication.run(BaseApplication.class, args);
}
}
package com.beagle.base;
import lombok.Data;
@Data
public class BasePointsPropertiesNewParam {
private String [] tagName;
}
package com.beagle.base;
import lombok.Data;
@Data
public class UserVo {
private String userId;
private String userType;
private String userName;
private String phone;
private String email;
}
package com.beagle.base.bean.vo;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class BasePointsPropertiesParam {
@NotNull(message = "id集合不能为空")
private int[] ids;
}
package com.beagle.base.bean.vo;
import com.rtdb.enums.DataSort;
import com.rtdb.model.SearchCondition;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class BaseSearchParam {
@NotNull(message = "搜索条件不能为空")
private SearchCondition condition;
@NotNull(message = "请求次数不能为空")
private Integer count;
@NotNull(message = "排序规则不能为空")
private DataSort sort;
}
package com.beagle.base.bean.vo;
import com.rtdb.enums.DataSort;
import com.rtdb.model.SearchConditionTotal;
import lombok.Data;
@Data
public class BaseSearchPointCountParam {
private SearchConditionTotal condition;
private DataSort sort;
}
package com.beagle.base.bean.vo;
import lombok.Data;
@Data
public class BaseTableTagNamesParam {
private int[] ids;
}
package com.beagle.base.bean.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
public class HistorianDoubleArchivedValuesParam {
@NotNull(message = "id不能为空")
private Integer id;
@NotNull(message = "过滤条件不能为空")
private Integer count;
@NotNull(message = "请求开始时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime;
@NotNull(message = "请求结束时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
}
package com.beagle.base.bean.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
public class HistorianFloatArchivedValuesFiltParam {
@NotNull(message = "id不能为空")
private Integer id;
@NotNull(message = "过滤条件不能为空")
private String filter;
@NotNull(message = "请求次数不能为空")
private Integer count;
@NotNull(message = "请求开始时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime;
@NotNull(message = "请求结束时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
}
package com.beagle.base.bean.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
public class HistorianFloatInterpoValuesParam {
@NotNull(message = "id不能为空")
private Integer id;
@NotNull(message = "请求次数不能为空")
private Integer count;
// Date dateStart = DateUtil.stringToDate("2017-11-16 18:05:55");
// Date dateEnd = DateUtil.stringToDate("2017-11-16 20:00:55");
//纳秒版本时间的传入方式
//DateTimeNS dateStart = new DateTimeNS(dateDateUtil.stringToDate("2017-11-16 18:05:55"), 0);
//DateTimeNS dateEnd = new DateTimeNS(DateUtil.stringToDate("2017-11-16 20:00:55"), 0);
@NotNull(message = "请求开始时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime;
@NotNull(message = "请求结束时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endTime;
}
package com.beagle.base.bean.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
@Data
public class HistorianFloatIntervalValuesParam {
@NotNull(message = "id不能为空")
private Integer id;
@NotNull(message = "请求次数不能为空")
private Integer count;
@NotNull(message = "请求频率不能为空")
private Long interval;
@NotNull(message = "请求时间不能为空")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date dateTime;
}
package com.beagle.base.bean.vo;
import lombok.Data;
@Data
public class SnapshotBlobParam {
private int[] ids;
}
package com.beagle.base.bean.vo;
import lombok.Data;
@Data
public class SnapshotCoorParam {
private int[] ids;
}
package com.beagle.base.bean.vo;
import lombok.Data;
@Data
public class SnapshotDoubleParam {
private int[] ids;
}
package com.beagle.base.bean.vo;
import lombok.Data;
@Data
public class SnapshotIntParam {
private int[] ids;
}
package com.beagle.base.bean.vo.resp;
import com.beagle.base.common.contant.CodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* @author wuwanli
*/
@Data
@ToString
@ApiModel
public class BaseResponse implements Serializable {
/**
* 返回码
*/
@ApiModelProperty("返回码")
private String code;
/**
* 返回描述
*/
@ApiModelProperty("返回描述")
private String desc;
public static BaseResponse success() {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(CodeEnum.SUCCESS.getCode());
baseResponse.setDesc(CodeEnum.SUCCESS.getDesc());
return baseResponse;
}
public static BaseResponse fail() {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(CodeEnum.UNKNOWN.getCode());
baseResponse.setDesc(CodeEnum.UNKNOWN.getDesc());
return baseResponse;
}
public static BaseResponse fail(CodeEnum codeEnum) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(codeEnum.getCode());
baseResponse.setDesc(codeEnum.getDesc());
return baseResponse;
}
public static BaseResponse fail(String code, String desc) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(code);
baseResponse.setDesc(desc);
return baseResponse;
}
public static BaseResponse fail(String desc) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.setCode(CodeEnum.UNKNOWN.getCode());
baseResponse.setDesc(desc);
return baseResponse;
}
}
package com.beagle.base.bean.vo.resp;
import com.beagle.base.common.contant.CodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* @author wuwanli
*/
@Data
@ToString
@ApiModel
public class ExtBaseResponse implements Serializable {
/**
* 返回码
*/
@ApiModelProperty("返回码")
private String code;
/**
* 返回描述
*/
@ApiModelProperty("返回描述")
private String msg;
public static ExtBaseResponse success() {
ExtBaseResponse baseResponse = new ExtBaseResponse();
baseResponse.setCode(CodeEnum.SUCCESS.getCode());
baseResponse.setMsg(CodeEnum.SUCCESS.getDesc());
return baseResponse;
}
public static ExtBaseResponse fail() {
ExtBaseResponse baseResponse = new ExtBaseResponse();
baseResponse.setCode(CodeEnum.UNKNOWN.getCode());
baseResponse.setMsg(CodeEnum.UNKNOWN.getDesc());
return baseResponse;
}
public static ExtBaseResponse fail(CodeEnum codeEnum) {
ExtBaseResponse baseResponse = new ExtBaseResponse();
baseResponse.setCode(codeEnum.getCode());
baseResponse.setMsg(codeEnum.getDesc());
return baseResponse;
}
public static ExtBaseResponse fail(String code, String desc) {
ExtBaseResponse baseResponse = new ExtBaseResponse();
baseResponse.setCode(code);
baseResponse.setMsg(desc);
return baseResponse;
}
public static ExtBaseResponse fail(String desc) {
ExtBaseResponse baseResponse = new ExtBaseResponse();
baseResponse.setCode(CodeEnum.UNKNOWN.getCode());
baseResponse.setMsg(desc);
return baseResponse;
}
}
package com.beagle.base.bean.vo.resp;
import com.beagle.base.common.contant.CodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @author wuwanli
*/
@Data
@ApiModel
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class ExtResponse<T> extends ExtBaseResponse {
/**
* 封装的返回对象
*/
@ApiModelProperty("返回对象")
private T data;
public ExtResponse(T data) {
this.setCode(CodeEnum.SUCCESS.getCode());
this.setMsg(CodeEnum.SUCCESS.getDesc());
this.data = data;
}
public ExtResponse(CodeEnum codeEnum) {
this.setCode(codeEnum.getCode());
this.setMsg(codeEnum.getCode());
}
}
package com.beagle.base.bean.vo.resp;
import com.beagle.base.common.contant.CodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @author wuwanli
*/
@Data
@ApiModel
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Response<T> extends BaseResponse {
/**
* 封装的返回对象
*/
@ApiModelProperty("返回对象")
private T data;
public Response(T data) {
this.setCode(CodeEnum.SUCCESS.getCode());
this.setDesc(CodeEnum.SUCCESS.getDesc());
this.data = data;
}
public Response(CodeEnum codeEnum) {
this.setCode(codeEnum.getCode());
this.setDesc(codeEnum.getCode());
}
}
package com.beagle.base.common.aspect;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson2.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Description;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import lombok.extern.slf4j.Slf4j;
/**
* @author wuwanli
*/
@Order(1)
@Slf4j
@Aspect
@Component
public class InterfaceLogAspect {
@Description("打印接口请求报文")
@Before("execution(* com.beagle.base.controller..*.*(..))")
public void before(JoinPoint joinPoint) {
try {
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
String[] parameterNames = methodSignature.getParameterNames();
Map<String, Object> paramMap = new HashMap<>(10);
Object[] args = joinPoint.getArgs();
if (parameterNames.length <= args.length) {
for (int i = 0; i < parameterNames.length; i++) {
paramMap.put(parameterNames[i], args[i]);
}
}
log.info(
"interface url : " + (attributes != null ? attributes.getRequest().getRequestURL() : null));
log.info("interface className : " + joinPoint.getTarget().getClass().getName());
log.info("interface methodName : " + joinPoint.getSignature().getName());
log.info("interface requestBody : " + JSONObject.toJSONString(paramMap));
} catch (Exception exception) {
log.error("InterfaceLogAspect.logInterfaceRequest Exception", exception);
}
}
@Description("打印接口响应报文")
@Around("execution(* com.beagle.base.controller..*.*(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
log.info("interface responseBody : " + (result != null ? JSONObject.toJSONString(result) : null));
log.info("interface time-consuming :{}", System.currentTimeMillis() - startTime);
return result;
}
}
package com.beagle.base.common.component;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author wuwanli
*/
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) throws BeansException {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) throws BeansException {
return applicationContext.getBean(name, clazz);
}
}
package com.beagle.base.common.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "beagle.xc.crypt")
public class CommonConfig {
/**
* 实例ID
*/
private String instanceId;
/**
* XC-Core平台地址
*/
private String xcCoreHost;
}
package com.beagle.base.common.config;
import com.beagle.base.common.filter.AuthenticationFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import com.beagle.base.common.filter.LogbackFilter;
/**
* @author wuwanli
*/
@Configuration
public class FilterConfig {
@Value("${server.servlet.context-path}")
private String consoleUrl;
@Bean
public FilterRegistrationBean<LogbackFilter> getLogbackFilter() {
FilterRegistrationBean<LogbackFilter> logbackFilter = new FilterRegistrationBean<>(new LogbackFilter());
logbackFilter.addUrlPatterns("/*");
logbackFilter.setOrder(Ordered.HIGHEST_PRECEDENCE);
return logbackFilter;
}
// 暂时去掉用户授权,验证主流程是否正确
// @Bean
public FilterRegistrationBean<AuthenticationFilter> authenticationFilterRegistration() {
FilterRegistrationBean<AuthenticationFilter> registration =
new FilterRegistrationBean<>(new AuthenticationFilter(consoleUrl));
registration.addUrlPatterns("/*");
registration.setName("authenticationFilter");
registration.setOrder(1);
return registration;
}
}
package com.beagle.base.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author wuwanli
*/
@EnableSwagger2
@Configuration
public class Knife4jConfiguration {
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder().description("APIs").termsOfServiceUrl("http://localhost:8080/base")
.version("1.0").build())
// 分组名称
.groupName("base").select()
// 这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.beagle.base.controller")).paths(PathSelectors.any()).build();
}
}
package com.beagle.base.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* @author wuwanli
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SkipSslVerificationHttpRequestFactory factory = new SkipSslVerificationHttpRequestFactory();
// 将响应超时时间设置大点
factory.setReadTimeout(30000);
factory.setConnectTimeout(15000);
return factory;
}
}
package com.beagle.base.common.config;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
/**
* @author wuwanli
*/
@Slf4j
public class SkipSslVerificationHttpRequestFactory extends SimpleClientHttpRequestFactory {
public SkipSslVerificationHttpRequestFactory() {}
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
this.prepareHttpsConnection((HttpsURLConnection)connection);
}
super.prepareConnection(connection, httpMethod);
}
private void prepareHttpsConnection(HttpsURLConnection connection) {
connection.setHostnameVerifier(new SkipHostnameVerifier());
try {
connection.setSSLSocketFactory(this.createSslSocketFactory());
} catch (Exception var3) {
log.error("prepareHttpsConnection Exception", var3);
}
}
private SSLSocketFactory createSslSocketFactory() throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] {new SkipX509TrustManager()}, new SecureRandom());
return context.getSocketFactory();
}
private static class SkipX509TrustManager implements X509TrustManager {
private SkipX509TrustManager() {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
}
private static class SkipHostnameVerifier implements HostnameVerifier {
private SkipHostnameVerifier() {}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
}
package com.beagle.base.common.contant;
import lombok.Getter;
/**
* @author wuwanli
*/
public enum CodeEnum {
/**
* 处理成功
*/
SUCCESS("200", "成功"),
/**
* 不支持 HTTP 方法
*/
HTTP_METHOD_NOT_SUPPORTED("4000001", "不支持 HTTP 方法"),
/**
* 参数校验失败
*/
ARGUMENT_VALID_ERROR("4000003", "参数校验失败"),
/**
* 参数类型错误
*/
ARGUMENT_TYPE_ERROR("4000002", "参数类型错误"),
/**
* 必填参数为空
*/
REQUIRED_PARAMETER_EMPTY("4001002", "必填参数为空"),
/**
* 未登录
*/
NOT_LOGIN("4001003", "用户未登录"),
/**
* 处理成功
*/
UNKNOWN("5000001", "系统异常"),
/**
* SQL改写规则不存在
*/
SQL_REWRITE_NOT_EXITS("5000002", "SQL改写规则不存在"),
/**
* SQL转换规则不存在
*/
SQL_CONVERT_NOT_EXITS("5000003", "SQL转换规则不存在"),
/**
* SQL转换规则不存在
*/
SOUTH_DATABASE_NOT_EXITS("5000004", "南向数据库不存在"),
/**
* SQL转换规则不存在
*/
NORTH_DATABASE_NOT_EXITS("5000005", "北向数据库不存在"),
/**
* 文件格式不正确
*/
FORMAT_MISMATCH_EXITS("5000005", "文件格式不正确"),
/**
* 实例端点地址不存在
*/
ENDPOINT_NOT_EXITS("5000006", "实例端点地址不存在"),
/**
* 数据库驱动地址为空
*/
DRIVER_JAR_URL_NOT_EXITS("5000007", "数据库驱动地址为空"),
INSTANCE_DATA_NOT_EXISTS("5000008", "实例规则管理数据为空"),
INSTANCE_INDEX_DATA_NOT_EXISTS("5000009", "实例对应的es索引数据为空"),
OVER_INDEX_OF_ES("5000010", "查询数据量过大, 建议缩小查询范围"),
INSTANCE_NOT_AUTH("5000011", "实例未授权"),
EXCEED_FILE_MAX("5000012", "单文件大小超过5M限制"),
EXCEED_TOTAL_FILE_MAX("5000013", "总文件大小超过5M限制"),
UPLOAD_FILE_NAME_EMPTY("5000014", "上传文件格式为空"),
UPLOAD_FILE_NAME_ERROR("5000015", "上传文件格式错误"),
EXCEPTION_OPEN_SEARCH("5000016", "OPENSEARCH服务异常"),
UNAUTHORIZED_OPEN_SEARCH("5000017", "OPENSEARCH未授权"),
CRYPT_CHECK_FAILED("5000018", "内容防篡改验证失败"),
;
/**
* 构造函数
*
* @param code 响应码
* @param desc 响应描述
*/
CodeEnum(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Getter
private final String code;
@Getter
private final String desc;
}
\ No newline at end of file
package com.beagle.base.common.contant;
/**
* 业务常量
*
* @author wuwanli
* @version 1.0
* @date 2021/8/4
*/
public interface LoginConstants {
/**
* 用户ID
*/
String AWE_TOKEN_PREFIX = "aweToken=";
/**
* 用户ID
*/
String USER_ID = "userId";
/**
* 用户名称
*/
String USER_NAME="userName";
/**
* 用户类型,1:超管;其他
*/
String USER_TYPE = "userType";
/**
* 用户类型,1:超管;其他
*/
String USER_TYPE_ADMIN = "1";
/**
* cookie中token的name
*/
String COOKIE_TOKEN_NAME = "aweToken";
/**
* cookie的name
*/
String COOKIE_NAME = "tokenCookie";
}
package com.beagle.base.common.exception;
import com.beagle.base.common.contant.CodeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @author wuwanli
*/
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class BeagleException extends RuntimeException {
/**
* 错误码
*/
protected String errorCode;
/**
* 错误信息
*/
protected String errorMsg;
public BeagleException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
public BeagleException(String errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public BeagleException(CodeEnum codeEnum) {
super(codeEnum.getDesc());
this.errorCode = codeEnum.getCode();
this.errorMsg = codeEnum.getDesc();
}
public BeagleException(String errorMsg, Throwable cause) {
super(errorMsg, cause);
}
public BeagleException(String errorCode, String errorMsg, Throwable cause) {
super(errorCode, cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
package com.beagle.base.common.exception;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import com.beagle.base.bean.vo.resp.BaseResponse;
import com.beagle.base.common.contant.CodeEnum;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import java.util.stream.Collectors;
/**
* @author wuwanli
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* @param exception 自定义异常
* @return BaseResponse
*/
@ExceptionHandler(value = BeagleException.class)
public BaseResponse beagleExceptionHandler(BeagleException exception) {
log.error("GlobalExceptionHandler.beagleExceptionHandler", exception);
BaseResponse baseResponse = BaseResponse.fail();
if (!StringUtils.isBlank(exception.getErrorCode())) {
baseResponse.setCode(exception.getErrorCode());
baseResponse.setDesc(exception.getErrorMsg());
}
return baseResponse;
}
@ExceptionHandler(value = MultipartException.class)
public BaseResponse MultipartExceptionHandler(MaxUploadSizeExceededException exception) {
log.error("GlobalExceptionHandler.MultipartException", exception);
String msg = "";
BaseResponse baseResponse = BaseResponse.fail();
if (exception.getCause().getCause() instanceof FileSizeLimitExceededException) {
log.error(exception.getMessage());
baseResponse = BaseResponse.fail(CodeEnum.EXCEED_FILE_MAX);
}else if (exception.getCause().getCause() instanceof SizeLimitExceededException) {
log.error(exception.getMessage());
baseResponse = BaseResponse.fail(CodeEnum.EXCEED_TOTAL_FILE_MAX);
}
return baseResponse;
}
/**
* @param exception 系统异常
* @return BaseResponse
*/
@ExceptionHandler(value = Exception.class)
public BaseResponse exceptionHandler(Exception exception) {
log.error("GlobalExceptionHandler.exceptionHandler", exception);
return BaseResponse.fail();
}
/**
* @param exception 不支持 HTTP 方法
* @return BaseResponse
*/
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public BaseResponse httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
log.error("GlobalExceptionHandler.httpRequestMethodNotSupportedException", exception);
return BaseResponse.fail(CodeEnum.HTTP_METHOD_NOT_SUPPORTED);
}
/**
* @param exception 参数校验失败
* @return BaseResponse
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public BaseResponse methodArgumentNotValidException(MethodArgumentNotValidException exception) {
log.error("GlobalExceptionHandler.methodArgumentNotValidException", exception);
BindingResult bindingResult = exception.getBindingResult();
if (bindingResult.hasErrors()) {
String errorInfo = bindingResult.getAllErrors().stream().map(ObjectError::getDefaultMessage)
.collect(Collectors.joining(";"));
return BaseResponse.fail(CodeEnum.ARGUMENT_VALID_ERROR.getCode(), errorInfo);
}
return BaseResponse.fail(CodeEnum.ARGUMENT_VALID_ERROR);
}
/**
* @param exception 参数类型错误
* @return BaseResponse
*/
@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
public BaseResponse methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) {
log.error("GlobalExceptionHandler.methodArgumentTypeMismatchException", exception);
return BaseResponse.fail(CodeEnum.ARGUMENT_TYPE_ERROR);
}
}
package com.beagle.base.common.filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson2.JSONObject;
import com.beagle.base.UserVo;
import com.beagle.base.common.component.ApplicationContextUtil;
import com.beagle.base.common.config.CommonConfig;
import com.beagle.base.common.contant.CodeEnum;
import com.beagle.base.common.contant.LoginConstants;
import com.beagle.base.common.util.ResponseUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author wuwanli
*/
@Slf4j
@Getter
@Setter
public class AuthenticationFilter implements Filter {
public static final String USER_INFO_API_URL = "/xc/core/api/auth/userinfo";
private static String[] whiteList ;
public AuthenticationFilter(String consoleUrl) {
whiteList = new String[]{
consoleUrl + "/doc.html","/swagger-resources","/api-docs",".html",".css",".js", consoleUrl + "/index"
};
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
try {
// 设置白名单
for (String whiteUrl : whiteList) {
if (request.getRequestURI().startsWith(whiteUrl)
|| request.getRequestURI().endsWith(whiteUrl)) {
filterChain.doFilter(request, response);
return;
}
}
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
ResponseUtil.returnBaseResponse(response, CodeEnum.NOT_LOGIN);
return;
}
List<String> cookieList = Arrays.stream(cookies)
.map(obj -> obj.getName() + "=" + obj.getValue())
.collect(Collectors.toList());
cookieList.forEach(item -> {
log.info("Cookie:{}",item);
});
JSONObject userJson = getUserInfo(cookieList);
UserVo userVo = new UserVo();
userVo.setUserId(userJson.getString("user_id"));
userVo.setUserType(userJson.getString("user_type"));
userVo.setUserName(userJson.getString("user_name"));
userVo.setPhone(userJson.getString("phone"));
userVo.setEmail(userJson.getString("email"));
String userId = userVo.getUserId();
if (StringUtils.isBlank(userId)) {
ResponseUtil.returnBaseResponse(response, CodeEnum.NOT_LOGIN);
return;
}
String userName = userVo.getUserName();
// 用户类型;1:超管
String userType = userVo.getUserType();
request.setAttribute(LoginConstants.COOKIE_NAME, cookieList);
request.setAttribute(LoginConstants.USER_ID, userId);
request.setAttribute(LoginConstants.USER_NAME, userName);
request.setAttribute(LoginConstants.USER_TYPE, userType);
log.info("----------------鉴权结束------------------------");
filterChain.doFilter(request, response);
} catch (Exception ex) {
log.error("authenticationFilter Exception: ", ex);
ResponseUtil.returnBaseResponse(response, CodeEnum.NOT_LOGIN);
}
}
/**
* 获取用户登录接口
* @param cookieList cookie数据
* @return 用户数据
*/
private JSONObject getUserInfo(List<String> cookieList){
JSONObject userJson = new JSONObject();
HttpHeaders headers = new HttpHeaders();
headers.put(HttpHeaders.COOKIE, cookieList);
RestTemplate restTemplate = ApplicationContextUtil.getBean(RestTemplate.class);
CommonConfig config = ApplicationContextUtil.getBean(CommonConfig.class);
String url = config.getXcCoreHost() + USER_INFO_API_URL;
log.info("调用xc-core用户登录接口地址:{}", url);
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<>(headers),JSONObject.class);
log.info("调用xc-core用户登录接口返回结果为:{},{}", responseEntity.getBody(), responseEntity.getStatusCodeValue());
if(HttpStatus.OK.value() == responseEntity.getStatusCodeValue()){
JSONObject resultJson = responseEntity.getBody();
if (resultJson == null) {
return userJson;
}
userJson = resultJson.getJSONObject("data");
log.debug("----------- userJson -> {}", userJson);
}
return userJson;
}
}
package com.beagle.base.common.filter;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* @author wuwanli
*/
public class LogbackFilter implements Filter {
private static final String TRACE_ID = "traceId";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
boolean result = this.insertMdc();
try {
filterChain.doFilter(servletRequest, servletResponse);
} finally {
if (result) {
MDC.remove(TRACE_ID);
}
}
}
private boolean insertMdc() {
try {
MDC.put(TRACE_ID, UUID.randomUUID().toString().replace("-", ""));
return true;
} catch (Exception exception) {
return false;
}
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
package com.beagle.base.common.util;
import cn.hutool.core.collection.CollUtil;
import com.beagle.base.BasePointsPropertiesNewParam;
import com.beagle.base.bean.vo.BasePointsPropertiesParam;
import com.beagle.base.bean.vo.BaseSearchParam;
import com.beagle.base.bean.vo.BaseSearchPointCountParam;
import com.beagle.base.bean.vo.BaseTableTagNamesParam;
import com.rtdb.model.Entity;
import com.rtdb.model.FullPoint;
import com.rtdb.model.MinPoint;
import java.util.ArrayList;
import java.util.List;
public class BaseUtil {
public static int[] search(BaseSearchParam param) {
int [] res = null;
try {
res = CommonUtil.getBaseImpl().search(param.getCondition(), param.getCount(), param.getSort());
if (res != null) {
return res;
}
return new int[]{};
}catch (Exception e) {
e.printStackTrace();
return new int[]{};
}
}
// 获取测点全属性
public static List<FullPoint> getPointsProperties(BasePointsPropertiesParam param) {
List<FullPoint> res = new ArrayList<>();
try {
Entity<FullPoint> entity = null;
entity = CommonUtil.getBaseImpl().getPointsProperties(param.getIds());
if (entity != null & CollUtil.isNotEmpty(entity.getList())) {
res = entity.getList();
}
return res;
}catch (Exception e){
e.printStackTrace();
return res;
}
}
public static Integer searchPointCount(BaseSearchPointCountParam param) {
int res = 0;
try {
res = CommonUtil.getBaseImpl().searchPointCount(param.getCondition(), param.getSort());
}catch (Exception e){
e.printStackTrace();
return res;
}
return res;
}
public static String[] getTableTagNames(BaseTableTagNamesParam param) {
String [] res = null;
try {
res = CommonUtil.getBaseImpl().getTableTagNames(param.getIds());
}catch (Exception e){
e.printStackTrace();
res = new String[0];
return res;
}
return res;
}
public static List<MinPoint> getPointsPropertiesTags(BasePointsPropertiesNewParam param) {
List<MinPoint> res = new ArrayList<>();;
try {
Entity<MinPoint> pointsProperties = CommonUtil.getBaseImpl().getPointsProperties(param.getTagName());
if (pointsProperties != null && CollUtil.isNotEmpty(pointsProperties.getList())) {
res = pointsProperties.getList();
}
}catch (Exception e){
e.printStackTrace();
return res;
}
return res;
}
}
package com.beagle.base.common.util;
import com.beagle.base.common.contant.CodeEnum;
import com.beagle.base.common.exception.BeagleException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.util.CollectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author SmileCircle
*/
public final class BeanUtil extends org.springframework.beans.BeanUtils {
private BeanUtil() {
}
public interface Callback<T, R> {
/**
* 回调方法
*
* @param source
* @param targetClass
* @return
*/
void doCallback(T source, R targetClass);
}
public static <T, R> R convert(T source, Class<R> targetClass, Callback<T, R>
callback, String... ignoreProperties) {
if (source == null) {
return null;
} else {
R target = null;
try {
target = targetClass.newInstance();
} catch (IllegalAccessException | InstantiationException var4) {
throw new BeagleException(CodeEnum.UNKNOWN);
}
copyProperties(source, target, ignoreProperties);
if (callback != null) {
callback.doCallback(source, target);
}
return target;
}
}
public static <T, R> R convert(T source, Class<R> targetClass, Callback<T, R> callback) {
return convert(source, targetClass, callback, (String[]) null);
}
public static <T, R> R convert(T source, Class<R> targetClass, String... ignoreProperties) {
return convert(source, targetClass, null, ignoreProperties);
}
public static <T, R> R convert(T source, Class<R> targetClass) {
return convert(source, targetClass, null, (String[]) null);
}
public static <T, R> List<R> convertList(Collection<T> collection, Class<R> targetType, Callback<T, R> callback, String... ignoreProperties) {
if (CollectionUtils.isEmpty(collection)) {
return new ArrayList<>();
} else {
List newList = new ArrayList(collection.size());
collection.forEach(item -> newList.add(convert(item, targetType, callback, ignoreProperties)));
return newList;
}
}
public static <T, R> List<R> convertList(Collection<T> collection, Class<R> targetType, String... ignoreProperties) {
return convertList(collection, targetType, null, ignoreProperties);
}
public static <T, R> List<R> convertList(Collection<T> collection, Class<R> targetType, Callback<T, R> callback) {
return convertList(collection, targetType, callback, (String[]) null);
}
public static <T, R> List<R> convertList(Collection<T> collection, Class<R> targetType) {
return convertList(collection, targetType, null, (String[]) null);
}
public static <T, R> Set<R> convertSet(Collection<T> collection, Class<R> targetType, Callback<T, R> callback, String... ignoreProperties) {
if (CollectionUtils.isEmpty(collection)) {
return new HashSet<>();
} else {
Set newSet = new HashSet(collection.size());
collection.forEach(item -> newSet.add(convert(item, targetType, callback, ignoreProperties)));
return newSet;
}
}
public static <T, R> Set<R> convertSet(Collection<T> collection, Class<R> targetType, String... ignoreProperties) {
return convertSet(collection, targetType, null, ignoreProperties);
}
public static <T, R> Set<R> convertSet(Collection<T> collection, Class<R> targetType, Callback<T, R> callback) {
return convertSet(collection, targetType, callback, (String[]) null);
}
public static <T, R> Set<R> convertSet(Collection<T> collection, Class<R> targetType) {
return convertSet(collection, targetType, null, (String[]) null);
}
public static void copyPropertiesIgnoreEmpty(Object source, Object target) throws BeansException {
PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(source.getClass());
List<String> ignoreProperties = new ArrayList<>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method readMethod = propertyDescriptor.getReadMethod();
try {
Object value = readMethod.invoke(source);
String propertiesName = null;
if(value instanceof Collection) {
if(CollectionUtils.isEmpty((Collection<?>) value)) {
propertiesName = readMethod.getName();
}
} else if (value instanceof String) {
if (StringUtils.isEmpty((CharSequence) value)) {
propertiesName = readMethod.getName();
}
} else {
if (Objects.isNull(value)) {
propertiesName = readMethod.getName();
}
}
if(StringUtils.isNotEmpty(propertiesName)) {
if(StringUtils.startsWith(propertiesName, "get")) {
propertiesName = propertiesName.substring(3);
} else if (StringUtils.startsWith(propertiesName, "is")) {
propertiesName = propertiesName.substring(2);
}
String firstName = propertiesName.substring(0, 1);
String otherName = propertiesName.substring(1);
propertiesName = firstName.toLowerCase(Locale.ROOT) + otherName;
ignoreProperties.add(propertiesName);
}
} catch (IllegalAccessException | InvocationTargetException e) {
throw new BeagleException(CodeEnum.UNKNOWN);
}
}
copyProperties(source, target, ignoreProperties.toArray(new String[0]));
}
}
package com.beagle.base.common.util;
import cn.hutool.core.text.CharSequenceUtil;
import com.rtdb.service.impl.*;
import com.rtdb.service.inter.Base;
import com.rtdb.service.inter.Historian;
import com.rtdb.service.inter.Snapshot;
public class CommonUtil {
private static final String IP = CharSequenceUtil.blankToDefault(System.getenv("GOLDEN_IP"), "10.253.1.97");
private static final Integer PORT = Integer.parseInt(CharSequenceUtil.blankToDefault(System.getenv("GOLDEN_PORT"), "6327"));
private static final String USER = CharSequenceUtil.blankToDefault(System.getenv("GOLDEN_USER"), "sa");
private static final String PASSWORD = CharSequenceUtil.blankToDefault(System.getenv("GOLDEN_PASSWORD"), "golden") ;
private static Historian his;
private static Base base;
private static Snapshot snap;
private static ServerImpl server;
private static ServerImplPool pool;
static {
try {
pool = new ServerImplPool(IP, PORT, USER, PASSWORD, 5, 10);
server = pool.getServerImpl();
his = new HistorianImpl(server);
base = new BaseImpl(server);
snap = new SnapshotImpl(server);
}catch (Exception e) {
e.printStackTrace();
}
}
public static Historian getHisImpl() {
return his;
}
public static Base getBaseImpl() {
return base;
}
public static Snapshot getSnapshotImpl() {
return snap;
}
}
package com.beagle.base.common.util;
import cn.hutool.core.collection.CollUtil;
import com.beagle.base.bean.vo.HistorianDoubleArchivedValuesParam;
import com.beagle.base.bean.vo.HistorianFloatArchivedValuesFiltParam;
import com.beagle.base.bean.vo.HistorianFloatInterpoValuesParam;
import com.beagle.base.bean.vo.HistorianFloatIntervalValuesParam;
import com.rtdb.model.DoubleData;
import java.util.ArrayList;
import java.util.List;
public class HistorianUtil {
public static List<DoubleData> getFloatIntervalValues(HistorianFloatIntervalValuesParam param ) {
List<DoubleData> res;
try {
res = CommonUtil.getHisImpl().getFloatIntervalValues(param.getId(), param.getInterval(), param.getCount(), param.getDateTime());
if (CollUtil.isNotEmpty(res)) {
return res;
}
return new ArrayList<>();
}catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
public static List<DoubleData> getFloatInterpoValues(HistorianFloatInterpoValuesParam param) {
List<DoubleData> res;
try {
res = CommonUtil.getHisImpl().getFloatInterpoValues(param.getId(), param.getCount(), param.getStartTime(), param.getEndTime());
if (CollUtil.isNotEmpty(res)) {
return res;
}
return new ArrayList<>();
}catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
public static List<DoubleData> getFloatArchivedValuesFilt(HistorianFloatArchivedValuesFiltParam param) {
List<DoubleData> res;
try {
res = CommonUtil.getHisImpl().getFloatArchivedValuesFilt(param.getId(), param.getFilter(), param.getCount(), param.getStartTime(), param.getEndTime());
if (CollUtil.isNotEmpty(res)) {
return res;
}
return new ArrayList<>();
}catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
public static List<DoubleData> getDoubleArchivedValues(HistorianDoubleArchivedValuesParam param) {
List<DoubleData> res;
try {
res = CommonUtil.getHisImpl().getDoubleArchivedValues(param.getId(), param.getCount(), param.getStartTime(), param.getEndTime());
if (CollUtil.isNotEmpty(res)) {
return res;
}
return new ArrayList<>();
}catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
}
package com.beagle.base.common.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson2.JSONObject;
import com.beagle.base.common.contant.CodeEnum;
import lombok.extern.slf4j.Slf4j;
/**
* @author wuwanli
*/
@Slf4j
public class ResponseUtil {
/**
* 封装返回报文
*
* @param response
* 返回对象
*/
public static void returnBaseResponse(HttpServletResponse response, CodeEnum codeEnum) {
PrintWriter writer = null;
try {
Map<String, String> baseResponse = new HashMap<>(10);
baseResponse.put("code", codeEnum.getCode());
baseResponse.put("desc", codeEnum.getDesc());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
writer = response.getWriter();
writer.print(JSONObject.toJSONString(baseResponse));
} catch (IOException ex) {
log.error("returnBaseResponse Fail:", ex);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
package com.beagle.base.common.util;
import cn.hutool.core.collection.CollUtil;
import com.beagle.base.bean.vo.SnapshotBlobParam;
import com.beagle.base.bean.vo.SnapshotCoorParam;
import com.beagle.base.bean.vo.SnapshotDoubleParam;
import com.beagle.base.bean.vo.SnapshotIntParam;
import com.rtdb.model.*;
import java.util.ArrayList;
import java.util.List;
public class SnapshotUtil {
public static List<DoubleData> getDoubleSnapshots(SnapshotDoubleParam param) {
List<DoubleData> res = new ArrayList<>();
try {
Entity<DoubleData> d = CommonUtil.getSnapshotImpl().getDoubleSnapshots(param.getIds());
if (d != null && CollUtil.isNotEmpty(d.getList())) {
res = d.getList();
}
return res;
}catch (Exception e) {
e.printStackTrace();
return res;
}
}
public static List<IntData> getIntSnapshots(SnapshotIntParam param) {
List<IntData> res = new ArrayList<>();
try {
Entity<IntData> intSnapshots = CommonUtil.getSnapshotImpl().getIntSnapshots(param.getIds());
if (intSnapshots != null && CollUtil.isNotEmpty(intSnapshots.getList())) {
res = intSnapshots.getList();
}
return res;
}catch (Exception e) {
e.printStackTrace();
return res;
}
}
public static List<BlobData> getBlobSnapshots(SnapshotBlobParam param) {
List<BlobData> res = new ArrayList<>();
try {
Entity<BlobData> blobSnapshots = CommonUtil.getSnapshotImpl().getBlobSnapshots(param.getIds());
if (blobSnapshots != null && CollUtil.isNotEmpty(blobSnapshots.getList())) {
res = blobSnapshots.getList();
}
return res;
}catch (Exception e) {
e.printStackTrace();
return res;
}
}
public static List<CoorData> getCoorSnapshots(SnapshotCoorParam param) {
List<CoorData> res = new ArrayList<>();
try {
Entity<CoorData> coorSnapshots = CommonUtil.getSnapshotImpl().getCoorSnapshots(param.getIds());
if (coorSnapshots != null && CollUtil.isNotEmpty(coorSnapshots.getList())) {
res = coorSnapshots.getList();
}
return res;
}catch (Exception e) {
e.printStackTrace();
return res;
}
}
}
package com.beagle.base.common.util;
import java.util.Iterator;
import java.util.Map;
/**
* @author wuwanli
*/
public class StringUtils {
public static String strip(String str) {
return org.apache.commons.lang3.StringUtils.strip(str);
}
public static String trim(String str) {
return org.apache.commons.lang3.StringUtils.trim(str);
}
public static boolean isNotBlank(CharSequence cs) {
return org.apache.commons.lang3.StringUtils.isNotBlank(cs);
}
public static boolean isBlank(CharSequence cs) {
return org.apache.commons.lang3.StringUtils.isBlank(cs);
}
public static String getRestUrlByMap(String url, Map paramMap){
StringBuffer stringBuffer = new StringBuffer(url);
Iterator iterator = paramMap.entrySet().iterator();
if (iterator.hasNext()) {
stringBuffer.append("?");
Object element;
while (iterator.hasNext()) {
element = iterator.next();
Map.Entry<String, Object> entry = (Map.Entry) element;
//过滤value为null,value为null时进行拼接字符串会变成 "null"字符串
if (entry.getValue() != null) {
stringBuffer.append(element).append("&");
}
url = stringBuffer.substring(0, stringBuffer.length() - 1);
}
}
return url;
}
}
package com.beagle.base.controller;
import com.beagle.base.BasePointsPropertiesNewParam;
import com.beagle.base.bean.vo.BasePointsPropertiesParam;
import com.beagle.base.bean.vo.BaseSearchParam;
import com.beagle.base.bean.vo.BaseSearchPointCountParam;
import com.beagle.base.bean.vo.BaseTableTagNamesParam;
import com.beagle.base.bean.vo.resp.Response;
import com.beagle.base.service.BaseService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rtdb.model.FullPoint;
import com.rtdb.model.MinPoint;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 数据库字段加密、防篡改接口
*
* @author lzz
*/
@Api(tags = "基本信息点服务实现类")
@RestController
@RequestMapping("/v1/base")
public class BaseController {
@Resource
private BaseService baseService;
@ApiOperationSupport(order = 1)
@ApiOperation(value = "在表中搜索符合条件的标签点,使用标签点名时支持通配符")
@PostMapping("/search")
public Response<int[]> search(@RequestBody @ApiParam(value = "入参") @Validated BaseSearchParam param) {
return new Response<>(baseService.search(param));
}
@ApiOperationSupport(order = 2)
@ApiOperation(value = "根据ids批量获取标签点属性")
@PostMapping("/getPointsProperties")
public Response<List<FullPoint>> getPointsProperties(@RequestBody @ApiParam(value = "入参") @Validated BasePointsPropertiesParam param) {
return new Response<>(baseService.getPointsProperties(param));
}
@ApiOperationSupport(order = 3)
@ApiOperation(value = "根据ids批量获取标签点属性")
@PostMapping("/searchPointCount")
public Response<Integer> searchPointCount(@RequestBody @ApiParam(value = "入参") @Validated BaseSearchPointCountParam param) {
return new Response<>(baseService.searchPointCount(param));
}
@ApiOperationSupport(order = 4)
@ApiOperation(value = "根据标签点ids获取测点全名称")
@PostMapping("/getTableTagNames")
public Response<String []> getTableTagNames(@RequestBody @ApiParam(value = "入参") @Validated BaseTableTagNamesParam param) {
return new Response<>(baseService.getTableTagNames(param));
}
@ApiOperationSupport(order = 5)
@ApiOperation(value = "根据标签点ids获取测点全名称")
@PostMapping("/getPointsProperties/tags")
public Response<List<MinPoint>> getPointsPropertiesTags(@RequestBody @ApiParam(value = "入参") @Validated BasePointsPropertiesNewParam param) {
return new Response<>(baseService.getPointsPropertiesTags(param));
}
}
package com.beagle.base.controller;
import com.beagle.base.bean.vo.HistorianDoubleArchivedValuesParam;
import com.beagle.base.bean.vo.HistorianFloatArchivedValuesFiltParam;
import com.beagle.base.bean.vo.HistorianFloatInterpoValuesParam;
import com.beagle.base.bean.vo.HistorianFloatIntervalValuesParam;
import com.beagle.base.bean.vo.resp.Response;
import com.beagle.base.service.HistorianService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rtdb.model.DoubleData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Nonnull;
import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
/**
* 数据库字段加密、防篡改接口
*
* @author lzz
*/
@Api(tags = "历史服务接口实现类")
@RestController
@RequestMapping("/v1/historian")
public class HistorianController {
@Resource
private HistorianService historianService;
@ApiOperationSupport(order = 1)
@ApiOperation(value = "读取单个标签点某个时刻之后一定数量的等间隔内插值替换的历史数值")
@PostMapping("/getFloatIntervalValues")
public Response<List<DoubleData>> getFloatIntervalValues(@RequestBody @ApiParam(value = "入参") @Validated HistorianFloatIntervalValuesParam param) {
return new Response<>(historianService.getFloatIntervalValues(param));
}
@ApiOperationSupport(order = 2)
@ApiOperation(value = "获取单个浮点类型标签点一段时间内等间隔历史插值")
@PostMapping("/getFloatInterpoValues")
public Response<List<DoubleData>> getFloatInterpoValues(@RequestBody @ApiParam(value = "入参") @Validated HistorianFloatInterpoValuesParam param) {
return new Response<>(historianService.getFloatInterpoValues(param));
}
@ApiOperationSupport(order = 3)
@ApiOperation(value = "读取单个浮点类型标签点在一段时间内经复杂条件筛选后的历史储存值")
@PostMapping("/getFloatArchivedValuesFilt")
public Response<List<DoubleData>> getFloatArchivedValuesFilt(@RequestBody @ApiParam(value = "入参") @Validated HistorianFloatArchivedValuesFiltParam param) {
return new Response<>(historianService.getFloatArchivedValuesFilt(param));
}
@ApiOperationSupport(order = 4)
@ApiOperation(value = "读取单个浮点类型标签点一段时间内的储存数据")
@PostMapping("/getDoubleArchivedValues")
public Response<List<DoubleData>> getDoubleArchivedValues(@RequestBody @ApiParam(value = "入参") @Validated HistorianDoubleArchivedValuesParam param) {
return new Response<>(historianService.getDoubleArchivedValues(param));
}
}
package com.beagle.base.controller;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = "服务心跳探针接口")
@RequestMapping("/index")
public class IndexController {
@GetMapping("/index")
@ApiOperationSupport(order = 1)
@ApiOperation(value = "服务心跳探针接口")
public String index() {
return "ok";
}
}
package com.beagle.base.controller;
import com.beagle.base.bean.vo.*;
import com.beagle.base.bean.vo.resp.Response;
import com.beagle.base.service.SnapshotService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rtdb.model.BlobData;
import com.rtdb.model.CoorData;
import com.rtdb.model.DoubleData;
import com.rtdb.model.IntData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* 数据库字段加密、防篡改接口
*
* @author lzz
*/
@Api(tags = "快照服务接口方法实现")
@RestController
@RequestMapping("/v1/snapshot")
public class SnapshotController {
@Resource
private SnapshotService snapshotService;
@ApiOperationSupport(order = 1)
@ApiOperation(value = "批量获取标签点类型为双精度浮点型的快照值(纳秒标签点)")
@PostMapping("/getDoubleSnapshots")
public Response<List<DoubleData>> getDoubleSnapshots(@RequestBody @ApiParam(value = "入参") @Validated SnapshotDoubleParam param) {
return new Response<>(snapshotService.getDoubleSnapshots(param));
}
@ApiOperationSupport(order = 2)
@ApiOperation(value = "批量读取开关量、模拟量快照数值")
@PostMapping("/getIntSnapshots")
public Response<List<IntData>> getIntSnapshots(@RequestBody @ApiParam(value = "入参") @Validated SnapshotIntParam param) {
return new Response<>(snapshotService.getIntSnapshots(param));
}
@ApiOperationSupport(order = 3)
@ApiOperation(value = "批量获取标签点类型为Blob/String型的快照值")
@PostMapping("/getBlobSnapshots")
public Response<List<BlobData>> getBlobSnapshots(@RequestBody @ApiParam(value = "入参") @Validated SnapshotBlobParam param) {
return new Response<>(snapshotService.getBlobSnapshots(param));
}
@ApiOperationSupport(order = 4)
@ApiOperation(value = "批量获取标签点类型为坐标类型的快照值")
@PostMapping("/getCoorSnapshots")
public Response<List<CoorData>> getCoorSnapshots(@RequestBody @ApiParam(value = "入参") @Validated SnapshotCoorParam param) {
return new Response<>(snapshotService.getCoorSnapshots(param));
}
}
package com.beagle.base.service;
import com.beagle.base.BasePointsPropertiesNewParam;
import com.beagle.base.bean.vo.BasePointsPropertiesParam;
import com.beagle.base.bean.vo.BaseSearchParam;
import com.beagle.base.bean.vo.BaseSearchPointCountParam;
import com.beagle.base.bean.vo.BaseTableTagNamesParam;
import com.rtdb.model.FullPoint;
import com.rtdb.model.MinPoint;
import java.util.List;
/**
* @author lzz
*/
public interface BaseService {
int[] search(BaseSearchParam param);
List<FullPoint> getPointsProperties(BasePointsPropertiesParam param);
Integer searchPointCount(BaseSearchPointCountParam param);
String[] getTableTagNames(BaseTableTagNamesParam param);
List<MinPoint> getPointsPropertiesTags(BasePointsPropertiesNewParam param);
}
package com.beagle.base.service;
import com.beagle.base.bean.vo.HistorianDoubleArchivedValuesParam;
import com.beagle.base.bean.vo.HistorianFloatArchivedValuesFiltParam;
import com.beagle.base.bean.vo.HistorianFloatInterpoValuesParam;
import com.beagle.base.bean.vo.HistorianFloatIntervalValuesParam;
import com.rtdb.model.DoubleData;
import java.util.List;
import java.util.Map;
/**
* @author lzz
*/
public interface HistorianService {
List<DoubleData> getFloatIntervalValues(HistorianFloatIntervalValuesParam param);
List<DoubleData> getFloatInterpoValues(HistorianFloatInterpoValuesParam param);
List<DoubleData> getFloatArchivedValuesFilt(HistorianFloatArchivedValuesFiltParam param);
List<DoubleData> getDoubleArchivedValues(HistorianDoubleArchivedValuesParam param);
}
package com.beagle.base.service;
import com.beagle.base.bean.vo.SnapshotBlobParam;
import com.beagle.base.bean.vo.SnapshotCoorParam;
import com.beagle.base.bean.vo.SnapshotDoubleParam;
import com.beagle.base.bean.vo.SnapshotIntParam;
import com.rtdb.model.BlobData;
import com.rtdb.model.CoorData;
import com.rtdb.model.DoubleData;
import com.rtdb.model.IntData;
import java.util.List;
/**
* @author lzz
*/
public interface SnapshotService {
List<DoubleData> getDoubleSnapshots(SnapshotDoubleParam param);
List<IntData> getIntSnapshots(SnapshotIntParam param);
List<BlobData> getBlobSnapshots(SnapshotBlobParam param);
List<CoorData> getCoorSnapshots(SnapshotCoorParam param);
}
package com.beagle.base.service.impl;
import com.beagle.base.BasePointsPropertiesNewParam;
import com.beagle.base.bean.vo.BasePointsPropertiesParam;
import com.beagle.base.bean.vo.BaseSearchParam;
import com.beagle.base.bean.vo.BaseSearchPointCountParam;
import com.beagle.base.bean.vo.BaseTableTagNamesParam;
import com.beagle.base.common.util.BaseUtil;
import com.beagle.base.service.BaseService;
import com.rtdb.model.FullPoint;
import com.rtdb.model.MinPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author lzz
*/
@Service
@Slf4j
public class BaseServiceImpl implements BaseService {
@Override
public int[] search(BaseSearchParam param) {
return BaseUtil.search(param);
}
@Override
public List<FullPoint> getPointsProperties(BasePointsPropertiesParam param) {
return BaseUtil.getPointsProperties(param);
}
@Override
public Integer searchPointCount(BaseSearchPointCountParam param) {
return BaseUtil.searchPointCount(param);
}
@Override
public String[] getTableTagNames(BaseTableTagNamesParam param) {
return BaseUtil.getTableTagNames(param);
}
@Override
public List<MinPoint> getPointsPropertiesTags(BasePointsPropertiesNewParam param) {
return BaseUtil.getPointsPropertiesTags(param);
}
}
package com.beagle.base.service.impl;
import com.beagle.base.bean.vo.HistorianDoubleArchivedValuesParam;
import com.beagle.base.bean.vo.HistorianFloatArchivedValuesFiltParam;
import com.beagle.base.bean.vo.HistorianFloatInterpoValuesParam;
import com.beagle.base.bean.vo.HistorianFloatIntervalValuesParam;
import com.beagle.base.common.util.HistorianUtil;
import com.beagle.base.service.HistorianService;
import com.rtdb.model.DoubleData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author lzz
*/
@Service
@Slf4j
public class HistorianServiceImpl implements HistorianService {
@Override
public List<DoubleData> getFloatIntervalValues(HistorianFloatIntervalValuesParam param) {
return HistorianUtil.getFloatIntervalValues(param);
}
@Override
public List<DoubleData> getFloatInterpoValues(HistorianFloatInterpoValuesParam param) {
return HistorianUtil.getFloatInterpoValues(param);
}
@Override
public List<DoubleData> getFloatArchivedValuesFilt(HistorianFloatArchivedValuesFiltParam param) {
return HistorianUtil.getFloatArchivedValuesFilt(param);
}
@Override
public List<DoubleData> getDoubleArchivedValues(HistorianDoubleArchivedValuesParam param) {
return HistorianUtil.getDoubleArchivedValues(param);
}
}
package com.beagle.base.service.impl;
import com.beagle.base.bean.vo.SnapshotBlobParam;
import com.beagle.base.bean.vo.SnapshotCoorParam;
import com.beagle.base.bean.vo.SnapshotDoubleParam;
import com.beagle.base.bean.vo.SnapshotIntParam;
import com.beagle.base.common.util.SnapshotUtil;
import com.beagle.base.service.SnapshotService;
import com.rtdb.model.BlobData;
import com.rtdb.model.CoorData;
import com.rtdb.model.DoubleData;
import com.rtdb.model.IntData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author lzz
*/
@Service
@Slf4j
public class SnapshotServiceImpl implements SnapshotService {
@Override
public List<DoubleData> getDoubleSnapshots(SnapshotDoubleParam param) {
return SnapshotUtil.getDoubleSnapshots(param);
}
@Override
public List<IntData> getIntSnapshots(SnapshotIntParam param) {
return SnapshotUtil.getIntSnapshots(param);
}
@Override
public List<BlobData> getBlobSnapshots(SnapshotBlobParam param) {
return SnapshotUtil.getBlobSnapshots(param);
}
@Override
public List<CoorData> getCoorSnapshots(SnapshotCoorParam param) {
return SnapshotUtil.getCoorSnapshots(param);
}
}
server:
port: 8080
servlet:
context-path: ${DATA_COMPUTING_ROUTE_PREFIX:/sdk/golden/api}
spring:
servlet:
multipart:
max-request-size: 5MB
max-file-size: 5MB
# max-file-size 用于限制单个文件的最大上传大小,而 max-request-size 用于限制整个请求体的大小,包括所有文件和其他表单字段的大小。
mvc:
pathmatch:
#Springfox 使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
matching-strategy: ant_path_matcher
logging:
config: classpath:log4j2.xml
# 接口文档配置
knife4j:
enable: true
basic:
enable: true
username: admin
password: Aa123456
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<!-- 控制台输出配置 -->
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<!-- 文件输出配置 -->
<File name="FileLogger" fileName="logs/app.log" append="true">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</File>
<!-- 也可以使用 RollingFile 输出配置,这样日志文件会根据大小进行滚动 -->
<RollingFile name="RollingFileLogger" fileName="logs/app-rolling.log"
filePattern="logs/app-rolling-%d{yyyy-MM-dd}-%i.log.gz" append="true">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<SizeBasedTriggeringPolicy size="10MB"/>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<!-- Root logger 设置 -->
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="FileLogger"/>
<AppenderRef ref="RollingFileLogger"/> <!-- 如果使用了 RollingFile -->
</Root>
<!-- 你可以为特定的包或类定义 Logger -->
<Logger name="com.example.myapp" level="debug" additivity="false">
<AppenderRef ref="FileLogger"/>
<AppenderRef ref="Console"/>
</Logger>
<!-- 其他 Logger -->
<Logger name="org.springframework" level="warn"/>
<Logger name="io.netty" level="warn"/>
</Loggers>
</Configuration>
\ No newline at end of file
import com.alibaba.fastjson2.JSON;
import com.beagle.base.BasePointsPropertiesNewParam;
import com.beagle.base.bean.vo.BaseSearchPointCountParam;
import com.beagle.base.bean.vo.resp.Response;
import com.rtdb.api.enums.SearchMask;
import com.rtdb.enums.DataSort;
import com.rtdb.enums.Quality;
import com.rtdb.enums.TagType;
import com.rtdb.enums.ValueType;
import com.rtdb.model.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Test {
public static void main(String[] args) {
testMinPoint();
}
private static void testDoubleData() {
List<DoubleData> list = new ArrayList<>();
DoubleData doubleData = new DoubleData();
doubleData.setId(1);
doubleData.setError(11);
doubleData.setNanosecond(1111111);
doubleData.setQuality(Short.parseShort("1"));
doubleData.setValue(Double.parseDouble("12.3"));
doubleData.setDateTime(Calendar.getInstance().getTime());
list.add(doubleData);
System.out.println(JSON.toJSONString(new Response<>(list)));
}
private static void testBlobData() {
List<BlobData> list = new ArrayList<>();
BlobData doubleData = new BlobData();
doubleData.setId(1);
doubleData.setError(11);
doubleData.setNanosecond(1111111);
doubleData.setQuality(Quality.BAD);
doubleData.setBlob("测试".getBytes(StandardCharsets.UTF_8));
doubleData.setDatetime(Calendar.getInstance().getTime());
doubleData.setLen(1);
list.add(doubleData);
System.out.println(JSON.toJSONString(new Response<>(list)));
}
private static void testCoorData() {
List<CoorData> list = new ArrayList<>();
CoorData doubleData = new CoorData();
doubleData.setId(1);
doubleData.setError(11);
doubleData.setNanosecond(1111111);
doubleData.setQuality(Short.parseShort("1"));
doubleData.setX(Float.parseFloat("1.2"));
doubleData.setY(Float.parseFloat("1.4"));
doubleData.setDateTime(Calendar.getInstance().getTime());
list.add(doubleData);
System.out.println(JSON.toJSONString(new Response<>(list)));
}
private static void testBaseSearchPointCountParam() {
SearchConditionTotal searchConditionTotal = new SearchConditionTotal();
searchConditionTotal.set_SearchCondition(SearchMask.SEARCH_ARCHIVE);
searchConditionTotal.set_TimeAccuracy(1);
searchConditionTotal.set_PointType(PointType.ALARM);
searchConditionTotal.setSearchMaskValue("test");
searchConditionTotal.set_ValueTypeString("test");
BaseSearchPointCountParam baseSearchPointCountParam = new BaseSearchPointCountParam();
baseSearchPointCountParam.setCondition(searchConditionTotal);
baseSearchPointCountParam.setSort(DataSort.SORT_BY_ID);
System.out.println(JSON.toJSONString(baseSearchPointCountParam));
}
private static void testSearchPointCount() {
System.out.println(JSON.toJSONString(new Response<>(1)));
}
private static void testGetTableTagNames() {
String[] tag = {"1"};
System.out.println(JSON.toJSONString(new Response<>(tag)));
}
private static void testGetPointsProperties_tags() {
String[] tag = {"1"};
BasePointsPropertiesNewParam basePointsPropertiesNewParam = new BasePointsPropertiesNewParam();
basePointsPropertiesNewParam.setTagName(tag);
System.out.println(JSON.toJSONString(basePointsPropertiesNewParam));
}
public static void testMinPoint() {
List<MinPoint> list = new ArrayList<>();
MinPoint minPoint = new MinPoint();
minPoint.setId(1);
minPoint.setDesc("desc");
minPoint.setTagName("tag name");
minPoint.setTableId(1);
minPoint.setTagType(TagType.ALARM);
minPoint.setValueType(ValueType.RTDB_BLOB);
minPoint.setUseMs(1);
list.add(minPoint);
System.out.println(JSON.toJSONString(new Response<>(list)));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment