Commit 3de62532 authored by licc's avatar licc

上传代码

parent 9d516726
Pipeline #232 canceled with stages
workspace
.project
.classpath
*.settings
.idea
*.class
target/
\ No newline at end of file
# shop-Mall
#### 技术选型
- 核心框架:Spring Boot 2.15
- 安全框架:Apache Shiro 1.4
- 视图框架:Spring MVC 5.0
- 持久层框架:MyBatis 3.3,mybatis-plus3.1.2
- 数据库连接池:Druid 1.1.13
- 日志管理:SLF4J 1.7
- 后端校验框架:Hibernate Validator
<br>
#### 安装教程
- git clone下载源码
- 安装lombok插件
- 修改配置文件application-dev.yml
- 启动项目
- Swagger文档路径:http://localhost:8080/swagger-ui.html
<br>
#### 项目结构
```
├─wisenergy-parent 父模块
│ ├─wisenergy-common 通用模块
│ ├─wisenergy-model 实体类
│ ├─wisenergy-mapper DAO接口
│ ├─wisenergy-service 业务实现
│ ├─wisenergy-web-admin web接口
└─
```
#### 部署
- 打包:maven clean package
- 启动:nohup java -jar wisenergy-web-admin-1.0.0-SNAPSHOT.jar > admin.log 2>&1 &
\ No newline at end of file
File added
<?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 http://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.1.5.RELEASE</version>
</parent>
<groupId>cn.wisenergy</groupId>
<artifactId>wisenergy-parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<name>${project.artifactId}</name>
<!-- 项目模块 -->
<modules>
<module>wisenergy-common</module>
<module>wisenergy-model</module>
<module>wisenergy-mapper</module>
<module>wisenergy-service</module>
<module>wisenergy-web-admin</module>
</modules>
<!--POM属性变量-->
<properties>
<!-- 文件拷贝时的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 编译时的编码 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<!--模块版本管理-->
<projectDevMode>SNAPSHOT</projectDevMode>
<moduleVersion.wisenergy-common>1.0.0-${projectDevMode}</moduleVersion.wisenergy-common>
<moduleVersion.wisenergy-model>1.0.0-${projectDevMode}</moduleVersion.wisenergy-model>
<moduleVersion.wisenergy-mapper>1.0.0-${projectDevMode}</moduleVersion.wisenergy-mapper>
<moduleVersion.wisenergy-service>1.0.0-${projectDevMode}</moduleVersion.wisenergy-service>
<moduleVersion.wisenergy-web-admin>1.0.0-${projectDevMode}</moduleVersion.wisenergy-web-admin>
</properties>
<!-- JAR 依赖 -->
<dependencies>
<!-- Apache Commons-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- lombok简化代码,需要本地配置 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!--谷歌工具包,对Java API的补充,对Java开发中常用功能进行更优雅的实现,使得编码更加轻松,代码容易理解-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
<!-- 阿里巴巴json工具类 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
</dependencies>
<!-- MVN构建插件 -->
<build>
<plugins>
<!-- 自动跳过单元测试 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.21.0</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<!--编译lib中的JAR文件到WAR包中-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
workspace
.project
.classpath
*.settings
.idea
*.class
target/
\ 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>wisenergy-parent</artifactId>
<groupId>cn.wisenergy</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>wisenergy-common</artifactId>
<version>${moduleVersion.wisenergy-common}</version>
<packaging>jar</packaging>
<!-- 项目依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!--spring aop依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--配置文件处理器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Secret key -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.54</version>
</dependency>
<!-- Swagger配置 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.7</version>
</dependency>
</dependencies>
<!-- MAVEN构建 -->
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
</project>
\ No newline at end of file
package cn.wisenergy.common.annotation;
import java.lang.annotation.*;
/**
* 数据权限注解,标注在方法上
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataAuth {
String value() default "dataAuthList";
}
package cn.wisenergy.common.annotation;
import java.lang.annotation.*;
/**
* 系统日志注解
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String value() default "";
}
package cn.wisenergy.common.camera;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* @author jiawei
*/
@Configuration
@ConfigurationProperties(prefix = "camera.isc.api")
@Data
public class CameraConfig {
private String appKey;
private String appSecret;
private String host;
private String path;
private String protocol="https";
}
package cn.wisenergy.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置
*
*/
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory factory;
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
@Bean
public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
return redisTemplate.opsForValue();
}
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
package cn.wisenergy.common.config.cors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 跨域过滤器设置
*
* @author wyy
* @date 2019-09-04 14:31
*/
@Configuration
public class CORSFilter {
/**
* 前置跨域设置【过滤器方式先于拦截器生效】
*
* @return
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
package cn.wisenergy.common.config.file;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
/**
* 文件上传配置
* @author wyy
* @date 2019-08-22 19:20
*/
@Configuration
public class FileUploadConfig {
/**
* 重新定义文件上传对象【springBoot request转化成MultipartHttpServletRequest】
* @return
*/
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
resolver.setResolveLazily(true);
resolver.setMaxInMemorySize(40960);
resolver.setMaxUploadSize(512 * 1024 * 1024);
return resolver;
}
}
package cn.wisenergy.common.constant;
/**
* 缓存常量
*/
public interface CacheConstants {
/**
* 菜单详情
*/
String MENU_DETAILS = "menu_details";
}
package cn.wisenergy.common.constant;
/**
* 公共参数
*/
public final class CommonAttributes {
/** 日期格式配比 */
public static final String[] DATE_PATTERNS = new String[] { "HH:mm", "yyyy", "yyyy-MM", "yyyyMM", "yyyy/MM", "yyyy-MM-dd", "yyyyMMdd", "yyyy/MM/dd","yyyy-MM-dd HH:mm", "yyyyMMddHHmm", "yyyy/MM/dd HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", "yyyy/MM/dd HH:mm:ss" };
/** xml文件路径 */
public static final String XML_PATH = "/app_config.xml";
/** properties文件路径 */
public static final String PROPERTIES_PATH = "/app_config.properties";
/**
* 不可实例化
*/
private CommonAttributes() {
}
public static final Integer NUM_ONE = 1;
}
package cn.wisenergy.common.constant;
/**
* 通用常量
*
*/
public interface CommonConstants {
/**
* 超级管理员ID
*/
String SUPER_ADMIN = "1";
}
package cn.wisenergy.common.constant;
public interface IscCameraConstants {
/**
* 查询编码设备列表v2
* 根据条件查询目录下有权限的编码设备列表。当返回字段对应的值为空时,该字段不返回。
* 综合安防管理平台iSecure Center V1.4及以上版本
*/
String encodeDevice_search = "";
/**
* 根据区域编码、资源操作权限码分页获取当前区域下(不包含子区域)有权限的编码设备列表,主要用于逐层获取区域下的编码设备信息。
* 综合安防管理平台iSecure Center v1.3及以上版本
*/
String encodeDevice_subResources = "/api/resource/v1/encodeDevice/subResources";
/**
* 根据编号获取监控点详细信息
* 获取单个监控点信息是指根据监控点唯一标识来获取指定的监控点信息。
*/
String cameras_indexCode = "/api/resource/v1/cameras/indexCode";
/**
* 分页获取监控点资源
*/
String cameras = "/api/resource/v1/cameras";
/**
* 获取监控点预览取流URLv2
* 综合安防管理平台iSecure Center V1.4及以上版本
*/
String previewURLs = "/api/video/v2/cameras/previewURLs";
/**
* 获取监控点回放取流URLv2
* 综合安防管理平台iSecure Center V1.4及以上版本
*/
String playbackURLs = "/api/video/v2/cameras/playbackURLs";
/**
* 查询对讲URL
* 该接口用于获取监控点的对讲url,为保证数据的安全性,URL设有有效时间,有效时间为5分钟。
* 综合安防管理平台iSecure Center V1.2及以上版本
*/
String talkURLs = "/api/video/v1/cameras/talkURLs";
/**
* 手动抓图
* 该接口用于手动触发设备抓图,返回图片的地址,抓图前请确保平台上已配置图片存储信息。抓图时间为触发手动抓图命令的时间。
* 综合安防管理平台iSecure Center V1.2及以上版本
*/
String manualCapture = "/api/video/v1/manualCapture";
/**
* 通过向中心存储接入服务下发锁定/解锁指定编码器,指定时间段的录像。
* 综合安防管理平台iSecure Center V1.4及以上版本
*/
String lock = "/api/video/v1/record/lock";
/**
* 开始手动录像
* 综合安防管理平台iSecure Center V1.3及以上版本
*/
String manualRecordStart = "/api/video/v1/manualRecord/start";
/**
* 停止手动录像
* 综合安防管理平台iSecure Center V1.5及以上版本
*/
String manualRecordStop = "/api/video/v1/manualRecord/stop";
/**
* 获取手动录像状态
* 综合安防管理平台iSecure Center V1.5及以上版本
*/
String manualRecordStatus = "/api/video/v1/manualRecord/status";
/**
* 查询手动录像编号
* 该接口用于根据用户id获取当前用户创建的手动录像任务ID,用于获取手动录像状态和停止手动录像
*/
String manualRecordSearch = "/api/video/v1/manualRecord/taskId/search";
/**
* 根据区域编号获取下一级区域列表v2
*/
String regionsSubRegions = "/api/resource/v2/regions/subRegions";
/**
* 获取根区域信息
*/
String regionsRoot = "/api/resource/v1/regions/root";
/**
* 查询区域列表v2
*/
String regionNodes = "/api/irds/v2/region/nodesByParams";
/**
* 根据区域编号获取下级监控点列表
*/
String regionIndexCodeCameras = "/api/resource/v1/regions/regionIndexCode/cameras";
/**
* 获取监控点在线状态
*/
String onlineCamera = "/api/nms/v1/online/camera/get";
/**
* 获取编码设备在线状态
*/
String onlineEncodeDevice = "/api/nms/v1/online/encode_device/get";
}
package cn.wisenergy.common.constant;
/**
* redis 常量
*/
public class RedisConsts {
/****************************** 后台管理端缓存设置开始 ******************************/
// 系统setting
public static final String SYSTEM_SETTING = "system:setting:setting";
// 接口Token参数设置
public final static String ADMIN_ACCTNAME = "admin:acctName:";
public final static int ADMIN_ACCTNAME_EXPIRE = 60 * 60 * 24 * 30;
/****************************** 后台管理端缓存设置结束 ******************************/
/************************** shiro 设置开始 ******************************** */
// shiroSession的redis-key
public static final String ADMIN_SHIRO_SESSION_KEY = "admin:shiro_redis_session:";
// shiroSession的过期时间,单位:秒,此值须大于spring-cache.xml中的全局session有效期
public static final int ADMIN_SHIRO_SESSION_EXPIRE = 3600;
// shiroRealm的redis-key
public static final String ADMIN_SHIRO_REALM_KEY = "admin:shiro_redis_realm:";
// shiroRealm的过期时间,单位:秒,设置与SHIRO_SESSION_EXPIRE相等
public static final int ADMIN_SHIRO_REALM_EXPIRE = 3600;
/************************** shiro 设置结束 ******************************** */
public static final String JWT_ACCESS_TOKEN = "jwt_access_token_";
}
package cn.wisenergy.common.enums;
/**
* 菜单类型枚举
*/
public enum MenuTypeEnum {
/**
* 目录
*/
CATALOG(0),
/**
* 菜单
*/
MENU(1),
/**
* 按钮
*/
BUTTON(2);
private int value;
MenuTypeEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
package cn.wisenergy.common.enums;
/**
* 响应码基类
*
* @author wyy
* @data 2019/08/15
*/
public enum RespCodeEnum {
/********************* SpringMBoot 系统异常 **********************/
MIS_REQ_PARAM("400", "请求参数丢失"),
NO_AUTH_REQUEST("401", "未授权"),
REJECT_REQUEST("403", "未授权"),
AUTH_ERROR("40104", "权限认证失败"),
RESOURCE_NOT_FOUND("404", "请求的资源不存在"),
METHOD_NOT_SUPPORTED("405", "不支持的请求方法"),
MEDIA_TYPE_NOT_ACCEPT("406", "无法接受请求中的媒体类型"),
REQUEST_TIME_OUT("408", "无法接受请求中的媒体类型"),
MEDIA_TYPE_NOT_SUPPORTED("415", "不支持的媒体类型"),
SERVER_ERROR("500", "获取数据异常"),
/* ******************** 业务自定义异常 ********************* */
RSA_PRIVATE_KEY_ERROR("1001", "生成RSA非对称加密公钥出错"),
RSA_NOT_EXIST("1002", "RSA非对称加密公钥不存在"),
RSA_DECRYPTION_ERROR("1003", "RSA解密错误"),
REQUIRED_IDENTIFY_NOT_EXIST("1005", "请求标识对象不存在"),
ILLEGAL_PARAMETER("1006", "非法参数"),
MISS_PARAMETER("1007", "缺少必须的参数"),
ACCT_NOT_EXIST("1007", "账号不存在"),
ACCT_OR_ACCOPASS_ERROR("1009", "账号或密码错误"),
ACCT_HAS_FROZEN("1010", "账号已冻结"),
NOT_LOGIN_ERROR("1011", "用户未登录"),
CAPTCHA_CODE_INVALID("1012", "验证码失效"),
CAPTCHA_CODE_ERROR("1013", "验证码错误"),
NO_DATA("1004", "数据为空"),
CAPTCHA_EXIST("1005", "验证码已发送,请稍等"),
TOKEN_IS_NOT_MISSING("40101", "TOKEN无效"),
TOKEN_IS_NOT_TIMEOUT("40102", "TOKEN超时,请检查TOKEN的有效期"),
TOKEN_IS_NOT_ERROR("40103", "TOKEN解析异常"),
DATA_AUTH_UNAUTHORIZED("40105", "数据权限不足"),
USERNAME_IS_NOT_ERROR("2001", "用户名不能为空"),
USERNAME_IS_EXIST_ERROR("2002", "用户名已存在"),
EMPLOYEE_IS_NULL_ERROR("2003", "人员编号不能为空"),
EMPLOYEE_IS_NOT_EXIST_ERROR("2004", "该员工不存在"),
USER_EXIST_EMPLOYEE_ERROR("2005", "该用户已分配人员"),
USER_IS_NOT_EXIST_ERROR("2006", "该用户不存在"),
USER_IS_NOT_ERROR("2000", "用户不能为空");
/**
* 错误编码
*/
public String code;
/**
* 错误编码信息
*/
public String msg;
/**
* 构造函数
*
* @param code 编码
* @param msg 编码信息
*/
RespCodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 获取编码
*/
public String getCode() {
return code;
}
/**
* 设置编码
*/
public void setCode(String code) {
this.code = code;
}
/**
* 获取编码信息
*/
public String getMsg() {
return msg;
}
/**
* 设置编码信息
*/
public void setMsg(String msg) {
this.msg = msg;
}
}
package cn.wisenergy.common.expection;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 自定义异常
*/
@Data
@EqualsAndHashCode(callSuper=false)
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public BaseException(String msg) {
super(msg);
this.msg = msg;
}
public BaseException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public BaseException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public BaseException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
}
package cn.wisenergy.common.expection;
import cn.wisenergy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
/**
* 统一异常处理器
* @author lut
*/
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {
/**
* 处理自定义异常
*/
@ExceptionHandler(BaseException.class)
public R<?> handleRRException(BaseException e){
log.error(e.getMessage(), e);
return R.error(e.getCode(), e.getMsg());
}
@ExceptionHandler(NoHandlerFoundException.class)
public R<?> handlerNoFoundException(NoHandlerFoundException e) {
log.error(e.getMessage(), e);
return R.error(404, "路径不存在,请检查路径是否正确");
}
@ExceptionHandler(DuplicateKeyException.class)
public R<?> handleDuplicateKeyException(DuplicateKeyException e){
log.error(e.getMessage(), e);
return R.error("数据库中已存在该记录");
}
@ExceptionHandler(AuthorizationException.class)
public R<?> handleAuthorizationException(AuthorizationException e){
log.error(e.getMessage(), e);
return R.error("没有权限,请联系管理员授权");
}
}
package cn.wisenergy.common.utils;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 工具类
*
* @author lut
*/
@Slf4j
public class BaseUtil {
/**
* 下载文件header头
*/
private static final String FileHeader = "attachment;filename=\"%1$s\";filename*=utf-8''%1$s";
/**
* 无参数url转换成有参url
*
* @param url
* @param params
* @return
*/
public static String getParamsUrl(String url, Map<String, Object> params) {
if (!params.isEmpty()) {
return Joiner.on("?").join(url, Joiner.on("&").join(params.keySet().stream()
.map(o -> String.format("%1$s={%1$s}", o)).collect(Collectors.toList())));
}
return url;
}
/**
* 设置下载文件名称(解决编码问题)
*
* @param response
* @param fileName
*/
public static void setDownloadFileHeader(HttpServletResponse response, String fileName) {
// IE8兼容
response.setHeader("Cache-Control", "must-revalidate");
response.setHeader("Cache-Control", "post-check=0");
response.setHeader("Cache-Control", "pre-check=0");
// 文件名称
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", String.format(FileHeader, getEncodeFileName(fileName)));
}
/**
* 获取编码文件名称
*
* @param fileName
* @return
*/
private static String getEncodeFileName(String fileName) {
try {
return URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
} catch (Exception e) {
log.error("文件名转码失败:{}", e);
}
return fileName;
}
/**
* 按日历日期增加
*/
public static Date addMonth(Date d1, int month) {
// 创建实例
Calendar calendar = Calendar.getInstance();
calendar.setTime(d1);
//日期
calendar.add(Calendar.MONTH, month);
// 一个月后的日期(Date类型)
Date date = calendar.getTime();
return date;
}
/**
* 按日历日期增加
*/
public static Date addDay(Date d1, int day) {
// 创建实例
Calendar calendar = Calendar.getInstance();
calendar.setTime(d1);
// 一个月后的日期
calendar.add(Calendar.DAY_OF_YEAR, day);
// 一个月后的日期(Date类型)
Date date = calendar.getTime();
return date;
}
/**
* 日期添加
*
* @param date
* @param day
* @return
*/
public static Date addDate(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, day);
date = cal.getTime();
return date;
}
/**
* 说明:日期增加一个月,获得一个月后的日期
*
* @param str1
* @return Date
*/
public static Date add1Month(String str1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
return addMonth(sdf.parse(str1), 1);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 说明:日期增加三个月,获得三个月后的日期
*
* @param str1
* @return Date
*/
public static Date add3Month(String str1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
return addMonth(sdf.parse(str1), 3);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 说明:日期增加十二个月,获得一年后的日期
*/
public static Date add1Year(String str1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
return addMonth(sdf.parse(str1), 12);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过出生日期获取年龄
*
* @param birth
* @param deadDate
* @return
*/
public static int getAgeByBirth(Date birth, Date deadDate) {
// 判定出生日期是否存在
if (birth != null) {
return birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
.until(deadDate != null ? deadDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : LocalDate.now())
.getYears();
}
return 0;
}
}
package cn.wisenergy.common.utils;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
/**
* 字节转换工具类
*/
public class ByteUtil {
/**
* 字节数组转字符数组
*
* @param bytes
* @return
*/
public static char[] byteArrTocharArr(byte[] bytes) {
Charset cs = Charset.forName("UTF-8");
ByteBuffer bb = ByteBuffer.allocate(bytes.length);
bb.put(bytes);
bb.flip();
CharBuffer cb = cs.decode(bb);
return cb.array();
}
/**
* char数组转Byte数组
*
* @param chars
* @return
*/
public static byte[] charArrToByteArr(char[] chars) {
Charset cs = Charset.forName("UTF-8");
CharBuffer cb = CharBuffer.allocate(chars.length);
cb.put(chars);
cb.flip();
ByteBuffer bb = cs.encode(cb);
return bb.array();
}
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}
/**
* 把字节数组转换成16进制字符串
*
* @param bArray
* @return
*/
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* 把字节数组转换为对象
*
* @param bytes
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static final Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(in);
Object o = oi.readObject();
oi.close();
return o;
}
/**
* 把可序列化对象转换成字节数组
*
* @param s
* @return
* @throws IOException
*/
public static final byte[] objectToBytes(Object s) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream ot = new ObjectOutputStream(out);
ot.writeObject(s);
ot.flush();
ot.close();
return out.toByteArray();
}
public static final String objectToHexString(Serializable s) throws IOException {
return bytesToHexString(objectToBytes(s));
}
public static final Object hexStringToObject(String hex) throws IOException, ClassNotFoundException {
return bytesToObject(hexStringToByte(hex));
}
/**
* @函数功能: BCD码转为10进制串(阿拉伯数据)
* @输入参数: BCD码
* @输出结果: 10进制串
*/
public static String bcd2Str(byte[] bytes) {
StringBuffer temp = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
temp.append((byte) (bytes[i] & 0x0f));
}
return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) : temp.toString();
}
/**
* @函数功能: 10进制串转为BCD码
* @输入参数: 10进制串
* @输出结果: BCD码
*/
public static byte[] str2Bcd(String asc) {
int len = asc.length();
int mod = len % 2;
if (mod != 0) {
asc = "0" + asc;
len = asc.length();
}
byte abt[] = new byte[len];
if (len >= 2) {
len = len / 2;
}
byte bbt[] = new byte[len];
abt = asc.getBytes();
int j, k;
for (int p = 0; p < asc.length() / 2; p++) {
if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
j = abt[2 * p] - '0';
} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
j = abt[2 * p] - 'a' + 0x0a;
} else {
j = abt[2 * p] - 'A' + 0x0a;
}
if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
k = abt[2 * p + 1] - '0';
} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
k = abt[2 * p + 1] - 'a' + 0x0a;
} else {
k = abt[2 * p + 1] - 'A' + 0x0a;
}
int a = (j << 4) + k;
byte b = (byte) a;
bbt[p] = b;
}
return bbt;
}
/**
* 低位到高位排列的字节数组
*
* @param byte2Arr
* @return
*/
public static int bytesTo16Int(byte[] byte2Arr) {
return (byte2Arr[0] & 0xFF) | (byte2Arr[1] << 8);
}
/**
* 低位到高位排列的字节数组
*
* @param byte4Arr
* @return
*/
public static int bytesTo32Int(byte[] byte4Arr) {
return (byte4Arr[0] & 0xFF) | ((byte4Arr[1] & 0xFF) << 8) | ((byte4Arr[2] & 0xFF) << 16) | ((byte4Arr[3] & 0xFF) << 24);
}
/**
* 低位到高位
*
* @param b
* @return
*/
public static float bytesTo32Float(byte[] b) {
int l;
l = b[0];
l &= 0xff;
l |= ((long) b[1] << 8);
l &= 0xffff;
l |= ((long) b[2] << 16);
l &= 0xffffff;
l |= ((long) b[3] << 24);
return Float.intBitsToFloat(l);
}
}
package cn.wisenergy.common.utils;
import cn.hutool.core.lang.UUID;
import java.io.Serializable;
import java.math.BigInteger;
/**
* 生成充值卡子卡卡号工具类
*/
public class CardNumberUtil implements Serializable {
private static final long serialVersionUID = -9056417839913098262L;
//字符串长度
static final int LENGTH= 11;
public static String cardNumber() {
//添加十一位数字生成卡号
String uuid = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
return uuid.toString().substring(0,LENGTH);
}
}
package cn.wisenergy.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ExcelUtils {
private static final String EXTENSION_XLS = "xls";
private static final String EXTENSION_XLSX = "xlsx";
/**
* 判断EXCEL版本
*
* @param in
* @param filename
* @return
* @throws IOException
*/
public static Workbook getWorkbook(InputStream in, String filename) throws IOException {
Workbook wb = null;
if (filename.endsWith(EXTENSION_XLS)) {
wb = new HSSFWorkbook(in);//Excel 2003
} else if (filename.endsWith(EXTENSION_XLSX)) {
wb = new XSSFWorkbook(in);//Excel 2007
}
return wb;
}
/**
* 文件校验是否是excel
*
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
public static void preReadCheck(String fileName) throws FileNotFoundException,
FileFormatException {
// 常规检查
if (StringUtils.isBlank(fileName)) {
throw new FileNotFoundException("传入的文件不存在:" + fileName);
}
if (!fileName.endsWith(EXTENSION_XLS) && !fileName.endsWith(EXTENSION_XLSX)) {
throw new FileFormatException("传入的文件不是excel");
}
}
/**
* 读取EXCEL
*
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
public static List<List<String>> readExcel(MultipartFile file) throws FileNotFoundException, FileFormatException {
// 检查
preReadCheck(file.getOriginalFilename());
// 获取workbook对象
Workbook workbook = null;
/*InputStream is = new FileInputStream(filePath);*/
List<List<String>> result = new ArrayList<List<String>>();
try {
workbook = getWorkbook(file.getInputStream(), file.getOriginalFilename());
// workbook = WorkbookFactory.create(is);
int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
// 读文件 一个sheet一个sheet地读取
for (int numSheet = 0; numSheet < sheetCount; numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {
// 读取数据行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);// 当前行
int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
List<String> rowList = new ArrayList<String>();
for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
rowList.add(currentCellValue);
}
//行为空的不读
Boolean flag = false;
for (String str : rowList) {
if (!StringUtils.isBlank(str)) {
flag = true;
break;
}
}
if (flag) {
result.add(rowList);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return result;
}
public static List<List<String>> readInlandCompare(String filePath, Integer startSheet, Integer endSheet) throws FileNotFoundException, FileFormatException {
// 检查
preReadCheck(filePath);
// 获取workbook对象
Workbook workbook = null;
InputStream is = new FileInputStream(filePath);
List<List<String>> result = new ArrayList<List<String>>();
try {
workbook = getWorkbook(is, filePath);
// workbook = WorkbookFactory.create(is);
int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
// 读文件 一个sheet一个sheet地读取
for (int numSheet = startSheet; numSheet < endSheet; numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
if (firstRowIndex != lastRowIndex && lastRowIndex != 0) {
// 读取数据行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);// 当前行
int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
List<String> rowList = new ArrayList<String>();
for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);// 当前单元格
String currentCellValue = getCellValue(currentCell, true);// 当前单元格的值
rowList.add(currentCellValue);
}
//行为空的不读
Boolean flag = false;
for (String str : rowList) {
if (!StringUtils.isBlank(str)) {
flag = true;
break;
}
}
if (flag) {
result.add(rowList);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return result;
}
/**
* 取单元格的值
*
* @param cell 单元格对象
* @param treatAsStr 为true时,当做文本来取值 (取到的是文本,不会把“1”取成“1.0”)
* @return
*/
public static String getCellValue(Cell cell, boolean treatAsStr) {
if (cell == null) {
return "";
}
/* if (treatAsStr) {
// 虽然excel中设置的都是文本,但是数字文本还被读错,如“1”取成“1.0”
// 加上下面这句,临时把它当做文本来读取
cell.setCellType(Cell.CELL_TYPE_STRING);
}*/
//SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
String cellValue = null;
int cellType = cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_STRING: // 文本
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: // 数字、日期
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm:ss");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
return sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
return sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
return format.format(value);
}
case Cell.CELL_TYPE_BOOLEAN: // 布尔型
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK: // 空白
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // 错误
cellValue = "错误";
break;
case Cell.CELL_TYPE_FORMULA: // 公式
/* try {
cellValue = cell.getStringCellValue();
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getNumericCellValue());
}*/
try {
cellValue = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getRichStringCellValue());
}
break;
default:
cellValue = "错误";
}
return cellValue;
}
}
package cn.wisenergy.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.*;
import java.util.Properties;
@Slf4j
public class FileUtil {
/**
* @param filePath
* @return
* @throws IOException
* @Title: readProperties
* @Description: 读取prop配置文件获取Properties对象
*/
public static Properties readProperties(String filePath) throws IOException {
// 创建Properties文件
Properties prop = new Properties();
// 获取流
InputStream input = FileUtil.class.getClassLoader().getResourceAsStream(filePath);
// 导入流
prop.load(input);
return prop;
}
/**
* @param filePath 文件的路径
* @return
* @Title: readJsonFile
* @Description: 将JSON文件读取为JSON字符串
*/
public static String readJsonFile(String filePath) {
String laststr = "";
File file = new File(filePath);// 打开文件
BufferedReader reader = null;
try {
FileInputStream in = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));// 读取文件
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr = laststr + tempString;
}
reader.close();
} catch (IOException e) {
log.error(e.getMessage(),e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException el) {
log.error(el.getMessage(),el);
}
}
}
return laststr;
}
/**
* 将URL远程路径文件转成InputStream返回
*
* @param url
* 远程地址
* @return InputStream
*/
public static InputStream remotePathToStream(String url) {
InputStream inputStream = null;
try {
CloseableHttpClient httpsClient = HttpUtil.createSSLClientDefault();
HttpGet get = new HttpGet(url);
HttpResponse response = httpsClient.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
inputStream = response.getEntity().getContent();
}
} catch (Exception e) {
ExceptionUtils.getStackTrace(e);
}
return inputStream;
}
}
package cn.wisenergy.common.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static String getDomain() {
HttpServletRequest request = getHttpServletRequest();
StringBuffer url = request.getRequestURL();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
}
public static String getOrigin() {
HttpServletRequest request = getHttpServletRequest();
return request.getHeader("Origin");
}
}
package cn.wisenergy.common.utils;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* @ClassName ListUtil
* @Description TODO
* @Author meng
* @Date 2020/3/4 15:58
* @Version 1.0
*/
public class ListUtil {
/**
* 将该集合中的元素向右移动index位置
* @param list
* @param index
* @return
*/
public static <T> List<T> moveRight(List<T> list, int index){
if(list == null || list.size()==0){
return list;
}
Queue queue = new LinkedList<T>();
//倒叙进队列
for(int i = list.size()-1;i>=0;i--) {
queue.offer(list.get(i));
}
for(int j = 0;j<index;j++) {
//出队列
T param = (T) queue.poll();
//进队列
queue.offer(param);
}
list = new ArrayList<T>();
int len = queue.size();
for(int i = 0;i<len;i++) {
list.add(0,(T) queue.poll());
}
return list;
}
}
package cn.wisenergy.common.utils;
/**
* @Author zyj
* @Date 2020/5/6 18:18
* @Description 计算一个经纬度在另一个经纬度什么方向
*/
public class LngLatDirection {
public static void main(String[] args) {
LngLatDirection lngLatDirection = new LngLatDirection();
String str = getDirection(39.915322, 116.404341, 39.954713, 116.45982);
System.out.println(str);
}
/**
* @param lat1 纬度1
* @param lng1 经度1
* @param lat2 纬度2
* @param lng2 经度2
* @return 方向
*/
public static String getDirection(double lat1, double lng1, double lat2, double lng2) {
double jiaodu = getAngle(lat1, lng1, lat2, lng2);
if ((jiaodu <= 10) || (jiaodu > 350))
return "东";
if ((jiaodu > 10) && (jiaodu <= 80))
return "东北";
if ((jiaodu > 80) && (jiaodu <= 100))
return "北";
if ((jiaodu > 100) && (jiaodu <= 170))
return "西北";
if ((jiaodu > 170) && (jiaodu <= 190))
return "西";
if ((jiaodu > 190) && (jiaodu <= 260))
return "西南";
if ((jiaodu > 260) && (jiaodu <= 280))
return "南";
if ((jiaodu > 280) && (jiaodu <= 350))
return "东南";
return "";
}
private static double getAngle(double lat1, double lng1, double lat2, double lng2) {
double x1 = lng1;
double y1 = lat1;
double x2 = lng2;
double y2 = lat2;
double pi = Math.PI;
double w1 = y1 / 180 * pi;
double j1 = x1 / 180 * pi;
double w2 = y2 / 180 * pi;
double j2 = x2 / 180 * pi;
double ret;
if (j1 == j2) {
if (w1 > w2)
return 270; // 北半球的情况,南半球忽略
else if (w1 < w2)
return 90;
else
return -1;// 位置完全相同
}
ret = 4 * Math.pow(Math.sin((w1 - w2) / 2), 2) - Math.pow(
Math.sin((j1 - j2) / 2) * (Math.cos(w1) - Math.cos(w2)), 2);
ret = Math.sqrt(ret);
double temp = (Math.sin(Math.abs(j1 - j2) / 2) * (Math.cos(w1) + Math
.cos(w2)));
ret = ret / temp;
ret = Math.atan(ret) / pi * 180;
if (j1 > j2) { // 1为参考点坐标
if (w1 > w2)
ret += 180;
else
ret = 180 - ret;
} else if (w1 > w2)
ret = 360 - ret;
return ret;
}
}
package cn.wisenergy.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class Md5Util {
private static Logger log = LoggerFactory.getLogger(Md5Util.class);
/**
* MD5加密
*
* @param value
* @return
*/
public static String digestMD5(String value) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
byte[] strTemp = value.getBytes();
MessageDigest mdTemp = null;
try {
mdTemp = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);
return null;
}
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; ++i) {
byte byte0 = md[i];
str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
str[(k++)] = hexDigits[(byte0 & 0xF)];
}
return new String(str);
}
/**
* @param len
* @return
* @throws Exception
* @Title generatePassword
* @Description: 随机生成8位密码 必须含有数字字母 特殊字符
* @date 2018年12月11日 下午6:29:28
* @author lut
*/
public static String generatePassword(int len) throws Exception {
char charr[] = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int x = 0; x < len; ++x) {
sb.append(charr[r.nextInt(charr.length)]);
}
return sb.toString();
}
}
package cn.wisenergy.common.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.http.HttpStatus;
import java.io.Serializable;
/**
* 响应信息类
*
* @author lut
*/
@Data
@ApiModel(description = "响应信息主体")
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("返回标记:成功标记=0,失败标记1")
private int code;
@ApiModelProperty("返回信息")
private String message;
@ApiModelProperty("数据")
private T data;
public R() {
this.code = 0;
this.message = "success";
}
public R(int code, String msg) {
this.code = code;
this.message = msg;
}
public R(int code, T data) {
this.code = code;
this.data = data;
}
public R(T data) {
this.code = 0;
this.message = "success";
this.data = data;
}
public R(T data, String msg) {
this.code = 0;
this.data = data;
this.message = msg;
}
public R(int code, String msg,T data) {
this.code = code;
this.data = data;
this.message = msg;
}
/**
* 请求成功
*/
public static <T> R<T> ok() {
return new R<>();
}
/**
* 请求成功,返回前端的信息
*
* @param msg 描述
* @return R
*/
public static <T> R<T> ok(String msg, T data) {
return new R<>(data, msg);
}
/**
* 请求成功,返回前端的信息
*
* @param data 返回值
* @return R
*/
public static <T> R<T> ok(T data) {
return new R<>(0, data);
}
/**
* 请求成功,返回前端信息
*
* @param code 状态码
* @param data 返回值
* @return R
*/
public static <T> R<T> ok(int code, T data) {
return new R<>(code, data);
}
/**
* 请求失败
*
* @return R
*/
public static <T> R<T> error() {
return new R<>(-1, "操作失败");
}
/**
* 请求失败,返回前台信息
*
* @param msg 描述
* @return R
*/
public static <T> R<T> error(String msg) {
return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
}
/**
* 请求失败,返回前台信息
*
* @param code 错误码
* @param msg 描述
* @return R
*/
public static <T> R<T> error(int code, String msg) {
return new R<>(code, msg);
}
/**
* 请求失败,返回前台信息
*
* @param code 错误码
* @param msg 描述
* @return R
*/
public static <T> R<T> error(int code, String msg,T data) {
return new R<>(code, msg,data);
}
}
package cn.wisenergy.common.utils;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Assert;
/**
* Utils - RSA加密解密
*
* @version 3.0
*/
public final class RSAUtil {
/**
* 安全服务提供者
*/
private static final Provider PROVIDER = new BouncyCastleProvider();
/**
* 密钥大小
*/
private static final int KEY_SIZE = 1024;
/**
* 加密解密模式 - 填充
*/
public static final String RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding";
/**
* 加密解密模式
*/
public static final String RSA = "RSA";
/**
* 不可实例化
*/
private RSAUtil() {
}
/**
* 生成密钥对
*
* @return 密钥对
*/
public static KeyPair generateKeyPair() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
"RSA", PROVIDER);
keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
return keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 通过公钥和数组加密
*
* @param publicKey
* 公钥
* @param data
* 数据
* @return 加密后的数据
*/
@SuppressWarnings("deprecation")
public static byte[] encrypt(PublicKey publicKey, byte[] data) {
Assert.notNull(publicKey);
Assert.notNull(data);
try {
Cipher cipher = Cipher.getInstance("RSA", PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int blockSize = cipher.getBlockSize();// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
// 加密块大小为127byte,加密后为128个byte;因此共有2个加密块,第一个127byte第二个为1个byte
int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize) {
cipher.doFinal(data, i * blockSize, blockSize, raw, i
* outputSize);
} else {
cipher.doFinal(data, i * blockSize, data.length - i
* blockSize, raw, i * outputSize);
}
i++;
}
return raw;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过公钥和字符串加密
*
* @param publicKey
* 公钥
* @param text
* 字符串
* @return Base64编码字符串
*/
@SuppressWarnings("deprecation")
public static String encrypt(PublicKey publicKey, String text) {
Assert.notNull(publicKey);
Assert.notNull(text);
byte[] data = encrypt(publicKey, text.getBytes());
return data != null ? Base64.encodeBase64String(data) : null;
}
/**
* 通过公钥的模量和指数构建公钥后加密字符串
*
* @param modulus
* @param exponent
* @param text
* @return
*/
public static String encrypt(String modulus, String exponent, String text) {
try {
byte[] aryExponent = Base64.decodeBase64(exponent);
byte[] aryModulus = Base64.decodeBase64(modulus);
BigInteger bigExponent = new BigInteger(1, aryExponent);
BigInteger bigModulus = new BigInteger(1, aryModulus);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigModulus,
bigExponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return encrypt(publicKey, text);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过私钥和数组解密
*
* @param privateKey
* 私钥
* @param data
* 数据
* @return 解密后的数据
*/
@SuppressWarnings({ "deprecation", "static-access" })
public static byte[] decrypt(PrivateKey privateKey, byte[] data) {
Assert.notNull(privateKey);
Assert.notNull(data);
try {
Cipher cipher = Cipher.getInstance("RSA", PROVIDER);
cipher.init(cipher.DECRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过私钥和数组解密 - 有模式
*
* @param mode
* 模式
* @param privateKey
* 私钥
* @param data
* 数据
* @return 解密后的数据
*/
@SuppressWarnings({ "deprecation", "static-access" })
public static byte[] decrypt(String mode, PrivateKey privateKey, byte[] data) {
Assert.notNull(privateKey);
Assert.notNull(data);
try {
Cipher cipher = Cipher.getInstance(mode, PROVIDER);
cipher.init(cipher.DECRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过私钥和数组解密 - 点位图用
*
* @param privateKey
* 私钥
* @param data
* 数据
* @return 解密后的数据
*/
@SuppressWarnings({ "deprecation", "static-access" })
public static byte[] decryptForBitmap(PrivateKey privateKey, byte[] data) {
Assert.notNull(privateKey);
Assert.notNull(data);
try {
// 点位图ios端使用了默认的填充模式: RSA/ECB/PKCS1Padding
Cipher cipher = Cipher
.getInstance("RSA/ECB/PKCS1Padding", PROVIDER);
cipher.init(cipher.DECRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 通过私钥和字符串解密
*
* @param privateKey
* 私钥
* @param text
* Base64编码字符串
* @return 解密后的数据
*/
@SuppressWarnings("deprecation")
public static String decrypt(PrivateKey privateKey, String text) {
Assert.notNull(privateKey);
Assert.notNull(text);
byte[] data = decrypt(privateKey, Base64.decodeBase64(text));
return data != null ? new String(data) : null;
}
/**
* 通过私钥和字符串解密 - 有模式
*
* @param mode
* 模式
* @param privateKey
* 私钥
* @param text
* Base64编码字符串
* @return 解密后的数据
*/
@SuppressWarnings("deprecation")
public static String decrypt(String mode, PrivateKey privateKey, String text) {
Assert.notNull(privateKey);
Assert.notNull(text);
byte[] data = decrypt(mode, privateKey, Base64.decodeBase64(text));
return data != null ? new String(data) : null;
}
/**
* 通过私钥和字符串解密 - 点位图
*
* @param privateKey
* 私钥
* @param text
* Base64编码字符串
* @return 解密后的数据
*/
@SuppressWarnings("deprecation")
public static String decryptForBitmap(PrivateKey privateKey, String text) {
Assert.notNull(privateKey);
Assert.notNull(text);
byte[] data = decryptForBitmap(privateKey, Base64.decodeBase64(text));
return data != null ? new String(data) : null;
}
/**
* 通过私钥的模量和指数构建私钥后和字符串解密
*
* @param modulus
* @param exponent
* @param text
* @return
*/
public static String decrypt(String modulus, String exponent, String text) {
try {
byte[] aryExponent = Base64.decodeBase64(exponent);
byte[] aryModulus = Base64.decodeBase64(modulus);
BigInteger bigExponent = new BigInteger(1, aryExponent);
BigInteger bigModulus = new BigInteger(1, aryModulus);
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigModulus,
bigExponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return decrypt(privateKey, text);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String exponent = "AQAB";
String modulus = "AKJ7e1Lhn5kBnQQ++UWl8MJn9dGwCoTdXExlOsI6YVZkq4+R+Qb3gNo5v1TgHgfS2EMQ0YChr2//nJdmKc1w8bAz6XPRD4L2ZXnKDTfTOmKcel1jC7CzNUY5M1ahhEQeI6f367loH2me9UwScBN8rtIeGEGhP8E8DVriTk9g1xFv";
String password = "admin123";
System.out.print(encrypt(modulus, exponent, password));
}
}
\ No newline at end of file
package cn.wisenergy.common.utils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类
*
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private ValueOperations<String, String> valueOperations;
@Autowired
private HashOperations<String, String, Object> hashOperations;
@Autowired
private ListOperations<String, Object> listOperations;
@Autowired
private SetOperations<String, Object> setOperations;
@Autowired
private ZSetOperations<String, Object> zSetOperations;
/** 不设置过期时长 */
public final static long NOT_EXPIRE = -1;
public void set(String key, Object value){
set(key, value);
}
public void set(String key, Object value, long expire){
valueOperations.set(key, toJson(value), expire, TimeUnit.SECONDS);
}
public void set(String key, Object value, long expire, TimeUnit var5){
valueOperations.set(key, toJson(value), expire, var5);
}
public <T> T get(String key, Class<T> clazz, long expire) {
String value = valueOperations.get(key);
if(expire != NOT_EXPIRE){
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value == null ? null : fromJson(value, clazz);
}
public <T> T get(String key, Class<T> clazz) {
return get(key, clazz, NOT_EXPIRE);
}
public String get(String key, long expire) {
String value = valueOperations.get(key);
if(expire != NOT_EXPIRE){
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value;
}
public String get(String key) {
return get(key, NOT_EXPIRE);
}
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
/**
* Object转成JSON数据
*/
private String toJson(Object object){
if(object instanceof Integer || object instanceof Long || object instanceof Float ||
object instanceof Double || object instanceof Boolean || object instanceof String){
return String.valueOf(object);
}
return JSON.toJSONString(object);
}
/**
* JSON数据,转成Object
*/
private <T> T fromJson(String json, Class<T> clazz){
return JSON.parseObject(json, clazz);
}
}
package cn.wisenergy.common.utils;
import java.util.Random;
/**
* 生成充值卡子卡秘钥工具类
* @author 86187
*/
public class SecretkeyUtil {
//字符串长度
static final int LENGTH= 16;
//开头数字最小长度
static final int MIN_LENGTH_OF_NUMBER= 4;
//字母拼接最大位置
static final int MAX_LENGTH_OF_STRING=11;
public static String getSecretkey(){
char[] chars={'a','b','c','d','e','f','g','h','l','j','k','i','m','n','o','p','q','r','s','t','y','u','w','x','v','z'};
StringBuilder stringBuilder=new StringBuilder(16);
Random random = new Random();
int i1 =random.nextInt(4)+MIN_LENGTH_OF_NUMBER;
for (int i = 0; i <i1; i++) {
stringBuilder.append(random.nextInt(9));
}
while (i1<MAX_LENGTH_OF_STRING) {
int i2 =random.nextInt(25);
if (i2 < 26) {
stringBuilder.append(chars[i2]);
i1++;
}
}
for (int i = MAX_LENGTH_OF_STRING; i <LENGTH ; i++) {
stringBuilder.append(random.nextInt(9));
}
return stringBuilder.toString();
}
}
package cn.wisenergy.common.utils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component("springUtils")
@Lazy(false)
public final class SpringUtils implements ApplicationContextAware,
DisposableBean {
/**
* applicationContext
*/
private static ApplicationContext applicationContext;
/**
* 不可实例化
*/
private SpringUtils() {
}
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtils.applicationContext = applicationContext;
}
public void destroy() throws Exception {
applicationContext = null;
}
/**
* 获取applicationContext
*
* @return applicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取实例
*
* @param name
* Bean名称
* @return 实例
*/
@SuppressWarnings("deprecation")
public static Object getBean(String name) {
Assert.hasText(name);
return applicationContext.getBean(name);
}
/**
* 获取实例
*
* @param name
* Bean名称
* @param type
* Bean类型
* @return 实例
*/
@SuppressWarnings("deprecation")
public static <T> T getBean(String name, Class<T> type) {
Assert.hasText(name);
Assert.notNull(type);
return applicationContext.getBean(name, type);
}
}
package cn.wisenergy.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 时间格式转换工具类
*/
public class TimeUtil {
private static final String timeFormat = "yyyy-MM-dd HH:mm";
private static final String dateFormat = "yyyy-MM-dd";
/**
* 时间日期格式
*
* @param time
* @return
* @throws ParseException
*/
public static Date getTime(String time) throws ParseException {
SimpleDateFormat ft = new SimpleDateFormat(timeFormat);
return ft.parse(time);
}
/**
* 时间日期格式
*
* @param time
* @return
*/
public static String getTime(Date time) {
SimpleDateFormat ft = new SimpleDateFormat(timeFormat);
return ft.format(time);
}
/**
* 日期格式
*
* @param date
* @return
* @throws ParseException
*/
public static Date getDate(String date) throws ParseException {
SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
return ft.parse(date);
}
/**
* 日期格式
*
* @param date
* @return
*/
public static String getDate(Date date) {
SimpleDateFormat ft = new SimpleDateFormat(dateFormat);
return ft.format(date);
}
/**
* 将日期转化成毫秒
*
* @param date
* @return
*/
public static Long getTimeMill(Date date) {
return date.getTime();
}
/**
* 将毫秒转化为日期
*
* @param time
* @return
*/
public static Date getTimeMill(Long time) {
Date date = new Date();
date.setTime(time);
return date;
}
/**
* 两个时间相差的分钟数
*
* @param time1
* @param time2
* @return
* @Description:
*/
public static Integer getDistanceMinutes(Date time1, Date time2) {
try {
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
String fromDate = simpleFormat.format(time1);
String toDate = simpleFormat.format(time2);
long from = simpleFormat.parse(fromDate).getTime();
long to = simpleFormat.parse(toDate).getTime();
int minutes = (int) ((to - from) / (1000 * 60));
return minutes;
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
}
package cn.wisenergy.common.utils.exception;
import cn.wisenergy.common.enums.RespCodeEnum;
/**
* 接口异常对象
*/
public class BaseCustomException extends RuntimeException {
private static final long serialVersionUID = -4974461182923482972L;
// 错误编码
private String errorCode;
// 错误编码信息
private String errorMsg;
/**
* 应用接口有参构造函数
*
* @param errorCode 错误编码
* @param errorMsg 错误信息
*/
public BaseCustomException(String errorCode, String errorMsg) {
super("errorCode:" + errorCode + " errorMsg:" + errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
/**
* 应用接口有参构造函数
*
* @param baseResponseCodeEnum 基本响应枚举类
*/
public BaseCustomException(RespCodeEnum baseResponseCodeEnum) {
super("errorCode:" + baseResponseCodeEnum.getCode() + " errorMsg:" + baseResponseCodeEnum.getMsg());
this.errorCode = baseResponseCodeEnum.getCode();
this.errorMsg = baseResponseCodeEnum.getMsg();
}
/**
* 获取错误编码
*/
public String getErrorCode() {
return errorCode;
}
/**
* 设置错误编码
*/
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
/**
* 获取异常编码
*/
public String getErrorMsg() {
return errorMsg;
}
/**
* 设置异常编码
*/
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
package cn.wisenergy.common.utils.exception;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author wyy
* @date 2019-10-11 20:51
*/
@Data
@ApiModel("返回结果")
public class Result<T> {
// 结果标识
@ApiModelProperty(value = "结果标识",example = "success")
private String result;
// 错误编码
@ApiModelProperty(value = "错误编码",example = "1001")
private String errorCode;
// 错误信息
@ApiModelProperty(value = "错误信息",example = "操作成功")
public String errorMsg;
// 封装数据的参数名称
@ApiModelProperty(value = "返回结果")
private T data;
/**
* 结果参数枚举
*/
public enum RESULT_FLG {
SUCCESS("success"),
FAIL("fail");
/**
* 值变量
*/
private String value;
/**
* 含有结果值的构造函数
*
* @param value
*/
private RESULT_FLG(String value) {
this.value = value;
}
/**
* 获取值
*
* @return
*/
public String getValue() {
return this.value;
}
}
}
package cn.wisenergy.common.utils.exportView.convert;
/**
* 类型转化接口
*/
public interface Convert {
String convert(String value);
}
This diff is collapsed.
workspace
.project
.classpath
*.settings
.idea
*.class
target/
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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