Commit 0ec928c3 authored by 王锦盛's avatar 王锦盛

宁夏统一模型管理系统启动

parent aea8cc3b
<?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.4.2</version>
</parent>
<groupId>com.pms.ocp</groupId>
<artifactId>operation-control-platform</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<spring-boot.version>2.4.2</spring-boot.version>
<swagger.version>3.0.0</swagger.version>
<!-- <mybatis-spring-boot.version>2.1.4</mybatis-spring-boot.version>-->
<!-- <pagehelper.boot.version>1.3.1</pagehelper.boot.version>-->
<!-- <fastjson.version>1.2.76</fastjson.version>-->
<!-- <oshi.version>5.8.0</oshi.version>-->
<!-- <jna.version>5.8.0</jna.version>-->
<!-- <commons.io.version>2.10.0</commons.io.version>-->
<!-- <commons.fileupload.version>1.4</commons.fileupload.version>-->
<!-- <poi.version>4.1.2</poi.version>-->
<!-- <velocity.version>1.7</velocity.version>-->
<!-- <lombok.version>1.18.8</lombok.version>-->
<!-- <minio.version>7.0.2</minio.version>-->
<!-- <alipay-sdk-java.version>4.8.10.ALL</alipay-sdk-java.version>-->
<!-- <ali-sms-sdk.version>4.5.0</ali-sms-sdk.version>-->
<knife4j-ui.version>2.0.8</knife4j-ui.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1212</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.16</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<!--文件上传poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.1</version>
</dependency>
<!--EasyPoi导入导出-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.3.0</version>
</dependency>
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- knife4j ui-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-ui</artifactId>
<version>${knife4j-ui.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>uat</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>uat</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>
<build>
<!-- 分环境打包 -->
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<excludes>
<exclude>application-*.properties</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<includes>
<include>application-${spring.profiles.active}.properties</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.pms.ocp.StartApp</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.pms.ocp;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
import springfox.documentation.oas.annotations.EnableOpenApi;
import java.util.TimeZone;
/**
* @Auther: wangjian
* @Date: 2022/2/21 15:48
* @Description:启动类
*/
@SpringBootApplication
@MapperScan(basePackages = {"com.pms.ocp.mapper"})
@ConfigurationPropertiesScan
@EnableOpenApi
public class OcpApplication {
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
SpringApplication.run(OcpApplication.class, args);
}
/**
* 注册分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
return interceptor;
}
}
package com.pms.ocp.common.aspectj;
import java.lang.annotation.*;
/**
* @Auther: wangjian
* @Date: 2022/3/8 17:17
* @Description:
*/
@Target(ElementType.METHOD) //target用于标识此注解能标记在方法上还是类上
@Retention(RetentionPolicy.RUNTIME) //retention用于决定此注解的生命周期
@Documented
public @interface OperLog {
/**
* 日志内容
*/
String value() default "";
/**
* 日志类型(1登录日志,2操作日志)
*/
int auditType() default 2;
/**
* 操作日志类型 1查询2添加3修改4删除
*/
int operStatus() default 0;
}
package com.pms.ocp.common.aspectj;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.pms.ocp.model.entity.ModelAudit;
import com.pms.ocp.service.ModelAuditService;
import org.apache.commons.lang3.StringUtils;
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.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
/**
* @Auther: wangjian
* @Date: 2022/3/8 17:21
* @Description:
*/
@Aspect
@Component
public class OperLogAspect {
@Autowired
private ModelAuditService modelAuditService;
private static Logger logger = LoggerFactory.getLogger(OperLogAspect.class);
@Pointcut("@annotation(com.pms.ocp.common.aspectj.OperLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
System.out.println("日志");
//执行方法
Object result = point.proceed();
//执行时长
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveSysLog(point, time, result);
return result;
}
private void saveSysLog(ProceedingJoinPoint point, long time, Object obj) {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
ModelAudit modelAudit = new ModelAudit();
OperLog operLog = method.getAnnotation(OperLog.class);
if (operLog != null) {
String content = operLog.value();
modelAudit.setAuditType(operLog.auditType());
modelAudit.setAuditMessageJson(content);
}
//请求的方法名
// String className = point.getTarget().getClass().getName();
String methodName = signature.getName();
// dto.setMethod(className + "." + methodName + "()");
//设置操作类型
if (modelAudit.getAuditType() == 3) {
modelAudit.setOperStatus(getOperateType(methodName, operLog.operStatus()));
}
//获取request
HttpServletRequest request = getHttpServletRequest();
//请求的参数
modelAudit.setAuditMessageJson(getRequestParams(request, point));
// //设置ip地址
// dto.setIp(getIpAddr(request));
//获取用户登录信息
// TODO
// TUser user = (TUser) SecurityUtils.getSubject().getPrincipal();
// if (user != null) {
// modelNote.setUserid(user.getUserName());
// modelNote.setUsername(user.getPassWord());
// }
// modelNote.setCostTime(time);
modelAudit.setAuditCtime(LocalDateTime.now());
modelAuditService.createModelAudit(modelAudit);
}
private int getOperateType(String methodName, int operateType) {
if (operateType >= 0) {
return operateType;
}
if (methodName.startsWith("create")) {
return 1;
}
if (methodName.startsWith("update")) {
return 2;
}
return 2;
}
private HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
private String getRequestParams(HttpServletRequest request, JoinPoint joinPoint) {
String httpMethod = request.getMethod();
String param = "";
if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {
Object[] paramArray = joinPoint.getArgs();
Object[] arguments = new Object[paramArray.length];
for (int i = 0; i < paramArray.length; i++) {
if (paramArray[i] instanceof BindingResult || paramArray[i] instanceof ServletRequest || paramArray[i] instanceof ServletResponse || paramArray[i] instanceof MultipartFile) {
continue;
}
arguments[i] = paramArray[i];
}
PropertyFilter propertyFilter = new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
if (value != null && value.toString().length() > 500) {
return false;
}
return true;
}
};
param = JSONObject.toJSONString(arguments, propertyFilter);
} else {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
//请求的方法参数值
Object[] args = joinPoint.getArgs();
//请求的方法名称
LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = u.getParameterNames(method);
if (args != null && parameterNames != null) {
for (int i = 0; i < args.length; i++) {
param += " " + parameterNames[i] + ": " + args[i];
}
}
}
return param;
}
public String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X-FORWARDED-FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IP error", e);
}
return ip;
}
}
package com.pms.ocp.common.component;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Bean 工具类
*
* @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);
}
}
package com.pms.ocp.common.component;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.MDC;
/**
* 日志统一增加traceId
*
* @author wuwanli
* @version 1.0
* @date 2021/8/6
*/
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 {
UUID uuid = UUID.randomUUID();
String uniqueId = uuid.toString().replace("-", "");
MDC.put(TRACE_ID, uniqueId);
return true;
} catch (Exception exception) {
return false;
}
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
package com.pms.ocp.common.config;
import com.pms.ocp.common.component.LogbackFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
/**
* 过滤器配置类
*
* @author wuwanli
* @version 1.0
* @date 2021/8/4
*/
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean<LogbackFilter> getLogbackFilter() {
FilterRegistrationBean<LogbackFilter> logbackFilter = new FilterRegistrationBean<>(new LogbackFilter());
logbackFilter.addUrlPatterns("/*");
logbackFilter.setOrder(Ordered.HIGHEST_PRECEDENCE);
return logbackFilter;
}
}
package com.pms.ocp.common.config;
import lombok.Data;
/**
* @Auther: wangjian
* @Date: 2022/1/13 18:51
* @Description:
*/
@Data
public class PageParam {
private String name;
private String type;
private int pageNum;
private int pageSize;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
package com.pms.ocp.common.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
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.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @Auther: wangjian
* @Date: 2022/2/23 16:24
* @Description:
*/
@Configuration
public class SwaggerConfig {
/**
* 是否开启swagger
*/
@Value("${swagger.enabled}")
private boolean enabled;
/**
* 创建API
*/
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
//是否開啓Swagger
.enable(enabled)
// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo())
//分组名称
.groupName("运营管控平台-模型应用服务库管理1.0版本")
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
.apis(RequestHandlerSelectors.basePackage("com.pms.ocp"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo() {
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("运营管控平台_接口文档")
// 描述
.description("关于模型库、应用库、服务库各管理接口文档")
// 作者信息
.contact(new Contact("", "", ""))
// 版本
.version("版本号: 1.0")
.build();
}
}
package com.pms.ocp.common.constants;
public interface AnalysisConstant {
interface exportOcpApiAuditName{
String OCPAPIAUDIT = "服务大事记.xls";
String OCPAPIAUDITNAME = "服务大事记导出数据";
}
interface exportOcpTenantApiName{
String OCPTENANTAPI = "应用大事记.xls";
String OCPTENANTAPINAME = "应用大事记导出数据";
}
}
package com.pms.ocp.common.constants;
public enum ChooseDateType {
ONE_WEEK(1, "最近一周"),
ONE_MONTH(2, "最近一个月"),
THREE_MONTHS(3, "最近三个月");
private Integer code;
private String desc;
ChooseDateType(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public Integer getCode() {
return code;
}
public String getDesc() {
return desc;
}
public static ChooseDateType getChooseDateType(Integer code) {
ChooseDateType[] values = ChooseDateType.values();
for (ChooseDateType c : values) {
if (c.getCode().equals(code)) {
return c;
}
}
return null;
}
}
package com.pms.ocp.common.constants;
import lombok.Getter;
/**
* @author wuwanli
* @version 1.0
* @date 2021/8/4
*/
public enum CodeEnum {
/**
* 处理成功
*/
SUCCESS("200", "处理成功", true),
/**
* 必填参数为空
*/
REQUIRED_PARAMETER_EMPTY("0", "必填参数为空", false),
/**
* 参数类型错误
*/
PARAMETER_TYPE_ERROR("0", "Parameter type error", false),
/**
* 未登录
*/
NOT_LOGIN("401001", "用户未登录", false),
/**
* 用户名或密码错误
*/
LOGIN_FAIL("401002", "用户名或密码错误", false),
/**
* 无权限访问
*/
NO_PERMISSION("401003", "无权限访问", false),
/**
* 系统异常
*/
UNKNOWN("9999", "System abnormal", false),
/**
* 数据异常
*/
NO_DATA("200", "数据库无数据", false),
UP_DATA_FAIL("401005", "更新失败", false),
INSERT_FAIL("401006", "插入数据失败", false),
DELETE_FAIL("401007", "修改失败", false),
DATA_REPETITION("250", "分类编码或分类名称重复", false);
/**
* 构造函数
*
* @param code 响应码
* @param desc 响应描述
*/
CodeEnum(String code, String desc, boolean success) {
this.code = code;
this.desc = desc;
this.success = success;
}
@Getter
private final String code;
@Getter
private final String desc;
@Getter
private final boolean success;
}
\ No newline at end of file
This diff is collapsed.
package com.pms.ocp.common.constants;
import com.pms.ocp.common.exception.ServiceException;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.regex.Pattern;
public class ExportUtils {
/**
* 校验Header Manipulation
* @param header 参数
* @return 数据
*/
public static String headerManipulation(String header) {
if(StringUtils.isNullOrEmpty(header)){
return header;
}
String regex = "[`~!@#$%^&*()\\+\\=\\{}|:\"?><【】\\/r\\/n]";
Pattern pattern = Pattern.compile(regex);
pattern.matcher(header).replaceAll("").trim();
return header;
}
/**
* 流导出文件至浏览器
*
* @param response
* @param in
* @param fileName
*/
public static void exportWorld(HttpServletResponse response, InputStream in, String fileName) {
OutputStream out = null;
try {
response.reset();
String fileHeaderName = URLEncoder.encode(fileName, Constant.Character.UTF8);
response.setHeader("Content-Disposition", "attachment;filename=" + headerManipulation(fileHeaderName));
response.setContentType("application/msword;charset=UTF-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Access-Control-Allow-Origin", "*");
out = response.getOutputStream();
//定义缓存
byte[] buffer = new byte[1024];
int i;
while ((i = in.read(buffer)) != Constant.Number.MINUS_ZERO) {
out.write(buffer, Constant.Number.ZERO, i);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
throw new ServiceException(com.pms.ocp.common.constants.ResultCode.INTERNAL_SERVER_ERROR);
} finally {
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Workbook导出浏览器
* 文件导出添加跨域 Access-Control-Allow-Origin
* @param response
* @param fileName
* @param workbook
*/
public static void exportExcel(HttpServletResponse response, String fileName, Workbook workbook) {
try {
response.reset();
String fileHeaderName = URLEncoder.encode(fileName, Constant.Character.UTF8);
response.setHeader("Content-Disposition", "attachment;filename=" + headerManipulation(fileHeaderName));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR);
}
}
/**
* 图片导出
*
* @param response
* @param in
* @param fileName
*/
public static void exportPic(HttpServletResponse response, InputStream in, String fileName) {
try {
if (in != null) {
response.reset();
String fileHeaderName = URLEncoder.encode(fileName, Constant.Character.UTF8);
String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase(Locale.ENGLISH);
switch (fileExtensionName) {
case "JEPG":
case "JPG":
response.setContentType("image/jepg;charset=UTF-8");
break;
case "PNG":
response.setContentType("image/png;charset=UTF-8");
break;
case "BMP":
response.setContentType("application/x-bmp;charset=UTF-8");
break;
default:
response.setContentType("application/octet-stream;charset=UTF-8");
break;
}
response.setHeader("Content-Disposition", "attachment;filename=" + headerManipulation(fileHeaderName));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Access-Control-Allow-Origin", "*");
byte[] buffer = new byte[1024];
OutputStream out = response.getOutputStream();
int i;
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
out.flush();
out.close();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new ServiceException(ResultCode.INTERNAL_SERVER_ERROR);
}
}
}
package com.pms.ocp.common.constants;
/**
* 异常枚举类
*/
public enum ResultCode {
/* ============================ 通用错误码 ========================== **/
/**
* 禁止访问 303
**/
PARAMS_NOT(303, "缺少参数"),
/**
* 存在错误参数 304
*/
PARAMS_NOT_RIGHT(304, "存在错误参数"),
/**
* 存在错误测试数据 305
*/
DATA_ERROR(305, "存在错误测试数据"),
/**
* 存在错误测试数据 305
*/
SERVER_ERROR(306, "服务异常"),
/**
* 校验失败 307
**/
VERIFICATION_FAIL(307, "校验失败"),
/**
* 错误请求 400
**/
BAD_REQUEST(400, "错误请求"),
/**
* 未经授权 401
**/
UNAUTHORIZED(401, "未经授权"),
/**
* 禁止访问 403
**/
FORBIDDEN(403, "禁止访问"),
/**
* 连接超时
**/
TIME_OUT(408, "连接超时"),
/**
* Feign连接错误
**/
FEIGN_CONNECT_ERROR(409, "feignClient 连接错误:%s"),
/**
* Feign连接错误
**/
BAD_REQUEST_METHOD(410, "不合法的请求方式"),
/**
* 操作异常 500
**/
INTERNAL_SERVER_ERROR(500, "操作异常"),
/**
* SQL异常
**/
SQL_ERROR_EXCEPTION(501, "SQL执行异常!"),
/**
* 操作失败
**/
OPERATION_FAILURE(507, "操作失败"),
/**
* 日期格式处理异常
**/
DATE_FORMAT_EXCEPTION(508, "日期格式处理异常"),
/**
* 项目启动文件异常
*/
SYSTEM_PROFILE_EXCEPTION(509, "错误的项目启动文件"),
/* ============================ 业务/错误码 start========================== **/
/* ===========================后台系统======================== **/
RECORD_NOT_EXIST(10001, "相关记录不存在!"),
SYS_USER_INVALID(10002, "用户登录已过期!"),
PERMISSION_NOT(10003, "无访问权限!"),
ACCOUNT_NOT(10004, "账号异常!"),
SHIRO_ERROR(10005, "鉴权/授权过程出错!"),
MENU_EXIST(10006, "菜单定义已存在!"),
ROLE_EXIST(10007, "角色定义已存在!"),
CODE_EXIST(10008, "编码已存在!"),
NAME_EXIST(10009, "名称已存在!"),
NO_DELETE(10010, "无法删除,有关联数据!"),
USER_ORGANIZATION_LEVEL_ERROR(10023, "用户组织机构关联层级有误!"),
USER_ORGANIZATION_INFO_ERROR(10024,"用户组织机构信息有误!"),
TOKEN_INVALID(9997, "登录失效,请重新登录!"),
/* ============================ 文件处理 错误码 ========================== **/
FILE_NOT_EXISTS(21001, "文件不存在"),
FILE_MUST_IS_EXCEL(21002, "文件类型必须是excel"),
UPLOAD_EXCEPTION(21003, "上传过程出现异常"),
EXCEL_RULE_NOT_EXISTS(21004, "excel校验规则不存在"),
EXCEL_TEMPLATE_NOT_EXISTS(21005, "excel模板不存在"),
EXCEL_TEMPLATE_NOT_CORRECT(21009, "excel模板不对,请重新下载"),
EXCEL_DATA_NOT_EXISTS(21006, "excle数据不存在"),
EXCEL_NOT_CORRECT(21007, "excel不正确"),
EXCEL_PARSE_CORRECT(21010,"excel解析错误"),
CURRENT_MONTH_NOT_EXISTS(21008, "当前年月数据不存在"),
BATCH_NOT_NEED(21009, "无需批量操作!"),
CELL_IS_NULL(21010, "值不能为空"),
CELL_FORMAT_ERROR(21011, "值格式不正确"),
CELL_MIN_LENGTH_ERROR(21012, "值小于最小长度"),
CELL_MAX_LENGTH_ERROR(21013, "值大于最大长度"),
CELL_REGULAR_ERROR(21014, "值正则验证不通过"),
CELL_OPTION_ERROR(21015, "值不在选项集范围内"),
ROW_DUPLICATE_ERROR(21016, "行重复性校验未通过"),
CELL_DATE_FORMAT_ERROR(21017,"日期范围格式不正确"),
DATA_MISSING_UNITS(21018, "数据缺少单位级别编码"),
PICTURE_NAME_ILLEGAL(21019, "图片名称不合法,请重新上传"),
FILE_MUST_IS_PIC(21020, "图片格式不合法,请重新上传!"),
NAME_CONFLICT(21021, "该组织机构下名称重复,请修改名称!"),
ENCRYPT_ERROR_CODE(21022, "解密失败"),
/* ===========================JoyhrError======================== **/
SIGN_ERROR(80001,"签名验证错误!"),
METHOD_ERROR(80002,"方法不存在!"),
/* ===========================CrmHookError======================== **/
CRM_MEMBER_FOUND_ERROR(81001,"会员信息已存在"),
CRM_MEMBER_NOT_FOUND_ERROR(81002,"会员信息不存在"),
/* =============主系统更改Error ================= **/
MASTER_DATA_RELY_ERROR(90001,"切换系统与中台数据存在数据不匹配"),
RELY_DATA_NOT_MATCH_BASE(90002,"切换系统依赖数据与中台数据存在不匹配数据"),
BUS_DATA_NOT_MATCH_BASE(90003,"切换系统业务数据与中台数据存在不匹配数据"),
DATA_MAPPING_NOT_MATCH_BASE(90004,"切换系统数据映射中数据与中台数据存在不匹配数据"),
/* =============中台大平台系统 ================= **/
LOGIN_TIME_OUT(130001,"登录失效或未登录,请重新登录"),
VERFICATION_CODE_ERROR(130002,"验证码不正确"),
NO_USER(130003,"用户不存在"),
PASSWORD_ERROR(130004,"密码不正确"),
MOBILE_USED(130005,"该手机号码已被注册"),
BANK_ACCOUNT_USED(130006,"该银行账号已被使用"),
OPEN_GOODS_FAIL(130009,"开通失败,请重新开通或联系相关人员"),
PROBATION_GOODS_FAIL(130010,"试用失败,请重新试用或联系相关人员"),
END_GOODS_FAIL(130011,"停用失败,请重新停用或联系相关人员"),
FIND_ORDER_LIST_FAIL(130012,"查询订单列表失败,请重新查询或联系相关人员"),
FIND_BILL_FAIL(130013,"查询账单列表失败,请重新查询或联系相关人员"),
FIND_SIX_MONTH_BILL(130014,"查询近6个月消费失败"),
FIND_MONTH_GOODS(130015,"查询该月份消费情况失败"),
/* =============数据维护 ================= **/
TOTAL_SYNC_RECORD_EXITS(110001,"已执行过全量同步!"),
TOTAL_SYNC_RECORD_NOT_EXITS(110002,"还没执行全量同步!");
public final int statusCode;
public String msg;
ResultCode(int statusCode, String msg) {
this.statusCode = statusCode;
this.msg = msg;
}
public int getStatusCode() {
return statusCode;
}
public String getMessage() {
return msg;
}
public void setMessage(String msg) {
this.msg = msg;
}
}
This diff is collapsed.
package com.pms.ocp.common.exception;
import lombok.Getter;
/**
* @author wuwanli
* @date 2021/8/3
*/
public class BeagleException extends RuntimeException {
/**
* 错误码
*/
@Getter
protected String errorCode;
/**
* 错误信息
*/
@Getter
protected String errorMsg;
public BeagleException() {
super();
}
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(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.pms.ocp.common.exception;
import com.pms.ocp.common.utils.BeagleStringUtils;
import com.pms.ocp.model.vo.BaseResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.pms.ocp.common.constants.CodeEnum;
import lombok.extern.slf4j.Slf4j;
/**
* @author wuwanli
* @version 1.0
* @date 2021/8/5
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = BeagleException.class)
public BaseResponse beagleExceptionHandler(BeagleException beagleException) {
log.error("GlobalExceptionHandler.beagleExceptionHandler", beagleException);
BaseResponse baseResponse = new BaseResponse();
if (BeagleStringUtils.isBlank(beagleException.getErrorCode())) {
baseResponse.setResponseCode(CodeEnum.UNKNOWN);
} else {
baseResponse.setCode(beagleException.getErrorCode());
baseResponse.setDesc(beagleException.getErrorMsg());
}
return baseResponse;
}
@ExceptionHandler(value = Exception.class)
public BaseResponse exceptionHandler(Exception exception) {
log.error("GlobalExceptionHandler.exceptionHandler", exception);
return new BaseResponse(CodeEnum.UNKNOWN);
}
}
package com.pms.ocp.common.exception;
import com.pms.ocp.common.constants.ResultCode;
/**
* @Auther: wangjian
* @Date: 2022/3/11 16:31
* @Description:
*/
public class ServiceException extends RuntimeException {
/**
* 自定义异常枚举类
*/
private ResultCode resultCode;
/**
* 错误码
*/
private int code;
/**
* 错误信息
*/
private String errorMsg;
public ServiceException() {
super();
}
public ServiceException(ResultCode resultCode) {
super("{code:" + resultCode.getStatusCode() + ",errorMsg:" + resultCode.getMessage() + "}");
this.resultCode = resultCode;
this.code = resultCode.getStatusCode();
this.errorMsg = resultCode.getMessage();
}
public ServiceException(int code, String errorMsg) {
super("{code:" + code + ",errorMsg:" + errorMsg + "}");
this.code = code;
this.errorMsg = errorMsg;
}
public ResultCode getErrorEnum() {
return resultCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
package com.pms.ocp.common.handler;
import org.apache.ibatis.type.LocalDateTimeTypeHandler;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
/**
* @Auther: wangjian
* @Date: 2022/3/10 10:10
* @Description:时间类型处理器
*/
public class MYLocalDateTimeTypeHandler extends LocalDateTimeTypeHandler {
// @Override
// public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
// Timestamp timestamp = rs.getTimestamp(columnName);
// Long remindTime = timestamp.getTime();
// return LocalDateTime.ofEpochSecond(remindTime,0, ZoneOffset.ofHours(8));
// }
// @Override
// public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
// Object object = rs.getObject(columnName);
// System.out.println(object);
// if (object instanceof java.sql.Timestamp) {//在这里强行转换,将sql的时间转换为LocalDateTime
// //可以根据自己的需要进行转化
// return LocalDateTime.ofInstant(((Timestamp) object).toInstant(), ZoneOffset.ofHours(0));
// }
// return super.getResult(rs, columnName);
// }
@Override
public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
Object object = rs.getObject(columnName);
if (object == null) {
return null;
}
// System.out.println(object);
// 如有需要 在这里强行转换,将sql的时间转换为LocalDateTime
if (object instanceof java.sql.Timestamp) {
//可以根据自己的需要进行转化
return LocalDateTime.ofInstant(((Timestamp) object).toInstant(), ZoneOffset.ofHours(8));
}
return super.getResult(rs, columnName);
}
}
package com.pms.ocp.common.handler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGTimestamp;
import java.sql.*;
import java.time.LocalDateTime;
/**
* @Auther: wangjian
* @Date: 2022/3/10 09:43
* @Description:
*/
@MappedTypes({LocalDateTime.class})
@MappedJdbcTypes({JdbcType.OTHER})
public class TimestampTypeHandler extends BaseTypeHandler {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
Timestamp p = null;
if (parameter != null) {
if (parameter instanceof LocalDateTime) {
PGTimestamp.valueOf(LocalDateTime.now());
p = PGTimestamp.valueOf((LocalDateTime) parameter);
}
ps.setObject(i, p);
}
}
/**
* Gets the nullable result.
*
* @param rs the rs
* @param columnName Colunm name, when configuration <code>useColumnLabel</code> is <code>false</code>
* @return the nullable result
* @throws SQLException the SQL exception
*/
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
return toFill(rs.getObject(columnName));
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return toFill(rs.getObject(columnIndex));
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return toFill(cs.getObject(columnIndex));
}
private Object toFill(Object v) {
if (v != null) {
if (v instanceof PGTimestamp) {
PGTimestamp p = (PGTimestamp) v;
return p.toLocalDateTime();
} else if (v instanceof Timestamp) {
return ((Timestamp) v).toLocalDateTime();
}
}
return v;
}
}
\ No newline at end of file
package com.pms.ocp.common.utils;
import org.apache.commons.lang3.StringUtils;
/**
* 字符串工具类
*
* @author wuwanli
* @version 1.0
* @date 2021/8/4
*/
public class BeagleStringUtils {
public static boolean isBlank(CharSequence cs) {
return StringUtils.isBlank(cs);
}
public static boolean isEmpty(CharSequence cs) {
return StringUtils.isEmpty(cs);
}
public static boolean isNotBlank(CharSequence cs) {
return StringUtils.isNotBlank(cs);
}
public static boolean isNotEmpty(CharSequence cs) {
return StringUtils.isNotEmpty(cs);
}
}
package com.pms.ocp.common.utils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @Auther: wangjian
* @Date: 2022/3/12 13:29
* @Description:数据结构处理工具类
*/
public class DataStructureHandleUtils {
/**
* List<Map<String, Object>> 到 List<T> 数据转换
*/
public static <T> List<T> setList(final List<Map<String, Object>> srcList, Class<T> clazz) {
List<T> list = new ArrayList<>();
for (int i = 0; i < srcList.size(); i++) {
try {
T t = clazz.newInstance();
Field[] fields = t.getClass().getDeclaredFields();
for (Field field : fields) {
if (!"serialVersionUID".equals(field.getName())) {
//设置对象的访问权限,保证对private的属性的访问
field.setAccessible(true);
//读取配置转换字段名,并从map中取出数据
Object v = srcList.get(i).get(field.getName());
field.set(t, convert(v, field.getType()));
}
}
list.add(t);
} catch (Exception ex) {
ex.toString();
}
}
;
return list;
}
/**
* 字段类型转换
*/
private static <T> T convert(Object obj, Class<T> type) throws ParseException {
if (obj != null && StringUtils.isNotBlank(obj.toString())) {
if (type.equals(String.class)) {
return (T) obj.toString();
} else if (type.equals(BigDecimal.class)) {
return (T) new BigDecimal(obj.toString());
} else if (type.equals(Double.class)) {
return (T) Double.valueOf(obj.toString());
} else if (type.equals(Integer.class)) {
return (T) Integer.valueOf(obj.toString());
} else if (type.equals(Date.class)) {
if (obj != null) {
String timeStr = String.valueOf(obj);
String s[] = timeStr.split("T");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return (T) sdf.parse(s[0] + " " + s[1]);
} else {
return null;
}
} else {
//其他类型转换
return (T) obj.toString();
}
}
return null;
}
}
This diff is collapsed.
package com.pms.ocp.common.utils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
/**
* @Auther: wangjian
* @Date: 2022/1/17 10:00
* @Description:
*/
public class ExcelImportUtils {
//@描述:判断是否是2003版的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
//@描述:判断是否是2007版的Excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/*
@描述:验证excel文件
@param:filePath
@return
*/
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath)) || !(isExcel2007(filePath))) {
return false;
} else {
return true;
}
}
/**
* 创建标题样式
*
* @param wb
* @return
*/
public static HSSFCellStyle createTitleCellStyle(HSSFWorkbook wb) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//背景颜色 cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
headerFont1.setBold(true); //字体加粗
headerFont1.setFontName("黑体"); // 设置字体类型
headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
cellStyle.setFont(headerFont1); // 为标题样式设置字体样式
return cellStyle;
}
/**
* 创建表头样式
*
* @param wb
* @return
*/
public static HSSFCellStyle createHeadCellStyle(HSSFWorkbook wb) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setWrapText(true);// 设置自动换行
//背景颜色 cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
cellStyle.setBorderRight(BorderStyle.THIN); //右边框
cellStyle.setBorderTop(BorderStyle.THIN); //上边框
HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
headerFont.setBold(true); //字体加粗
headerFont.setFontName("黑体"); // 设置字体类型
headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
cellStyle.setFont(headerFont); // 为标题样式设置字体样式
return cellStyle;
}
/**
* 创建内容样式
*
* @param wb
* @return
*/
public static HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
cellStyle.setWrapText(true);// 设置自动换行
cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
cellStyle.setBorderRight(BorderStyle.THIN); //右边框
cellStyle.setBorderTop(BorderStyle.THIN); //上边框
// 生成12号字体
HSSFFont font = wb.createFont();
font.setColor((short) 8);
font.setFontHeightInPoints((short) 12);
cellStyle.setFont(font);
return cellStyle;
}
}
This diff is collapsed.
package com.pms.ocp.common.utils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 文件导出工具
* @author guofanfan
*/
public class FileExport {
private static final Logger logger = LoggerFactory.getLogger(FileExport.class);
/** CSV文件列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";
private static final String CSV_COLUM_TABLE = "\t";
/** CSV文件列分隔符 */
private static final String CSV_RN = "\r\n";
/**
* 导出Excel文件
*
* @param excelHeader
* 导出文件中表格头
* @param list
* 导出的内容
* @param response
* HttpServletResponse对象,用来获得输出流向客户端写导出的文件
* @param sheetName
* Excel的sheet名称,加上时间戳作为导出文件的名称
*/
public static void exportExcel(String [] excelHeader, List<Object> list, String sheetName, HttpServletResponse response, HttpServletRequest request) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
HSSFRow row = sheet.createRow((int) 0);
/******设置单元格是否显示网格线******/
sheet.setDisplayGridlines(true);
/******设置头单元格样式******/
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
Font fontHeader = wb.createFont();
fontHeader.setBold(true);
fontHeader.setFontHeight((short) 240);
style.setFont(fontHeader);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
/******设置头内容******/
for (int i = 0; i < excelHeader.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(" " +excelHeader[i] + " ");
cell.setCellStyle(style);
}
/******设置内容单元格样式******/
HSSFCellStyle styleCell = wb.createCellStyle();
Font fontCell = wb.createFont();
// fontCell.setColor(HSSFColor.BLACK.index);
// fontCell.setColor(HSSFColor.B);
styleCell.setAlignment(HorizontalAlignment.CENTER);
styleCell.setFont(fontCell);
styleCell.setBorderBottom(BorderStyle.THIN);
styleCell.setBorderLeft(BorderStyle.THIN);
styleCell.setBorderRight(BorderStyle.THIN);
styleCell.setBorderTop(BorderStyle.THIN);
/******设置单元格内容******/
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
/******设置行高******/
row.setHeightInPoints(20);
Object[] obj = (Object[]) list.get(i);
for (int j = 0; j < excelHeader.length; j++) {
styleCell.setWrapText(false);
HSSFCell cell = row.createCell(j);
if (obj[j] != null){
cell.setCellValue(obj[j].toString());
}else{
cell.setCellValue("");
}
// if(obj[j].toString().length()>20)
// styleCell.setWrapText(true);
cell.setCellStyle(styleCell);
sheet.autoSizeColumn(j);
}
}
OutputStream ouputStream = null;
try {
String encoding = "UTF-8";
/** 获取浏览器相关的信息 */
String userAgent = request.getHeader("user-agent");
/** 判断是否为msie浏览器 */
if (userAgent.toLowerCase().indexOf("msie") != -1){
encoding = "gbk";
}
response.setCharacterEncoding(encoding);
response.setContentType("application/vnd.ms-excel");
String fileName = sheetName;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHMMSS");
fileName += (dateFormat.format(new Date())).toString()+".xls";
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, encoding));
ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(ouputStream!=null) {
ouputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 导出CSV文件
* @param dataList 集合数据
* @param colNames 表头部数据
* @param mapKey 查找的对应数据
*/
public static boolean doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) {
try {
StringBuffer buf = new StringBuffer();
String[] colNamesArr = null;
String[] mapKeyArr = null;
colNamesArr = colNames.split(",");
mapKeyArr = mapKey.split(",");
/******完成数据csv文件的封装******/
/******输出列头******/
for (int i = 0; i < colNamesArr.length; i++) {
buf.append(colNamesArr[i]).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
if (null != dataList) {
/******输出数据******/
for (int i = 0; i < dataList.size(); i++) {
for (int j = 0; j < mapKeyArr.length; j++) {
buf.append(dataList.get(i).get(mapKeyArr[j])).append(CSV_COLUM_TABLE).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
/******写出响应******/
os.write(buf.toString().getBytes("GBK"));
os.flush();
return true;
} catch (Exception e) {
logger.error("doExport错误...", e);
}
return false;
}
/**
* 设置响应格式
* @param fileName
* @param response
* @throws UnsupportedEncodingException
*/
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
/******设置文件后缀******/
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName + sdf.format(new Date()).toString() + ".csv";
/******读取字符编码******/
String utf = "UTF-8";
/******设置响应******/
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
}
}
package com.pms.ocp.common.utils;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.NoSuchElementException;
/**
* 导入工具类
* @author guofanfan
*
*/
public class FileUtil {
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)
throws Exception {
if (file == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
} catch (NoSuchElementException e) {
throw new Exception("excel文件不能为空");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return list;
}
}
package com.pms.ocp.common.utils;
import com.pms.ocp.model.vo.Menu;
import java.util.ArrayList;
import java.util.List;
/**
* @author guofanfan
* 树形
*/
public class MenuTree {
private List<Menu> menuList = new ArrayList<Menu>();
public MenuTree(List<Menu> menuList) {
this.menuList=menuList;
}
//建立树形结构
public List<Menu> builTree(){
List<Menu> treeMenus =new ArrayList<Menu>();
for(Menu menuNode : getRootNode()) {
menuNode=buildChilTree(menuNode);
treeMenus.add(menuNode);
}
return treeMenus;
}
//递归,建立子树形结构
private Menu buildChilTree(Menu pNode){
List<Menu> chilMenus =new ArrayList<Menu>();
for(Menu menuNode : menuList) {
if(menuNode.getParentId().equals(pNode.getId())) {
chilMenus.add(buildChilTree(menuNode));
}
}
pNode.setChildren(chilMenus);
return pNode;
}
//获取根节点
private List<Menu> getRootNode() {
List<Menu> rootMenuLists =new ArrayList<Menu>();
for(Menu menuNode : menuList) {
if("0".equals(menuNode.getParentId())) {
rootMenuLists.add(menuNode);
}
}
return rootMenuLists;
}
}
\ No newline at end of file
package com.pms.ocp.common.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @param <T>
* @author admin
*/
@Data
@ApiModel(value = "分页工具类", description = "分页工具类")
public class PageRequest<T> {
private static final long serialVersionUID = 8167917284229912157L;
@ApiModelProperty(value = "当前页码")
private int pageSize;
@ApiModelProperty(value = "每页大小")
private int pageNum;
@ApiModelProperty(value = "其他查询条件")
private T query;
}
\ No newline at end of file
package com.pms.ocp.common.utils;
import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author huxiuwu
* @version 1.0
* @date 2022/3/14 15:38
*/
@Data
public class PageUtil<T> {
/**
* 实体类列表
*/
List<T> content;
/**
* 是否首页
*/
boolean first;
/**
* 是否尾页
*/
boolean last;
/**
* 总记录数
*/
Integer totalElements;
/**
* 总页数
*/
Integer totalPages;
Integer numberOfElements;
/**
* 每页记录数
*/
Integer size;
/**
* 当前页
*/
Integer number;
public void startPage(Integer page, Integer size, List<T> list) {
List<T> list1 = list.stream().skip((page - 1) * size).limit(size).collect(Collectors.toList());
int length = list.size();
this.first = (page == 0);//是否第一页
this.last = (page == (length - 1) / size);//是否最后一页
this.totalPages = ((length - 1) / size + 1);//总页数
this.totalElements = (length);//总elements
this.size = (size);//每页多少elements
this.content = (list1);//内容
this.numberOfElements = (list1.size());//当前页elements
this.number = (page);//当前页数,第一页是0
}
}
package com.pms.ocp.common.utils;
import java.util.Random;
/**
* @author zhaochengming
* 随机生成字符串
*/
public class RandomStringUtils {
/**
* length 字符串长度
* @param length
* @return
*/
public static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<length;i++){
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
}
package com.pms.ocp.common.utils;
import com.pms.ocp.model.entity.TreeNode;
import java.util.*;
/**
* @author huxiuwu
* @version 1.0
* @date 2022/3/8 17:51
*/
public class TreeUtils {
/**
* 根据pid,构建树节点
*/
public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) {
List<T> treeList = new ArrayList<>();
for(T treeNode : treeNodes) {
if (pid.equals(treeNode.getpCode())) {
treeList.add(findChildren(treeNodes, treeNode));
}
}
return treeList;
}
/**
* 查找子节点
*/
private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
for(T treeNode : treeNodes) {
if(rootNode.getCode().equals(treeNode.getpCode())) {
rootNode.getChildren().add(findChildren(treeNodes, treeNode));
}
}
return rootNode;
}
/**
* 构建树节点
*/
public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
List<T> result = new ArrayList<>();
//list转map
Map<String, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
for(T treeNode : treeNodes){
nodeMap.put(treeNode.getCode(), treeNode);
}
for(T node : nodeMap.values()) {
T parent = nodeMap.get(node.getpCode());
if(parent != null && (node.getpCode().equals(parent.getCode()))
&& (!"".equals(node.getpCode())|| !"".equals(parent.getCode()))){
if (parent.getChildren() == null){
parent.setChildren(new LinkedList<>());
}
parent.getChildren().add(node);
continue;
}
result.add(node);
}
return result;
}
}
package com.pms.ocp.controller;
import com.pms.ocp.model.dto.ApiBaseDto;
import com.pms.ocp.model.entity.OcpApiBase;
import com.pms.ocp.model.vo.OcpApiBaseVo;
import com.pms.ocp.model.vo.ResponseVO;
import com.pms.ocp.service.ApiDetailsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.RestController;
import java.util.List;
@Slf4j
@RequestMapping("/api-base/v1")
@RestController
@Api(tags = "服务库服务详情接口")
public class ApiDetailsController {
@Autowired
private ApiDetailsService apiDetailsService;
@ApiOperation("服务库服务详情-查询")
@GetMapping("/query")
public ResponseVO<OcpApiBaseVo> getApiDetails(String apiCode) {
return apiDetailsService.getApiDetails(apiCode);
}
}
package com.pms.ocp.controller;
import com.pms.ocp.model.entity.OcpTenantGroup;
import com.pms.ocp.model.vo.ResponseVO;
import com.pms.ocp.service.AppArrangeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* @className: AppArrangeController
* @Dscription:应用分类管理接口
* * @atuthor: pei-chenxi
* * @DateTime: 2022/3/9 14:15e
*/
@Slf4j
@RestController
@RequestMapping("/app-arrange/vl")
@Api(tags = "应用分类管理接口")
public class AppArrangeController {
@Autowired
private AppArrangeService appArrangeService;
@PostMapping("/update/app")
@ApiOperation("应用分类修改")
public ResponseVO updateApp(@RequestBody OcpTenantGroup ocpTenantGroup){
boolean flag = appArrangeService.updateApp(ocpTenantGroup);
if (flag){
return ResponseVO.ok();
}
return ResponseVO.error("您输入的分类编码重复,请重新输入");
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
package com.pms.ocp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pms.ocp.model.dto.OcpApiBaseDto;
import com.pms.ocp.model.entity.OcpApiBase;
import com.pms.ocp.model.vo.OcpApiBaseVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.sql.Timestamp;
import java.util.List;
/**
* @author guofanfan
*/
@Mapper
public interface ApiBasicManagementMapper extends BaseMapper<OcpApiBase> {
List<OcpApiBaseVo> selectApiExport(List<String> list);
List<OcpApiBaseVo> queryOcpApiBaseDto(@Param("keyword") String keyword,@Param("apiUnit") String apiUnit, @Param("startTime") Timestamp startTime, @Param("endTime") Timestamp endTime, @Param("apiCode") String apiCode, @Param("pageSize") int pageSize, @Param("pageNum") int pageNum);
}
package com.pms.ocp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pms.ocp.model.entity.OcpApiBase;
import com.pms.ocp.model.vo.OcpApiBaseVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface ApiDetailsMapper extends BaseMapper<OcpApiBase> {
OcpApiBaseVo selectByCode(@Param("apiCode") String apiCode);
}
package com.pms.ocp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pms.ocp.model.entity.OcpTenantGroup;
import org.apache.ibatis.annotations.Mapper;
/**
* @className: AppArrangeMapper
* @Description:应用分类数据层
* @atuthor: pei-chenxi
* @DateTime: 2022/3/9 14:18
*/
@Mapper
public interface AppArrangeMapper extends BaseMapper<OcpTenantGroup> {
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
package com.pms.ocp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.pms.ocp.model.entity.OcpApiBase;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface OcpApiBaseMapper extends BaseMapper<OcpApiBase> {
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment