Commit cc19b0a8 by 王能兵

Merge branch 'dev' into 'master'

初始化商城项目

See merge request !1
2 parents 27ffba4a 9d5a3c9e
Showing 558 changed files with 162 additions and 3809 deletions
...@@ -128,7 +128,7 @@ _商品素材取自小米商城_ ...@@ -128,7 +128,7 @@ _商品素材取自小米商城_
## 如果下面配置无法自动建表并导入测试数据文件;则可以手动初始化数据库,手动使用的初始化文件文件位于:doc/database.sql ## 如果下面配置无法自动建表并导入测试数据文件;则可以手动初始化数据库,手动使用的初始化文件文件位于:doc/database.sql
spring.jpa.hibernate.ddl-auto=create spring.jpa.hibernate.ddl-auto=create
``` ```
- 启动linjiashop-admin-api主类:cn.enilu.flash.api.AdminApiApplication,访问http://localhost:8082/swagger-ui.html , 保证api服务启动成功 - 启动linjiashop-admin-api主类:com.glsx.shop.api.AdminApiApplication,访问http://localhost:8082/swagger-ui.html , 保证api服务启动成功
- 启动后台管理的前端界面:linjiashop-admin - 启动后台管理的前端界面:linjiashop-admin
- 运行 npm install --registry=https://registry.npm.taobao.org - 运行 npm install --registry=https://registry.npm.taobao.org
- 运行npm run dev - 运行npm run dev
...@@ -136,7 +136,7 @@ _商品素材取自小米商城_ ...@@ -136,7 +136,7 @@ _商品素材取自小米商城_
- 启动手机端商城 - 启动手机端商城
- 启动手商城的api服务:linjiashop-mobile-api - 启动手商城的api服务:linjiashop-mobile-api
- 修改linjiashop-mobile-api中数据库连接欸配置 - 修改linjiashop-mobile-api中数据库连接欸配置
- 启动linjiashop-mobile-api主类:cn.enilu.flash.MobileApiApplication,访问http://localhost:8081/swagger-ui.html , 保证api服务启动成功 - 启动linjiashop-mobile-api主类:com.glsx.shop.MobileApiApplication,访问http://localhost:8081/swagger-ui.html , 保证api服务启动成功
- 启动手机商城的前端:linjiashop-mobile - 启动手机商城的前端:linjiashop-mobile
- 运行 npm install --registry=https://registry.npm.taobao.org - 运行 npm install --registry=https://registry.npm.taobao.org
- 运行npm run dev - 运行npm run dev
......
This diff could not be displayed because it is too large.
DROP TABLE IF EXISTS `t_platform_customer`;
CREATE TABLE `t_platform_customer` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`customer_name` VARCHAR(32) DEFAULT NULL COMMENT '客户名称',
`contact_person` VARCHAR(32) DEFAULT NULL COMMENT '联系人',
`password` VARCHAR(64) DEFAULT NULL COMMENT '密码',
`contact_number` VARCHAR(11) DEFAULT NULL COMMENT '联系电话',
`contact_email` VARCHAR(32) DEFAULT NULL COMMENT '联系邮箱',
`province` INT(11) DEFAULT NULL COMMENT '省份 sys_area的id',
`city` INT(11) DEFAULT NULL COMMENT '城市 sys_area的id',
`address` VARCHAR(128) DEFAULT NULL COMMENT '详细地址',
`status` TINYINT(2) DEFAULT NULL COMMENT '账号状态 0 停用 1 正常 2 待审核 3 审核未通过',
`public_key` VARCHAR(256) DEFAULT NULL COMMENT '公钥',
`private_key` VARCHAR(256) DEFAULT NULL COMMENT '私钥',
`channel_number` VARCHAR(32) DEFAULT NULL COMMENT '渠道号',
`create_time` DATETIME DEFAULT NULL COMMENT '创建d时间',
`update_time` DATETIME DEFAULT NULL COMMENT '更新时间',
`create_by` INT(11) DEFAULT NULL COMMENT '创建人',
`update_by` INT(11) DEFAULT NULL COMMENT '更新人',
`remark` VARCHAR(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
UNIQUE KEY `contact_channel_number` (`contact_number`, `channel_number`)
) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8mb4 COMMENT ='客户管理表';
DROP TABLE IF EXISTS `t_platform_customer`;
CREATE TABLE `t_platform_device` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`device_sn` varchar(32) DEFAULT NULL COMMENT '设备SN',
`device_type` varchar(32) DEFAULT NULL COMMENT '类型',
`customer_id` int(11) DEFAULT NULL COMMENT '客户id t_platform_customer表的id',
`activat_time` datetime DEFAULT NULL COMMENT '激活时间',
`status` tinyint(2) DEFAULT NULL COMMENT '设备状态 0 异常 1 正常',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`create_by` int(11) DEFAULT NULL COMMENT '创建人',
`update_by` int(11) DEFAULT NULL COMMENT '更新人',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='设备管理表';
DROP TABLE IF EXISTS `t_platform_user`;
CREATE TABLE `t_platform_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`nickname` varchar(32) DEFAULT NULL COMMENT '昵称,账号',
`contact_number` varchar(11) DEFAULT NULL COMMENT '联系电话',
`wechat_id` varchar(32) DEFAULT NULL COMMENT '微信ID',
`province` int(11) DEFAULT NULL COMMENT '省份 sys_area的id',
`city` int(11) DEFAULT NULL COMMENT '城市 sys_area的id',
`customer_id` int(11) DEFAULT NULL COMMENT '客户id t_platform_customer表的id',
`last_login_time` datetime DEFAULT NULL COMMENT '最后登录时间',
`app_account_id` int(11) DEFAULT NULL COMMENT 'APP 账户ID',
`tu_ya_id` int(11) DEFAULT NULL COMMENT '涂鸦平台ID',
`create_time` datetime DEFAULT NULL COMMENT '创建时间 注册时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`create_by` int(11) DEFAULT NULL COMMENT '创建人',
`update_by` int(11) DEFAULT NULL COMMENT '更新人',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`),
UNIQUE KEY `contact_number` (`contact_number`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='用户管理表';
DROP TABLE IF EXISTS `t_platform_api`;
CREATE TABLE `t_platform_api` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`api_classification` tinyint(2) DEFAULT NULL COMMENT 'API分类 1 授权管理 2 设备管理 3 数据服务',
`api_name` varchar(32) DEFAULT NULL COMMENT 'API名称',
`request_method` tinyint(2) DEFAULT NULL COMMENT '请求方式 1 GET 2 POST',
`api_interface` varchar(255) DEFAULT NULL COMMENT 'API接口',
`description` varchar(128) DEFAULT NULL COMMENT '说明',
`status` tinyint(2) DEFAULT NULL COMMENT '状态 0 停用 1 可用',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`create_by` int(11) DEFAULT NULL COMMENT '创建人',
`update_by` int(11) DEFAULT NULL COMMENT '更新人',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='api管理表';
DROP TABLE IF EXISTS `t_platform_api_call`;
CREATE TABLE `t_platform_api_call` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`customer_id` int(11) DEFAULT NULL COMMENT '客户id t_platform_customer表的id',
`api_id` int(11) DEFAULT NULL COMMENT '调用API id t_platform_api 的id',
`call_result` tinyint(2) DEFAULT NULL COMMENT '调用结果 0 失败 1 成功',
`create_time` datetime DEFAULT NULL COMMENT '创建时间 访问时间',
`create_by` int(11) DEFAULT NULL COMMENT '创建人',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='api调用表';
DROP TABLE IF EXISTS `t_platform_ad`;
CREATE TABLE `t_platform_ad` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`title` varchar(32) DEFAULT NULL COMMENT '标题',
`image` varchar(128) DEFAULT NULL COMMENT '图片',
`position` tinyint(2) DEFAULT NULL COMMENT '位置 1 商城banner 2 智能-家 3 启动页',
`interface_type` tinyint(2) DEFAULT NULL COMMENT ' 界面类型 1 APP 2 H5',
`interface_url` varchar(128) DEFAULT NULL COMMENT '界面参数',
`status` tinyint(2) DEFAULT NULL COMMENT '是否上架 0 下架 1 上架',
`create_time` datetime DEFAULT NULL COMMENT '创建时间 添加时间',
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
`create_by` int(11) DEFAULT NULL COMMENT '创建人',
`update_by` int(11) DEFAULT NULL COMMENT '更新人',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='广告管理表';
DROP TABLE IF EXISTS `t_platform_app_download`;
CREATE TABLE `t_platform_app_download` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`customer_id` int(11) DEFAULT NULL COMMENT '客户id t_platform_customer表的id',
`create_time` datetime DEFAULT NULL COMMENT '创建时间 下载时间',
`create_by` int(11) DEFAULT NULL COMMENT '创建人',
`remark` varchar(50) DEFAULT NULL COMMENT '备注',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='APP下载数量表';
...@@ -1277,8 +1277,8 @@ CREATE TABLE `t_sys_task` ( ...@@ -1277,8 +1277,8 @@ CREATE TABLE `t_sys_task` (
-- ---------------------------- -- ----------------------------
-- Records of t_sys_task -- Records of t_sys_task
-- ---------------------------- -- ----------------------------
INSERT INTO `t_sys_task` VALUES ('1', '1', '2018-12-28 09:54:00', '-1', '2020-01-20 10:04:57', '0', '0 0/30 * * * ?', '{\n\"appname\": \"linjiashop\",\n\"version\":1}', '0', '2020-01-20 10:04:57', '执行成功', 'cn.enilu.flash.service.task.job.HelloJob', 'default', '测试任务', '测试任务,每30分钟执行一次'); INSERT INTO `t_sys_task` VALUES ('1', '1', '2018-12-28 09:54:00', '-1', '2020-01-20 10:04:57', '0', '0 0/30 * * * ?', '{\n\"appname\": \"linjiashop\",\n\"version\":1}', '0', '2020-01-20 10:04:57', '执行成功', 'com.glsx.shop.service.task.job.HelloJob', 'default', '测试任务', '测试任务,每30分钟执行一次');
INSERT INTO `t_sys_task` VALUES ('2', '1', '2020-01-19 17:40:02', '-1', '2020-01-20 10:04:57', '0', '0 0 0/1 * * ?', '', '0', '2020-01-19 19:25:00', '执行失败', 'cn.enilu.flash.service.task.job.UpdateWeixinTokenJob', null, '更新微信token', '获取微信token,每小时获取一次'); INSERT INTO `t_sys_task` VALUES ('2', '1', '2020-01-19 17:40:02', '-1', '2020-01-20 10:04:57', '0', '0 0 0/1 * * ?', '', '0', '2020-01-19 19:25:00', '执行失败', 'com.glsx.shop.service.task.job.UpdateWeixinTokenJob', null, '更新微信token', '获取微信token,每小时获取一次');
-- ---------------------------- -- ----------------------------
-- Table structure for `t_sys_task_log` -- Table structure for `t_sys_task_log`
......
...@@ -127,7 +127,7 @@ linjiashop包含了后台管理功能和手机端商城业务功能 ...@@ -127,7 +127,7 @@ linjiashop包含了后台管理功能和手机端商城业务功能
## 如果下面配置无法自动建表并导入测试数据文件;则可以手动初始化数据库,手动使用的初始化文件文件位于:doc/database.sql ## 如果下面配置无法自动建表并导入测试数据文件;则可以手动初始化数据库,手动使用的初始化文件文件位于:doc/database.sql
spring.jpa.hibernate.ddl-auto=create spring.jpa.hibernate.ddl-auto=create
``` ```
- 启动linjiashop-admin-api主类:cn.enilu.flash.api.AdminApiApplication,访问http://localhost:8082/swagger-ui.html , 保证api服务启动成功 - 启动linjiashop-admin-api主类:com.glsx.shop.api.AdminApiApplication,访问http://localhost:8082/swagger-ui.html , 保证api服务启动成功
- 启动后台管理的前端界面:linjiashop-admin - 启动后台管理的前端界面:linjiashop-admin
- 运行 npm install --registry=https://registry.npm.taobao.org - 运行 npm install --registry=https://registry.npm.taobao.org
- 运行npm run dev - 运行npm run dev
...@@ -135,7 +135,7 @@ linjiashop包含了后台管理功能和手机端商城业务功能 ...@@ -135,7 +135,7 @@ linjiashop包含了后台管理功能和手机端商城业务功能
- 启动手机端商城 - 启动手机端商城
- 启动手商城的api服务:linjiashop-mobile-api - 启动手商城的api服务:linjiashop-mobile-api
- 修改linjiashop-mobile-api中数据库连接欸配置 - 修改linjiashop-mobile-api中数据库连接欸配置
- 启动linjiashop-mobile-api主类:cn.enilu.flash.MobileApiApplication,访问http://localhost:8081/swagger-ui.html , 保证api服务启动成功 - 启动linjiashop-mobile-api主类:com.glsx.shop.MobileApiApplication,访问http://localhost:8081/swagger-ui.html , 保证api服务启动成功
- 启动手机商城的前端:linjiashop-mobile - 启动手机商城的前端:linjiashop-mobile
- 运行 npm install --registry=https://registry.npm.taobao.org - 运行 npm install --registry=https://registry.npm.taobao.org
- 运行npm run dev - 运行npm run dev
......
...@@ -51,7 +51,7 @@ ...@@ -51,7 +51,7 @@
- 该模块为linjiashop-admin提供数据接口服务 - 该模块为linjiashop-admin提供数据接口服务
- 开发过程中可以通过swagger来调试接口,通过swagger提供了在线测试工具,项目启动后,可以访问https://ip:端口/swagger-ui.html,比如本项目演示环境的api测试地址为:[http://linjiashop-admin-api.microapp.store/swagger-ui.html](http://linjiashop-admin-api.microapp.store/swagger-ui.html) - 开发过程中可以通过swagger来调试接口,通过swagger提供了在线测试工具,项目启动后,可以访问https://ip:端口/swagger-ui.html,比如本项目演示环境的api测试地址为:[http://linjiashop-admin-api.microapp.store/swagger-ui.html](http://linjiashop-admin-api.microapp.store/swagger-ui.html)
- 测试的时候,需要先调用/account/login登录系统并获取token,然后调用每个接口测试的时候将token放进去 - 测试的时候,需要先调用/account/login登录系统并获取token,然后调用每个接口测试的时候将token放进去
- 如果要定义自己的过滤规则,可以通过修改:cn.enilu.flash.api.config.ShiroConfig中的配置来实现。 - 如果要定义自己的过滤规则,可以通过修改:com.glsx.shop.api.config.ShiroConfig中的配置来实现。
## 用户端系统 ## 用户端系统
......
####
POST {{domain_admin}}/account/login?username=test1&password=123456
> {% client.global.set("auth", response.body.data.token) %}
####
GET {{domain_admin}}/area/getFullAreaName?id=
Authorization: {{auth}}
####
GET {{domain_admin}}/area/getList?parentId=
Authorization: {{auth}}
####
GET {{domain_admin}}/area/getListRecursively?parentId=0
Authorization: {{auth}}
####
POST {{domain_mobile}}/file/uploadFile
Authorization: {{auth}}
####
POST {{domain_mobile}}/file/deleteFile?fileUrl=http://qcimg01.glsx.net:7060/group1/M00/00/06/wKgD3l_Yj_mAZrJLAAjtN_iqiFA500.sql
Authorization: {{auth}}
{
"local": {
"domain_admin": "http://localhost:8082",
"domain_mobile": "http://localhost:8081"
}
}
package cn.enilu.flash.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 跨域配置
*
* @author enilu
* @version 2018-07-25
*/
@Configuration
public class CORSConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("*");
}
};
}
}
\ No newline at end of file \ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
/** /**
* prism.js default theme for JavaScript, CSS and HTML * prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com) * Based on dabblet (http://dabblet.com)
* @author Lea Verou * @author glsx
*/ */
code[class*="language-"], code[class*="language-"],
......
package cn.enilu.flash.bean.vo.front;
public class Rets {
public static final Integer SUCCESS = 20000;
public static final Integer FAILURE = 9999;
public static final Integer TOKEN_EXPIRE = 50014;
public static Ret success(Object data) {
return new Ret(Rets.SUCCESS, "成功", data);
}
public static Ret failure(String msg) {
return new Ret(Rets.FAILURE, msg, null);
}
public static Ret success() {
return new Ret(Rets.SUCCESS, "成功", null);
}
public static Ret expire() {
return new Ret(Rets.TOKEN_EXPIRE, "token 过期", null);
}
}
package cn.enilu.flash.dao.cms;
import cn.enilu.flash.bean.entity.cms.Channel;
import cn.enilu.flash.dao.BaseRepository;
public interface ChannelRepository extends BaseRepository<Channel, Long> {
}
package cn.enilu.flash.dao.cms;
import cn.enilu.flash.bean.entity.cms.Contacts;
import cn.enilu.flash.dao.BaseRepository;
public interface ContactsRepository extends BaseRepository<Contacts, Long> {
}
package cn.enilu.flash.dao.promotion;
import cn.enilu.flash.bean.entity.promotion.Topic;
import cn.enilu.flash.dao.BaseRepository;
public interface TopicRepository extends BaseRepository<Topic, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.Address;
import cn.enilu.flash.dao.BaseRepository;
public interface AddressRepository extends BaseRepository<Address, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.AttrKey;
import cn.enilu.flash.dao.BaseRepository;
public interface AttrKeyRepository extends BaseRepository<AttrKey, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.AttrVal;
import cn.enilu.flash.dao.BaseRepository;
public interface AttrValRepository extends BaseRepository<AttrVal, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.Cart;
import cn.enilu.flash.dao.BaseRepository;
public interface CartRepository extends BaseRepository<Cart, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.Category;
import cn.enilu.flash.dao.BaseRepository;
public interface CategoryRepository extends BaseRepository<Category, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.Favorite;
import cn.enilu.flash.dao.BaseRepository;
public interface FavoriteRepository extends BaseRepository<Favorite, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.Goods;
import cn.enilu.flash.dao.BaseRepository;
public interface GoodsRepository extends BaseRepository<Goods, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.GoodsSku;
import cn.enilu.flash.dao.BaseRepository;
public interface GoodsSkuRepository extends BaseRepository<GoodsSku, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.OrderItem;
import cn.enilu.flash.dao.BaseRepository;
public interface OrderItemRepository extends BaseRepository<OrderItem, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.OrderLog;
import cn.enilu.flash.dao.BaseRepository;
public interface OrderLogRepository extends BaseRepository<OrderLog, Long> {
}
package cn.enilu.flash.dao.shop;
import cn.enilu.flash.bean.entity.shop.Order;
import cn.enilu.flash.dao.BaseRepository;
public interface OrderRepository extends BaseRepository<Order, Long> {
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.Dept;
import cn.enilu.flash.dao.BaseRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* Created on 2018/3/21 0021.
*
* @author enilu
*/
public interface DeptRepository extends BaseRepository<Dept, Long> {
List<Dept> findByPidsLike(String pid);
@Query(nativeQuery = true, value = "SELECT id, pid AS pId, simplename AS NAME, ( CASE WHEN (pId = 0 OR pId IS NULL) THEN 'true' ELSE 'false' END ) AS isOpen FROM t_sys_dept")
List tree();
List<Dept> findBySimplenameLikeOrFullnameLike(String name, String name2);
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.Express;
import cn.enilu.flash.dao.BaseRepository;
public interface ExpressRepository extends BaseRepository<Express, Long> {
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.FileInfo;
import cn.enilu.flash.dao.BaseRepository;
public interface FileInfoRepository extends BaseRepository<FileInfo, Long> {
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.LoginLog;
import cn.enilu.flash.dao.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
/**
* Created on 2018/3/21 0021.
*
* @author enilu
*/
public interface LoginLogRepository extends BaseRepository<LoginLog, Long> {
@Modifying
@Transactional
@Query(nativeQuery = true, value = "delete from t_sys_login_log")
int clear();
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.OperationLog;
import cn.enilu.flash.dao.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
/**
* Created on 2018/3/21 0021.
*
* @author enilu
*/
public interface OperationLogRepository extends BaseRepository<OperationLog, Long> {
@Modifying
@Transactional
@Query(nativeQuery = true, value = "delete from t_sys_operation_log")
int clear();
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.Relation;
import cn.enilu.flash.dao.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
/**
* Created on 2018/3/21 0021.
*
* @author enilu
*/
public interface RelationRepository extends BaseRepository<Relation, Long> {
@Transactional
@Modifying
@Query(nativeQuery = true, value = "delete from t_sys_relation where roleid=?1")
int deleteByRoleId(Long roleId);
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.Role;
import cn.enilu.flash.dao.BaseRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* Created on 2018/3/21 0021.
*
* @author enilu
*/
public interface RoleRepository extends BaseRepository<Role, Long> {
@Query(nativeQuery = true, value = "SELECT id, pId, NAME, ( CASE WHEN (pId = 0 OR pId IS NULL) THEN 'true' ELSE 'false' END ) OPEN FROM t_sys_role")
List roleTreeList();
@Query(nativeQuery = true, value = "SELECT r.id AS id, pId AS pId, NAME AS NAME, ( CASE WHEN (pId = 0 OR pId IS NULL) THEN 'true' ELSE 'false' END ) \"open\", ( CASE WHEN (r1.ID = 0 OR r1.ID IS NULL) THEN 'false' ELSE 'true' END ) AS checked FROM t_sys_role r LEFT JOIN ( SELECT ID FROM t_sys_role WHERE ID IN (?1)) r1 ON r.ID = r1.ID ORDER BY pId, num ASC")
List roleTreeListByRoleId(Long[] ids);
List findByName(String roleName);
}
package cn.enilu.flash.dao.system;
import cn.enilu.flash.bean.entity.system.TaskLog;
import cn.enilu.flash.dao.BaseRepository;
public interface TaskLogRepository extends BaseRepository<TaskLog, Long> {
}
package cn.enilu.flash.security;
import org.apache.shiro.authc.AuthenticationToken;
/**
* @author :enilu
* @date :Created in 2019/7/30 22:58
*/
public class JwtToken implements AuthenticationToken {
/**
* 密钥
*/
private String token;
public JwtToken(String token) {
this.token = token;
}
@Override
public Object getPrincipal() {
return token;
}
@Override
public Object getCredentials() {
return token;
}
}
\ No newline at end of file \ No newline at end of file
package cn.enilu.flash.security;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.utils.JsonUtil;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author :enilu
* @date :Created in 11/19/2019 2:28 PM
*/
public class SystemLogoutFilter extends LogoutFilter {
private static final Logger logger = LoggerFactory.getLogger(SystemLogoutFilter.class);
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
Subject subject = getSubject(request, response);
try {
subject.logout();
} catch (Exception ex) {
logger.error("退出登录错误", ex);
}
this.writeResult(response);
//不执行后续的过滤器
return false;
}
private void writeResult(ServletResponse response) {
//响应Json结果
PrintWriter out = null;
try {
out = response.getWriter();
out.append(JsonUtil.toJson(Rets.success()));
} catch (IOException e) {
logger.error("返回Response信息出现IOException异常:" + e.getMessage());
} finally {
if (out != null) {
out.close();
}
}
}
}
package cn.enilu.flash.service;
/**
* @author :enilu
* @date :Created in 2019/6/29 22:29
*/
public interface DeleteService<T, ID> {
/**
* 删除指定实体
*
* @param record
*/
void delete(T record);
/**
* 根据主键删除记录
*
* @param id 主键
*/
void deleteById(ID id);
/**
* 根据主键删除记录
*
* @param ids 主键集合
*/
void delete(Iterable<ID> ids);
/**
* 删除指定的数据列表
*
* @param list
*/
void deleteAll(Iterable<T> list);
/**
* 清空表数据
*/
void clear();
}
package cn.enilu.flash.service;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.utils.factory.Page;
import org.springframework.data.domain.Sort;
import java.util.List;
import java.util.Map;
/**
* @author :enilu
* @date :Created in 2019/6/29 22:30
*/
public interface SelectService<T, ID> {
/**
* 根据主键查询
*
* @param id 主键
* @return 查询结果, 无结果时返回{@code null}
*/
T get(ID id);
T get(SearchFilter filter);
T get(List<SearchFilter> filters);
Object get(String sql, Class<?> klass);
List<Map> queryBySql(String sql);
Map getMapBySql(String sql);
/**
* 根据多个主键查询
*
* @param ids 主键集合
* @return 查询结果, 如果无结果返回空集合
*/
List<T> query(Iterable<ID> ids);
/**
* 查询所有结果
*
* @return 所有结果, 如果无结果则返回空集合
*/
List<T> queryAll();
/**
* 查询所有结果
*
* @return 获取分页结果
*/
Page<T> queryPage(Page<T> page);
/**
* 根据多个条件查询列表数据
*
* @param filters
* @return
*/
List<T> queryAll(List<SearchFilter> filters);
/**
* 根据多个条件查询列表数据,并排序
*
* @param filters
* @param sort
* @return
*/
List<T> queryAll(List<SearchFilter> filters, Sort sort);
/**
* 根据的单个条件查询列表数据
*
* @param filter
* @return
*/
List<T> queryAll(SearchFilter filter);
/**
* 根据的单个条件查询列表数据
*
* @param filter
* @param sort
* @return
*/
List<T> queryAll(SearchFilter filter, Sort sort);
/**
* 查询记录数
*
* @param filter
* @return
*/
long count(SearchFilter filter);
/**
* 查询总记录
*
* @return
*/
long count();
/**
* 查询记录数
*
* @param filters
* @return
*/
long count(List<SearchFilter> filters);
}
package cn.enilu.flash.service;
/**
* @author :enilu
* @date :Created in 2019/6/29 22:30
*/
public interface UpdateService<T, ID> {
/**
* 修改记录信息
*
* @param record 要修改的对象
* @return 返回修改的记录
*/
T update(T record);
/**
* 批量更新
*
* @param list
*/
void update(Iterable<T> list);
}
package cn.enilu.flash.service.api;
import lombok.Data;
import java.util.List;
/**
* @author :enilu
* @date :Created in 2020/6/1 0:22
*/
@Data
public class KdniaoResponse {
private Boolean Success;
private String State;
private String StateEx;
private String Location;
private List<Trace> Traces;
@Data
class Trace {
private String AcceptTime;
private String AcceptStation;
}
}
{
"LogisticCode": "YT45782342348",
"ShipperCode": "YTO",
"Traces": [
{
"AcceptStation": "【上海市奉贤区南桥公司】 已收件 取件人: 仰琪锋 (02167190359)",
"AcceptTime": "2020-05-25 15:59:59"
},
{
"AcceptStation": "【宁波转运中心公司】 已收入",
"AcceptTime": "2020-05-26 03:01:31"
},
{
"AcceptStation": "【宁波转运中心】 已发出 下一站 【上海市浦东新区博兴公司】",
"AcceptTime": "2020-05-26 03:22:31"
},
{
"AcceptStation": "【浙江省舟山市公司】 已收入",
"AcceptTime": "2020-05-26 06:31:51"
},
{
"AcceptStation": "快件已由上海市莱阳路431号店菜鸟驿站代收,请及时取件,如有疑问请联系13262707273",
"AcceptTime": "2020-05-28 11:33:33"
},
{
"AcceptStation": "客户签收人: 已签收,签收人凭取货码签收。 已签收 感谢使用圆通速递,期待再次为您服务 如有疑问请联系:13381798120,投诉电话:18521102150",
"AcceptTime": "2020-05-28 18:59:55"
}
],
"State": "3",
"EBusinessID": "1627883",
"Success": true
}
package cn.enilu.flash.service.cms;
import cn.enilu.flash.bean.entity.cms.Article;
import cn.enilu.flash.bean.enumeration.cms.ChannelEnum;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.dao.cms.ArticleRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.factory.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ArticleService extends BaseService<Article, Long, ArticleRepository> {
@Autowired
private ArticleRepository articleRepository;
/**
* 查询首页最近5条资讯数据
*
* @return
*/
public List<Article> queryIndexNews() {
Page<Article> page = query(1, 5, ChannelEnum.NEWS.getId());
return page.getRecords();
}
public Page<Article> query(int currentPage, int size, Long idChannel) {
Page page = new Page(currentPage, size, "id");
page.addFilter(SearchFilter.build("idChannel", SearchFilter.Operator.EQ, idChannel));
return queryPage(page);
}
}
package cn.enilu.flash.service.cms;
import cn.enilu.flash.bean.entity.cms.Banner;
import cn.enilu.flash.bean.enumeration.cms.BannerTypeEnum;
import cn.enilu.flash.bean.vo.offcialsite.BannerVo;
import cn.enilu.flash.dao.cms.BannerRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BannerService extends BaseService<Banner, Long, BannerRepository> {
@Autowired
private BannerRepository bannerRepository;
/**
* 查询首页banner数据
*
* @return
*/
public BannerVo queryIndexBanner() {
return queryBanner(BannerTypeEnum.INDEX.getValue());
}
public BannerVo queryBanner(String type) {
BannerVo banner = new BannerVo();
List<cn.enilu.flash.bean.entity.cms.Banner> bannerList = bannerRepository.findAllByType(type);
banner.setIndex(0);
banner.setList(bannerList);
return banner;
}
}
package cn.enilu.flash.service.cms;
import cn.enilu.flash.bean.entity.cms.Channel;
import cn.enilu.flash.dao.cms.ChannelRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.stereotype.Service;
/**
* 文章频道service
*
* @author :enilu
* @date :Created in 2019/6/30 13:06
*/
@Service
public class ChannelService extends BaseService<Channel, Long, ChannelRepository> {
}
package cn.enilu.flash.service.cms;
import cn.enilu.flash.bean.entity.cms.Contacts;
import cn.enilu.flash.dao.cms.ContactsRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.stereotype.Service;
@Service
public class ContactsService extends BaseService<Contacts, Long, ContactsRepository> {
}
package cn.enilu.flash.service.dashboard;
import cn.enilu.flash.bean.enumeration.shop.OrderEnum;
import cn.enilu.flash.service.shop.CartService;
import cn.enilu.flash.service.shop.OrderService;
import cn.enilu.flash.service.shop.ShopUserService;
import cn.enilu.flash.utils.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author :enilu
* @date :Created in 1/7/2020 2:25 PM
*/
@Service
public class DashboardService {
@Autowired
private OrderService orderService;
@Autowired
private ShopUserService shopUserService;
@Autowired
private CartService cartService;
public Map getDashboardData() {
long orderCount = orderService.count();
long userCount = shopUserService.count();
long cartCount = cartService.count();
Map orderSumPrice = orderService.getMapBySql("select sum(real_price) as realPrice from t_shop_order where status<>" + OrderEnum.OrderStatusEnum.UN_PAY.getId());
Map result = Maps.newHashMap(
"orderCount", orderCount,
"userCount", userCount,
"cartCount", cartCount,
"orderSumPrice", orderSumPrice != null ? (Double.valueOf(orderSumPrice.get("realPrice").toString()) / 100) : "0"
);
return result;
}
}
package cn.enilu.flash.service.message;
import cn.enilu.flash.bean.entity.message.MessageSender;
import cn.enilu.flash.bean.entity.message.MessageTemplate;
import cn.enilu.flash.dao.message.MessagesenderRepository;
import cn.enilu.flash.dao.message.MessagetemplateRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* MessagesenderService
*
* @author enilu
* @version 2019/05/17 0017
*/
@Service
public class MessagesenderService extends BaseService<MessageSender, Long, MessagesenderRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private MessagesenderRepository messageSenderRepository;
@Autowired
private MessagetemplateRepository messagetemplateRepository;
public void save(MessageSender messageSender) {
messageSenderRepository.save(messageSender);
}
@Override
public void deleteById(Long id) {
List<MessageTemplate> templateList = messagetemplateRepository.findByIdMessageSender(id);
if (templateList.isEmpty()) {
messageSenderRepository.deleteById(id);
} else {
throw new RuntimeException("有模板使用该发送器,无法删除");
}
}
}
package cn.enilu.flash.service.message;
import cn.enilu.flash.bean.entity.message.MessageTemplate;
import cn.enilu.flash.dao.message.MessagetemplateRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.stereotype.Service;
/**
* MessagetemplateService
*
* @author enilu
* @version 2019/05/17 0017
*/
@Service
public class MessagetemplateService extends BaseService<MessageTemplate, Long, MessagetemplateRepository> {
}
package cn.enilu.flash.service.message.email;
import cn.enilu.flash.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.internet.MimeMessage;
/**
* 默认的邮件发送服务类
*
* @author :enilu
* @date :Created in 2019/6/11 15:19
*/
@Service
public class DefaultEmailSender implements EmailSender {
@Autowired
private JavaMailSender javaMailSender;
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content) {
return sendEmail(from, to, cc, title, content, null, null);
}
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource) {
MimeMessage message = null;
try {
message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
if (StringUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
helper.setSubject(title);
helper.setText(content, true);
if (inputStreamSource != null) {
helper.addAttachment(attachmentFilename, inputStreamSource);
}
javaMailSender.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
package cn.enilu.flash.service.message.email;
import org.springframework.core.io.InputStreamSource;
/**
* descript
*
* @author :enilu
* @date :Created in 2019/6/17 19:33
*/
public interface EmailSender {
/**
* 发送邮件
*
* @param from
* @param to
* @param cc
* @param title
* @param content
* @return
*/
boolean sendEmail(String from, String to, String cc, String title, String content);
/**
* 发送带附件的邮件
*
* @param from
* @param to
* @param cc
* @param title
* @param content
* @param attachmentFilename
* @param inputStreamSource
* @return
*/
boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource);
}
package cn.enilu.flash.service.message.sms;
public interface SmsSender {
/**
* 发送短信,如果内容content不为空,则直接发送内容
*
* @param tplCode 短信运营商模板号码
* @param receiver
* @param args
* @param content
* @return
*/
boolean sendSms(String tplCode, String receiver, String[] args, String content);
}
package cn.enilu.flash.service.message.sms.tencent;
import cn.enilu.flash.bean.constant.CfgKey;
import cn.enilu.flash.service.message.sms.SmsSender;
import cn.enilu.flash.service.system.CfgService;
import cn.enilu.flash.utils.StringUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TencentSmsSender implements SmsSender {
private Logger logger = LoggerFactory.getLogger(TencentSmsSender.class);
@Autowired
private CfgService cfgService;
@Override
public boolean sendSms(String tplCode, String receiver, String[] args, String content) {
Integer appid = Integer.valueOf(cfgService.getCfgValue(CfgKey.API_TENCENT_SMS_APPID));
String appkey = cfgService.getCfgValue(CfgKey.API_TENCENT_SMS_APPKEY);
String smsSign = cfgService.getCfgValue(CfgKey.API_TENCENT_SMS_SIGN);
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
SmsSingleSenderResult result = null;
try {
if (StringUtil.isNotEmpty(tplCode)) {
//根据指定模板id发送短信
// 签名参数未提供或者为空时,会使用默认签名发送短信
result = ssender.sendWithParam("86", receiver,
Integer.valueOf(tplCode), args, smsSign, "", "");
} else {
//发送固定内容短信
result = ssender.send(0, "86", receiver,
content, "", "");
}
logger.info("腾讯短信发送结果:{}", result.errMsg);
return result.result == 0;
} catch (Exception e) {
logger.error("发送短信异常", e);
}
return false;
}
}
package cn.enilu.flash.service.promotion;
import cn.enilu.flash.bean.entity.promotion.Topic;
import cn.enilu.flash.dao.promotion.TopicRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TopicService extends BaseService<Topic, Long, TopicRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private TopicRepository topicRepository;
public Topic changeDisabled(Long id, Boolean disabled) {
Topic topic = get(id);
topic.setDisabled(disabled);
update(topic);
return topic;
}
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.Address;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.dao.shop.AddressRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AddressService extends BaseService<Address, Long, AddressRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private AddressRepository addressRepository;
/**
* 获取用户默认收货地址
*
* @param idUser
* @return
*/
public Address getDefaultAddr(Long idUser) {
List<SearchFilter> filterList = Lists.newArrayList(
SearchFilter.build("idUser", SearchFilter.Operator.EQ, idUser),
SearchFilter.build("isDefault", SearchFilter.Operator.EQ, true),
SearchFilter.build("isDelete", SearchFilter.Operator.EQ, false)
);
return get(filterList);
}
public Address get(Long idUser, Long id) {
return get(Lists.newArrayList(
SearchFilter.build("idUser", SearchFilter.Operator.EQ, idUser),
SearchFilter.build("id", SearchFilter.Operator.EQ, id),
SearchFilter.build("isDelete", SearchFilter.Operator.EQ, false)
));
}
public void delete(Long idUser, Long id) {
Address address = get(Lists.newArrayList(
SearchFilter.build("idUser", SearchFilter.Operator.EQ, idUser),
SearchFilter.build("id", SearchFilter.Operator.EQ, id)
));
address.setIsDelete(true);
update(address);
}
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.constant.cache.Cache;
import cn.enilu.flash.bean.entity.shop.AttrKey;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.dao.shop.AttrKeyRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AttrKeyService extends BaseService<AttrKey, Long, AttrKeyRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private AttrKeyRepository attrKeyRepository;
@CacheEvict(value = Cache.APPLICATION, key = "#root.targetClass.simpleName+':'+#idCategory")
public List<AttrKey> queryBy(Long idCategory) {
return queryAll(SearchFilter.build("idCategory", idCategory));
}
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.constant.cache.Cache;
import cn.enilu.flash.bean.entity.shop.AttrVal;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.dao.shop.AttrValRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AttrValService extends BaseService<AttrVal, Long, AttrValRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private AttrValRepository attrValRepository;
@CacheEvict(value = Cache.APPLICATION, key = "#root.targetClass.simpleName+':'+#idCategory")
public List<AttrVal> queryBy(Long idCategory) {
return queryAll(SearchFilter.build("idCategory", idCategory));
}
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.CategoryBannerRel;
import cn.enilu.flash.dao.shop.CategoryBannerRelRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CategoryBannerRelService extends BaseService<CategoryBannerRel, Long, CategoryBannerRelRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private CategoryBannerRelRepository categoryBannerRelRepository;
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.Category;
import cn.enilu.flash.dao.shop.CategoryRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CategoryService extends BaseService<Category, Long, CategoryRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private CategoryRepository categoryRepository;
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.Favorite;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.dao.shop.FavoriteRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FavoriteService extends BaseService<Favorite, Long, FavoriteRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private FavoriteRepository favoriteRepository;
public Favorite get(Long idUser, Long idGoods) {
return get(Lists.newArrayList(
SearchFilter.build("idUser", idUser),
SearchFilter.build("idGoods", idGoods)
));
}
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.Goods;
import cn.enilu.flash.bean.entity.shop.GoodsSku;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.bean.vo.shop.GoodsVo;
import cn.enilu.flash.dao.shop.GoodsRepository;
import cn.enilu.flash.dao.system.FileInfoRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class GoodsService extends BaseService<Goods, Long, GoodsRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private GoodsRepository goodsRepository;
@Autowired
private GoodsSkuService goodsSkuService;
@Autowired
private FileInfoRepository fileInfoRepository;
@Override
public void deleteById(Long id) {
Goods goods = get(id);
goods.setIsDelete(true);
update(goods);
}
public GoodsVo getDetail(Long id) {
Goods goods = get(id);
List<GoodsSku> skuList = goodsSkuService.queryAll(Lists.newArrayList(
SearchFilter.build("idGoods", id),
SearchFilter.build("isDeleted", false)
));
GoodsVo vo = new GoodsVo();
vo.setGoods(goods);
vo.setSkuList(skuList);
return vo;
}
/**
* 商品上架或者下架
*
* @param id
* @param isOnSale
*/
public void changeIsOnSale(Long id, Boolean isOnSale) {
Goods goods = get(id);
goods.setIsOnSale(isOnSale);
update(goods);
}
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.GoodsSku;
import cn.enilu.flash.dao.shop.GoodsSkuRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GoodsSkuService extends BaseService<GoodsSku, Long, GoodsSkuRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private GoodsSkuRepository goodsSkuRepository;
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.OrderItem;
import cn.enilu.flash.dao.shop.OrderItemRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderItemService extends BaseService<OrderItem, Long, OrderItemRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OrderItemRepository orderItemRepository;
}
package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.OrderLog;
import cn.enilu.flash.dao.shop.OrderLogRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderLogService extends BaseService<OrderLog, Long, OrderLogRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OrderLogRepository orderLogRepository;
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.cache.TokenCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* AccountService
*
* @author enilu
* @version 2018/9/12 0012
*/
@Service
public class AccountService {
@Autowired
private TokenCache tokenCache;
public void logout(String token) {
tokenCache.remove(token);
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.Cfg;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.cache.ConfigCache;
import cn.enilu.flash.dao.system.CfgRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* CfgService
*
* @author enilu
* @version 2018/11/17 0017
*/
@Service
@Transactional
public class CfgService extends BaseService<Cfg, Long, CfgRepository> {
@Autowired
private ConfigCache configCache;
/**
* 切记更新配置的时候调用该方法,而不要调用其父类的insert或者update方法,该方法会连同缓存一起更新
*
* @param cfg
* @return
*/
public Cfg saveOrUpdate(Cfg cfg) {
if (cfg.getId() == null) {
insert(cfg);
} else {
update(cfg);
}
configCache.cache();
return cfg;
}
@Override
public void deleteById(Long id) {
super.deleteById(id);
configCache.cache();
}
public Cfg getByCfgName(String cfgName) {
return get(SearchFilter.build("cfgName", cfgName));
}
/**
* 根据参数名获取参数值
* 系统获取参数值统一使用该方法
* 如果参数无法做到后台管理系统和用户端系统同步,这里建议直接从数据库获取
* todo 建议生产中使用redis来统一管理该参数,这里从redis缓存中获取
*
* @param cfgName
* @return
*/
public String getCfgValue(String cfgName) {
// return configCache.get(cfgName);
return getByCfgName(cfgName).getCfgValue();
}
public void update(String cfgName, String cfgValue) {
Cfg cfg = getByCfgName(cfgName);
cfg.setCfgValue(cfgValue);
update(cfg);
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.Dept;
import cn.enilu.flash.bean.vo.node.DeptNode;
import cn.enilu.flash.bean.vo.node.ZTreeNode;
import cn.enilu.flash.dao.system.DeptRepository;
import cn.enilu.flash.service.BaseService;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created on 2018/3/21 0021.
*
* @author enilu
*/
@Service
public class DeptService extends BaseService<Dept, Long, DeptRepository> {
@Autowired
private DeptRepository deptRepository;
public List<ZTreeNode> tree() {
List<Object[]> list = deptRepository.tree();
List<ZTreeNode> nodes = new ArrayList<>();
for (Object[] obj : list) {
ZTreeNode node = transfer(obj);
nodes.add(node);
}
return nodes;
}
private ZTreeNode transfer(Object[] obj) {
ZTreeNode node = new ZTreeNode();
node.setId(Long.valueOf(obj[0].toString()));
node.setpId(Long.valueOf(obj[1].toString()));
node.setName(obj[2].toString());
node.setIsOpen(Boolean.valueOf(obj[3].toString()));
return node;
}
public List<Dept> query(String condition) {
List<Dept> list = new ArrayList<>();
if (Strings.isNullOrEmpty(condition)) {
list = (List<Dept>) deptRepository.findAll();
} else {
condition = "%" + condition + "%";
list = deptRepository.findBySimplenameLikeOrFullnameLike(condition, condition);
}
return list;
}
public void deleteDept(Long deptId) {
Dept dept = get(deptId);
List<Dept> subDepts = deptRepository.findByPidsLike("%[" + dept.getId() + "]%");
deptRepository.deleteAll(subDepts);
deptRepository.delete(dept);
}
public List<DeptNode> queryAllNode() {
List<Dept> list = super.queryAll();
return generateTree(list);
}
public void deptSetPids(Dept dept) {
if (dept.getPid() == null || dept.getPid().intValue() == 0) {
dept.setPid(0L);
dept.setPids("[0],");
} else {
Long pid = dept.getPid();
Dept temp = get(pid);
String pids = "";
if (temp != null) {
pids = temp.getPids();
}
dept.setPid(pid);
dept.setPids(pids + "[" + pid + "],");
}
}
private List<DeptNode> generateTree(List<Dept> list) {
List<DeptNode> nodes = new ArrayList<>(20);
for (Dept dept : list) {
DeptNode deptNode = new DeptNode();
BeanUtils.copyProperties(dept, deptNode);
nodes.add(deptNode);
}
for (DeptNode deptNode : nodes) {
for (DeptNode child : nodes) {
if (child.getPid().intValue() == deptNode.getId().intValue()) {
deptNode.getChildren().add(child);
}
}
}
List<DeptNode> result = new ArrayList<>(20);
for (DeptNode node : nodes) {
if (node.getPid().intValue() == 0) {
result.add(node);
}
}
return result;
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.Dict;
import cn.enilu.flash.cache.DictCache;
import cn.enilu.flash.dao.system.DictRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.factory.MutiStrFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* 字典服务
*
* @author fengshuonan
* @date 2017-04-27 17:00
*/
@Service
public class DictService extends BaseService<Dict, Long, DictRepository> {
private Logger logger = LoggerFactory.getLogger(DictService.class);
@Resource
DictRepository dictRepository;
@Autowired
private DictCache dictCache;
public void addDict(String dictName, String dictValues) {
//判断有没有该字典
List<Dict> dicts = dictRepository.findByNameAndPid(dictName, 0L);
if (dicts != null && dicts.size() > 0) {
return;
}
//解析dictValues
List<Map<String, String>> items = MutiStrFactory.parseKeyValue(dictValues);
//添加字典
Dict dict = new Dict();
dict.setName(dictName);
dict.setNum("0");
dict.setPid(0L);
this.dictRepository.save(dict);
//添加字典条目
for (Map<String, String> item : items) {
String num = item.get(MutiStrFactory.MUTI_STR_KEY);
String name = item.get(MutiStrFactory.MUTI_STR_VALUE);
Dict itemDict = new Dict();
itemDict.setPid(dict.getId());
itemDict.setName(name);
try {
itemDict.setNum(num);
} catch (NumberFormatException e) {
logger.error(e.getMessage(), e);
}
this.dictRepository.save(itemDict);
}
dictCache.cache();
}
public void editDict(Long dictId, String dictName, String dicts) {
//删除之前的字典
this.delteDict(dictId);
//重新添加新的字典
this.addDict(dictName, dicts);
dictCache.cache();
}
public void delteDict(Long dictId) {
//删除这个字典的子词典
List<Dict> subList = dictRepository.findByPid(dictId);
dictRepository.deleteAll(subList);
//删除这个词典
dictRepository.deleteById(dictId);
dictCache.cache();
}
@Override
public Dict get(Long id) {
Optional<Dict> optional = dictRepository.findById(id);
if (optional.isPresent()) {
return optional.get();
}
return null;
}
public List<Dict> findByNameLike(String name) {
return dictRepository.findByNameLike(name);
}
public List<Dict> findByPid(Long pid) {
return dictRepository.findByPid(pid);
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.Express;
import cn.enilu.flash.dao.system.ExpressRepository;
import cn.enilu.flash.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ExpressService extends BaseService<Express, Long, ExpressRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ExpressRepository expressRepository;
public void changeDisabled(Long id, Boolean disabled) {
Express express = get(id);
express.setDisabled(disabled);
update(express);
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.*;
import cn.enilu.flash.bean.vo.DictVo;
import java.util.List;
/**
* 常量生产工厂的接口
*
* @author fengshuonan
* @date 2017-06-14 21:12
*/
public interface IConstantFactory {
/**
* 根据用户id获取用户名称
*
* @author stylefeng
* @Date 2017/5/9 23:41
*/
String getUserNameById(Long userId);
/**
* 根据用户id获取用户账号
*
* @author stylefeng
* @date 2017年5月16日21:55:371
*/
String getUserAccountById(Long userId);
/**
* 通过角色ids获取角色名称
*/
String getRoleName(String roleIds);
/**
* 通过角色id获取角色名称
*/
String getSingleRoleName(Long roleId);
/**
* 通过角色id获取角色英文名称
*/
String getSingleRoleTip(Long roleId);
/**
* 获取部门名称
*/
String getDeptName(Long deptId);
/**
* 获取菜单的名称们(多个)
*/
String getMenuNames(String menuIds);
/**
* 获取菜单名称
*/
String getMenuName(Long menuId);
/**
* 获取菜单名称通过编号
*/
String getMenuNameByCode(String code);
/**
* 根据字典名称获取字典列表
*
* @param dictName
* @return
*/
List<DictVo> findByDictName(String dictName);
/**
* 获取字典名称
*/
String getDictName(Long dictId);
/**
* 获取通知标题
*/
String getNoticeTitle(Long dictId);
/**
* 根据字典名称和字典中的值获取对应的名称
*/
String getDictsByName(String name, String val);
/**
* 获取性别名称
*/
String getSexName(Integer sex);
/**
* 获取银行卡类型名称
*
* @param cardType
* @return
*/
String getCardTypeName(String cardType);
/**
* 获取个人证件类型
*
* @param cardType
* @return
*/
String getIdCardTypeName(String cardType);
/**
* 获取联系人关系
*
* @param relation
* @return
*/
String getRelationName(String relation);
/**
* 获取用户登录状态
*/
String getStatusName(Integer status);
/**
* 获取菜单状态
*/
String getMenuStatusName(Integer status);
/**
* 查询字典
*/
List<Dict> findInDict(Long id);
/**
* 获取被缓存的对象(用户删除业务)
*/
String getCacheObject(String para);
/**
* 获取子部门id
*/
List<Long> getSubDeptId(Long deptid);
/**
* 获取所有父部门id
*/
List<Integer> getParentDeptIds(Long deptid);
/**
* 获取指定名称下的字典列表
*
* @param pname
* @return
*/
List<Dict> getDicts(String pname);
/**
* 获取全局参数
*
* @param cfgName
* @return
*/
String getCfg(String cfgName);
Role getRole(Long id);
Dept getDept(Long id);
Menu getMenu(Long id);
Notice getNotice(Long id);
void cleanLocalCache();
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.vo.SpringContextHolder;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import java.io.Serializable;
/**
* 被修改的bean临时存放的地方
*
* @author enilu
* @date 2019-08-13
*/
@Component
@Scope(scopeName = WebApplicationContext.SCOPE_SESSION)
public class LogObjectHolder implements Serializable {
private Object object = null;
public void set(Object obj) {
try {
//为表面后面的逻辑对obj进行变更,这里克隆一份存储,用于后续变化对比
Object cloneObj = BeanUtils.cloneBean(obj);
this.object = cloneObj;
} catch (Exception e) {
e.printStackTrace();
}
}
public Object get() {
return object;
}
public static LogObjectHolder me() {
LogObjectHolder bean = SpringContextHolder.getBean(LogObjectHolder.class);
return bean;
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.LoginLog;
import cn.enilu.flash.dao.system.LoginLogRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.stereotype.Service;
/**
* Created on 2018/3/26 0026.
*
* @author enilu
*/
@Service
public class LoginLogService extends BaseService<LoginLog, Long, LoginLogRepository> {
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.User;
import cn.enilu.flash.cache.CacheDao;
import cn.enilu.flash.dao.system.UserRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created on 2018/3/23 0023.
*
* @author enilu
*/
@Service
public class ManagerService extends BaseService<User, Long, UserRepository> {
@Autowired
private UserRepository userRepository;
@Autowired
private CacheDao cacheDao;
public User findByAccount(String account) {
//由于:@Cacheable标注的方法,如果其所在的类实现了某一个接口,那么该方法也必须出现在接口里面,否则cache无效。
//具体的原因是, Spring把实现类装载成为Bean的时候,会用代理包装一下,所以从Spring Bean的角度看,只有接口里面的方法是可见的,其它的都隐藏了,自然课看不到实现类里面的非接口方法,@Cacheable不起作用。
//所以这里手动控制缓存
User user = cacheDao.hget(CacheDao.SESSION, account, User.class);
if (user != null) {
return user;
}
user = userRepository.findByAccount(account);
cacheDao.hset(CacheDao.SESSION, account, user);
return user;
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.Notice;
import cn.enilu.flash.dao.system.NoticeRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* descript
*
* @author :enilu
* @date :Created in 2019/6/30 11:14
*/
@Service
public class NoticeService extends BaseService<Notice, Long, NoticeRepository> {
@Autowired
private NoticeRepository noticeRepository;
public List<Notice> findByTitleLike(String title) {
return noticeRepository.findByTitleLike("%" + title + "%");
}
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.OperationLog;
import cn.enilu.flash.dao.system.OperationLogRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.stereotype.Service;
/**
* Created on 2018/3/26 0026.
*
* @author enilu
*/
@Service
public class OperationLogService extends BaseService<OperationLog, Long, OperationLogRepository> {
}
package cn.enilu.flash.service.system;
import cn.enilu.flash.bean.entity.system.Relation;
import cn.enilu.flash.bean.entity.system.Role;
import cn.enilu.flash.bean.vo.node.Node;
import cn.enilu.flash.bean.vo.node.ZTreeNode;
import cn.enilu.flash.dao.system.RelationRepository;
import cn.enilu.flash.dao.system.RoleRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.Convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Created on 2018/3/25 0025.
*
* @author enilu
*/
@Service
public class RoleService extends BaseService<Role, Long, RoleRepository> {
@Autowired
private RoleRepository roleRepository;
@Autowired
private RelationRepository relationRepository;
public List<ZTreeNode> roleTreeList() {
List list = roleRepository.roleTreeList();
List<ZTreeNode> treeNodes = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Object[] arr = (Object[]) list.get(i);
ZTreeNode node = new ZTreeNode();
node.setId(Long.valueOf(arr[0].toString()));
node.setpId(Long.valueOf(arr[1].toString()));
node.setName(arr[2].toString());
node.setOpen(Boolean.valueOf(arr[3].toString()));
treeNodes.add(node);
}
return treeNodes;
}
public List<ZTreeNode> roleTreeListByRoleId(Long[] ids) {
List list = roleRepository.roleTreeListByRoleId(ids);
List<ZTreeNode> treeNodes = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Object[] arr = (Object[]) list.get(i);
ZTreeNode node = new ZTreeNode();
node.setId(Long.valueOf(arr[0].toString()));
node.setpId(Long.valueOf(arr[1].toString()));
node.setName(arr[2].toString());
node.setOpen(Boolean.valueOf(arr[3].toString()));
node.setChecked(Boolean.valueOf(arr[4].toString()));
treeNodes.add(node);
}
return treeNodes;
}
public void setAuthority(Long roleId, String ids) {
// 删除该角色所有的权限
relationRepository.deleteByRoleId(roleId);
// 添加新的权限
for (Long id : Convert.toLongArray(true, Convert.toStrArray(",", ids))) {
Relation relation = new Relation();
relation.setRoleid(roleId);
relation.setMenuid(id);
relationRepository.save(relation);
}
}
public void delRoleById(Long roleId) {
//删除角色
roleRepository.deleteById(roleId);
// 删除该角色所有的权限
relationRepository.deleteByRoleId(roleId);
}
public List<Node> generateRoleTree(List<ZTreeNode> list) {
List<Node> nodes = new ArrayList<>();
for (ZTreeNode role : list) {
Node roleNode = new Node();
roleNode.setId(role.getId());
roleNode.setName(role.getName());
roleNode.setPid(role.getpId());
roleNode.setChecked(role.getChecked());
nodes.add(roleNode);
}
return nodes;
}
@Override
public Role get(Long id) {
Optional<Role> optional = roleRepository.findById(id);
if (optional.isPresent()) {
return optional.get();
}
return null;
}
public List<Role> findByName(String name) {
return roleRepository.findByName(name);
}
}
package cn.enilu.flash.service.task;
import cn.enilu.flash.bean.vo.QuartzJob;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
@Component
public class BaseJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap data = context.getJobDetail().getJobDataMap();
QuartzJob job = (QuartzJob) data.get("job");
try {
TaskUtils.executeJob(job);
} catch (Exception e) {
throw new JobExecutionException(e);
}
}
}
package cn.enilu.flash.service.task;
import cn.enilu.flash.bean.entity.system.Task;
import cn.enilu.flash.bean.entity.system.TaskLog;
import cn.enilu.flash.bean.vo.QuartzJob;
import cn.enilu.flash.dao.system.TaskLogRepository;
import cn.enilu.flash.dao.system.TaskRepository;
import cn.enilu.flash.utils.StringUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Map;
@Component
public abstract class JobExecuter {
protected static final Logger log = LoggerFactory.getLogger(JobExecuter.class);
@Autowired
private TaskService taskService;
@Autowired
private TaskLogRepository taskLogRepository;
@Autowired
private TaskRepository taskRepository;
private QuartzJob job;
public void setJob(QuartzJob job) {
this.job = job;
}
public void execute() {
Map dataMap = job.getDataMap();
String taskId = job.getJobName();
Task task = taskService.get(Long.valueOf(taskId));
final String taskName = task.getName();
log.info(">>>>>>>>>>>>>>>>>开始执行定时任务[" + taskName + "]...<<<<<<<<<<<<<<<<<<<");
String exeResult = "执行成功";
final TaskLog taskLog = new TaskLog();
taskLog.setName(taskName);
final Date exeAt = new Date();
taskLog.setExecAt(exeAt);
taskLog.setIdTask(task.getId());
//默认是成功 出异常后改成失败
taskLog.setExecSuccess(TaskLog.EXE_SUCCESS_RESULT);
try {
execute(dataMap);
task.setExecResult(exeResult);
} catch (Exception e) {
task.setExecResult("执行失败");
log.error("exeucte " + getClass().getName() + " error : ", e);
exeResult = "执行失败\n";
exeResult += ExceptionUtils.getStackTrace(e);
taskLog.setExecSuccess(TaskLog.EXE_FAILURE_RESULT);
taskLog.setJobException(exeResult);
}
task.setExecAt(exeAt);
taskLogRepository.save(taskLog);
taskRepository.save(task);
log.info(">>>>>>>>>>>>>>>>>执行定时任务[" + taskName + "]结束<<<<<<<<<<<<<<<<<<<");
}
/**
* @param dataMap 数据库配置的参数
*/
public abstract void execute(Map<String, Object> dataMap) throws Exception;
public String getEmail() {
return getEmail("snowalert@xuezhongdai.cn");
}
public String getEmail(String defaultEmail) {
Map<String, Object> dataMap = job.getDataMap();
String toEmail = null;
if (dataMap != null && dataMap.containsKey("email")) {
toEmail = StringUtil.sNull(dataMap.get("email"));
}
if (StringUtil.isEmpty(toEmail)) {
toEmail = defaultEmail;
}
return toEmail;
}
}
package cn.enilu.flash.service.task;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.stereotype.Component;
@Component
@DisallowConcurrentExecution
public class NoConurrentBaseJob extends BaseJob {
}
package cn.enilu.flash.service.task;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfigration {
@Bean(name = "scheduler")
public SchedulerFactoryBean schedulerFactory() {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
return bean;
}
}
package cn.enilu.flash.service.task;
import cn.enilu.flash.bean.entity.system.TaskLog;
import cn.enilu.flash.dao.system.TaskLogRepository;
import cn.enilu.flash.service.BaseService;
import org.springframework.stereotype.Service;
/**
* 定时任务日志服务类
*
* @author enilu
* @date 2019-08-13
*/
@Service
public class TaskLogService extends BaseService<TaskLog, Long, TaskLogRepository> {
}
package cn.enilu.flash.service.task;
import cn.enilu.flash.bean.entity.system.Task;
import cn.enilu.flash.bean.exception.ApplicationException;
import cn.enilu.flash.bean.exception.ApplicationExceptionEnum;
import cn.enilu.flash.bean.vo.QuartzJob;
import cn.enilu.flash.dao.system.TaskRepository;
import cn.enilu.flash.service.BaseService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 定时任务服务类
*
* @author enilu
* @date 2019-06-13
*/
@Service
public class TaskService extends BaseService<Task, Long, TaskRepository> {
private static final Logger logger = LoggerFactory.getLogger(TaskService.class);
@Autowired
private TaskRepository taskRepository;
@Autowired
private JobService jobService;
public Task save(Task task) {
logger.info("新增定时任务%s", task.getName());
task = taskRepository.save(task);
try {
jobService.addJob(jobService.getJob(task));
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
return task;
}
@Override
public Task update(Task record) {
logger.info("更新定时任务:{}", record.getName());
taskRepository.save(record);
try {
QuartzJob job = jobService.getJob(record.getId().toString(), record.getJobGroup());
if (job != null) {
jobService.deleteJob(job);
}
jobService.addJob(jobService.getJob(record));
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
return record;
}
public Task disable(Long id) {
Task task = get(id);
task.setDisabled(true);
taskRepository.save(task);
logger.info("禁用定时任务:{}", id.toString());
try {
QuartzJob job = jobService.getJob(task.getId().toString(), task.getJobGroup());
if (job != null) {
jobService.deleteJob(job);
}
} catch (SchedulerException e) {
logger.error(e.getMessage(), e);
}
return task;
}
public Task enable(Long id) {
Task task = get(id);
task.setDisabled(false);
taskRepository.save(task);
logger.info("启用定时任务{}", id.toString());
try {
QuartzJob job = jobService.getJob(task.getId().toString(), task.getJobGroup());
if (job != null) {
jobService.deleteJob(job);
}
if (!task.isDisabled()) {
jobService.addJob(jobService.getJob(task));
}
} catch (SchedulerException e) {
throw new ApplicationException(ApplicationExceptionEnum.TASK_CONFIG_ERROR);
}
return task;
}
@Override
public void deleteById(Long id) {
Task task = get(id);
task.setDisabled(true);
taskRepository.delete(task);
try {
logger.info("删除定时任务{}", id.toString());
QuartzJob job = jobService.getJob(task);
if (job != null) {
jobService.deleteJob(job);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public List<Task> queryAllByNameLike(String name) {
return taskRepository.findByNameLike("%" + name + "%");
}
}
package cn.enilu.flash.service.task;
import cn.enilu.flash.bean.vo.QuartzJob;
import cn.enilu.flash.bean.vo.SpringContextHolder;
import cn.enilu.flash.utils.StringUtil;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.util.Date;
/**
* Created by czhou on 1/10/17.
*/
public class TaskUtils {
private static final Logger logger = LoggerFactory.getLogger(TaskUtils.class);
/**
* 通过反射调用job中定义的方法
*
* @param job
* @throws Exception
*/
public static void executeJob(QuartzJob job) throws Exception {
JobExecuter jobExecuter = null;
Class<?> clazz = null;
if (StringUtil.isNotEmpty(job.getJobClass())) {
clazz = Class.forName(job.getJobClass());
jobExecuter = (JobExecuter) SpringContextHolder.getBean(clazz);
jobExecuter.setJob(job);
}
if (jobExecuter == null) {
throw new RuntimeException("任务名称 = [" + job.getDescription() + "]未启动成功,请检查执行类是否配置正确!!!");
}
jobExecuter.execute();
}
/**
* 判断cron时间表达式正确性
*
* @param cronExpression
* @return
*/
public static boolean isValidExpression(final String cronExpression) {
CronTriggerImpl trigger = new CronTriggerImpl();
try {
trigger.setCronExpression(cronExpression);
Date date = trigger.computeFirstFireTime(null);
return date != null && date.after(new Date());
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
return false;
}
public static void main(String[] args) {
System.out.println(isValidExpression("0 0/1 * * * ?"));
}
}
package cn.enilu.flash.service.task.job;
import cn.enilu.flash.bean.entity.system.Cfg;
import cn.enilu.flash.service.system.CfgService;
import cn.enilu.flash.service.task.JobExecuter;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* HelloJob
*
* @author zt
* @version 2018/12/30 0030
*/
@Component
public class HelloJob extends JobExecuter {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private CfgService cfgService;
@Override
public void execute(Map<String, Object> dataMap) throws Exception {
Cfg cfg = cfgService.get(1L);
cfg.setCfgDesc("应用名称");
cfgService.update(cfg);
logger.info("hello :" + Json.toJson(dataMap));
}
}
package cn.enilu.flash.service.task.job;
import cn.enilu.flash.service.api.WeixinService;
import cn.enilu.flash.service.task.JobExecuter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 定时获取微信token<br>
* 微信token有效期是两个小时,所以建议定时任务执行频率小于两个小时
*
* @author :enilu
* @date :Created in 1/19/2020 4:30 PM
*/
@Component
public class UpdateWeixinTokenJob extends JobExecuter {
@Autowired
private WeixinService weixinService;
@Override
public void execute(Map<String, Object> dataMap) throws Exception {
weixinService.updateWeixinToken();
}
}
package cn.enilu.flash.utils;
/**
* @author :enilu
* @date :Created in 2020/6/1 0:03
*/
public class Base64Util {
private static char[] base64EncodeChars = new char[]{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
public static String base64Encode(byte[] data) {
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
}
package cn.enilu.flash.utils;
import java.util.HashMap;
import java.util.Map;
/**
* 基本变量类型的枚举
*
* @author xiaoleilu
*/
public enum BasicType {
BYTE, SHORT, INT, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, CHAR, CHARACTER, STRING;
/**
* 原始类型为Key,包装类型为Value,例如: int.class -> Integer.class.
*/
public static final Map<Class<?>, Class<?>> WRAPPER_PRIMITIVE_MAP = new HashMap<Class<?>, Class<?>>(8);
/**
* 包装类型为Key,原始类型为Value,例如: Integer.class -> int.class.
*/
public static final Map<Class<?>, Class<?>> PRIMITIVE_WRAPPER_MAP = new HashMap<Class<?>, Class<?>>(8);
static {
WRAPPER_PRIMITIVE_MAP.put(Boolean.class, boolean.class);
WRAPPER_PRIMITIVE_MAP.put(Byte.class, byte.class);
WRAPPER_PRIMITIVE_MAP.put(Character.class, char.class);
WRAPPER_PRIMITIVE_MAP.put(Double.class, double.class);
WRAPPER_PRIMITIVE_MAP.put(Float.class, float.class);
WRAPPER_PRIMITIVE_MAP.put(Integer.class, int.class);
WRAPPER_PRIMITIVE_MAP.put(Long.class, long.class);
WRAPPER_PRIMITIVE_MAP.put(Short.class, short.class);
for (Map.Entry<Class<?>, Class<?>> entry : WRAPPER_PRIMITIVE_MAP.entrySet()) {
PRIMITIVE_WRAPPER_MAP.put(entry.getValue(), entry.getKey());
}
}
}
package cn.enilu.flash.utils;
import java.util.Base64;
/**
* 加密工具类
*
* @author enilu
*/
public class CryptUtil {
public static String encodeBASE64(byte[] bytes) {
String encode = Base64.getEncoder().encodeToString(bytes);
encode = encode.replaceAll("\n", "");
return encode;
}
}
/**
* Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.enilu.flash.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
public class HttpUtil {
public static String getIp() {
return HttpUtil.getRequest().getRemoteHost();
}
/**
* 获取所有请求的值
*/
public static Map<String, String> getRequestParameters() {
HashMap<String, String> values = new HashMap<>(20);
HttpServletRequest request = HttpUtil.getRequest();
Enumeration enums = request.getParameterNames();
while (enums.hasMoreElements()) {
String paramName = (String) enums.nextElement();
String paramValue = request.getParameter(paramName);
values.put(paramName, paramValue);
}
return values;
}
/**
* 获取 HttpServletRequest
*/
public static HttpServletResponse getResponse() {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
return response;
}
/**
* 获取 包装防Xss Sql注入的 HttpServletRequest
*
* @return request
*/
public static HttpServletRequest getRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return new WafRequestWrapper(request);
}
public static String getToken() {
return getRequest().getHeader("Authorization");
}
public static void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.enilu.flash.utils;
import cn.enilu.flash.bean.entity.system.User;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 封装json工具类<br>
* 通过该类减少项目中对特定的json库依赖,方便统一切换json库,目前使用jackson
*
* @author :enilu
* @date :Created in 2020/5/31 21:55
*/
public class JsonUtil {
public static String toJsonForHuman(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String toJson(Object obj) {
StringWriter sw = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(sw, obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
return sw.toString();
}
public static String toJsonNotNull(Object obj) {
StringWriter sw = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.writeValue(sw, obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
return sw.toString();
}
public static <T> T fromJson(Class<T> klass, String jsonStr) {
ObjectMapper mapper = new ObjectMapper();
T obj = null;
try {
obj = mapper.readValue(jsonStr, klass);
} catch (Exception e) {
throw new RuntimeException(e);
}
return obj;
}
public static <T> List<T> fromJsonAsList(Class<T> klass, String jsonStr) {
ObjectMapper mapper = new ObjectMapper();
List<T> objList = null;
try {
JavaType t = mapper.getTypeFactory().constructParametricType(
List.class, klass);
objList = mapper.readValue(jsonStr, t);
} catch (Exception e) {
throw new RuntimeException(e);
}
return objList;
}
/**
* 判断给定的字符串是否是json格式
*
* @param jsonStr
* @return
*/
public static boolean isJson(String jsonStr) {
try {
if (jsonStr.startsWith("{")) {
fromJson(Map.class, jsonStr);
} else {
fromJsonAsList(Map.class, jsonStr);
}
return true;
} catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
User user = new User();
user.setAccount("admin");
user.setCreateTime(new Date());
String json = toJson(user);
System.out.println("压缩后的json字符串:========》");
System.out.println(json);
System.out.println("方便调试查看的json字符串:===》");
System.out.println(toJsonForHuman(user));
System.out.println("不输出值为null的json字符串:==》");
System.out.println(toJsonNotNull(user));
User user2 = fromJson(User.class, json);
System.out.println("json字符串转对象:==========》");
System.out.println(user2.getAccount() + user2.getCreateTime());
List<User> users = Lists.newArrayList(user);
String jsons = toJson(users);
List<User> users2 = fromJsonAsList(User.class, jsons);
System.out.println("转换为集合后的集合长度:=======》");
System.out.println(users2.size());
System.out.println(isJson(json));
System.out.println(isJson(jsons));
System.out.println(isJson("{\"aaaa\":}"));
}
}
package cn.enilu.flash.utils;
import java.util.HashMap;
/**
* Map 工具类
*
* @author enilu
*/
public final class Maps {
private Maps() {
}
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>(100);
}
public static <K, V> HashMap<K, V> newHashMap(K k, V v) {
HashMap<K, V> map = new HashMap<K, V>(100);
map.put(k, v);
return map;
}
@SuppressWarnings("unchecked")
public static <K, V> HashMap<K, V> newHashMap(K k, V v,
Object... extraKeyValues) {
if (extraKeyValues.length % 2 != 0) {
throw new IllegalArgumentException();
}
HashMap<K, V> map = new HashMap<K, V>(100);
map.put(k, v);
for (int i = 0; i < extraKeyValues.length; i += 2) {
k = (K) extraKeyValues[i];
v = (V) extraKeyValues[i + 1];
map.put(k, v);
}
return map;
}
}
\ No newline at end of file \ No newline at end of file
package cn.enilu.flash.utils;
import java.util.Random;
/**
* @author :enilu
* @date :Created in 2019/10/29 22:48
*/
public class RandomUtil {
static String number = "0123456789";
static String str = "abcdefghijklmnopqrstuvwxyz0123456789";
public static String getRandomNumber(int length) {
return getRandom(length, number);
}
public static String getRandomString(int length) {
return getRandom(length, str);
}
public static String getRandom(int length, String base) {
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
/**
* Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.enilu.flash.utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
/**
* 高频方法集合类
*/
public class ToolUtil {
/**
* 获取异常的具体信息
*
* @author fengshuonan
* @Date 2017/3/30 9:21
* @version 2.0
*/
public static String getExceptionMsg(Exception e) {
StringWriter sw = new StringWriter();
try {
e.printStackTrace(new PrintWriter(sw));
} finally {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.getBuffer().toString().replaceAll("\\$", "T");
}
/**
* 计算对象长度,如果是字符串调用其length函数,集合类调用其size函数,数组调用其length属性,其他可遍历对象遍历计算长度
*
* @param obj 被计算长度的对象
* @return 长度
*/
public static int length(Object obj) {
if (obj == null) {
return 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length();
}
if (obj instanceof Collection) {
return ((Collection<?>) obj).size();
}
if (obj instanceof Map) {
return ((Map<?, ?>) obj).size();
}
int count;
if (obj instanceof Iterator) {
Iterator<?> iter = (Iterator<?>) obj;
count = 0;
while (iter.hasNext()) {
count++;
iter.next();
}
return count;
}
if (obj instanceof Enumeration) {
Enumeration<?> enumeration = (Enumeration<?>) obj;
count = 0;
while (enumeration.hasMoreElements()) {
count++;
enumeration.nextElement();
}
return count;
}
if (obj.getClass().isArray() == true) {
return Array.getLength(obj);
}
return -1;
}
/**
* 去掉指定后缀
*
* @param str 字符串
* @param suffix 后缀
* @return 切掉后的字符串,若后缀不是 suffix, 返回原字符串
*/
public static String removeSuffix(String str, String suffix) {
if (StringUtil.isEmpty(str) || StringUtil.isEmpty(suffix)) {
return str;
}
if (str.endsWith(suffix)) {
return str.substring(0, str.length() - suffix.length());
}
return str;
}
}
\ No newline at end of file \ No newline at end of file
/**
* Copyright (c) 2011-2014, hubin (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.enilu.flash.utils;
import java.util.regex.Pattern;
/**
* Web防火墙工具类
* <p>
* @author hubin
* @Date 2014-5-8
*/
public class WafKit {
/**
* @Description 过滤XSS脚本内容
* @param value
* 待处理内容
* @return
*/
public static String stripXSS(String value) {
String rlt = null;
if (null != value) {
// NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
// avoid encoded attacks.
// value = ESAPI.encoder().canonicalize(value);
// Avoid null characters
rlt = value.replaceAll("", "");
// Avoid anything between script tags
Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Remove any lonesome </script> tag
scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Remove any lonesome <script ...> tag
scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid eval(...) expressions
scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid expression(...) expressions
scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid javascript:... expressions
scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid vbscript:... expressions
scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
rlt = scriptPattern.matcher(rlt).replaceAll("");
// Avoid onload= expressions
scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE | Pattern.DOTALL);
rlt = scriptPattern.matcher(rlt).replaceAll("");
}
return rlt;
}
/**
* @Description 过滤SQL注入内容
* @param value
* 待处理内容
* @return
*/
public static String stripSqlInjection(String value) {
return (null == value) ? null : value.replaceAll("('.+--)|(--)|(%7C)", ""); //value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
}
/**
* @Description 过滤SQL/XSS注入内容
* @param value
* 待处理内容
* @return
*/
public static String stripSqlXSS(String value) {
return stripXSS(stripSqlInjection(value));
}
}
/**
* Copyright (c) 2011-2014, hubin (jobob@qq.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package cn.enilu.flash.utils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
/**
* Request请求过滤包装
* <p>
* @author hubin
* @Date 2014-5-8
*/
public class WafRequestWrapper extends HttpServletRequestWrapper {
private boolean filterXSS = true;
private boolean filterSQL = true;
public WafRequestWrapper(HttpServletRequest request, boolean filterXSS, boolean filterSQL) {
super(request);
this.filterXSS = filterXSS;
this.filterSQL = filterSQL;
}
public WafRequestWrapper(HttpServletRequest request) {
this(request, true, true);
}
/**
* @Description 数组参数过滤
* @param parameter
* 过滤参数
* @return
*/
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = filterParamString(values[i]);
}
return encodedValues;
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Map getParameterMap() {
Map<String, String[]> primary = super.getParameterMap();
Map<String, String[]> result = new HashMap<String, String[]>(primary.size());
for (Map.Entry<String, String[]> entry : primary.entrySet()) {
result.put(entry.getKey(), filterEntryString(entry.getValue()));
}
return result;
}
protected String[] filterEntryString(String[] rawValue) {
for (int i = 0; i < rawValue.length; i++) {
rawValue[i] = filterParamString(rawValue[i]);
}
return rawValue;
}
/**
* @Description 参数过滤
* @param parameter
* 过滤参数
* @return
*/
@Override
public String getParameter(String parameter) {
return filterParamString(super.getParameter(parameter));
}
/**
* @Description 请求头过滤
* @param name
* 过滤内容
* @return
*/
@Override
public String getHeader(String name) {
return filterParamString(super.getHeader(name));
}
/**
* @Description Cookie内容过滤
* @return
*/
@Override
public Cookie[] getCookies() {
Cookie[] existingCookies = super.getCookies();
if (existingCookies != null) {
for (int i = 0; i < existingCookies.length; ++i) {
Cookie cookie = existingCookies[i];
cookie.setValue(filterParamString(cookie.getValue()));
}
}
return existingCookies;
}
/**
* @Description 过滤字符串内容
* @param rawValue
* 待处理内容
* @return
*/
protected String filterParamString(String rawValue) {
if (null == rawValue) {
return null;
}
String tmpStr = rawValue;
if (this.filterXSS) {
tmpStr = WafKit.stripXSS(rawValue);
}
if (this.filterSQL) {
tmpStr = WafKit.stripSqlInjection(tmpStr);
}
return tmpStr;
}
}
package cn.enilu.flash.utils;
import java.math.BigDecimal;
import java.util.Date;
public class XlsUtils {
public String dateFmt(Date date, String fmt) {
if (date == null) {
return "";
}
return DateUtil.formatDate(date, fmt);
}
/**
* 将以分为单位的金额转换为人民币形式,比如74900转为为:¥749
*
* @param amount
* @return
*/
public String toRMB(BigDecimal amount) {
if (amount == null) {
return "";
}
return "¥" + amount.divide(new BigDecimal(100)).toPlainString();
}
}
package cn.enilu.flash.utils.cache;
import cn.enilu.flash.utils.Maps;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* Created by enilu on 2017/4/12 0012.
*/
public class TimeCacheMap<K, V> {
private static final int DEFAULT_NUM_BUCKETS = 3;
/**
* 回调函数实现这个接口就可以,至少可以把删掉的元素传回去
*
* @param <K>
* @param <V>
*/
public static interface ExpiredCallback<K, V> {
public void expire(K key, V val);
}
/**
* 把数据分成多个桶,用链表是因为在头尾的增减操作时O(1)
*/
private LinkedList<HashMap<K, V>> buckets;
private final Object lock = new Object();
private Thread cleaner;
private ExpiredCallback callback;
public TimeCacheMap(int expirationSecs, int numBuckets, ExpiredCallback<K, V> callback) {
if (numBuckets < 2) {
throw new IllegalArgumentException("numBuckets must be >= 2");
}
//构造函数中,按照桶的数量,初始桶
buckets = new LinkedList<HashMap<K, V>>();
for (int i = 0; i < numBuckets; i++) {
buckets.add(new HashMap<K, V>());
}
this.callback = callback;
final long expirationMillis = expirationSecs * 1000L;
final long sleepTime = expirationMillis / (numBuckets - 1);
cleaner = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
Map<K, V> dead = null;
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
// Time.sleep(sleepTime);
synchronized (lock) {
//删掉最后一个桶,在头补充一个新的桶,最后一个桶的数据是最旧的
dead = buckets.removeLast();
buckets.addFirst(Maps.newHashMap());
}
if (TimeCacheMap.this.callback != null) {
for (Map.Entry<K, V> entry : dead.entrySet()) {
TimeCacheMap.this.callback.expire(entry.getKey(), entry.getValue());
}
}
}
}
});
//作为守护线程运行,一旦主线程不在,这个线程自动结束
cleaner.setDaemon(true);
cleaner.start();
}
public TimeCacheMap(int expirationSecs, ExpiredCallback<K, V> callback) {
this(expirationSecs, DEFAULT_NUM_BUCKETS, callback);
}
public TimeCacheMap(int expirationSecs) {
this(expirationSecs, DEFAULT_NUM_BUCKETS);
}
public TimeCacheMap(int expirationSecs, int numBuckets) {
this(expirationSecs, numBuckets, null);
}
public boolean containsKey(K key) {
if (buckets.getFirst().containsKey(key)) {
return true;
} else {
return false;
}
}
public V get(K key) {
return buckets.getFirst().get(key);
}
public void put(K key, V value) {
buckets.getFirst().put(key, value);
}
public Object remove(K key) {
return buckets.getFirst().remove(key);
}
public int size() {
return buckets.getFirst().size();
}
/**
* 中断清理线程中的sleep,_cleaner线程会抛出异常,然后_cleaner线程就死了,不再清理过期数据了
* 调用了interrupt后,再跑sleep就会抛InterruptedException异常
*/
public void neverCleanup() {
cleaner.interrupt();
}
}
\ No newline at end of file \ No newline at end of file
package cn.enilu.flash.utils.cache.exception;
import cn.enilu.flash.utils.StringUtil;
/**
* 工具类初始化异常
*/
public class ToolBoxException extends RuntimeException {
private static final long serialVersionUID = 8247610319171014183L;
public ToolBoxException(Throwable e) {
super(e.getMessage(), e);
}
public ToolBoxException(String message) {
super(message);
}
public ToolBoxException(String messageTemplate, Object... params) {
super(StringUtil.format(messageTemplate, params));
}
public ToolBoxException(String message, Throwable throwable) {
super(message, throwable);
}
public ToolBoxException(Throwable throwable, String messageTemplate, Object... params) {
super(StringUtil.format(messageTemplate, params), throwable);
}
}
package cn.enilu.flash.utils.factory;
import cn.enilu.flash.utils.StringUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 组合字符串生产者
*
* @author fengshuonan
* @date 2017-04-27 16:42
*/
public class MutiStrFactory {
/**
* 每个条目之间的分隔符
*/
public static final String ITEM_SPLIT = ";";
/**
* 属性之间的分隔符
*/
public static final String ATTR_SPLIT = ":";
/**
* 拼接字符串的id
*/
public static final String MUTI_STR_ID = "ID";
/**
* 拼接字符串的key
*/
public static final String MUTI_STR_KEY = "KEY";
/**
* 拼接字符串的value
*/
public static final String MUTI_STR_VALUE = "VALUE";
/**
* 解析一个组合字符串(例如: "1:启用;2:禁用;3:冻结" 这样的字符串)
*
* @author fengshuonan
* @Date 2017/4/27 16:44
*/
public static List<Map<String, String>> parseKeyValue(String mutiString) {
if (StringUtil.isEmpty(mutiString)) {
return new ArrayList<>();
} else {
ArrayList<Map<String, String>> results = new ArrayList<>();
String[] items = StringUtil.split(StringUtil.removeSuffix(mutiString, ITEM_SPLIT), ITEM_SPLIT);
for (String item : items) {
String[] attrs = item.split(ATTR_SPLIT);
HashMap<String, String> itemMap = new HashMap<>(100);
itemMap.put(MUTI_STR_KEY, attrs[0]);
itemMap.put(MUTI_STR_VALUE, attrs[1]);
results.add(itemMap);
}
return results;
}
}
/**
* 解析id:key:value这样类型的字符串
*
* @author fengshuonan
* @Date 2017/4/28 11:06
*/
public static List<Map<String, String>> parseIdKeyValue(String mutiString) {
if (StringUtil.isEmpty(mutiString)) {
return new ArrayList<>();
} else {
ArrayList<Map<String, String>> results = new ArrayList<>();
String[] items = StringUtil.split(StringUtil.removeSuffix(mutiString, ITEM_SPLIT), ITEM_SPLIT);
for (String item : items) {
String[] attrs = item.split(ATTR_SPLIT);
HashMap<String, String> itemMap = new HashMap<>(100);
itemMap.put(MUTI_STR_ID, attrs[0]);
itemMap.put(MUTI_STR_KEY, attrs[1]);
itemMap.put(MUTI_STR_VALUE, attrs[2]);
results.add(itemMap);
}
return results;
}
}
}
package cn.enilu.flash.utils.factory;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.utils.Lists;
import cn.enilu.flash.utils.StringUtil;
import org.springframework.data.domain.Sort;
import java.util.Collections;
import java.util.List;
/**
* Created on 2018/3/22 0022.
*
* @author enilu
*/
public class Page<T> {
private Sort sort;
/**
* 该操作只是为了忽略RowBounds属性
*/
private transient int offset;
/**
* 该操作只是为了忽略RowBounds属性
*/
private transient int limit;
/**
* 总数
*/
private int total;
/**
* 每页显示条数,默认 10
*/
private int size = 10;
/**
* 总页数
*/
private int pages;
/**
* 当前页
*/
private int current = 1;
/**
* 查询总记录数(默认 true)
*/
private transient boolean searchCount = true;
/**
* 查询数据列表
*/
private List<T> records = Collections.emptyList();
private transient List<SearchFilter> filters;
public Page() {
}
public Page(int current, int size, String orderByField) {
this(current, size, orderByField, true);
}
public Page(int current, int size, String orderByField, boolean isAsc) {
this(current, size);
setSort(Sort.by(isAsc ? Sort.Direction.ASC : Sort.Direction.DESC, orderByField));
}
/**
* <p>
* 分页构造函数
* </p>
*
* @param current 当前页
* @param size 每页显示条数
*/
public Page(int current, int size) {
this(current, size, true);
}
public Page(int current, int size, boolean searchCount) {
setOffset(offsetCurrent(current, size));
setLimit(size);
if (current > 1) {
this.current = current;
}
this.size = size;
this.searchCount = searchCount;
}
protected static int offsetCurrent(int current, int size) {
if (current > 0) {
return (current - 1) * size;
}
return 0;
}
public Sort getSort() {
return sort;
}
public void setSort(Sort sort) {
this.sort = sort;
}
public int offsetCurrent() {
return offsetCurrent(this.current, this.size);
}
public boolean hasPrevious() {
return this.current > 1;
}
public boolean hasNext() {
return this.current < this.pages;
}
public int getTotal() {
return total;
}
public Page setTotal(int total) {
this.total = total;
return this;
}
public int getSize() {
return size;
}
public Page setSize(int size) {
this.size = size;
return this;
}
public int getPages() {
if (this.size == 0) {
return 0;
}
this.pages = this.total / this.size;
if (this.total % this.size != 0) {
this.pages++;
}
return this.pages;
}
public int getCurrent() {
return current;
}
public Page setCurrent(int current) {
this.current = current;
return this;
}
public boolean isSearchCount() {
return searchCount;
}
public Page setSearchCount(boolean searchCount) {
this.searchCount = searchCount;
return this;
}
public int getOffset() {
return offset;
}
public Page setOffset(int offset) {
this.offset = offset;
return this;
}
public int getLimit() {
return limit;
}
public Page setLimit(int limit) {
this.limit = limit;
return this;
}
public List<T> getRecords() {
return records;
}
public Page<T> setRecords(List<T> records) {
this.records = records;
return this;
}
public List<SearchFilter> getFilters() {
return filters;
}
public void setFilters(List<SearchFilter> filters) {
this.filters = filters;
}
public void addFilter(SearchFilter filter) {
if (filter == null) {
return;
}
if (filters == null) {
filters = Lists.newArrayList();
}
filters.add(filter);
}
public void addFilter(String fieldName, SearchFilter.Operator operator, Object value) {
if (!StringUtil.isNullOrEmpty(value)) {
addFilter(SearchFilter.build(fieldName, operator, value));
}
}
public void addFilter(String fieldName, Object value) {
addFilter(fieldName, SearchFilter.Operator.EQ, value);
}
@Override
public String toString() {
StringBuilder pg = new StringBuilder();
pg.append(" Page:{ [").append(super.toString()).append("], ");
if (records != null) {
pg.append("records-size:").append(records.size());
} else {
pg.append("records is null");
}
return pg.append(" }").toString();
}
}
package cn.enilu.flash.warpper;
import java.util.List;
import java.util.Map;
/**
* 控制器查询结果的包装类基类
*
* @author fengshuonan
* @date 2017年2月13日 下午10:49:36
*/
public abstract class BaseControllerWarpper {
public Object obj = null;
public BaseControllerWarpper(Object obj) {
this.obj = obj;
}
@SuppressWarnings("unchecked")
public Object warp() {
if (this.obj instanceof List) {
List<Map<String, Object>> list = (List<Map<String, Object>>) this.obj;
for (Map<String, Object> map : list) {
warpTheMap(map);
}
return list;
} else if (this.obj instanceof Map) {
Map<String, Object> map = (Map<String, Object>) this.obj;
warpTheMap(map);
return map;
} else {
return this.obj;
}
}
/**
* 数据转换
*
* @param map
*/
protected abstract void warpTheMap(Map<String, Object> map);
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!