供货商

This commit is contained in:
2026-02-11 21:10:06 +08:00
parent 5331f61192
commit 1e3181172b
1158 changed files with 178379 additions and 597 deletions

View File

@@ -0,0 +1,24 @@
package com.bomaos;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.wf.jwtp.configuration.EnableJwtPermission;
@EnableJwtPermission
@EnableAsync
@MapperScan("com.bomaos.**.mapper")
@SpringBootApplication
public class BomaosApplication /*extends SpringBootServletInitializer*/ {
public static void main(String[] args) {
SpringApplication.run(BomaosApplication.class, args);
}
/*@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ZlianWebApplication.class);
}*/
}

View File

@@ -0,0 +1,223 @@
package com.bomaos.carmi.controller;
import com.bomaos.carmi.entity.Cards;
import com.bomaos.carmi.service.CardsService;
import com.bomaos.carmi.vo.CardsDts;
import com.bomaos.carmi.vo.CardsVo;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.*;
import com.bomaos.products.entity.Classifys;
import com.bomaos.products.entity.Products;
import com.bomaos.products.service.ClassifysService;
import com.bomaos.products.service.ProductsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* 卡密管理
* Created by Panyoujie on 2021-03-28 00:33:15
*/
@Controller
@RequestMapping("/carmi/cards")
public class CardsController extends BaseController {
@Autowired
private CardsService cardsService;
@Autowired
private ClassifysService classifysService;
@Autowired
private ProductsService productsService;
@RequiresPermissions("carmi:cards:view")
@RequestMapping()
public String view(Model model) {
List<Classifys> classifysList = classifysService.listAll(null);
model.addAttribute("classifysList", classifysList);
// 供应商数据隔离:只显示自己的商品
Integer supplierId = getLoginUserSupplierId();
List<Products> productsList;
if (supplierId != null) {
productsList = productsService.list(
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Products>()
.eq("supplier_id", supplierId));
} else {
productsList = productsService.listAll(null);
}
model.addAttribute("productsList", productsList);
return "carmi/cards.html";
}
@RequiresPermissions("carmi:cards:view")
@RequestMapping("/add")
public String ViewAdd(Model model) {
List<Classifys> classifysList = classifysService.listAll(null);
model.addAttribute("classifysList", classifysList);
return "carmi/cards-add.html";
}
/**
* 分页查询卡密
*/
@RequiresPermissions("carmi:cards:list")
@OperLog(value = "卡密管理", desc = "分页查询")
@ResponseBody
@RequestMapping("/page")
public PageResult<CardsVo> page(HttpServletRequest request) {
PageParam<Cards> pageParam = new PageParam<>(request);
// 供应商数据隔离
Integer supplierId = getLoginUserSupplierId();
if (supplierId != null) {
pageParam.put("supplierId", supplierId);
}
List<Cards> records = cardsService.page(pageParam, pageParam.getWrapper()).getRecords();
List<CardsVo> cardsVoList = records.stream().map((cards) -> {
CardsVo cardsVo = new CardsVo();
BeanUtils.copyProperties(cards, cardsVo);
// 查出商品的名称
Products products = productsService.getById(cards.getProductId());
cardsVo.setProductName(products.getName());
return cardsVo;
}).collect(Collectors.toList());
return new PageResult<>(cardsVoList, pageParam.getTotal());
}
/**
* 查询全部卡密
*/
@RequiresPermissions("carmi:cards:list")
@OperLog(value = "卡密管理", desc = "查询全部")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<Cards> pageParam = new PageParam<>(request);
return JsonResult.ok().setData(cardsService.list(pageParam.getOrderWrapper()));
}
/**
* 根据id查询卡密
*/
@RequiresPermissions("carmi:cards:list")
@OperLog(value = "卡密管理", desc = "根据id查询")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
return JsonResult.ok().setData(cardsService.getById(id));
}
/**
* 添加卡密
*/
@RequiresPermissions("carmi:cards:save")
@OperLog(value = "卡密管理", desc = "添加", param = false, result = true)
@ResponseBody
@RequestMapping("/save")
public JsonResult save(CardsDts cardsDts) {
Products products = productsService.getById(cardsDts.getProductId());
// 供应商只能向自己的商品添加卡密
Integer supplierId = getLoginUserSupplierId();
if (supplierId != null && !supplierId.equals(products.getSupplierId())) {
return JsonResult.error("无权操作此商品的卡密!");
}
if (products.getSellType() != cardsDts.getSellType()) { // 重复销售
return JsonResult.error("本商品为重复售卡类型、请使用重复售卡来导入卡密!!");
}
return cardsService.addCards(cardsDts);
}
/**
* 修改卡密
*/
@RequiresPermissions("carmi:cards:update")
@OperLog(value = "卡密管理", desc = "修改", param = false, result = true)
@ResponseBody
@RequestMapping("/update")
public JsonResult update(Cards cards) {
if (cardsService.updateById(cards)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除卡密
*/
@RequiresPermissions("carmi:cards:remove")
@OperLog(value = "卡密管理", desc = "删除", result = true)
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (cardsService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量添加卡密
*/
@RequiresPermissions("carmi:cards:save")
@OperLog(value = "卡密管理", desc = "批量添加", param = false, result = true)
@ResponseBody
@RequestMapping("/saveBatch")
public JsonResult saveBatch(@RequestBody List<Cards> list) {
if (cardsService.saveBatch(list)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 批量修改卡密
*/
@RequiresPermissions("carmi:cards:update")
@OperLog(value = "卡密管理", desc = "批量修改", result = true)
@ResponseBody
@RequestMapping("/updateBatch")
public JsonResult updateBatch(@RequestBody BatchParam<Cards> batchParam) {
if (batchParam.update(cardsService, "id")) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 批量删除卡密
*/
@RequiresPermissions("carmi:cards:remove")
@OperLog(value = "卡密管理", desc = "批量删除", result = true)
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (cardsService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 卡密导出
*
* @param request
* @throws Exception
*/
@RequiresPermissions("carmi:cards:list")
@OperLog(value = "卡密管理", desc = "导出指定的数据")
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void exportCardSecret(HttpServletRequest request) throws Exception {
cardsService.export(request);
}
}

View File

@@ -0,0 +1,42 @@
package com.bomaos.carmi.dto;
import com.bomaos.carmi.excel.Excel;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
@Data
@ToString
@Excel("卡券导出信息")
public class CardsDto implements Serializable {
private static final long serialVersionUID = 1L;
@Excel("ID")
private Integer id;
/**
* 对应商品id
*/
@Excel("对应商品ID")
private String productName;
/**
* 卡密
*/
@Excel("卡密")
private String cardInfo;
/**
* 卡密状态
*/
@Excel("卡密状态")
private String status;
/**
* 创建时间
*/
@Excel("创建时间")
private String createdAt;
}

View File

@@ -0,0 +1,73 @@
package com.bomaos.carmi.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* 卡密
* Created by Panyoujie on 2021-03-28 00:33:15
*/
@Data
@ToString
@TableName("sys_cards")
public class Cards implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 对应商品id
*/
private Integer productId;
/**
* 卡密
*/
private String cardInfo;
/**
* 卡密状态
*/
private Integer status;
/**
* 售卡类型
*/
private Integer sellType;
/**
* 总数
*/
private Integer number;
/**
* 售出数量
*/
private Integer sellNumber;
/**
* 创建时间
*/
private Date createdAt;
/**
* 更新时间
*/
private Date updatedAt;
/**
* 供应商id
*/
private Integer supplierId;
}

View File

@@ -0,0 +1,22 @@
package com.bomaos.carmi.excel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface Excel {
// 字段标题名称或文件名称
String value();
// excel操作类型ExcelType
ExcelType type() default ExcelType.ALL;
// 字段字典标识,用于导入导出时进行字典转换(只支持导出操作)
String dict() default "";
// 关联操作实体对象字段名称,用于获取关联数据(只支持导出操作)
String joinField() default "";
}

View File

@@ -0,0 +1,223 @@
package com.bomaos.carmi.excel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author lixy
* @className: ExcelSxssFUtil
* @Version 1.0
* @description: TODO 大批量数据导出
* @Email 2542130759@qq.com
* @date 2020/12/16 17:14
*/
public class ExcelSxssFUtil {
public static <T> void exportExcel(List<Field> fields, SXSSFWorkbook workbook, List<T> list, String sheetTitle) {
List<String> fns = getFieldName(fields);
SXSSFSheet sheet = getCommon(workbook, sheetTitle, fields);
CellStyle cellStyle = getCellStyle(workbook);
// 时间样式
CellStyle dateStyle = workbook.createCellStyle();
dateStyle.cloneStyleFrom(cellStyle);
DataFormat format = workbook.createDataFormat();
dateStyle.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm:ss"));
for (int i = 0; i < list.size(); i++) {
SXSSFRow row = sheet.createRow(i + 2);
T item = list.get(i);
// 通过反射机制获取实体对象的状态
try {
final BeanInfo bi = Introspector.getBeanInfo(item.getClass());
for (final PropertyDescriptor pd : bi.getPropertyDescriptors()) {
if (fns.contains(pd.getName())) {
Object value = pd.getReadMethod().invoke(item, (Object[]) null);
int index = fns.indexOf(pd.getName());
SXSSFCell cell = row.createCell(index);
if (value != null) {
Excel excel = fields.get(index).getAnnotation(Excel.class);
// 给单元格赋值
if (value instanceof Number) {
cell.setCellValue((Double.valueOf(String.valueOf(value))));
} else if (value instanceof Date) {
cell.setCellValue((Date) value);
cell.setCellStyle(dateStyle);
continue;
} else {
cell.setCellValue(String.valueOf(value));
}
}
cell.setCellStyle(cellStyle);
}
}
} catch (InvocationTargetException | IntrospectionException | IllegalAccessException e) {
String message = "导入失败:字段名称匹配失败!";
throw new IllegalArgumentException(message, e);
}
}
}
/**
* 获取通用样式
*/
private static CellStyle getCellStyle(SXSSFWorkbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setAlignment(HorizontalAlignment.LEFT);
XSSFFont font = (XSSFFont) workbook.createFont();
font.setFontName("Microsoft YaHei UI");
cellStyle.setFont(font);
return cellStyle;
}
/**
* 功能模板(标题及表头)
*/
public static SXSSFSheet getCommon(SXSSFWorkbook workbook, String sheetTitle, List<Field> fields) {
SXSSFSheet sheet = workbook.createSheet(sheetTitle);
// 设置列宽度
for (int i = 0; i < fields.size(); i++) {
sheet.setColumnWidth(i, 16 * 256);
}
// 通用样式
CellStyle cellStyle = getCellStyle(workbook);
// 标题样式
CellStyle titleStyle = workbook.createCellStyle();
titleStyle.cloneStyleFrom(cellStyle);
titleStyle.setAlignment(HorizontalAlignment.CENTER);
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Font titleFont = workbook.createFont();
titleFont.setFontName("Microsoft YaHei UI");
titleFont.setBold(true);
titleFont.setFontHeightInPoints((short) 14);
titleStyle.setFont(titleFont);
// 表头样式
CellStyle thStyle = workbook.createCellStyle();
thStyle.cloneStyleFrom(titleStyle);
thStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
thStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font thFont = workbook.createFont();
thFont.setFontName("Microsoft YaHei UI");
thFont.setBold(titleFont.getBold());
thFont.setColor(IndexedColors.WHITE.getIndex());
thStyle.setFont(thFont);
// 创建标题样式、表格表头
SXSSFRow titleRow = sheet.createRow(0);
SXSSFRow thsRow = sheet.createRow(1);
for (int i = 0; i < fields.size(); i++) {
Excel excel = fields.get(i).getAnnotation(Excel.class);
SXSSFCell title = titleRow.createCell(i);
title.setCellStyle(titleStyle);
SXSSFCell th = thsRow.createCell(i);
th.setCellValue(excel.value());
th.setCellStyle(thStyle);
}
// 绘制标题
titleRow.setHeight((short) (26 * 20));
SXSSFCell titleCell = titleRow.createCell(0);
titleCell.setCellValue(sheetTitle);
titleCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, fields.size() - 1));
return sheet;
}
public static List<Field> getExcelList(Class<?> entity, ExcelType type) {
List<Field> list = new ArrayList<>();
Field[] fields = entity.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Excel.class)) {
ExcelType fieldType = field.getAnnotation(Excel.class).type();
if (fieldType.equals(ExcelType.ALL) || fieldType.equals(type)) {
list.add(field);
}
}
}
return list;
}
/**
* 获取实体类带有@Excel字段名
*/
private static List<String> getFieldName(List<Field> fields) {
List<String> list = new ArrayList<>();
for (Field field : fields) {
list.add(field.getName());
}
return list;
}
public static void download(SXSSFWorkbook workbook, String fileName) {
try {
fileName = URLEncoder.encode(fileName + ".xlsx", "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ServletRequestAttributes getServletRequest = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = getServletRequest.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream ros = null;
try {
ros = response.getOutputStream();
workbook.write(ros);
ros.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ros != null) {
try {
ros.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@@ -0,0 +1,5 @@
package com.bomaos.carmi.excel;
public enum ExcelType {
ALL, IMPORT, EXPORT
}

View File

@@ -0,0 +1,37 @@
package com.bomaos.carmi.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bomaos.carmi.entity.Cards;
import com.bomaos.common.core.web.PageParam;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 卡密Mapper接口
* Created by Panyoujie on 2021-03-28 00:33:15
*/
public interface CardsMapper extends BaseMapper<Cards> {
/**
* 分页查询
*/
List<Cards> listPage(@Param("page") PageParam<Cards> page);
/**
* 查询全部
*/
List<Cards> listAll(@Param("page") Map<String, Object> page);
/**
* 查询卡密
*
* @param status
* @param productId
* @return
*/
List<Cards> getCard(Integer status, Integer productId, Integer number);
}

View File

@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bomaos.carmi.mapper.CardsMapper">
<!-- 关联查询sql -->
<sql id="relSelect">
SELECT a.*
FROM sys_cards a
<where>
<if test="page!=null and page.pageData!=null">
<if test="page.pageData.id != null">
AND a.id = #{page.pageData.id}
</if>
<if test="page.pageData.productId != null">
AND a.product_id = #{page.pageData.productId}
</if>
<if test="page.pageData.cardInfo != null">
AND a.card_info LIKE CONCAT('%', #{page.pageData.cardInfo}, '%')
</if>
<if test="page.pageData.status != null">
AND a.status = #{page.pageData.status}
</if>
<if test="page.pageData.sellType != null">
AND a.sell_type = #{page.pageData.sellType}
</if>
<if test="page.pageData.number != null">
AND a.number = #{page.pageData.number}
</if>
<if test="page.pageData.sellNumber != null">
AND a.sell_number = #{page.pageData.sellNumber}
</if>
<if test="page.pageData.createdAt != null">
AND a.created_at LIKE CONCAT('%', #{page.pageData.createdAt}, '%')
</if>
<if test="page.pageData.updatedAt != null">
AND a.updated_at LIKE CONCAT('%', #{page.pageData.updatedAt}, '%')
</if>
<if test="page.pageData.supplierId != null">
AND a.supplier_id = #{page.pageData.supplierId}
</if>
</if>
</where>
</sql>
<!-- 分页查询 -->
<select id="listPage" resultType="com.bomaos.carmi.entity.Cards">
<include refid="relSelect"></include>
</select>
<!-- 查询全部 -->
<select id="listAll" resultType="com.bomaos.carmi.entity.Cards">
<include refid="relSelect"></include>
</select>
<select id="getCard" resultType="com.bomaos.carmi.entity.Cards">
select *
from sys_cards
WHERE status = #{status}
and product_id = #{productId}
ORDER BY rand() LIMIT #{number}
</select>
</mapper>

View File

@@ -0,0 +1,35 @@
package com.bomaos.carmi.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.bomaos.carmi.entity.Cards;
import com.bomaos.carmi.vo.CardsDts;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
/**
* 卡密服务类
* Created by Panyoujie on 2021-03-28 00:33:15
*/
public interface CardsService extends IService<Cards> {
/**
* 分页查询
*/
PageResult<Cards> listPage(PageParam<Cards> page);
/**
* 查询所有
*/
List<Cards> listAll(Map<String, Object> page);
JsonResult addCards(CardsDts cardsDts);
List<Cards> getCard(Integer status, Integer productId, Integer number);
void export(HttpServletRequest request);
}

View File

@@ -0,0 +1,158 @@
package com.bomaos.carmi.service.impl;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bomaos.carmi.dto.CardsDto;
import com.bomaos.carmi.entity.Cards;
import com.bomaos.carmi.excel.Excel;
import com.bomaos.carmi.excel.ExcelSxssFUtil;
import com.bomaos.carmi.excel.ExcelType;
import com.bomaos.carmi.mapper.CardsMapper;
import com.bomaos.carmi.service.CardsService;
import com.bomaos.carmi.vo.CardsDts;
import com.bomaos.common.core.utils.CoreUtil;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.products.entity.Products;
import com.bomaos.products.mapper.ProductsMapper;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 卡密服务实现类
* Created by Panyoujie on 2021-03-28 00:33:15
*/
@Service
@Transactional
public class CardsServiceImpl extends ServiceImpl<CardsMapper, Cards> implements CardsService {
@Autowired
private ProductsMapper productsMapper;
@Override
public PageResult<Cards> listPage(PageParam<Cards> page) {
List<Cards> records = baseMapper.listPage(page);
return new PageResult<>(records, page.getTotal());
}
@Override
public List<Cards> listAll(Map<String, Object> page) {
return baseMapper.listAll(page);
}
@Override
public JsonResult addCards(CardsDts cardsDts) {
if (cardsDts.getSellType() == 0) { // 单卡销售
String[] cardsInfo = cardsDts.getCardInfo().split("\\n");
List<String> newlist = new ArrayList();
for (int i = 0; i < cardsInfo.length; ++i) {
if (cardsDts.getRepeat() == 0) {
newlist.add(CoreUtil.getStringNoBlank(cardsInfo[i]));
} else if (cardsDts.getRepeat() == 1 && !newlist.contains(cardsInfo[i])) {
newlist.add(CoreUtil.getStringNoBlank(cardsInfo[i]));
}
}
while (newlist.remove(null)) ;
while (newlist.remove("")) ;
List<Cards> cardsArrayList = new ArrayList<>();
for (String cardInfo : newlist) {
Cards cards = new Cards();
cards.setProductId(cardsDts.getProductId());
cards.setCardInfo(CoreUtil.getStringNoBlank(cardInfo));
cards.setStatus(0); // 设置未出售
cards.setSellType(0);
cards.setNumber(1);
cards.setSellNumber(0);
cards.setCreatedAt(new Date());
cards.setUpdatedAt(new Date());
cardsArrayList.add(cards);
}
boolean batch = this.saveBatch(cardsArrayList);
if (batch) {
return JsonResult.ok("批量添加卡密成功!");
}
return JsonResult.error("添加卡密失败");
} else { // 重复销售
Cards cards1 = this.getOne(new QueryWrapper<Cards>().eq("product_id", cardsDts.getProductId()).eq("status", 0).eq("sell_type", 1));
if (!ObjectUtils.isEmpty(cards1)) {
return JsonResult.error("当前商品为重复销售类型、已存在一个重复销售的卡密、请勿重复添加,如需修改当前卡密数量请前往卡密管理进行操作。");
}
Cards cards = new Cards();
cards.setProductId(cardsDts.getProductId());
cards.setCardInfo(CoreUtil.getStringNoBlank(cardsDts.getCardInfo()));
cards.setStatus(0); // 设置未出售
cards.setSellType(1);
cards.setNumber(cardsDts.getSellNumber());
cards.setSellNumber(0);
cards.setCreatedAt(new Date());
cards.setUpdatedAt(new Date());
boolean save = this.save(cards);
if (save) {
return JsonResult.ok("重复销售卡密添加成功!");
}
return JsonResult.error("重复销售的卡密添加失败。");
}
}
@Override
public List<Cards> getCard(Integer status, Integer productId, Integer number) {
return baseMapper.getCard(status, productId, number);
}
@Override
public void export(HttpServletRequest request) {
PageParam<Cards> pageParam = new PageParam<>(request);
List<Cards> cardsList = this.list(pageParam.getOrderWrapper());
List<CardsDto> cardsDtoList = cardsList.stream().map((cards -> {
CardsDto cardsDto = new CardsDto();
BeanUtils.copyProperties(cards, cardsDto);
// TODO 导出时间这里需要抓换String否则导出数据异常可优化
cardsDto.setCreatedAt(DateUtil.formatDateTime(cards.getCreatedAt()));
if (cards.getStatus() == 1) {
cardsDto.setStatus("已出售");
} else {
cardsDto.setStatus("未出售");
}
Products products = productsMapper.selectById(cards.getProductId());
if (!ObjectUtils.isEmpty(products)) {
cardsDto.setProductName(products.getName());
} else {
cardsDto.setProductName("商品已删除");
}
return cardsDto;
})).collect(Collectors.toList());
for (CardsDto cardsDto : cardsDtoList) {
System.out.println(cardsDto);
}
Excel excel = CardsDto.class.getAnnotation(Excel.class);
List<Field> fields = ExcelSxssFUtil.getExcelList(CardsDto.class, ExcelType.EXPORT);
String sheetTitle = excel.value();
SXSSFWorkbook workbook = new SXSSFWorkbook();
ExcelSxssFUtil.exportExcel(fields, workbook, cardsDtoList, sheetTitle);
ExcelSxssFUtil.download(workbook, sheetTitle);
}
}

View File

@@ -0,0 +1,35 @@
package com.bomaos.carmi.vo;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class CardsDts {
/**
* 商品id
*/
private Integer productId;
/**
* 销售类型
*/
private Integer sellType;
/**
* 卡密信息
*/
private String cardInfo;
/**
* 销售次数
*/
private Integer sellNumber;
/**
* 过滤重复
*/
private Integer repeat;
}

View File

@@ -0,0 +1,57 @@
package com.bomaos.carmi.vo;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
@Data
@ToString
public class CardsVo {
/**
* 自增ID
*/
private Integer id;
/**
* 对应商品id
*/
private String productName;
/**
* 卡密
*/
private String cardInfo;
/**
* 卡密状态
*/
private Integer status;
/**
* 售卡类型
*/
private Integer sellType;
/**
* 总数
*/
private Integer number;
/**
* 售出数量
*/
private Integer sellNumber;
/**
* 创建时间
*/
private Date createdAt;
/**
* 更新时间
*/
private Date updatedAt;
}

View File

@@ -0,0 +1,41 @@
package com.bomaos.common.core;
import org.springframework.util.ResourceUtils;
import java.io.FileNotFoundException;
/**
* 系统常量
* Created by Panyoujie on 2019-10-29 15:55
*/
public class Constants {
/* 文件服务器配置 */
/*public static final String UPLOAD_DIR = System.getProperty("user.dir") + "/upload/"; // 上传的目录*/
public static String UPLOAD_DIR = ""; // 上传的目录
static {
try {
UPLOAD_DIR = ResourceUtils.getURL("classpath:").getPath() + "/static/upload/";
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static final boolean UPLOAD_UUID_NAME = false; // 文件上传是否用uuid命名
public static final boolean UPLOAD_MD5_NAME = true; // 文件上传是否用MD5命名
// OpenOffice在不同操作系统上的安装路径
public static final String OPEN_OFFICE_PATH_WINDOWS = "C:/OpenOffice";
public static final String OPEN_OFFICE_PATH_LINUX = "/opt/openoffice.org3";
public static final String OPEN_OFFICE_PATH_MAC = "/Applications/OpenOffice.org.app/Contents/";
/* 返回结果统一 */
public static final int RESULT_OK_CODE = 0; // 默认成功码
public static final int RESULT_ERROR_CODE = 1; // 默认失败码
/**
* 支付超时时间(分钟)
*/
public static Integer PAY_TIMEOUT_MINUTES = 5;
}

View File

@@ -0,0 +1,36 @@
package com.bomaos.common.core.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 操作日志记录注解
* Created by Panyoujie on 2020-03-21 17:03
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OperLog {
/**
* 模块
*/
String value();
/**
* 功能
*/
String desc();
/**
* 是否记录请求参数
*/
boolean param() default true;
/**
* 是否记录返回结果
*/
boolean result() default false;
}

View File

@@ -0,0 +1,102 @@
package com.bomaos.common.core.aspect;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.utils.UserAgentGetter;
import com.bomaos.common.system.entity.OperRecord;
import com.bomaos.common.system.entity.User;
import com.bomaos.common.system.service.OperRecordService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
/**
* 操作日志记录
* Created by Panyoujie on 2020-03-21 16:58
*/
@Aspect
@Component
public class OperLogAspect {
private final ThreadLocal<Long> startTime = new ThreadLocal<>();
@Autowired
private OperRecordService operRecordService;
@Pointcut("@annotation(com.bomaos.common.core.annotation.OperLog)")
public void operLog() {
}
@Before("operLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
}
@AfterReturning(pointcut = "operLog()", returning = "result")
public void doAfterReturning(JoinPoint joinPoint, Object result) {
saveLog(joinPoint, result, null);
}
@AfterThrowing(value = "operLog()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
saveLog(joinPoint, null, e);
}
private void saveLog(JoinPoint joinPoint, Object result, Exception e) {
// 获取reques对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (attributes == null ? null : attributes.getRequest());
// 构建操作日志
OperRecord operRecord = new OperRecord();
operRecord.setUserId(getLoginUserId());
if (startTime.get() != null) operRecord.setSpendTime(System.currentTimeMillis() - startTime.get());
if (request != null) {
operRecord.setRequestMethod(request.getMethod());
operRecord.setUrl(request.getRequestURI());
operRecord.setIp(UserAgentGetter.getIp(request));
}
// 记录异常信息
if (e != null) {
operRecord.setState(1);
operRecord.setComments(StrUtil.sub(e.toString(), 0, 2000));
}
// 记录模块名、操作功能、请求方法、请求参数、返回结果
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
operRecord.setOperMethod(joinPoint.getTarget().getClass().getName() + "." + signature.getName());
Method method = signature.getMethod();
if (method != null) {
OperLog operLog = method.getAnnotation(OperLog.class);
if (operLog != null) {
operRecord.setModel(operLog.value());
operRecord.setDescription(operLog.desc());
if (operLog.param() && request != null) {
operRecord.setParam(StrUtil.sub(JSON.toJSONString(request.getParameterMap()), 0, 2000));
}
if (operLog.result() && result != null) {
operRecord.setResult(StrUtil.sub(JSON.toJSONString(result), 0, 2000));
}
}
}
operRecordService.saveAsync(operRecord);
}
/**
* 获取当前登录的userId
*/
private Integer getLoginUserId() {
Subject subject = SecurityUtils.getSubject();
if (subject == null) return null;
Object object = subject.getPrincipal();
if (object instanceof User) return ((User) object).getUserId();
return null;
}
}

View File

@@ -0,0 +1,59 @@
package com.bomaos.common.core.config;
import com.bomaos.common.core.shiro.ShiroExt;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.ext.spring.BeetlSpringViewResolver;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
/**
* Beetl配置
* Created by Panyoujie on 2018-02-22 11:29
*/
@Configuration
public class BeetlConfiguration {
@Value("${beetl.templatesPath:templates}")
private String templatesPath; // 模板根目录
@Value("${beetl.suffix:html}")
private String suffix; // 模板后缀
@Value("${beetl.dev:true}")
private boolean dev; // 开启热加载
@Bean(name = "beetlConfig")
public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
BeetlGroupUtilConfiguration bguc = new BeetlGroupUtilConfiguration();
Properties extProperties = new Properties();
extProperties.put("RESOURCE.autoCheck", dev ? "true" : "false");
extProperties.put("HTML_TAG_FLAG", ":");
bguc.setConfigProperties(extProperties);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) loader = BeetlConfiguration.class.getClassLoader();
bguc.setResourceLoader(new ClasspathResourceLoader(loader, templatesPath));
bguc.init();
// 增加自定义函数
bguc.getGroupTemplate().registerFunctionPackage("so", new ShiroExt());
// 增加自定义标签
bguc.getGroupTemplate().registerTag("include", org.beetl.ext.tag.html.IncludeResourceHtmlTag.class);
bguc.getGroupTemplate().registerTag("layout", org.beetl.ext.tag.html.LayoutResourceHtmlTag.class);
bguc.getGroupTemplate().registerTag("set", org.beetl.ext.tag.html.SetHtmlTag.class);
bguc.getGroupTemplate().registerTag("if", org.beetl.ext.tag.html.IfHtmlTag.class);
bguc.getGroupTemplate().registerTag("for", org.beetl.ext.tag.html.ForeachHtmlTag.class);
return bguc;
}
@Bean(name = "beetlViewResolver")
public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration bguc) {
BeetlSpringViewResolver bsvr = new BeetlSpringViewResolver();
bsvr.setContentType("text/html;charset=UTF-8");
bsvr.setViewNames("*." + suffix, "*." + suffix + "#*");
bsvr.setOrder(0);
bsvr.setConfig(bguc);
return bsvr;
}
}

View File

@@ -0,0 +1,53 @@
package com.bomaos.common.core.config;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 日期类型转换器
* Created by Panyoujie on 2018-08-17 08:43
*/
@Component
public class DateConverterConfig implements Converter<String, Date> {
private static final List<String> formats = new ArrayList<>();
/*
* 以下几种时间格式自动转成Date类型
*/
static {
formats.add("yyyy-MM-dd");
formats.add("yyyy-MM-dd HH:mm");
formats.add("yyyy-MM-dd HH:mm:ss");
}
@Override
public Date convert(String s) {
if (s == null || s.trim().isEmpty()) {
return null;
} else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
return parseDate(s, formats.get(0));
} else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) {
return parseDate(s, formats.get(1));
} else if (s.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
return parseDate(s, formats.get(2));
} else {
throw new IllegalArgumentException("DateConverterConfig: Invalid date value '" + s + "'");
}
}
private Date parseDate(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,28 @@
package com.bomaos.common.core.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* MybatisPlus配置
* Created by Panyoujie on 2018-02-22 11:29
*/
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}

View File

@@ -0,0 +1,34 @@
package com.bomaos.common.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.FormContentFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvc配置, 拦截器、资源映射等都在此配置
* Created by Panyoujie on 2019-06-12 10:11
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 支持跨域访问
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").maxAge(3600)
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "x-requested-with", "X-Custom-Header", "Authorization");
}
/**
* 支持PUT、DELETE请求
*/
@Bean
public FormContentFilter httpPutFormContentFilter() {
return new FormContentFilter();
}
}

View File

@@ -0,0 +1,32 @@
package com.bomaos.common.core.enmu;
public enum Alipay {
MQPAY_ALIPAY("mqpay_alipay"),
EPAY_ALIPAY("epay_alipay"),
BUDPAY_ALIPAY("budpay_alipay"),
YUNGOUOS_ALIPAY("yungouos_alipay"),
XUNHUPAY_ALIPAY("xunhupay_alipay"),
PAYJS_ALIPAY("payjs_alipay"),
ALIPAY("alipay"),
ALIPAY_PC("alipay_pc");
Alipay(String code) {
this.code = code;
}
private final String code;
public String getCode() {
return code;
}
public static boolean getByValue(String value) {
for (Alipay alipay : values()) {
if (alipay.getCode().equals(value)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,25 @@
package com.bomaos.common.core.enmu;
public enum Paypal {
PAYPAL("paypal");
Paypal(String code) {
this.code = code;
}
private final String code;
public String getCode() {
return code;
}
public static boolean getByValue(String value) {
for (Paypal paypal : values()) {
if (paypal.getCode().equals(value)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,24 @@
package com.bomaos.common.core.enmu;
public enum QQPay {
EPAY_QQPAY("epay_qqpay");
QQPay(String code) {
this.code = code;
}
private final String code;
public String getCode() {
return code;
}
public static boolean getByValue(String value) {
for (QQPay qqPay : values()) {
if (qqPay.getCode().equals(value)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,25 @@
package com.bomaos.common.core.enmu;
public enum USDT {
EPUSDT("epusdt");
USDT(String code) {
this.code = code;
}
private final String code;
public String getCode() {
return code;
}
public static boolean getByValue(String value) {
for (USDT usdt : values()) {
if (usdt.getCode().equals(value)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,31 @@
package com.bomaos.common.core.enmu;
public enum Wxpay {
MQPAY_WXPAY("mqpay_wxpay"),
EPAY_WXPAY("epay_wxpay"),
YUNGOUOS_WXPAY("yungouos_wxpay"),
XUNHUPAY_WXPAY("xunhupay_wxpay"),
PAYJS_WXPAY("payjs_wxpay"),
WXPAY("wxpay"),
WXPAU_H5("wxpay_h5");
Wxpay(String code) {
this.code = code;
}
private final String code;
public String getCode() {
return code;
}
public static boolean getByValue(String value) {
for (Wxpay wxpay : values()) {
if (wxpay.getCode().equals(value)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,39 @@
package com.bomaos.common.core.exception;
/**
* 业务异常
* Created by Panyoujie on 2018-02-22 11:29
*/
public class BusinessException extends IException {
private static final long serialVersionUID = 5450935008012318697L;
public BusinessException() {
super();
}
public BusinessException(String message) {
super(message);
}
public BusinessException(Integer code, String message) {
super(code, message);
}
@Override
public Integer getCode() {
Integer code = super.getCode();
if (code == null) {
code = 500;
}
return code;
}
@Override
public String getMessage() {
String message = super.getMessage();
if (message == null) {
message = "系统错误";
}
return message;
}
}

View File

@@ -0,0 +1,75 @@
package com.bomaos.common.core.exception;
import com.alibaba.fastjson.JSON;
import com.bomaos.common.core.Constants;
import com.bomaos.common.core.web.JsonResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 全局异常处理器
* Created by Panyoujie on 2018-02-22 11:29
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class.getName());
@ExceptionHandler(Exception.class)
public String errorHandler(Exception ex, HttpServletRequest request, HttpServletResponse response) {
// 对不同错误进行不同处理
if (ex instanceof IException) {
return doHandler("error/500.html", ((IException) ex).getCode(), ex.getMessage(), ex.toString(), request, response);
} else if (ex instanceof UnauthorizedException) {
return doHandler("error/403.html", 403, "没有访问权限", ex.toString(), request, response);
}
logger.error(ex.getMessage(), ex);
return doHandler("error/500.html", Constants.RESULT_ERROR_CODE, "系统错误", ex.toString(), request, response);
}
/**
* 处理错误,ajax返回json非ajax跳转页面
*/
private String doHandler(String url, Integer code, String msg, String error, HttpServletRequest request, HttpServletResponse response) {
if (isAjax(request)) {
cross(response); // 支持跨域
response.setContentType("application/json;charset=utf-8");
try {
PrintWriter out = response.getWriter();
out.write(JSON.toJSONString(JsonResult.error(code, msg).put("error", error)));
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
return url;
}
/**
* 判断是不是ajax请求
*/
private boolean isAjax(HttpServletRequest request) {
String xHeader = request.getHeader("X-Requested-With");
return (xHeader != null && xHeader.contains("XMLHttpRequest"));
}
/**
* 支持跨域请求
*/
private void cross(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization");
}
}

View File

@@ -0,0 +1,30 @@
package com.bomaos.common.core.exception;
/**
* 自定义异常基类
* Created by Panyoujie on 2018-02-22 11:29
*/
public abstract class IException extends RuntimeException {
private static final long serialVersionUID = -1582874427218948396L;
private Integer code;
public IException() {
}
public IException(String message) {
super(message);
}
public IException(Integer code, String message) {
super(message);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}

View File

@@ -0,0 +1,39 @@
package com.bomaos.common.core.exception;
/**
* 参数异常
* Created by Panyoujie on 2018-02-22 11:29
*/
public class ParameterException extends IException {
private static final long serialVersionUID = 7993671808524980055L;
public ParameterException() {
super();
}
public ParameterException(String message) {
super(message);
}
public ParameterException(Integer code, String message) {
super(code, message);
}
@Override
public Integer getCode() {
Integer code = super.getCode();
if (code == null) {
code = 400;
}
return code;
}
@Override
public String getMessage() {
String message = super.getMessage();
if (message == null) {
message = "参数错误";
}
return message;
}
}

View File

@@ -0,0 +1,105 @@
package com.bomaos.common.core.pays.alipay;
import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.bomaos.settings.entity.Pays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* authorpanyoujie
* date2022-0902
*/
public class AlipayUtil {
private static final Logger logger = LoggerFactory.getLogger(AlipayUtil.class);
/**
* 支付宝当面付
*
* @param subject 自定义内容
* @param orderNo 订单号
* @param totalAmount 订单金额
* @return
*/
public static String getFaceToFace(Pays pays, String subject, String orderNo, String totalAmount) {
// 获取支付配置信息
Map mapTypes = JSON.parseObject(pays.getConfig());
String app_id = mapTypes.get("app_id").toString();
String private_key = mapTypes.get("private_key").toString();
String alipay_public_key = mapTypes.get("alipay_public_key").toString();
String notify_url = mapTypes.get("notify_url").toString() + "/alipay/notify"; // 异步通知地址
// 1. 设置参数(全局只需设置一次)
Factory.setOptions(getOptions(app_id, private_key, alipay_public_key, notify_url));
try {
// 2. 发起API调用使用面对面支付中的预下单
AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(subject, orderNo, totalAmount);
// 3. 处理响应或异常
if ("10000".equals(response.code)) {
logger.info("调用成功:{}", response.qrCode);
return response.qrCode; //返回二维码
} else {
logger.error("调用失败,原因:{},{}", response.msg, response.subMsg);
}
} catch (Exception e) {
logger.error("调用遭遇异常,原因:{}", e.getMessage());
throw new RuntimeException(e.getMessage(), e);
}
return null;
}
/**
* 支付宝电脑网站支付
*
* @param subject 自定义内容
* @param orderNo 订单号
* @param totalAmount 订单金额
* @return
*/
public static String getPcPage(Pays pays, String subject, String orderNo, String totalAmount) {
// 获取支付配置信息
Map mapTypes = JSON.parseObject(pays.getConfig());
String app_id = mapTypes.get("app_id").toString();
String private_key = mapTypes.get("private_key").toString();
String alipay_public_key = mapTypes.get("alipay_public_key").toString();
String url = mapTypes.get("notify_url").toString();
String notify_url = url + "/alipay/notify";
String return_url = url + "/alipay/return_url";
// 1. 设置参数(全局只需设置一次)
Factory.setOptions(getOptions(app_id, private_key, alipay_public_key, notify_url));
try {
// 2. 发起API调用使用面对面支付中的预下单
AlipayTradePagePayResponse response = Factory.Payment.Page().pay(subject, orderNo, totalAmount, return_url);
// 3. 处理响应或异常
return response.getBody();
} catch (Exception e) {
logger.error("调用遭遇异常,原因:{}", e.getMessage());
throw new RuntimeException(e.getMessage(), e);
}
}
private static Config getOptions(String appId, String privateKey, String publicKey, String notifyUrl) {
Config config = new Config();
config.protocol = "https";
config.gatewayHost = "openapi.alipay.com";
config.signType = "RSA2";
// 请更换为您的AppId
config.appId = appId;
// 请更换为您的PKCS8格式的应用私钥
config.merchantPrivateKey = privateKey;
config.alipayPublicKey = publicKey;
// 如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
config.notifyUrl = notifyUrl; //这里是支付宝接口回调地址
return config;
}
}

View File

@@ -0,0 +1,90 @@
package com.bomaos.common.core.pays.budpay;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bomaos.settings.entity.Pays;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class BudpayUtil {
public static String budpaySendPay(Pays pays, String price, String payId, String param) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String key = mapTypes.get("key").toString();
String pid = mapTypes.get("pid").toString();
String create_url = mapTypes.get("create_url").toString();
String notify_url = mapTypes.get("notify_url").toString();
String notifyUrl = notify_url + "/budpay/notifyUrl";
String returnUrl = notify_url + "/budpay/returnUrl";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("method", "epay://pay/create");
paramMap.put("mch_id", pid);
if (pays.getDriver().equals("budpay_alipay")) {
paramMap.put("pay_type", "alipay");
} else if (pays.getDriver().equals("budpay_wechat")) {
paramMap.put("pay_type", "wechat");
}
paramMap.put("out_trade_no", payId);
paramMap.put("notify_url", notifyUrl);
paramMap.put("return_url", returnUrl);
paramMap.put("name", param);
paramMap.put("amount", price);
String sign = createSign(paramMap, key);
paramMap.put("sign", sign);
String httpsPost = RequestUtil.getHttpsPost(create_url, paramMap);
JSONObject jsonObject = JSON.parseObject(httpsPost);
String url = jsonObject.get("url").toString();
System.out.println(url);
return url;
}
/**
* 生成密钥
*
* @param params
* @param privateKey
* @return
*/
public static String createSign(Map<String, Object> params, String privateKey) {
// 生成签名前先去除sign
params.remove("sign");
Map<String, String> newmap = new HashMap<>();
for (Map.Entry<String, Object> param : params.entrySet()) {
String value = (String) param.getValue();
if (StringUtils.isBlank(value)) {
continue;
}
newmap.put(param.getKey(), param.getValue().toString());
}
// 使用HashMap并使用Arrays.sort排序
String[] sortedKeys = newmap.keySet().toArray(new String[]{});
Arrays.sort(sortedKeys);// 排序请求参数
StringBuilder builder = new StringBuilder();
for (String key : sortedKeys) {
if (StringUtils.isBlank(key)) {
continue;
}
builder.append(key).append("=").append(params.get(key)).append("&");
}
/**
* 拼接上appsecret
*/
String stringSignTemp = builder + "key=" + privateKey;
String signValue = SecureUtil.md5(stringSignTemp);
return signValue;
}
}

View File

@@ -0,0 +1,44 @@
package com.bomaos.common.core.pays.budpay;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 虎皮椒工具类
* author Panyoujie
* Url https://zdins.cn
*/
public class RequestUtil {
/**
* 虎皮椒请求接口
*
* @param url
* @param params
* @return
*/
public static String getHttpsPost(String url, Map<String, Object> params) {
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
multiValueMap.add(stringObjectEntry.getKey(), stringObjectEntry.getValue());
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multiValueMap, headers);
//执行HTTP请求将返回的结构使用ResultVO类格式化
ResponseEntity<String> exchange = restTemplate.exchange(url, method, requestEntity, String.class);
return exchange.getBody();
}
}

View File

@@ -0,0 +1,102 @@
package com.bomaos.common.core.pays.epay;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.bomaos.settings.entity.Pays;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class EpayUtil {
public static String epaySendPay(Pays pays, String price, String payId, String param) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String key = mapTypes.get("key").toString();
String pid = mapTypes.get("pid").toString();
String create_url = mapTypes.get("create_url").toString();
String notify_url = mapTypes.get("notify_url").toString();
String notifyUrl = notify_url + "/epay/notifyUrl";
String returnUrl = notify_url + "/epay/returnUrl";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("pid", pid);
String type = "";
if (pays.getDriver().equals("epay_alipay")) {
type = "alipay";
paramMap.put("type", "alipay");
} else if (pays.getDriver().equals("epay_wxpay")) {
type = "wxpay";
paramMap.put("type", "wxpay");
} else if (pays.getDriver().equals("epay_qqpay")) {
type = "qqpay";
paramMap.put("type", "qqpay");
}
paramMap.put("out_trade_no", payId);
paramMap.put("notify_url", notifyUrl);
paramMap.put("return_url", returnUrl);
paramMap.put("name", param);
paramMap.put("money", price);
String sign = createSign(paramMap, key);
paramMap.put("sign", sign);
String sign_type = "MD5";
paramMap.put("sign_type", sign_type);
String urls = create_url + "/submit.php"
+ "?pid=" + pid + "&type=" + type + "&out_trade_no=" + payId
+ "&notify_url=" + notifyUrl + "&return_url=" + returnUrl
+ "&name=" + param + "&money=" + price + "&sign=" + sign
+ "&sign_type=" + sign_type;
return urls;
}
/**
* 生成密钥
*
* @param params
* @param privateKey
* @return
*/
public static String createSign(Map<String, Object> params, String privateKey) {
// 生成签名前先去除sign
params.remove("sign");
params.remove("sign_type");
Map<String, String> newmap = new HashMap<>();
for (Map.Entry<String, Object> param : params.entrySet()) {
String value = (String) param.getValue();
if (StringUtils.isBlank(value)) {
continue;
}
newmap.put(param.getKey(), param.getValue().toString());
}
// 使用HashMap并使用Arrays.sort排序
String[] sortedKeys = newmap.keySet().toArray(new String[]{});
Arrays.sort(sortedKeys);// 排序请求参数
StringBuilder builder = new StringBuilder();
for (String key : sortedKeys) {
if (StringUtils.isBlank(key)) {
continue;
}
builder.append(key).append("=").append(params.get(key)).append("&");
}
String result = builder.deleteCharAt(builder.length() - 1).toString();
/**
* 拼接上appsecret
*/
String stringSignTemp = result + privateKey;
String signValue = SecureUtil.md5(stringSignTemp);
return signValue;
}
}

View File

@@ -0,0 +1,16 @@
package com.bomaos.common.core.pays.epusdt;
import lombok.Data;
import lombok.ToString;
import java.math.BigDecimal;
@Data
@ToString
public class Epusdt {
private String order_id;
private BigDecimal amount;
private String notify_url;
private String redirect_url;
private String signature;
}

View File

@@ -0,0 +1,36 @@
package com.bomaos.common.core.pays.epusdt;
import com.alibaba.fastjson.JSONObject;
import com.bomaos.common.core.pays.epusdt.entity.EpusdtEntity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* epusdt sdk
* date: 2022-05-23 15:56
* Url github.com/panyoujies
*/
public class RequestUtil {
/**
* epusdt 请求接口
*
* @param url
* @param params
* @return
*/
public static EpusdtEntity sendPost(String url, Map<String, Object> params) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(JSONObject.toJSONString(params), headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<EpusdtEntity> exchange = restTemplate.postForEntity(url, requestEntity, EpusdtEntity.class);
return exchange.getBody();
}
}

View File

@@ -0,0 +1,16 @@
package com.bomaos.common.core.pays.epusdt.entity;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class EpusdtData {
private String trade_id;
private String order_id;
private Float amount;
private Float actual_amount;
private String token;
private Integer expiration_time;
private String payment_url;
}

View File

@@ -0,0 +1,13 @@
package com.bomaos.common.core.pays.epusdt.entity;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class EpusdtEntity {
private Integer status_code;
private String message;
private EpusdtData data;
private String request_id;
}

View File

@@ -0,0 +1,22 @@
package com.bomaos.common.core.pays.epusdt.entity;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
@Data
@ToString
public class EpusdtNotify implements Serializable {
private static final long serialVersionUID = 1L;
private String trade_id;
private String order_id;
private BigDecimal amount;
private BigDecimal actual_amount;
private String token;
private String block_transaction_id;
private String signature;
private Integer status;
}

View File

@@ -0,0 +1,72 @@
package com.bomaos.common.core.pays.epusdt;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.bomaos.common.core.pays.epusdt.entity.EpusdtEntity;
import com.bomaos.settings.entity.Pays;
import org.springframework.util.ObjectUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Map;
/**
* authorgithub.com/panyoujies
* date: 2022-05-23 15:56
*/
public class sendPay {
/**
* 创建支付
*
* @param pays 支付驱动
* @param price 金额
* @param payId 订单id
* @param param 附加内容
* @return 付款链接
*/
public static EpusdtEntity createPayment(Pays pays, String price, String payId, String param) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String key = mapTypes.get("key").toString();
String create_url = mapTypes.get("create_url").toString();
String notify_url = mapTypes.get("notify_url").toString();
String bigDecimal = new BigDecimal(price).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
Epusdt dujiao = new Epusdt();
dujiao.setAmount(new BigDecimal(bigDecimal));
dujiao.setOrder_id(payId);
dujiao.setNotify_url(notify_url + "/epusdt/notifyUrl");
dujiao.setRedirect_url(notify_url + "/epusdt/returnUrl?order_id=" + payId);
String sign = createSign(dujiao, key);
dujiao.setSignature(sign);
EpusdtEntity curl = RequestUtil.sendPost(create_url, JSON.parseObject(JSON.toJSONString(dujiao), Map.class));
return curl;
}
public static String createSign(Object dujiao, String signKey) {
Map<String, Object> params = JSON.parseObject(JSON.toJSONString(dujiao), Map.class);
params.remove("signature");
// 使用HashMap并使用Arrays.sort排序
String[] sortedKeys = params.keySet().toArray(new String[]{});
Arrays.sort(sortedKeys); // 排序请求参数
StringBuilder builder = new StringBuilder();
for (String key : sortedKeys) {
if (ObjectUtils.isEmpty(params.get(key))) {
continue;
}
builder.append(key).append("=").append(params.get(key)).append("&");
}
// 去除后一位&
builder.deleteCharAt(builder.length() - 1).toString();
/**
* 拼接上appsecret
*/
builder.append(signKey);
String signValue = SecureUtil.md5(builder.toString());
return signValue;
}
}

View File

@@ -0,0 +1,36 @@
package com.bomaos.common.core.pays.jiepay;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.bomaos.settings.entity.Pays;
import java.util.Map;
public class JiepaySend {
public static String jiePayUtils(Pays pays, String price, String payId, String param) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String appid = mapTypes.get("appid").toString();
String apptoken = mapTypes.get("apptoken").toString();
String sign = SecureUtil.md5(appid + apptoken);
Integer type = 1;
if (pays.getDriver().equals("jiepay_alipay")) {
type = 1;
} else if (pays.getDriver().equals("jiepay_wxpay")) {
type = 2;
}
String is_ok = "true";
String url = "http://pay.joo.life/Corder?appid="
+ appid + "&code=" + type + "&order_id="
+ payId + "&order_rmb=" + price + "&sign="
+ sign + "&is_ok=" + is_ok + "&diy=" + param;
return url;
}
}

View File

@@ -0,0 +1,41 @@
package com.bomaos.common.core.pays.mqpay;
import com.alibaba.fastjson.JSON;
import com.bomaos.settings.entity.Pays;
import org.springframework.util.DigestUtils;
import java.util.Map;
public class mqPay {
public static String sendCreateMqPay(Pays pays, String price, String payId, String cloudPayid, String param) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String key = mapTypes.get("key").toString();
String create_url = mapTypes.get("create_url").toString();
String notify_url = mapTypes.get("notify_url").toString();
Integer type = 2; // 默认支付宝
if (pays.getDriver().equals("mqpay_alipay")) {
type = 2;
} else if (pays.getDriver().equals("mqpay_wxpay")) {
type = 1;
}
String notifyUrl = notify_url + "/mqpay/notifyUrl";
String returnUrl = notify_url + "/mqpay/returnUrl";
String jsSign = md5(payId + param + type + price + key);
String url = create_url + "/createOrder?payId=" + payId + "&type=" + type + "&price=" + price + "&notifyUrl=" + notifyUrl + "&returnUrl=" + returnUrl + "&sign=" + jsSign + "&param=" + param + "&isHtml=1";
return url;
}
public static String md5(String text) {
//加密后的字符串
String encodeStr = DigestUtils.md5DigestAsHex(text.getBytes());
return encodeStr;
}
}

View File

@@ -0,0 +1,244 @@
package com.bomaos.common.core.pays.payjs;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
/**
* 发送http和https
*
* @author zhangwp 289022259@qq.com
* @date 2017-04
*/
@SuppressWarnings("deprecation")
public class HttpsUtils {
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static String httpsPost(String url, String content, String charset) throws NoSuchAlgorithmException, KeyManagementException, IOException {
byte[] bb = HttpsUtils.post(url, content, charset);
String str = new String(bb, StandardCharsets.UTF_8);
return str;
}
/**
* post方式请求服务器(https协议)
*
* @param url 请求地址
* @param content 参数
* @param charset 编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @author zhangwp 289022259@qq.com
* @date 2017-04
*/
public static byte[] post(String url, String content, String charset) throws NoSuchAlgorithmException, KeyManagementException, IOException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(content.getBytes(charset));
// 刷新、关闭
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toByteArray();
}
return null;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param token 环信token
* @return URL 所代表远程资源的响应结果
* @author zhangwp 289022259@qq.com
* @date 2017-04
*/
public static String sendGet(String url, String param, String token) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
// connection.setRequestProperty("accept", "*/*");
// connection.setRequestProperty("connection", "Keep-Alive");
// connection.setRequestProperty("user-agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 6.1;SV1)");
// 设置环信token
if (token != null && !"".equals(token)) {
conn.setRequestProperty("Authorization", "Bearer " + token);
}
conn.setConnectTimeout(1000 * 5);
conn.setReadTimeout(1000 * 5);
// 建立实际的连接
conn.connect();
// 获取所有响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数json格式
* @param token 环信token
* @return 所代表远程资源的响应结果
* @throws IOException
* @author zhangwp 289022259@qq.com
* @date 2017-04
*/
public static String sendPost(String url, String param, String token) throws IOException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
// conn.setRequestProperty("accept", "*/*");
// conn.setRequestProperty("connection", "Keep-Alive");
// conn.setRequestProperty("user-agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 设置参数格式为json
conn.setRequestProperty("Content-Type", "application/json");
// 设置环信token
if (token != null && !"".equals(token)) {
conn.setRequestProperty("Authorization", "Bearer " + token);
}
conn.setConnectTimeout(1000 * 5);
conn.setReadTimeout(1000 * 5);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPostHttps(String url, String param, String token, String charset) throws IOException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + token);
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(param.getBytes(charset));
// 刷新、关闭
out.flush();
out.close();
InputStream is = conn.getInputStream();
if (is != null) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
return outStream.toString(String.valueOf(StandardCharsets.UTF_8));
}
return null;
}
}

View File

@@ -0,0 +1,22 @@
package com.bomaos.common.core.pays.payjs;
/**
* @Author chengtianqi
* @create 2020/8/28 17:08
*/
public class PayjsConfig {
// API 地址
public final static String nativeUrl = "https://payjs.cn/api/native";
public final static String jsapiUrl = "https://payjs.cn/api/jsapi";
public final static String micropayUrl = "https://payjs.cn/api/micropay";
public final static String cashierUrl = "https://payjs.cn/api/cashier";
public final static String checkUrl = "https://payjs.cn/api/check";
public final static String closeUrl = "https://payjs.cn/api/close";
public final static String reverseUrl = "https://payjs.cn/api/reverse";
public final static String refundUrl = "https://payjs.cn/api/refund";
public final static String infoUrl = "https://payjs.cn/api/info";
public final static String complaintUrl = "https://payjs.cn/api/complaint";
public final static String bankUrl = "https://payjs.cn/api/bank";
public final static String mwebUrl = "https://payjs.cn/api/mweb";
}

View File

@@ -0,0 +1,64 @@
package com.bomaos.common.core.pays.payjs;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class SignUtil {
//签名算法
public static String sign(Map<String, Object> params, String secret) {
String sign = "";
StringBuilder sb = new StringBuilder();
//step1先对请求参数排序
Set<String> keyset = params.keySet();
TreeSet<String> sortSet = new TreeSet<String>();
sortSet.addAll(keyset);
Iterator<String> it = sortSet.iterator();
//step2把参数的key value链接起来 secretkey放在最后面得到要加密的字符串
while (it.hasNext()) {
String key = it.next();
String value = params.get(key).toString();
sb.append(key).append("=").append(value).append("&");
}
sb.append("key=").append(secret);
byte[] md5Digest;
try {
//得到Md5加密得到sign
md5Digest = getMD5Digest(sb.toString());
sign = byte2hex(md5Digest);
} catch (IOException e) {
System.out.println("生成签名错误" + e);
}
return sign;
}
private static String byte2hex(byte[] bytes) {
StringBuilder sign = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
sign.append("0");
}
sign.append(hex.toUpperCase());
}
return sign.toString();
}
private static byte[] getMD5Digest(String data) throws IOException {
byte[] bytes = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
bytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
} catch (GeneralSecurityException gse) {
throw new IOException(gse);
}
return bytes;
}
}

View File

@@ -0,0 +1,63 @@
package com.bomaos.common.core.pays.payjs;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bomaos.settings.entity.Pays;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
public class sendPayjs {
/**
* payjs 支付
*
* @param pays 本地支付驱动
* @param price 付款金额
* @param ordersMember 本地订单号
* @param goodsName 商品名称
* @param goodsDescription 自定义内容
* @return 返回收款二维码
* @throws IOException
*/
public static String pay(Pays pays, String price, String ordersMember, String goodsName, String goodsDescription) throws IOException {
Map mapTypes = JSON.parseObject(pays.getConfig());
String mchId = mapTypes.get("mchId").toString(); //
String key = mapTypes.get("key").toString(); //
String notifyUrl = mapTypes.get("notify_url").toString() + "/payjs/notify"; //
BigDecimal bigDecimal = new BigDecimal(price);
BigDecimal multiply = bigDecimal.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
String format = new DecimalFormat("0.##").format(multiply);
Map<String, Object> payData = new HashMap<>();
payData.put("mchid", mchId);
payData.put("total_fee", format);
payData.put("out_trade_no", ordersMember); // 订单号 随便输的,自己生成一下就好了
payData.put("body", goodsName);
payData.put("attach", goodsDescription);
payData.put("notify_url", notifyUrl);
/**
* 支付宝付款参数
*/
if (pays.getDriver().equals("payjs_alipay")) {
payData.put("type", "alipay");
}
// 进行sign签名
payData.put("sign", SignUtil.sign(payData, key));
// 请求payjs获取二维码
String result = HttpsUtils.sendPost(PayjsConfig.nativeUrl, JSON.toJSONString(payData), null);
JSONObject jsonObject = JSON.parseObject(result);
String code_url = jsonObject.get("code_url").toString(); // 获取付款二维码
return code_url;
}
}

View File

@@ -0,0 +1,93 @@
package com.bomaos.common.core.pays.paypal;
import com.alibaba.fastjson.JSON;
import com.bomaos.common.core.pays.paypal.config.PaypalPaymentIntent;
import com.bomaos.common.core.pays.paypal.config.PaypalPaymentMethod;
import com.bomaos.settings.entity.Pays;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 说明:用于创建 paypal 国际支付收款
* 调用 createPayment 方法即可发起支付
* 作者Panyoujie
* 时间2021-08-24
*/
public class PaypalSend {
private static final String mode = "live"; // live (正式环境) sandbox (测试环境)
public static Payment createPayment(Pays pays,
String total,
String currency,
PaypalPaymentMethod method,
PaypalPaymentIntent intent,
String description) throws PayPalRESTException {
Map mapTypes = JSON.parseObject(pays.getConfig());
String clientId = mapTypes.get("clientId").toString();
String clientSecret = mapTypes.get("clientSecret").toString();
String successUrl = mapTypes.get("return_url").toString() + "/paypal/success";
String cancelUrl = mapTypes.get("return_url").toString() + "/paypal/cancel";
APIContext apiContext = apiContext(clientId, clientSecret, mode);
Amount amount = new Amount();
amount.setCurrency(currency);
amount.setTotal(total);
Transaction transaction = new Transaction();
transaction.setDescription(description);
transaction.setAmount(amount);
List<Transaction> transactions = new ArrayList<>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod(method.toString());
Payment payment = new Payment();
payment.setIntent(intent.toString());
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(cancelUrl);
redirectUrls.setReturnUrl(successUrl);
payment.setRedirectUrls(redirectUrls);
apiContext.setMaskRequestId(true);
return payment.create(apiContext);
}
public static Payment executePayment(String clientId, String clientSecret, String paymentId, String payerId) throws PayPalRESTException {
APIContext apiContext = apiContext(clientId, clientSecret, mode);
Payment payment = new Payment();
payment.setId(paymentId);
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId(payerId);
return payment.execute(apiContext, paymentExecute);
}
public static Map<String, String> paypalSdkConfig(String mode) {
Map<String, String> sdkConfig = new HashMap<>();
sdkConfig.put("mode", mode);
return sdkConfig;
}
public static OAuthTokenCredential authTokenCredential(String clientId, String clientSecret, String mode) {
return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig(mode));
}
public static APIContext apiContext(String clientId, String clientSecret, String mode) throws PayPalRESTException {
APIContext apiContext = new APIContext(authTokenCredential(clientId, clientSecret, mode).getAccessToken());
apiContext.setConfigurationMap(paypalSdkConfig(mode));
return apiContext;
}
}

View File

@@ -0,0 +1,10 @@
package com.bomaos.common.core.pays.paypal.config;
/**
* 说明Paypal 枚举类
* 作者Panyoujie
* 时间2021-08-24
*/
public enum PaypalPaymentIntent {
sale, authorize, order
}

View File

@@ -0,0 +1,10 @@
package com.bomaos.common.core.pays.paypal.config;
/**
* 说明Paypal 枚举类
* 作者Panyoujie
* 时间2021-08-24
*/
public enum PaypalPaymentMethod {
credit_card, paypal
}

View File

@@ -0,0 +1,148 @@
package com.bomaos.common.core.pays.wxpay;
import com.alibaba.fastjson.JSON;
import com.bomaos.settings.entity.Pays;
import com.github.wxpay.sdk.WXPay;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
public class SendWxPay {
/**
* 微信官方支付 Native
*
* @param pays 支付驱动
* @param price 金额
* @param ordersMember 商品id
* @param goodsName 商品名称
* @param goodsDescription 附加内容
* @param ip 用户ip地址
* @return 返回url
*/
public static String payNattve(Pays pays, String price, String ordersMember, String goodsName, String goodsDescription, String ip) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String appId = mapTypes.get("appId").toString();
String mchId = mapTypes.get("mchId").toString();
String key = mapTypes.get("key").toString();
String notifyUrl = mapTypes.get("notify_url").toString() + "/wxpay/notify"; // 异步通知地址
/**
* 处理金额
*/
BigDecimal bigDecimal = new BigDecimal(price);
BigDecimal multiply = bigDecimal.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
String money = new DecimalFormat("0.##").format(multiply);
WXPayConfigImpl wxPayConfig = new WXPayConfigImpl();
wxPayConfig.setAppID(appId);
wxPayConfig.setMchID(mchId);
wxPayConfig.setKey(key);
wxPayConfig.setCertPath("resources/cert/wxpay/apiclient_cert.p12"); // 证书地址
wxPayConfig.setPayNotifyUrl(notifyUrl); // 异步通知
WXPay wxPay = new WXPay(wxPayConfig);
Map<String, String> requestMap = new HashMap<>();
requestMap.put("body", goodsName); // 商品描述
requestMap.put("out_trade_no", ordersMember); // 商户订单号
requestMap.put("total_fee", money); // 总金额
requestMap.put("spbill_create_ip", ip); // 终端IP
requestMap.put("trade_type", "NATIVE"); // Native支付类型
requestMap.put("product_id", ordersMember); // trade_type=NATIVE时此参数必传。此参数为二维码中包含的商品ID商户自行定义。
requestMap.put("attach", goodsDescription); // 附加数据
requestMap.put("notify_url", wxPayConfig.getPayNotifyUrl()); // 接收微信支付异步通知回调地址
try {
Map<String, String> stringStringMap = wxPay.unifiedOrder(requestMap);
String result_code = stringStringMap.get("result_code");
if ("SUCCESS".equals(result_code)) {
String code_url = stringStringMap.get("code_url");
return code_url;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 微信官方h5支付
*
* @param pays 支付驱动
* @param price 金额
* @param ordersMember 商品id
* @param goodsName 商品名称
* @param goodsDescription 附加内容
* @param ip 用户ip地址
* @return 返回url
*/
public static String payMweb(Pays pays, String price, String ordersMember, String goodsName, String goodsDescription, String ip) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String appId = mapTypes.get("appId").toString();
String mchId = mapTypes.get("mchId").toString();
String key = mapTypes.get("key").toString();
String notifyUrl = mapTypes.get("notify_url").toString() + "/wxpay/notify"; // 异步通知地址
String wap_url = mapTypes.get("notify_url").toString();
//支付回调页面
String REDIRECT_URL = wap_url + "/search/order/";
/**
* 处理金额
*/
BigDecimal bigDecimal = new BigDecimal(price);
BigDecimal multiply = bigDecimal.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
String money = new DecimalFormat("0.##").format(multiply);
WXPayConfigImpl wxPayConfig = new WXPayConfigImpl();
wxPayConfig.setAppID(appId);
wxPayConfig.setMchID(mchId);
wxPayConfig.setKey(key);
wxPayConfig.setCertPath("resources/cert/wxpay/apiclient_cert.p12"); // 证书地址
wxPayConfig.setPayNotifyUrl(notifyUrl); // 异步通知
WXPay wxPay = new WXPay(wxPayConfig);
Map<String, String> requestMap = new HashMap<>();
requestMap.put("body", goodsName); // 商品描述
requestMap.put("out_trade_no", ordersMember); // 商户订单号
requestMap.put("total_fee", money); // 总金额
requestMap.put("trade_type", "MWEB"); // Mweb支付类型
requestMap.put("spbill_create_ip", ip); // 终端IP
Map<String, String> map = new HashMap<>();
Map<String, String> map1 = new HashMap<>();
map1.put("type", "Wap");
map1.put("wap_url", wap_url);
map1.put("wap_name", goodsName);
String jsonString = JSON.toJSONString(map1);
map.put("h5_info", jsonString);
String jsonString1 = JSON.toJSONString(map);
requestMap.put("scene_info", jsonString1);
requestMap.put("attach", goodsDescription); // 附加数据
requestMap.put("notify_url", wxPayConfig.getPayNotifyUrl()); // 接收微信支付异步通知回调地址
try {
Map<String, String> stringStringMap = wxPay.unifiedOrder(requestMap);
String result_code = stringStringMap.get("result_code");
if ("SUCCESS".equals(result_code)) {
// String trade_type = stringStringMap.get("trade_type");
String mweb_url = stringStringMap.get("mweb_url");
String url = URLEncoder.encode(REDIRECT_URL + ordersMember, "utf-8");
mweb_url = mweb_url + "&redirect_url=" + url;
return mweb_url;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,71 @@
package com.bomaos.common.core.pays.wxpay;
import com.github.wxpay.sdk.WXPayConfig;
import lombok.Data;
import lombok.ToString;
import java.io.InputStream;
@Data
@ToString
public class WXPayConfigImpl implements WXPayConfig {
/**
* 获取 App ID
*
* @return App ID
*/
private String appID;
/**
* 获取 Mch ID
*
* @return Mch ID
*/
private String mchID;
/**
* 获取 API 密钥
*
* @return API密钥
*/
private String key;
/**
* 获取商户证书内容
*
* @return 商户证书内容
*/
private String certPath;
/**
* HTTP(S) 连接超时时间,单位毫秒
*
* @return
*/
private int httpConnectTimeoutMs = 8000;
/**
* HTTP(S) 读数据超时时间,单位毫秒
*
* @return
*/
private int httpReadTimeoutMs = 10000;
/**
* 微信支付异步通知地址
*/
private String payNotifyUrl;
/**
* 微信退款异步通知地址
*/
private String refundNotifyUrl;
@Override
public InputStream getCertStream() {
InputStream certStream = getClass().getClassLoader().getResourceAsStream(certPath);
return certStream;
}
}

View File

@@ -0,0 +1,144 @@
package com.bomaos.common.core.pays.xunhupay;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.bomaos.settings.entity.Pays;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.HttpClientErrorException;
import java.util.*;
/**
* 虎皮椒支付
* author Panyoujie
* Url https://zdins.cn
*/
public class PayUtils {
/**
* 虎皮椒支付
*
* @param product_type 商品名称
* @param price 金额
* @param orderMember 订单id
* @return
*/
public static Map pay(String webName, Pays pays, String product_type, String price, String orderMember, String plugins) {
String config = pays.getConfig();
JSONObject configs = JSONObject.parseObject(config);
/**
* @param appid 商品名称
* @param appsecret 密钥
* @param url 订单id
*/
String appid = (String) configs.get("appid");
String appsecret = (String) configs.get("appsecret");
String create_url = (String) configs.get("create_url");
String notify_url = (String) configs.get("notify_url");
Map<String, Object> sortParams = new HashMap<>();
sortParams.put("version", "1.1");
sortParams.put("lang", "zh-cn");
sortParams.put("plugins", plugins);
sortParams.put("appid", appid);
sortParams.put("trade_order_id", orderMember);
if (StringUtils.equals(pays.getDriver(), "xunhupay_wxpay")) {
sortParams.put("payment", "wechat"); // 微信
sortParams.put("type", "WAP");
sortParams.put("wap_url", notify_url);
sortParams.put("wap_name", webName);
} else {
sortParams.put("payment", "alipay"); // 支付宝
}
sortParams.put("total_fee", price);
sortParams.put("title", product_type);
sortParams.put("time", getSecondTimestamp(new Date()));
sortParams.put("notify_url", notify_url + "/xunhupay/notifyUrl");
sortParams.put("return_url", notify_url + "/xunhupay/returnUrl?trade_order_id=" + orderMember);
sortParams.put("callback_url", notify_url);
sortParams.put("nonce_str", getRandomNumber(9));
sortParams.put("hash", createSign(sortParams, appsecret));
Map map1 = null;
try {
XunhuEntity xunhuEntity = RequestUtil.getHttpsPost(create_url, sortParams);
if (xunhuEntity.getErrcode() == 0 && xunhuEntity.getErrmsg().equals("success!")) {
HashMap<String, String> map = new HashMap<>();
map.put("url_qrcode", xunhuEntity.getUrl_qrcode());
map.put("url1", xunhuEntity.getUrl());
map1 = map;
}
} catch (HttpClientErrorException e) {
System.out.println("e.getMessage() = " + e.getMessage());
}
return map1;
}
/**
* 生成密钥
*
* @param params
* @param privateKey
* @return
*/
public static String createSign(Map<String, Object> params, String privateKey) {
params.remove("hash");
// 使用HashMap并使用Arrays.sort排序
String[] sortedKeys = params.keySet().toArray(new String[]{});
Arrays.sort(sortedKeys);// 排序请求参数
StringBuilder builder = new StringBuilder();
for (String key : sortedKeys) {
if (ObjectUtils.isEmpty(params.get(key))) {
continue;
}
builder.append(key).append("=").append(params.get(key)).append("&");
}
String result = builder.deleteCharAt(builder.length() - 1).toString();
/**
* 拼接上appsecret
*/
String stringSignTemp = result + privateKey;
String signValue = SecureUtil.md5(stringSignTemp);
return signValue;
}
/**
* 获取精确到秒的时间戳 原理 获取毫秒时间戳,因为 1秒 = 100毫秒 去除后三位 就是秒的时间戳
*
* @return
*/
public static int getSecondTimestamp(Date date) {
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime());
int length = timestamp.length();
if (length > 3) {
return Integer.valueOf(timestamp.substring(0, length - 3));
} else {
return 0;
}
}
/**
* 生成一个随机数字
*
* @param length 长度自定义
* @return
*/
public static String getRandomNumber(int length) {
String str = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
int number = random.nextInt(str.length());
sb.append(str.charAt(number));
}
return sb.toString();
}
}

View File

@@ -0,0 +1,44 @@
package com.bomaos.common.core.pays.xunhupay;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* 虎皮椒工具类
* author Panyoujie
* Url https://zdins.cn
*/
public class RequestUtil {
/**
* 虎皮椒请求接口
*
* @param url
* @param params
* @return
*/
public static XunhuEntity getHttpsPost(String url, Map<String, Object> params) {
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> stringObjectEntry : params.entrySet()) {
multiValueMap.add(stringObjectEntry.getKey(), stringObjectEntry.getValue());
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multiValueMap, headers);
//执行HTTP请求将返回的结构使用ResultVO类格式化
ResponseEntity<XunhuEntity> exchange = restTemplate.exchange(url, method, requestEntity, XunhuEntity.class);
return exchange.getBody();
}
}

View File

@@ -0,0 +1,15 @@
package com.bomaos.common.core.pays.xunhupay;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class XunhuEntity {
private Integer errcode;
private String errmsg;
private String hash;
private String openid;
private String url_qrcode;
private String url;
}

View File

@@ -0,0 +1,70 @@
package com.bomaos.common.core.pays.yungouos;
import com.alibaba.fastjson.JSON;
import com.bomaos.settings.entity.Pays;
import com.yungouos.pay.alipay.AliPay;
import com.yungouos.pay.wxpay.WxPay;
import java.util.Map;
public class YunGouosConfig {
/**
* yungou微信支付接口
*
* @param pays 支付配置
* @param price 金额
* @param ordersMember 本地订单号
* @param goodsDescription 附加内容
* @return
*/
public static String yunGouosWxPay(Pays pays, String price, String ordersMember, String goodsName, String goodsDescription) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String mchId = mapTypes.get("mchId").toString(); //
String key = mapTypes.get("key").toString(); //
String notifyUrl = mapTypes.get("notify_url").toString() + "/yungouos/notify"; //
String result = null;
try {
/**
* 扫码支付 返回二维码连接
*/
result = WxPay.nativePay(ordersMember, price, mchId, goodsName, "1", goodsDescription, notifyUrl, null, null, null, null, key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param pays
* @param price
* @param ordersMember
* @param goodsName
* @param goodsDescription
* @return
*/
public static String yunGouosAliPay(Pays pays, String price, String ordersMember, String goodsName, String goodsDescription) {
Map mapTypes = JSON.parseObject(pays.getConfig());
String mchId = mapTypes.get("mchId").toString(); //
String key = mapTypes.get("key").toString(); //
String notifyUrl = mapTypes.get("notify_url").toString() + "/yungouos/notify"; //
String result = null;
try {
/**
* 扫码支付 返回二维码连接
*/
result = AliPay.nativePay(ordersMember, price, mchId, goodsName, "1", goodsDescription, notifyUrl, key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}

View File

@@ -0,0 +1,213 @@
package com.bomaos.common.core.shiro;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.io.ResourceUtils;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import javax.servlet.Filter;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* shiro框架配置
* Created by Panyoujie on 2017-04-28 09:45
*/
@Configuration
public class ShiroConfig {
/**
* shiro过滤器
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
// 登录配置
shiroFilter.setLoginUrl("/login");
shiroFilter.setSuccessUrl("/admin");
shiroFilter.setUnauthorizedUrl("/error?code=403");
// 自定义过滤器
Map<String, Filter> filtersMap = new LinkedHashMap<>();
filtersMap.put("slf", new ShiroLoginFilter());
shiroFilter.setFilters(filtersMap);
// 拦截配置
Map<String, String> filterChainDefinitions = new LinkedHashMap<>();
filterChainDefinitions.put("/assets/**", "anon");
filterChainDefinitions.put("/default/**", "anon");
filterChainDefinitions.put("/favicon.ico", "anon");
filterChainDefinitions.put("/file/**", "anon");
filterChainDefinitions.put("/ads.txt", "anon");
/**
* 首页
*/
filterChainDefinitions.put("/", "anon");
filterChainDefinitions.put("/index", "anon");
filterChainDefinitions.put("/article", "anon");
filterChainDefinitions.put("/article/**", "anon");
filterChainDefinitions.put("/getArticleList", "anon");
filterChainDefinitions.put("/search", "anon");
filterChainDefinitions.put("/search/order/**", "anon");
filterChainDefinitions.put("/exportCards", "anon");
filterChainDefinitions.put("/orders/orders/pageAll", "anon");
filterChainDefinitions.put("/getProductSearchList", "anon");
filterChainDefinitions.put("/getShoppingNotes", "anon");
filterChainDefinitions.put("/file/enQrcode", "anon");
filterChainDefinitions.put("/content/article/updateLike", "anon");
/**
* 商品
*/
filterChainDefinitions.put("/product/**", "anon");
filterChainDefinitions.put("/getProductById", "anon");
filterChainDefinitions.put("/getProductList", "anon");
// 订单创建
filterChainDefinitions.put("/buy", "anon");
// 支付
filterChainDefinitions.put("/pay/**", "anon");
filterChainDefinitions.put("/alipayPc/**", "anon");
filterChainDefinitions.put("/order/state/**", "anon");
filterChainDefinitions.put("/pay/state/**", "anon");
// 异步通知
filterChainDefinitions.put("/mqpay/notifyUrl", "anon");
filterChainDefinitions.put("/mqpay/returnUrl", "anon");
filterChainDefinitions.put("/epay/notifyUrl", "anon");
filterChainDefinitions.put("/epay/returnUrl", "anon");
filterChainDefinitions.put("/budpay/notifyUrl", "anon");
filterChainDefinitions.put("/budpay/returnUrl", "anon");
filterChainDefinitions.put("/xunhupay/notifyUrl", "anon");
filterChainDefinitions.put("/xunhupay/returnUrl", "anon");
filterChainDefinitions.put("/yungouos/notify", "anon");
filterChainDefinitions.put("/payjs/notify", "anon");
filterChainDefinitions.put("/wxpay/notify", "anon");
filterChainDefinitions.put("/alipay/notify", "anon");
filterChainDefinitions.put("/alipay/return_url", "anon");
filterChainDefinitions.put("/paypal/cancel", "anon");
filterChainDefinitions.put("/paypal/success", "anon");
filterChainDefinitions.put("/epusdt/notifyUrl", "anon");
filterChainDefinitions.put("/epusdt/returnUrl", "anon");
filterChainDefinitions.put("/wxpusher/callback", "anon");
// api
filterChainDefinitions.put("/api/**", "anon");
filterChainDefinitions.put("/error", "anon");
filterChainDefinitions.put("/login", "anon");
filterChainDefinitions.put("/logout", "logout");
//filterChainDefinitions.put("/**", "slf,authc");
filterChainDefinitions.put("/**", "slf,user"); // 记住密码也能访问
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitions);
return shiroFilter;
}
/**
* userRealm
*/
@Bean(name = "userRealm")
@DependsOn("lifecycleBeanPostProcessor")
public UserRealm userRealm() {
UserRealm userRealm = new UserRealm();
// 密码凭证器
userRealm.setCredentialsMatcher(new HashedCredentialsMatcher("md5"));
return userRealm;
}
/**
* 安全管理器
*/
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm());
securityManager.setSessionManager(sessionManager());
securityManager.setCacheManager(cacheManager());
securityManager.setRememberMeManager(cookieRememberMeManager());
return securityManager;
}
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
/**
* 缓存管理器
*/
@Bean(name = "cacheManager")
public EhCacheManager cacheManager() {
EhCacheManager cacheManager = new EhCacheManager();
net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.getCacheManager("shirocache");
if (cm == null) {
String configFile = "classpath:ehcache/ehcache-shiro.xml";
InputStream is = null;
try {
is = ResourceUtils.getInputStreamForPath(configFile);
cm = new net.sf.ehcache.CacheManager(is);
} catch (IOException e) {
throw new IllegalStateException("Unable to obtain input stream for cacheManagerConfigFile [" + configFile + "]", e);
} finally {
ResourceUtils.close(is);
}
}
cacheManager.setCacheManager(cm);
return cacheManager;
}
/**
* 记住密码cookie
*/
@Bean
public SimpleCookie rememberMeCookie() {
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
simpleCookie.setMaxAge(60 * 60 * 24 * 7); // 过期时间7天
return simpleCookie;
}
/**
* 记住密码cookie管理器
*/
@Bean
public CookieRememberMeManager cookieRememberMeManager() {
CookieRememberMeManager manager = new CookieRememberMeManager();
manager.setCookie(rememberMeCookie());
manager.setCipherKey(Base64.decode("BT7lf0hw4W/QMxpS/Rb+Ng=="));
return manager;
}
/**
* 开启shiro注解功能
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager());
return advisor;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
}

View File

@@ -0,0 +1,190 @@
package com.bomaos.common.core.shiro;
import com.bomaos.common.system.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
/**
* shiro常用方法
* Created by Panyoujie on 2017-04-28 09:45
*/
public class ShiroExt {
/**
* 是否是游客访问(用户没有登录)
*/
public boolean isGuest() {
return getSubject() == null || getSubject().getPrincipal() == null;
}
/**
* 是否已经认证(包含登录和记住密码)
*/
public boolean isUser() {
return getSubject() != null && getSubject().getPrincipal() != null;
}
/**
* 是否是登录通过认证的
*/
public boolean isAuthenticated() {
return getSubject() != null && getSubject().isAuthenticated();
}
/**
* 是否是没有进行登录通过认证(记住密码)
*/
public boolean isNotAuthenticated() {
return !isAuthenticated();
}
/**
* 获取当前用户信息
*/
public String principal() {
return principal(null);
}
/**
* 获取当前用户信息
*
* @param property 用户属性名
*/
public String principal(String property) {
return principal(property, User.class.getName());
}
/**
* 获取当前用户信息
*
* @param property 用户属性名
* @param className 用户class名
*/
public String principal(String property, String className) {
String strValue = null;
if (getSubject() != null) {
Object principal;
if (className == null) {
principal = getSubject().getPrincipal();
} else {
principal = getPrincipalFromClassName(className);
}
if (principal != null) {
if (property == null) {
strValue = principal.toString();
} else {
strValue = getPrincipalProperty(principal, property);
}
}
}
return strValue;
}
/**
* 是否具有某个角色
*
* @param role 角色标识
*/
public boolean hasRole(String role) {
return getSubject() != null && getSubject().hasRole(role);
}
/**
* 是否没有有某个角色
*
* @param role 角色标识
*/
public boolean lacksRole(String role) {
return !hasRole(role);
}
/**
* 是否具有任意一个角色
*
* @param roles 角色标识
*/
public boolean hasAnyRole(String roles) {
boolean hasAnyRole = false;
Subject subject = getSubject();
if (subject != null) {
for (String role : roles.split(",")) {
if (subject.hasRole(role.trim())) {
hasAnyRole = true;
break;
}
}
}
return hasAnyRole;
}
/**
* 是否具有某个权限
*
* @param p 权限标识
*/
public boolean hasPermission(String p) {
return getSubject() != null && getSubject().isPermitted(p);
}
/**
* 是否没有某个权限
*
* @param p 权限标识
*/
public boolean lacksPermission(String p) {
return !hasPermission(p);
}
/**
* 根据class获取当前用户
*/
private Object getPrincipalFromClassName(String className) {
Object principal = null;
try {
Class<?> clazz = Class.forName(className);
principal = getSubject().getPrincipals().oneByType(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return principal;
}
/**
* 获取当前用户的某个属性
*/
private String getPrincipalProperty(Object principal, String property) {
String strValue = null;
try {
BeanInfo bi = Introspector.getBeanInfo(principal.getClass());
boolean foundProperty = false;
for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
if (pd.getName().equals(property)) {
Object value = pd.getReadMethod().invoke(principal, (Object[]) null);
if (value != null) strValue = value.toString();
foundProperty = true;
break;
}
}
if (!foundProperty) {
String message = "Property [" + property + "] not found in principal of type [" + principal.getClass().getName() + "]";
throw new RuntimeException(message);
}
} catch (Exception e) {
String message = "Error reading property [" + property + "] from principal of type [" + principal.getClass().getName() + "]";
throw new RuntimeException(message, e);
}
return strValue;
}
/**
* 获取当前登录的用户
*/
protected Subject getSubject() {
return SecurityUtils.getSubject();
}
}

View File

@@ -0,0 +1,45 @@
package com.bomaos.common.core.shiro;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
/**
* 自定义shiro过滤器
* Created by Panyoujie on 2017-04-28 09:45
*/
public class ShiroLoginFilter extends AccessControlFilter {
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
return false;
}
@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
Subject subject = getSubject(servletRequest, servletResponse);
if (!subject.isAuthenticated() && !subject.isRemembered()) {
if (isAjax((HttpServletRequest) servletRequest)) {
servletResponse.setContentType("application/json;charset=UTF-8");
PrintWriter out = servletResponse.getWriter();
out.write("{\"msg\": \"登录过期,请重新登录\", \"code\": 401}");
out.flush();
return false;
}
}
return true;
}
/**
* 判断是不是ajax请求
*/
private boolean isAjax(HttpServletRequest request) {
String xHeader = request.getHeader("X-Requested-With");
return (xHeader != null && xHeader.contains("XMLHttpRequest"));
}
}

View File

@@ -0,0 +1,63 @@
package com.bomaos.common.core.shiro;
import com.bomaos.common.system.entity.Role;
import com.bomaos.common.system.entity.User;
import com.bomaos.common.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import java.util.HashSet;
import java.util.Set;
/**
* Shiro认证和授权
* Created by Panyoujie on 2017-04-28 09:45
*/
public class UserRealm extends AuthorizingRealm {
@Lazy
@Autowired
private UserService userService;
/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String username = (String) authenticationToken.getPrincipal();
User user = userService.getByUsername(username);
if (user == null) throw new UnknownAccountException(); // 账号不存在
if (user.getState() != 0) throw new LockedAccountException(); // 账号被锁定
return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
/**
* 授权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
userService.selectRoleAndAuth(user);
// 角色
Set<String> roles = new HashSet<>();
for (Role r : user.getRoles()) {
if (r.getDeleted() == 0) roles.add(r.getRoleCode());
}
authorizationInfo.setRoles(roles);
// 权限
Set<String> permissions = new HashSet<>();
for (String auth : user.getAuthorities()) {
if (auth != null && !auth.trim().isEmpty()) permissions.add(auth);
}
authorizationInfo.setStringPermissions(permissions);
return authorizationInfo;
}
}

View File

@@ -0,0 +1,320 @@
package com.bomaos.common.core.utils;
import cn.hutool.core.util.StrUtil;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 常用工具方法
* Created by Panyoujie on 2017-6-10 10:10
*/
public class CoreUtil {
private static final String[] chars = new String[]{"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", "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"};
/**
* toString为null返回空白字符
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
/**
* 连接多个字符串null自动过滤
*/
public static String connect(Object... objects) {
StringBuilder sb = new StringBuilder();
for (Object obj : objects) sb.append(toString(obj));
return sb.toString();
}
/**
* 首字母大写
*/
public static String upperHead(String str) {
if (str == null || str.length() == 0) return str;
if (str.length() == 1) return str.toUpperCase();
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
/**
* 生成8位uuid
*/
public static String randomUUID8() {
StringBuffer buffer = new StringBuffer();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
buffer.append(chars[x % 0x3E]);
}
return buffer.toString();
}
/**
* 生成16位uuid
*/
public static String randomUUID16() {
StringBuffer buffer = new StringBuffer();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 16; i++) {
String str = uuid.substring(i * 2, i * 2 + 2);
int x = Integer.parseInt(str, 16);
buffer.append(chars[x % 0x3E]);
}
return buffer.toString();
}
/**
* 把对象转成Map
*/
public static <T> Map<String, Object> objectToMap(T t) {
return objectToMap(t, null);
}
/**
* 把对象集合转成Map集合
*/
public static <T> List<Map<String, Object>> objectToMap(List<T> ts) {
return objectToMap(ts, null);
}
/**
* 把对象转成Map只包含指定字段
*
* @param t 对象
* @param fields 包含的字段
* @return Map
*/
public static <T> Map<String, Object> objectToMap(T t, String[] fields) {
if (t == null) return null;
List<String> fieldList = null;
if (fields != null) fieldList = Arrays.asList(fields);
Map<String, Object> map = new HashMap<>();
Field[] fieldArray = t.getClass().getDeclaredFields();
for (Field field : fieldArray) {
field.setAccessible(true);
if (fieldList == null || fieldList.contains(field.getName())) {
try {
map.put(field.getName(), field.get(t));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return map;
}
/**
* 把对个对象集合转成Map集合只包含指定字段
*
* @param ts 对象集合
* @param fields 包含的字段
* @return List<Map>
*/
public static <T> List<Map<String, Object>> objectToMap(List<T> ts, String[] fields) {
List<Map<String, Object>> rs = new ArrayList<>();
for (T t : ts) {
Map<String, Object> map = objectToMap(t, fields);
if (map != null) rs.add(map);
}
return rs;
}
/**
* 复制父类的属性的值到子类
*
* @param f 父类对象
* @param c 子类对象
*/
public static <F, C extends F> void copyAttribute(F f, C c) {
for (Field field : f.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
Field cf = c.getClass().getField(field.getName());
cf.setAccessible(true);
cf.set(c, field.get(f));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 把父类克隆为子类
*
* @param father 父类对象
* @param clazz 子类类型
*/
public static <F, C extends F> C cloneToChild(F father, Class<C> clazz) {
try {
C child = clazz.newInstance();
copyAttribute(father, child);
return child;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 判断excel某列是否有空值
*/
public static String excelCheckBlank(List<List<Object>> list, int startRow, int... cols) {
StringBuilder sb = new StringBuilder();
for (int col : cols) {
for (int i = 0; i < list.size(); i++) {
Object value = list.get(i).get(col);
if (value == null || StrUtil.isBlank(value.toString())) {
if (sb.length() != 0) sb.append("\r\n");
sb.append("").append(i + startRow + 1).append("行第");
sb.append(col + 1).append("列不能为空.");
}
}
}
return sb.toString();
}
/**
* 判断excel某列是否有重复值
*/
public static String excelCheckRepeat(List<List<Object>> list, int startRow, int... cols) {
StringBuilder sb = new StringBuilder();
for (int col : cols) {
for (int i = 0; i < list.size(); i++) {
Object value = list.get(i).get(col);
for (int j = 0; j < list.size(); j++) {
if (i != j && value != null && value.equals(list.get(j).get(col))) {
if (sb.length() != 0) sb.append("\r\n");
sb.append("").append(i + startRow + 1).append("行第").append(col + 1).append("列与第");
sb.append(j + startRow + 1).append("行第").append(col + 1).append("列重复.");
}
}
}
}
return sb.toString();
}
/**
* 检查list集合中元素字段是否有重复
*
* @param list 集合
* @param field 字段名称
* @return 返回重复的元素
*/
public static <T> T listCheckRepeat(List<T> list, String field) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (i != j) {
Object value = getFieldValue(list.get(i), field);
if (value != null && value.equals(getFieldValue(list.get(j), field))) {
return list.get(j);
}
}
}
}
return null;
}
/**
* 检查list集合中元素字段是否有重复
*
* @param list 集合
* @param field 字段名称
* @param field 字段中文名称,用于错误提示
* @return 返回错误提示信息
*/
public static <T> String listCheckRepeat(List<T> list, String field, String zhName) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (i != j) {
Object value = getFieldValue(list.get(i), field);
if (value != null && value.equals(getFieldValue(list.get(j), field))) {
if (sb.length() != 0) sb.append("\r\n");
sb.append("").append(i + 1).append("条与第").append(j + 1).append("条数据的").append(zhName).append("重复.");
}
}
}
}
return sb.toString();
}
/**
* 检查list集合中元素字段是否有空值
*
* @param list 集合
* @param field 字段名称
* @return 返回为空的元素
*/
public static <T> T listCheckBlank(List<T> list, String field) {
for (int i = 0; i < list.size(); i++) {
Object value = getFieldValue(list.get(i), field);
if (value == null || StrUtil.isBlank(value.toString())) {
return list.get(i);
}
}
return null;
}
/**
* 检查list集合中元素字段是否有空值
*
* @param list 集合
* @param field 字段名称
* @param field 字段中文名称,用于错误提示
* @return 返回错误提示信息
*/
public static <T> String listCheckBlank(List<T> list, String field, String zhName) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
Object value = getFieldValue(list.get(i), field);
if (value == null || StrUtil.isBlank(value.toString())) {
if (sb.length() != 0) sb.append("\r\n");
sb.append("").append(i + 1).append("条数据的").append(zhName).append("不能为空.");
}
}
return sb.toString();
}
/**
* 获取某个对象的某个字段的值
*/
public static Object getFieldValue(Object t, String field) {
if (t == null || field == null) return null;
try {
Field clazzField = t.getClass().getDeclaredField(field);
clazzField.setAccessible(true);
return clazzField.get(t);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 去除回车和空格
*
* @param str
* @return
*/
public static String getStringNoBlank(String str) {
if (str != null && !"".equals(str)) {
str.replaceAll("\n", "");
Pattern p = Pattern.compile("(^\\s*)|(\\s*$)");
Matcher m = p.matcher(str);
String strNoBlank = m.replaceAll("");
return strNoBlank;
} else {
return "";
}
}
}

View File

@@ -0,0 +1,153 @@
package com.bomaos.common.core.utils;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtil {
public static String subData() {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
return date;
}
public static String getDate() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");//设置日期格式
String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
return date;
}
public static String getSubDate(Date date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String dateToString = df.format(date);// new Date()为获取当前系统时间,也可使用当前时间戳
return dateToString;
}
/**
* 设置到秒
*
* @param date
* @return
*/
public static String getSubDateMiao(Date date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");//设置日期格式
String dateToString = df.format(date);// new Date()为获取当前系统时间,也可使用当前时间戳
return dateToString;
}
// 获取当天的开始时间
public static Date getDayBegin() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
// 获取当天的结束时间
public static Date getDayEnd() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
// 获取大大大大前天的开始时间
public static Long getStartDayTime(Integer day) {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayBegin());
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime().getTime();
}
// 获取大大大大前天的结束时间
public static Long getEndDayTime(Integer day) {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayEnd());
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime().getTime();
}
// 获取本周的开始时间
@SuppressWarnings("unused")
public static Long getBeginDayOfWeek() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek);
return getDayStartTime(cal.getTime()).getTime();
}
// 获取本周的结束时间
public static Long getEndDayOfWeek() {
Calendar cal = Calendar.getInstance();
cal.setTime(getBeginDayOfWeek1());
cal.add(Calendar.DAY_OF_WEEK, 6);
Date weekEndSta = cal.getTime();
return getDayEndTime(weekEndSta).getTime();
}
// 获取本周的开始时间
@SuppressWarnings("unused")
public static Date getBeginDayOfWeek1() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek);
return getDayStartTime(cal.getTime());
}
// 获取某个日期的开始时间
public static Timestamp getDayStartTime(Date d) {
Calendar calendar = Calendar.getInstance();
if (null != d)
calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new Timestamp(calendar.getTimeInMillis());
}
// 获取某个日期的结束时间
public static Timestamp getDayEndTime(Date d) {
Calendar calendar = Calendar.getInstance();
if (null != d)
calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new Timestamp(calendar.getTimeInMillis());
}
/*
* 将时间戳转换为时间
*/
public static String stampToDate(String stap) {
String time;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(stap);
Date date = new Date(lt);
time = simpleDateFormat.format(date);
return time;
}
}

View File

@@ -0,0 +1,22 @@
package com.bomaos.common.core.utils;
import javax.servlet.http.HttpServletRequest;
public class DeviceUtils {
public static boolean isMobileDevice(HttpServletRequest request) {
String userAgent = request.getHeader("User-Agent");
// 判断是否为移动设备的关键字
String[] mobileKeywords = {"Mobile", "Android", "iPhone", "iPad", "Windows Phone"};
// 遍历关键字判断User-Agent中是否包含
for (String keyword : mobileKeywords) {
if (userAgent.contains(keyword)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,325 @@
package com.bomaos.common.core.utils;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.bomaos.common.core.Constants;
import com.bomaos.common.core.web.JsonResult;
import org.apache.tika.Tika;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 文件上传下载工具类
* Created by Panyoujie on 2018-12-14 08:38
*/
public class FileUploadUtil {
// 文件上传的目录
public static final String UPLOAD_FILE_DIR = Constants.UPLOAD_DIR + "file/";
// 缩略图存放的目录
private static final String UPLOAD_SM_DIR = Constants.UPLOAD_DIR + "thumbnail/";
/**
* 上传文件
*
* @param file MultipartFile
* @return 示例:{"code": 0, "msg": "", "url": "", "fileName": ""}
*/
public static JsonResult upload(MultipartFile file, HttpServletRequest request) {
String path; // 文件保存路径
// 文件原始名称
String orgName = file.getOriginalFilename(), dir = getDateDir();
if (orgName == null) return JsonResult.error("上传失败");
File outFile;
String suffix = orgName.substring(orgName.lastIndexOf(".") + 1); // 获取文件后缀
if (Constants.UPLOAD_MD5_NAME) { // 使用md5命名方式解决图片重复上传问题
try {
String md5 = SecureUtil.md5(file.getInputStream());
path = dir + md5 + "." + suffix;
outFile = new File(UPLOAD_FILE_DIR, path);
} catch (Exception e) {
e.printStackTrace();
return JsonResult.error("上传失败").put("error", e.getMessage());
}
} else if (Constants.UPLOAD_UUID_NAME) { // uuid命名
path = dir + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
outFile = new File(UPLOAD_FILE_DIR, path);
} else { // 使用原名称,存在相同着加(1)
path = dir + orgName;
outFile = new File(UPLOAD_FILE_DIR, path);
int sameSize = 1;
String prefix = orgName.substring(0, orgName.lastIndexOf(".")); // 获取文件名称
while (outFile.exists()) {
path = dir + prefix + "(" + sameSize + ")." + suffix;
outFile = new File(UPLOAD_FILE_DIR, path);
sameSize++;
}
}
try {
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) return JsonResult.error("上传失败");
}
file.transferTo(outFile);
JsonResult jsonResult = JsonResult.ok("上传成功").put("url", path).put("fileName", orgName)
.put("dir", "/" + StrUtil.removeSuffix(dir, "/"));
if (request != null) {
jsonResult.put("location", "/file/" + path);
}
return jsonResult;
} catch (Exception e) {
e.printStackTrace();
return JsonResult.error("上传失败").put("error", e.getMessage());
}
}
/**
* 上传文件base64格式
*
* @param base64 base64编码字符
* @return 示例:{"code": 0, "msg": "", "url": ""}
*/
public static JsonResult upload(String base64, HttpServletRequest request) {
if (base64 == null || base64.trim().isEmpty()) return JsonResult.error("上传失败");
String suffix = base64.substring(11, base64.indexOf(";")); // 获取文件格式
String dir = getDateDir();
String path = dir + UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
File outFile = new File(UPLOAD_FILE_DIR, path);
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) return JsonResult.error("上传失败");
}
try {
byte[] bytes = Base64.getDecoder().decode(base64.substring(base64.indexOf(";") + 8).getBytes());
IoUtil.write(new FileOutputStream(outFile), true, bytes);
} catch (Exception e) {
e.printStackTrace();
return JsonResult.error("上传失败").put("error", e.getMessage());
}
JsonResult jsonResult = JsonResult.ok("上传成功").put("url", path)
.put("dir", "/" + StrUtil.removeSuffix(dir, "/"));
if (request != null) {
jsonResult.put("location", StrUtil.removeSuffix(
StrUtil.removeSuffix(request.getRequestURL(), "upload/base64")
, "upload") + path);
}
return jsonResult;
}
/**
* 按照日期分存放目录
*/
public static String getDateDir() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd/");
return sdf.format(new Date());
}
/**
* 预览文件
*/
public static void preview(File file, HttpServletResponse response) {
if (file == null || !file.exists()) {
outNotFund(response);
return;
}
// 支持word、excel预览
if (OpenOfficeUtil.canConverter(file.getName())) {
File pdfFile = OpenOfficeUtil.converterToPDF(file.getAbsolutePath());
if (pdfFile != null) file = pdfFile;
}
String contentType = getFileType(file); // 获取文件类型
if (contentType != null) {
response.setContentType(contentType);
} else {
setDownloadHeader(response, file.getName());
}
try {
output(file, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 预览源文件
*/
public static void preview(String path, HttpServletResponse response) {
preview(new File(UPLOAD_FILE_DIR, path), response);
}
/**
* 下载源文件
*/
public static void download(String path, HttpServletResponse response) {
File file = new File(UPLOAD_FILE_DIR, path);
if (!file.exists()) {
outNotFund(response);
return;
}
setDownloadHeader(response, file.getName());
try {
output(file, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 预览缩略图
*/
public static void thumbnail(String path, HttpServletResponse response) {
// 如果是图片并且缩略图不存在则生成
File file = new File(UPLOAD_FILE_DIR, path);
File smFile = new File(UPLOAD_SM_DIR, path);
if (!smFile.exists() && isImgFile(file)) {
// 大于100kb生成100kb的缩略图
long fileSize = file.length();
if ((fileSize / 1024) > 100) {
try {
if (smFile.getParentFile().mkdirs()) {
ImgUtil.scale(file, smFile, 100f / (fileSize / 1024f));
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
preview(file, response);
return;
}
}
preview(smFile, response);
}
/**
* 输出文件流
*/
public static void output(File file, OutputStream os) {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[1024 * 256];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 删除文件
*/
public static boolean delete(String path) {
File file = new File(UPLOAD_FILE_DIR, path);
if (file.delete()) new File(UPLOAD_SM_DIR, path).delete();
return true;
}
/**
* 获取文件列表
*/
public static List<Map<String, Object>> list(String dir) {
dir = dir == null ? "" : dir;
List<Map<String, Object>> list = new ArrayList<>();
File file = new File(UPLOAD_FILE_DIR + dir);
File[] files = file.listFiles();
if (files == null) return list;
for (File f : files) {
Map<String, Object> map = new HashMap<>();
map.put("name", f.getName());
map.put("size", f.length());
map.put("isDir", f.isDirectory());
if (!f.isDirectory()) {
map.put("url", dir + "/" + f.getName());
map.put("smUrl", "thumbnail" + dir + "/" + f.getName());
}
map.put("updateTime", f.lastModified());
list.add(map);
}
return list;
}
/**
* 获取文件类型
*/
public static String getFileType(File file) {
String contentType = null;
try {
contentType = new Tika().detect(file);
} catch (IOException e) {
e.printStackTrace();
}
return contentType;
}
/**
* 判断是否是图片类型
*/
public static boolean isImgFile(File file) {
String contentType = getFileType(file);
return contentType != null && contentType.startsWith("image/");
}
/**
* 设置下载文件的header
*/
public static void setDownloadHeader(HttpServletResponse response, String fileName) {
response.setContentType("application/force-download");
try {
fileName = URLEncoder.encode(fileName, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
}
/**
* 输出文件不存在
*/
public static void outNotFund(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
outMessage("404 Not Found", response);
}
/**
* 输出错误信息
*/
public static void outMessage(String message, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter writer = response.getWriter();
writer.write("<!doctype html>");
writer.write("<title>" + message + "</title>");
writer.write("<h1 style=\"text-align: center\">" + message + "</h1>");
writer.write("<hr/><p style=\"text-align: center\">Zlianpay File Server</p>");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,199 @@
package com.bomaos.common.core.utils;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Objects;
/**
* 格式校验工具类
* Created by Panyoujie on 2018-12-14 8:38
*/
public class FormCheckUtil {
/**
* 密码是否符合格式(5-12位非空白字符)
*/
public static boolean isPassword(String password) {
return test(password, "^[\\S]{5,12}$");
}
/**
* 两个对象是否相等
*/
public static boolean equals(Object obj1, Object obj2) {
return Objects.equals(obj1, obj2);
}
/**
* 是否是手机号
*/
public static boolean isPhone(String phone) {
return test(phone, "^1\\d{10}$");
}
/**
* 是否是邮箱
*/
public static boolean isEmail(String email) {
return test(email, "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
}
/**
* 是否是网址
*/
public static boolean isUrl(String url) {
return test(url, "(^#)|(^http(s*):\\/\\/[^\\s]+\\.[^\\s]+)");
}
/**
* 是否是数字
*/
public static boolean isNumber(String number) {
return test(number, "^1\\d{10}$");
}
/**
* 是否是日期
*/
public static boolean isDate(String date) {
return test(date, "^(\\d{4})[-\\/](\\d{1}|0\\d{1}|1[0-2])([-\\/](\\d{1}|0\\d{1}|[1-2][0-9]|3[0-1]))*$");
}
/**
* 是否是身份证
*/
public static boolean isIdentity(String identity) {
return test(identity, "(^\\d{15}$)|(^\\d{17}(x|X|\\d)$)");
}
/**
* 是否是整数
*/
public static boolean isDigits(String str) {
return test(str, "^-?\\d+$");
}
/**
* 是否是正整数
*/
public static boolean isDigitsP(String str) {
return test(str, "^[1-9]\\d*$");
}
/**
* 是否是负整数
*/
public static boolean isDigitsN(String str) {
return test(str, "^-[1-9]\\d*$");
}
/**
* 是否是非负整数(正整数或0)
*/
public static boolean isDigitsPZ(String str) {
return test(str, "^\\d+$");
}
/**
* 是否是非正整数(负整数或0)
*/
public static boolean isDigitsNZ(String str) {
return test(str, "^-[1-9]\\d*|0");
}
/**
* 验证最大长度、最小长度
*/
public static boolean maxMinLength(String str, Integer maxLength, Integer minLength) {
if (maxLength != null && (str == null || str.length() > maxLength)) {
return false;
}
return !(minLength != null && (str == null || str.length() < minLength));
}
/**
* 验证最大值、最小值
*/
public static boolean maxMin(Integer value, Integer max, Integer min) {
if (max != null && value != null && value > max) {
return false;
}
return !(min != null && value != null && value < min);
}
/**
* 字符串是否匹配正则表达式
*/
public static boolean test(String str, String reg) {
return str != null && str.matches(reg);
}
/**
* 是否是身份证(强校验)
*/
public static String isIdentityStrong(String identity) {
if (!isIdentity(identity)) {
return "身份证号码格式错误";
}
String ai;
if (identity.length() == 18) {
ai = identity.substring(0, 17);
} else {
ai = identity.substring(0, 6) + "19" + identity.substring(6, 15);
}
// 验证出生年月
String year = ai.substring(6, 10); // 年
String birthday = year + "-" + ai.substring(10, 12) + "-" + ai.substring(12, 14);
if (!isDate(birthday)) {
return "身份证号码出生日期无效";
}
try {
long time = new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime();
GregorianCalendar gc = new GregorianCalendar();
if ((gc.get(Calendar.YEAR) - Integer.parseInt(year)) > 150 || (gc.getTime().getTime() - time) < 0) {
return "身份证号码出生日期不在有效范围";
}
} catch (Exception e) {
e.printStackTrace();
return "身份证号码校验失败";
}
// 验证地区码
String[] areaCodes = new String[]{"11", "12", "13", "14", "15", "21", "22", "23",
"31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46",
"50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91"};
if (!Arrays.asList(areaCodes).contains(ai.substring(0, 2))) {
return "身份证号码地区编码错误";
}
// 验证最后一位
if (identity.length() == 18) {
String[] valCode = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
String[] wi = {"7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"};
int totalMulAiWi = 0;
for (int i = 0; i < 17; i++) {
totalMulAiWi += Integer.parseInt(String.valueOf(ai.charAt(i))) * Integer.parseInt(wi[i]);
}
ai += valCode[totalMulAiWi % 11];
if (!ai.equals(identity)) {
return "身份证号码最后一位错误";
}
}
return null;
}
/**
* 值是否在给定值内
*/
public static boolean isIn(Object value, Object... values) {
if (value != null) {
for (Object obj : values) {
if (value.equals(obj)) {
return true;
}
}
}
return false;
}
}

View File

@@ -0,0 +1,376 @@
package com.bomaos.common.core.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* JSON解析工具类
* Created by Panyoujie on 2017-06-10 10:10
*/
public class JSONUtil {
/**
* 获取code
*/
public static int getCode(String json) {
return getIntValue(json, "code");
}
/**
* 获取message
*/
public static String getMessage(String json) {
return getString(json, "msg");
}
/**
* 得到String类型值
*/
public static String getString(String json, String key) {
String result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getString(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到int类型的值
*/
public static int getIntValue(String json, String key) {
int result = 0;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getIntValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到boolean类型的值
*/
public static boolean getBooleanValue(String json, String key) {
boolean result = false;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getBooleanValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到long类型的值
*/
public static long getLongValue(String json, String key) {
long result = 0;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getLongValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到double类型的值
*/
public static double getDoubleValue(String json, String key) {
double result = 0;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getDoubleValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到float类型的值
*/
public static float getFloatValue(String json, String key) {
float result = 0;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getFloatValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到byte类型的值
*/
public static byte getByteValue(String json, String key) {
byte result = 0;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getByteValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到short类型的值
*/
public static short getShortValue(String json, String key) {
short result = 0;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getShortValue(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Integer类型的值
*/
public static Integer getInteger(String json, String key) {
Integer result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getInteger(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Boolean类型的值
*/
public static Boolean getBoolean(String json, String key) {
Boolean result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getBoolean(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Long类型的值
*/
public static Long getLong(String json, String key) {
Long result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getLong(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Double类型的值
*/
public static Double getDouble(String json, String key) {
Double result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getDouble(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Float类型的值
*/
public static Float getFloat(String json, String key) {
Float result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getFloat(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Byte类型的值
*/
public static Byte getByte(String json, String key) {
Byte result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getByte(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Short类型的值
*/
public static Short getShort(String json, String key) {
Short result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getShort(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到byte[]类型的值
*/
public static byte[] getBytes(String json, String key) {
byte[] result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getBytes(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到BigInteger类型的值
*/
public static BigInteger getBigInteger(String json, String key) {
BigInteger result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getBigInteger(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到BigDecimal类型的值
*/
public static BigDecimal getBigDecimal(String json, String key) {
BigDecimal result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getBigDecimal(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到Date类型的值
*
* @param json
* @param key
* @return
*/
public static Date getDate(String json, String key) {
Date result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getDate(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到对象类型的值
*/
public static <T> T getObject(String json, String key, Class<T> clazz) {
T result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
result = jsonObject.getObject(key, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 得到对象类型的集合
*
* @param json
* @param key
* @param clazz
* @return
*/
public static <T> List<T> getArray(String json, String key, Class<T> clazz) {
List<T> result = null;
try {
JSONObject jsonObject = JSON.parseObject(json);
String string = jsonObject.getString(key);
result = JSON.parseArray(string, clazz);
} catch (Exception e) {
e.printStackTrace();
}
if (result == null) {
result = new ArrayList<>();
}
return result;
}
/**
* json转换换成对象
*
* @param json
* @param clazz
* @return
*/
public static <T> T parseObject(String json, Class<T> clazz) {
T result = null;
try {
result = JSON.parseObject(json, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* json转换换成集合
*
* @param json
* @param clazz
* @return
*/
public static <T> List<T> parseArray(String json, Class<T> clazz) {
List<T> result = null;
try {
result = JSON.parseArray(json, clazz);
} catch (Exception e) {
e.printStackTrace();
}
if (result == null) {
result = new ArrayList<>();
}
return result;
}
}

View File

@@ -0,0 +1,120 @@
package com.bomaos.common.core.utils;
import com.bomaos.common.core.Constants;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import java.io.File;
import java.util.Arrays;
import java.util.Base64;
import java.util.regex.Pattern;
/**
* OpenOfficeUtil
* Created by Panyoujie on 2018-12-14 08:38
*/
public class OpenOfficeUtil {
// pdf转换后的目录
private static final String PDF_TEMP_DIR = Constants.UPLOAD_DIR + "pdf/";
// 支持转换pdf的文件后缀列表
private static final String[] CAN_CONVERTER_FILES = new String[]{"doc", "docx", "xls", "xlsx", "ppt", "pptx"};
/**
* 文件转pdf
*
* @param filePath 源文件路径
* @return File
*/
public static File converterToPDF(String filePath) {
return converterToPDF(filePath, true);
}
/**
* 文件转pdf
*
* @param filePath 源文件路径
* @param cache 是否使用上次转换过的文件
* @return File
*/
public static File converterToPDF(String filePath, boolean cache) {
if (filePath == null || filePath.trim().isEmpty()) {
return null;
}
File srcFile = new File(filePath);
if (!srcFile.exists()) {
return null;
}
// 是否转换过
File outFile = new File(PDF_TEMP_DIR, Base64.getEncoder().encodeToString(filePath.getBytes()) + ".pdf");
if (cache && outFile.exists()) {
return outFile;
}
// 转换
OfficeManager officeManager = null;
try {
officeManager = getOfficeManager();
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
return converterFile(srcFile, outFile, converter);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (officeManager != null) {
officeManager.stop();
}
}
return null;
}
/**
* 转换文件
*/
public static File converterFile(File inFile, File outFile, OfficeDocumentConverter converter) {
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) return outFile;
}
converter.convert(inFile, outFile);
return outFile;
}
/**
* 判断文件后缀是否可以转换pdf
*/
public static boolean canConverter(String path) {
try {
String suffix = path.substring(path.lastIndexOf(".") + 1);
return Arrays.asList(CAN_CONVERTER_FILES).contains(suffix);
} catch (Exception e) {
return false;
}
}
/**
* 连接并启动OpenOffice
*/
public static OfficeManager getOfficeManager() {
String officeHome = getOfficeHome();
if (officeHome == null) return null;
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
config.setOfficeHome(officeHome); // 设置OpenOffice安装目录
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start(); // 启动OpenOffice服务
return officeManager;
}
/**
* 根据操作系统获取OpenOffice安装目录
*/
public static String getOfficeHome() {
String osName = System.getProperty("os.name");
if (Pattern.matches("Linux.*", osName)) {
return Constants.OPEN_OFFICE_PATH_LINUX;
} else if (Pattern.matches("Windows.*", osName)) {
return Constants.OPEN_OFFICE_PATH_WINDOWS;
} else if (Pattern.matches("Mac.*", osName)) {
return Constants.OPEN_OFFICE_PATH_MAC;
}
return null;
}
}

View File

@@ -0,0 +1,109 @@
package com.bomaos.common.core.utils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
/**
* 图片压缩Utils
*/
public class PicUtils {
private static final Logger logger = LoggerFactory.getLogger(PicUtils.class);
/*public static void main(String[] args) throws IOException {
byte[] bytes = FileUtils.readFileToByteArray(new File("D:/a.png"));
long l = System.currentTimeMillis();
bytes = PicUtils.compressPicForScale(bytes, 30, "x");// 图片小于300kb
System.out.println(System.currentTimeMillis() - l);
FileUtils.writeByteArrayToFile(new File("D:/aa.png"), bytes);
}*/
/**
* 根据指定大小压缩图片
*
* @param imageBytes 源图片字节数组
* @param desFileSize 指定图片大小单位kb
* @param imageId 影像编号
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize, String imageId) {
if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < desFileSize * 1024) {
return imageBytes;
}
long srcSize = imageBytes.length;
double accuracy = getAccuracy(srcSize / 1024);
try {
while (imageBytes.length > desFileSize * 1024) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
.scale(accuracy)
.outputQuality(accuracy)
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
logger.info("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb", imageId, srcSize / 1024, imageBytes.length / 1024);
} catch (Exception e) {
logger.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
/**
* 自动调节精度(经验数值)
*
* @param size 源图片大小
* @return 图片压缩质量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < 900) {
accuracy = 0.85;
} else if (size < 2047) {
accuracy = 0.6;
} else if (size < 3275) {
accuracy = 0.44;
} else {
accuracy = 0.4;
}
return accuracy;
}
/**
* 图片指定宽度高度
*
* @param path 图片地址
* @param width 图片宽度
* @param height 图片高度
* @return
*/
public static void changeSize(String path, int width, int height, HttpServletResponse response) {
try {
File file = new File(FileUploadUtil.UPLOAD_FILE_DIR + path);
if (!file.exists()) {
// 文件不存在
return;
}
byte[] imageBytes = FileUtils.readFileToByteArray(file);
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
BufferedImage image = Thumbnails.of(inputStream).size(width, height).keepAspectRatio(false).asBufferedImage();
//以JPEG格式向客户端发送
ServletOutputStream os = response.getOutputStream();
ImageIO.write(image, "JPG", os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,26 @@
package com.bomaos.common.core.utils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class RequestParamsUtil {
public static Map<String, String> getParameterMap(HttpServletRequest request) {
Map<String, String> params = new HashMap<>(); //申明hashMap变量储存接收到的参数名用于排序
Map requestParams = request.getParameterMap(); //获取请求的全部参数
String valueStr = ""; //申明字符变量 保存接收到的变量
for (
Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
String name = (String) iter.next();
String[] values = (String[]) requestParams.get(name);
valueStr = values[0];
//乱码解决这段代码在出现乱码时使用。如果sign不相等也可以使用这段代码转化
//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
params.put(name, valueStr);//增加到params保存
}
return params;
}
}

View File

@@ -0,0 +1,35 @@
package com.bomaos.common.core.utils;
import com.bomaos.orders.entity.Orders;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RmbUtil {
/**
* 根据查询到订单数量统计订单的总金额
*
* @param ordersList
* @return
*/
public static Map getRmbCount(List<Orders> ordersList) {
// 今天的收款金额
BigDecimal decimal = new BigDecimal("0.00");
Integer longTotal = 0; // 今天的成交订单
for (Orders orders : ordersList) {
BigDecimal bigDecimal = new BigDecimal(orders.getMoney().toString());
longTotal++;
decimal = decimal.add(bigDecimal);
}
HashMap<String, Object> map = new HashMap<>();
map.put("totalSumlong", decimal);
map.put("longTotal", longTotal);
return map;
}
}

View File

@@ -0,0 +1,33 @@
package com.bomaos.common.core.utils;
import java.util.Random;
public class StringUtil {
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
int number = random.nextInt(str.length());
sb.append(str.charAt(number));
}
return sb.toString();
}
public static String getRandomNumber(int length) {
String str = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
int number = random.nextInt(str.length());
sb.append(str.charAt(number));
}
return sb.toString();
}
}

View File

@@ -0,0 +1,99 @@
package com.bomaos.common.core.utils;
import eu.bitwalker.useragentutils.UserAgent;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 获取客户端设备信息
* Created by Panyoujie on 2017-6-10 10:10
*/
public class UserAgentGetter {
private final UserAgent userAgent;
private final String userAgentString;
private final HttpServletRequest userRequest;
public UserAgentGetter(HttpServletRequest request) {
this.userRequest = request;
this.userAgentString = request.getHeader("User-Agent");
this.userAgent = UserAgent.parseUserAgentString(userAgentString);
}
/**
* 获取浏览器类型
*/
public String getBrowser() {
if (null == userAgent) return "Unknown";
return userAgent.getBrowser().getName();
}
/**
* 获取操作系统
*/
public String getOS() {
if (null == userAgent) return "Unknown";
return userAgent.getOperatingSystem().getName();
}
/**
* 获取设备型号
*/
public String getDevice() {
if (null == userAgentString) return "Unknown";
if (userAgentString.contains("Android")) {
String[] str = userAgentString.split("[()]+");
str = str[1].split("[;]");
String[] res = str[str.length - 1].split("Build/");
return res[0].trim();
} else if (userAgentString.contains("iPhone")) {
String[] str = userAgentString.split("[()]+");
String res = "iphone" + str[1].split("OS")[1].split("like")[0];
return res.trim();
} else if (userAgentString.contains("iPad")) {
return "iPad";
} else {
return getOS().trim();
}
}
/**
* 获取ip地址
*/
public String getIp() {
return getIp(userRequest);
}
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (isBlankIp(ip)) ip = request.getHeader("Proxy-Client-IP");
if (isBlankIp(ip)) ip = request.getHeader("WL-Proxy-Client-IP");
if (isBlankIp(ip)) ip = request.getHeader("HTTP_CLIENT_IP");
if (isBlankIp(ip)) ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (isBlankIp(ip)) ip = request.getRemoteAddr();
// 多个ip获取第一个
if (!isBlankIp(ip) && ip.length() > 15) ip = ip.split(",")[0];
} catch (Exception e) {
e.printStackTrace();
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return ip;
}
private static boolean isBlankIp(String ip) {
return ip == null || ip.trim().isEmpty() || "unknown".equalsIgnoreCase(ip);
}
}

View File

@@ -0,0 +1,27 @@
package com.bomaos.common.core.web;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.util.SubjectUtil;
import javax.servlet.http.HttpServletRequest;
public class BaseApiController extends BaseController {
/**
* 获取当前登录的token
*/
public Token getLoginToken(HttpServletRequest request) {
return SubjectUtil.getToken(request);
}
/**
* 获取当前登录的userId
*
* @param request
* @return
*/
public Long getLoginUserId(HttpServletRequest request) {
Token token = getLoginToken(request);
return token == null ? null : Long.parseLong(token.getUserId());
}
}

View File

@@ -0,0 +1,60 @@
package com.bomaos.common.core.web;
import com.bomaos.common.system.entity.User;
import com.bomaos.website.entity.Website;
import com.bomaos.website.service.WebsiteService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Controller基类
* Created by Panyoujie on 2017-06-10 10:10
*/
public class BaseController {
@Autowired
private WebsiteService websiteService;
/**
* 获取当前登录的user
*/
public User getLoginUser() {
Subject subject = SecurityUtils.getSubject();
if (subject == null) return null;
Object object = subject.getPrincipal();
if (object != null) return (User) object;
return null;
}
/**
* 获取当前登录的userId
*/
public Integer getLoginUserId() {
User loginUser = getLoginUser();
return loginUser == null ? null : loginUser.getUserId();
}
public String getWebName() {
Website website = websiteService.getById(1);
return website.getWebsiteName();
}
/**
* 获取当前登录用户的supplierId管理员返回null
*/
public Integer getLoginUserSupplierId() {
User loginUser = getLoginUser();
if (loginUser == null) return null;
Integer supplierId = loginUser.getSupplierId();
return (supplierId != null && supplierId > 0) ? supplierId : null;
}
/**
* 判断当前用户是否为供应商
*/
public boolean isSupplier() {
return getLoginUserSupplierId() != null;
}
}

View File

@@ -0,0 +1,52 @@
package com.bomaos.common.core.web;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import java.io.Serializable;
import java.util.List;
/**
* 批量修改通用参数
* Created by Panyoujie on 2020-03-13 0:11
*/
public class BatchParam<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id集合
*/
private List<Serializable> ids;
/**
* 批量修改多个字段
*/
private T data;
/**
* 通用批量修改方法
*
* @param service IService
* @param idName id字段名称
* @return boolean
*/
public boolean update(IService<T> service, String idName) {
if (data == null) return false;
return service.update(data, new UpdateWrapper<T>().in(idName, this.getIds()));
}
public List<Serializable> getIds() {
return ids;
}
public void setIds(List<Serializable> ids) {
this.ids = ids;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@@ -0,0 +1,103 @@
package com.bomaos.common.core.web;
import com.bomaos.common.core.Constants;
import java.util.HashMap;
/**
* 接口返回结果对象
* Created by Panyoujie on 2017-06-10 10:10
*/
public class JsonResult extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
private static final String CODE_NAME = "code"; // 状态码字段名称
private static final String MSG_NAME = "msg"; // 状态信息字段名称
private static final String DATA_NAME = "data"; // 数据字段名称
private static final int DEFAULT_OK_CODE = Constants.RESULT_OK_CODE; // 默认成功码
private static final int DEFAULT_ERROR_CODE = Constants.RESULT_ERROR_CODE; // 默认失败码
private static final String DEFAULT_OK_MSG = "操作成功"; // 默认成功msg
private static final String DEFAULT_ERROR_MSG = "操作失败"; // 默认失败msg
private JsonResult() {
}
/**
* 返回成功
*/
public static JsonResult ok() {
return ok(null);
}
/**
* 返回成功
*/
public static JsonResult ok(String message) {
return ok(DEFAULT_OK_CODE, message);
}
/**
* 返回成功
*/
public static JsonResult ok(int code, String message) {
if (message == null) message = DEFAULT_OK_MSG;
JsonResult jsonResult = new JsonResult();
jsonResult.put(CODE_NAME, code);
jsonResult.put(MSG_NAME, message);
return jsonResult;
}
/**
* 返回失败
*/
public static JsonResult error() {
return error(null);
}
/**
* 返回失败
*/
public static JsonResult error(String message) {
return error(DEFAULT_ERROR_CODE, message);
}
/**
* 返回失败
*/
public static JsonResult error(int code, String message) {
if (message == null) message = DEFAULT_ERROR_MSG;
return ok(code, message);
}
public JsonResult setCode(Integer code) {
return put(CODE_NAME, code);
}
public JsonResult setMsg(String message) {
return put(MSG_NAME, message);
}
public JsonResult setData(Object object) {
return put(DATA_NAME, object);
}
public Integer getCode(int code) {
Object o = get(CODE_NAME);
return o == null ? null : Integer.parseInt(o.toString());
}
public String getMsg() {
Object o = get(MSG_NAME);
return o == null ? null : o.toString();
}
public Object getData() {
return get(DATA_NAME);
}
@Override
public JsonResult put(String key, Object object) {
if (key != null && object != null) super.put(key, object);
return this;
}
}

View File

@@ -0,0 +1,441 @@
package com.bomaos.common.core.web;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* 列表分页、排序、搜索通用接收参数封装
* Created by Panyoujie on 2019-04-26 10:34
*/
public class PageParam<T> extends Page<T> {
private static final String FILED_PAGE = "page"; // 第几页参数名称
private static final String FILED_LIMIT = "limit"; // 每页显示数量参数名称
private static final String FILED_SORT = "sort"; // 排序字段参数名称
private static final String FILED_ORDER = "order"; // 排序方式参数名称
private static final String VALUE_ORDER_ASC = "asc"; // 表示升序的值
private static final String VALUE_ORDER_DESC = "desc"; // 表示降序的值
private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]"); // 驼峰转下划线正则匹配
/**
* 除分页、排序外的其他参数
*/
private Map<String, Object> pageData;
/**
* 是否把字段名称驼峰转下划线
*/
private boolean needToLine = true;
public PageParam() {
super();
}
public PageParam(HttpServletRequest request) {
init(request);
}
public PageParam(HttpServletRequest request, boolean needToLine) {
setNeedToLine(needToLine);
init(request);
}
public boolean isNeedToLine() {
return needToLine;
}
public PageParam<T> setNeedToLine(boolean needToLine) {
this.needToLine = needToLine;
return this;
}
public Map<String, Object> getPageData() {
return pageData;
}
public void setPageData(Map<String, Object> data) {
this.pageData = data;
}
/**
* 从request中获取参数并填充到PageParam中
*/
public PageParam<T> init(HttpServletRequest request) {
String sortValue = null, orderValue = null;
Map<String, Object> map = new HashMap<>();
Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = request.getParameter(name);
if (value == null || value.isEmpty() || value.replace(" ", "").isEmpty()) {
continue;
}
if (FILED_PAGE.equals(name)) {
setCurrent(Long.parseLong(value));
} else if (FILED_LIMIT.equals(name)) {
setSize(Long.parseLong(value));
} else if (FILED_SORT.equals(name)) {
sortValue = (needToLine ? humpToLine(value) : value);
} else if (FILED_ORDER.equals(name)) {
orderValue = value;
} else {
map.put(name, value);
}
}
setPageData(map);
// 同步排序方式到MyBatisPlus中
if (sortValue != null) {
/* if (VALUE_ORDER_ASC.equals(orderValue))*/
setOrder(sortValue, !VALUE_ORDER_DESC.equals(orderValue));
}
return this;
}
/**
* 获取升序排序的字段
*/
public List<String> getOrderAscs() {
List<String> ascs = new ArrayList<>();
List<OrderItem> orders = getOrders();
if (orders != null) {
for (OrderItem order : orders) {
if (order.isAsc()) ascs.add(order.getColumn());
}
}
return ascs;
}
/**
* 获取降序排序的字段
*/
public List<String> getOrderDescs() {
List<String> descs = new ArrayList<>();
List<OrderItem> orders = getOrders();
if (orders != null) {
for (OrderItem order : orders) {
if (!order.isAsc()) descs.add(order.getColumn());
}
}
return descs;
}
/**
* 增加asc排序方式
*/
public PageParam<T> addOrderAsc(String... ascs) {
if (ascs != null) {
List<String> tAscs = getOrderAscs();
List<OrderItem> orderItems = new ArrayList<>();
for (String column : ascs) {
if (!tAscs.contains(column)) {
OrderItem orderItem = new OrderItem();
orderItem.setAsc(true);
orderItem.setColumn(column);
orderItems.add(orderItem);
}
}
if (getOrders() == null) {
setOrders(orderItems);
} else {
getOrders().addAll(orderItems);
}
}
return this;
}
/**
* 增加desc排序方式
*/
public PageParam<T> addOrderDesc(String... descs) {
if (descs != null) {
List<String> tDescs = getOrderDescs();
List<OrderItem> orderItems = new ArrayList<>();
for (String column : descs) {
if (!tDescs.contains(column)) {
OrderItem orderItem = new OrderItem();
orderItem.setAsc(false);
orderItem.setColumn(column);
orderItems.add(orderItem);
}
}
if (getOrders() == null) {
setOrders(orderItems);
} else {
getOrders().addAll(orderItems);
}
}
return this;
}
/**
* 移除某个排序字段
*/
public PageParam<T> removeOrder(String order, Boolean isAsc) {
List<OrderItem> orderItems = getOrders();
if (orderItems != null) {
Iterator<OrderItem> iterator = orderItems.iterator();
while (iterator.hasNext()) {
OrderItem item = iterator.next();
if (isAsc == null || isAsc == item.isAsc()) {
if (order.equals(item.getColumn())) iterator.remove();
}
}
}
return this;
}
/**
* 设置排序方式
*/
public PageParam<T> setOrder(String order, boolean isAsc) {
List<OrderItem> orderItems = new ArrayList<>();
if (order != null) {
OrderItem orderItem = new OrderItem();
orderItem.setAsc(isAsc);
orderItem.setColumn(order);
orderItems.add(orderItem);
}
setOrders(orderItems);
return this;
}
/**
* 设置默认排序方式
*/
public PageParam<T> setDefaultOrder(String[] ascs, String[] descs) {
List<OrderItem> orderItems = getOrders();
if (orderItems == null || orderItems.size() == 0) {
addOrderAsc(ascs);
addOrderDesc(descs);
}
return this;
}
/**
* 往pageData里面增加参数
*/
public PageParam<T> put(String key, Object value) {
if (pageData == null) pageData = new HashMap<>();
pageData.put(key, value);
return this;
}
/**
* 获取pageData里面参数
*/
public Object get(String key) {
return pageData.get(key);
}
public String getString(String key) {
Object o = pageData.get(key);
if (o != null) return String.valueOf(o);
return null;
}
public Integer getInt(String key) {
String str = getString(key);
if (str != null) return Integer.parseInt(str);
return null;
}
public Long getLong(String key) {
String str = getString(key);
if (str != null) return Long.parseLong(str);
return null;
}
public Float getFloat(String key) {
String str = getString(key);
if (str != null) return Float.parseFloat(str);
return null;
}
public Double getDouble(String key) {
String str = getString(key);
if (str != null) return Double.parseDouble(str);
return null;
}
public Boolean getBoolean(String key) {
String str = getString(key);
if (str != null) return Boolean.parseBoolean(str);
return null;
}
/**
* 构建查询条件
*
* @param excludes 不包含的参数
* @return QueryWrapper
*/
public QueryWrapper<T> getWrapper(String... excludes) {
List<String> exList = Arrays.asList(excludes);
QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
for (String key : pageData.keySet()) {
if (!exList.contains(key)) buildWrapper(queryWrapper, key, getString(key));
}
return queryWrapper;
}
/**
* 构建查询条件
*
* @param columns 只包含的参数
* @return QueryWrapper
*/
public QueryWrapper<T> getWrapperWith(String... columns) {
List<String> keyList = Arrays.asList(columns);
QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
for (String key : pageData.keySet()) {
if (keyList.contains(key)) buildWrapper(queryWrapper, key, getString(key));
}
return queryWrapper;
}
/**
* 逐个构建QueryWrapper
*/
private void buildWrapper(QueryWrapper<T> queryWrapper, String key, String value) {
if (value == null || "deleted".equals(key)) return;
if (Arrays.asList("id", "sortNumber", "state").contains(key) || key.endsWith("Id")) {
queryWrapper.eq(needToLine ? humpToLine(key) : key, value);
} else if ("createTimeStart".equals(key)) {
queryWrapper.ge("create_time", value);
} else if ("createTimeEnd".equals(key)) {
queryWrapper.le("create_time", value);
} else {
queryWrapper.like(needToLine ? humpToLine(key) : key, value);
}
}
/**
* 构建排序的QueryWrapper
*
* @param queryWrapper 搜索条件的wrapper
* @return QueryWrapper
*/
public QueryWrapper<T> getOrderWrapper(QueryWrapper<T> queryWrapper) {
if (queryWrapper == null) queryWrapper = new QueryWrapper<T>();
queryWrapper.orderByAsc(getOrderAscs());
queryWrapper.orderByDesc(getOrderDescs());
return queryWrapper;
}
/**
* 构建包含排序的查询条件
*
* @return QueryWrapper
*/
public QueryWrapper<T> getOrderWrapper() {
return getOrderWrapper(getWrapper());
}
/**
* 获取不分页的参数包含排序和pageData
*
* @return Map
*/
public Map<String, Object> getNoPageParam() {
Map<String, Object> map = new HashMap<>();
map.put("pageData", this.pageData);
List<OrderItem> orders = getOrders();
if (orders != null && orders.size() > 0) map.put("orders", orders);
return map;
}
/**
* 获取查询结果中第一条数据
*/
public T getOne(List<T> records) {
return records == null || records.size() == 0 ? null : records.get(0);
}
/**
* 代码排序查询结果实现类似SQL语句的排序效果
*/
public List<T> sortRecords(List<T> records) {
if (records == null || records.size() <= 1) return records;
List<OrderItem> orderItems = getOrders();
if (orderItems != null) {
Comparator<T> comparator = null;
for (OrderItem order : orderItems) {
if (order.getColumn() != null) {
Function keyExtractor = t -> getFieldValue(t, needToLine ? lineToHump(order.getColumn()) : order.getColumn());
if (comparator == null) {
if (order.isAsc()) {
comparator = Comparator.comparing(keyExtractor);
} else {
comparator = Comparator.comparing(keyExtractor, Comparator.reverseOrder());
}
} else {
if (order.isAsc()) {
comparator.thenComparing(keyExtractor);
} else {
comparator.thenComparing(keyExtractor, Comparator.reverseOrder());
}
}
}
}
if (comparator != null) {
return records.stream().sorted(comparator).collect(Collectors.toList());
}
}
return records;
}
/**
* 驼峰转下划线
*/
public static String humpToLine(String str) {
if (str == null) return null;
Matcher matcher = HUMP_PATTERN.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 下划线转驼峰
*/
public static String lineToHump(String str) {
if (str == null) return null;
StringBuilder sb = new StringBuilder();
String[] ss = str.split("_");
sb.append(ss[0]);
for (int i = 1; i < ss.length; i++) {
if (ss[i].length() > 0) sb.append(ss[i].substring(0, 1).toUpperCase());
if (ss[i].length() > 1) sb.append(ss[i].substring(1));
}
return sb.toString();
}
/**
* 获取对象某个字段的值
*
* @param t 对象
* @param field 字段
* @return Object
*/
public static Object getFieldValue(Object t, String field) {
if (t == null || field == null) return null;
try {
Field clazzField = t.getClass().getDeclaredField(field);
clazzField.setAccessible(true);
return clazzField.get(t);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,83 @@
package com.bomaos.common.core.web;
import java.io.Serializable;
import java.util.List;
/**
* 分页查询通用返回结果
* Created by Panyoujie on 2017-06-10 10:10
*/
public class PageResult<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 状态码
*/
private int code = 0;
/**
* 提示信息
*/
private String msg;
/**
* 总数量
*/
private long count;
/**
* 当前页数据
*/
private List<T> data;
public PageResult() {
}
public PageResult(List<T> rows) {
this(rows, rows == null ? 0 : rows.size());
}
public PageResult(List<T> rows, long total) {
this.count = total;
this.data = rows;
}
public PageResult(int code, List<T> rows, long total) {
this.code = code;
this.count = total;
this.data = rows;
}
public int getCode() {
return code;
}
public PageResult setCode(int code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public PageResult setMsg(String msg) {
this.msg = msg;
return this;
}
public long getCount() {
return count;
}
public PageResult setCount(long count) {
this.count = count;
return this;
}
public List<T> getData() {
return data;
}
public PageResult setData(List<T> data) {
this.data = data;
return this;
}
}

View File

@@ -0,0 +1,174 @@
package com.bomaos.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.utils.CoreUtil;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.common.system.entity.Dictionary;
import com.bomaos.common.system.service.DictionaryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* 字典管理
* Created by Panyoujie on 2020-03-14 11:29:03
*/
@Controller
@RequestMapping("/sys/dict")
public class DictionaryController extends BaseController {
@Autowired
private DictionaryService dictionaryService;
@RequiresPermissions("sys:dict:view")
@RequestMapping()
public String view() {
return "system/dictionary.html";
}
/**
* 分页查询字典
*/
@OperLog(value = "字典管理", desc = "分页查询")
@RequiresPermissions("sys:dict:list")
@ResponseBody
@RequestMapping("/page")
public PageResult<Dictionary> page(HttpServletRequest request) {
PageParam<Dictionary> pageParam = new PageParam<>(request);
return new PageResult<>(dictionaryService.page(pageParam, pageParam.getWrapper()).getRecords(), pageParam.getTotal());
}
/**
* 查询全部字典
*/
@OperLog(value = "字典管理", desc = "查询全部")
@RequiresPermissions("sys:dict:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<Dictionary> pageParam = new PageParam<>(request);
return JsonResult.ok().setData(dictionaryService.list(pageParam.getOrderWrapper()));
}
/**
* 根据id查询字典
*/
@OperLog(value = "字典管理", desc = "根据id查询")
@RequiresPermissions("sys:dict:list")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
return JsonResult.ok().setData(dictionaryService.getById(id));
}
/**
* 添加字典
*/
@OperLog(value = "字典管理", desc = "添加", param = false, result = true)
@RequiresPermissions("sys:dict:save")
@ResponseBody
@RequestMapping("/save")
public JsonResult save(Dictionary dictionary) {
if (dictionaryService.count(new QueryWrapper<Dictionary>().eq("dict_code", dictionary.getDictCode())) > 0) {
return JsonResult.error("字典标识已存在");
}
if (dictionaryService.count(new QueryWrapper<Dictionary>().eq("dict_name", dictionary.getDictName())) > 0) {
return JsonResult.error("字典名称已存在");
}
if (dictionaryService.save(dictionary)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改字典
*/
@OperLog(value = "字典管理", desc = "修改", param = false, result = true)
@RequiresPermissions("sys:dict:update")
@ResponseBody
@RequestMapping("/update")
public JsonResult update(Dictionary dictionary) {
if (dictionaryService.count(new QueryWrapper<Dictionary>().eq("dict_code", dictionary.getDictCode())
.ne("dict_id", dictionary.getDictId())) > 0) {
return JsonResult.error("字典代码已存在");
}
if (dictionaryService.count(new QueryWrapper<Dictionary>().eq("dict_name", dictionary.getDictName())
.ne("dict_id", dictionary.getDictId())) > 0) {
return JsonResult.error("字典名称已存在");
}
if (dictionaryService.updateById(dictionary)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除字典
*/
@OperLog(value = "字典管理", desc = "删除", result = true)
@RequiresPermissions("sys:dict:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (dictionaryService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量添加字典
*/
@OperLog(value = "字典管理", desc = "批量添加", param = false, result = true)
@RequiresPermissions("sys:dict:save")
@ResponseBody
@RequestMapping("/saveBatch")
public JsonResult saveBatch(@RequestBody List<Dictionary> list) {
// 对集合本身进行非空和重复校验
StringBuilder sb = new StringBuilder();
sb.append(CoreUtil.listCheckBlank(list, "dictCode", "字典标识"));
sb.append(CoreUtil.listCheckBlank(list, "dictName", "字典名称"));
sb.append(CoreUtil.listCheckRepeat(list, "dictCode", "字典标识"));
sb.append(CoreUtil.listCheckRepeat(list, "dictName", "字典名称"));
if (sb.length() != 0) return JsonResult.error(sb.toString());
// 数据库层面校验
if (dictionaryService.count(new QueryWrapper<Dictionary>().in("dict_code",
list.stream().map(Dictionary::getDictCode).collect(Collectors.toList()))) > 0) {
return JsonResult.error("字典标识已存在");
}
if (dictionaryService.count(new QueryWrapper<Dictionary>().in("dict_name",
list.stream().map(Dictionary::getDictName).collect(Collectors.toList()))) > 0) {
return JsonResult.error("字典名称已存在");
}
if (dictionaryService.saveBatch(list)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 批量删除字典
*/
@OperLog(value = "字典管理", desc = "批量删除", result = true)
@RequiresPermissions("sys:dict:remove")
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (dictionaryService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
}

View File

@@ -0,0 +1,162 @@
package com.bomaos.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.common.system.entity.DictionaryData;
import com.bomaos.common.system.service.DictionaryDataService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 字典项管理
* Created by Panyoujie on 2020-03-14 11:29:04
*/
@Controller
@RequestMapping("/sys/dictdata")
public class DictionaryDataController extends BaseController {
@Autowired
private DictionaryDataService dictionaryDataService;
/**
* 分页查询字典项
*/
@OperLog(value = "字典项管理", desc = "分页查询")
@RequiresPermissions("sys:dict:list")
@ResponseBody
@RequestMapping("/page")
public PageResult<DictionaryData> page(HttpServletRequest request) {
PageParam<DictionaryData> pageParam = new PageParam<>(request);
return dictionaryDataService.listPage(pageParam);
}
/**
* 查询全部字典项
*/
@OperLog(value = "字典项管理", desc = "查询全部")
@RequiresPermissions("sys:dict:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<DictionaryData> pageParam = new PageParam<>(request);
List<DictionaryData> records = dictionaryDataService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.sortRecords(records));
}
/**
* 根据id查询字典项
*/
@OperLog(value = "字典项管理", desc = "根据id查询")
@RequiresPermissions("sys:dict:list")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
PageParam<DictionaryData> pageParam = new PageParam<>();
pageParam.put("dictDataId", id);
List<DictionaryData> records = dictionaryDataService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.getOne(records));
}
/**
* 添加字典项
*/
@OperLog(value = "字典项管理", desc = "添加", param = false, result = true)
@RequiresPermissions("sys:dict:save")
@ResponseBody
@RequestMapping("/save")
public JsonResult add(DictionaryData dictionaryData) {
if (dictionaryDataService.count(new QueryWrapper<DictionaryData>()
.eq("dict_id", dictionaryData.getDictId())
.eq("dict_data_name", dictionaryData.getDictDataName())) > 0) {
return JsonResult.error("字典项名称已存在");
}
if (dictionaryDataService.count(new QueryWrapper<DictionaryData>()
.eq("dict_id", dictionaryData.getDictId())
.eq("dict_data_code", dictionaryData.getDictDataCode())) > 0) {
return JsonResult.error("字典项标识已存在");
}
if (dictionaryDataService.save(dictionaryData)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改字典项
*/
@OperLog(value = "字典项管理", desc = "修改", param = false, result = true)
@RequiresPermissions("sys:dict:update")
@ResponseBody
@RequestMapping("/update")
public JsonResult update(DictionaryData dictionaryData) {
if (dictionaryDataService.count(new QueryWrapper<DictionaryData>()
.eq("dict_id", dictionaryData.getDictId())
.eq("dict_data_name", dictionaryData.getDictDataName())
.ne("dict_data_id", dictionaryData.getDictDataId())) > 0) {
return JsonResult.error("字典项名称已存在");
}
if (dictionaryDataService.count(new QueryWrapper<DictionaryData>()
.eq("dict_id", dictionaryData.getDictId())
.eq("dict_data_code", dictionaryData.getDictDataCode())
.ne("dict_data_id", dictionaryData.getDictDataId())) > 0) {
return JsonResult.error("字典项标识已存在");
}
if (dictionaryDataService.updateById(dictionaryData)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除字典项
*/
@OperLog(value = "字典项管理", desc = "删除", result = true)
@RequiresPermissions("sys:dict:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (dictionaryDataService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量添加字典项
*/
@OperLog(value = "字典项管理", desc = "批量添加", param = false, result = true)
@RequiresPermissions("sys:dict:save")
@ResponseBody
@RequestMapping("/saveBatch")
public JsonResult saveBatch(@RequestBody List<DictionaryData> dictDataList) {
if (dictionaryDataService.saveBatch(dictDataList)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 批量删除字典项
*/
@OperLog(value = "字典项管理", desc = "批量删除", result = true)
@RequiresPermissions("sys:dict:remove")
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (dictionaryDataService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
}

View File

@@ -0,0 +1,47 @@
package com.bomaos.common.system.controller;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.system.service.EmailService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.mail.MessagingException;
/**
* 邮件功能
* Created by Panyoujie on 2020-03-21 0:37
*/
@Controller
@RequestMapping("/sys/email")
public class EmailController {
@Autowired
private EmailService emailService;
@RequiresPermissions("sys:email:view")
@RequestMapping()
public String view() {
return "system/email.html";
}
/**
* 发送邮件
*/
@OperLog(value = "邮件功能", desc = "发送邮件", result = true, param = false)
@RequiresPermissions("sys:email:view")
@ResponseBody
@RequestMapping("/send")
public JsonResult send(String title, String html, String email) {
try {
emailService.sendFullTextEmail(title, html, new String[]{email});
return JsonResult.ok("发送成功");
} catch (MessagingException e) {
e.printStackTrace();
}
return JsonResult.error("发送失败");
}
}

View File

@@ -0,0 +1,194 @@
package com.bomaos.common.system.controller;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.utils.FileUploadUtil;
import com.bomaos.common.core.utils.PicUtils;
import com.bomaos.common.core.web.JsonResult;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* 文件服务器
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/file")
public class FileController {
@RequiresPermissions("sys:file:view")
@RequestMapping("/manage")
public String view() {
return "system/file.html";
}
/**
* 上传文件
*/
@OperLog(value = "文件管理", desc = "上传文件", param = false, result = true)
@ResponseBody
@PostMapping("/upload")
public JsonResult upload(@RequestParam MultipartFile file, HttpServletRequest request) {
return FileUploadUtil.upload(file, request);
}
/**
* 上传base64文件
*/
@OperLog(value = "文件管理", desc = "上传base64文件", param = false, result = true)
@ResponseBody
@PostMapping("/upload/base64")
public JsonResult uploadBase64(String base64, HttpServletRequest request) {
return FileUploadUtil.upload(base64, request);
}
@ResponseBody
@GetMapping("/enQrcode")
public void enQrcode(HttpServletResponse resp, String url) throws IOException {
if (url != null && !"".equals(url)) {
ServletOutputStream stream = null;
try {
int width = 240;//图片的宽度
int height = 240;//高度
/*
* 定义二维码的参数
*/
HashMap hashMap = new HashMap();
// 设置二维码字符编码
hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 设置二维码纠错等级
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 设置二维码边距
hashMap.put(EncodeHintType.MARGIN, 1);
stream = resp.getOutputStream();
QRCodeWriter writer = new QRCodeWriter();
BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width, hashMap);
MatrixToImageWriter.writeToStream(m, "png", stream);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}
}
@PostMapping("/import")
@ResponseBody
public void importZip(@RequestParam("file") MultipartFile file) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream(), Charset.forName("gbk"));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
if (!zipEntry.isDirectory()) {
// do nothing
String name = zipEntry.getName();
long size = zipEntry.getSize();
byte[] extra = zipEntry.getExtra();
if (size == -1) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true) {
int bytes = zipInputStream.read();
if (bytes == -1) break;
baos.write(bytes);
}
baos.close();
System.out.println(baos.toString());
} else {
byte[] bytes = new byte[(int) zipEntry.getSize()];
zipInputStream.read(bytes, 0, (int) zipEntry.getSize());
System.out.println(new String(bytes));
}
}
}
zipInputStream.closeEntry();
zipInputStream.close();
}
/**
* 预览文件
*/
@GetMapping("/{dir}/{name:.+}")
public void file(@PathVariable("dir") String dir, @PathVariable("name") String name, Integer width, Integer height, HttpServletResponse response) {
if (width != null && width > 0 && height != null && height > 0) {
PicUtils.changeSize(dir + "/" + name, width, height, response);
} else {
FileUploadUtil.preview(dir + "/" + name, response);
}
}
/**
* 下载文件
*/
@GetMapping("/download/{dir}/{name:.+}")
public void downloadFile(@PathVariable("dir") String dir, @PathVariable("name") String name, HttpServletResponse response) {
FileUploadUtil.download(dir + "/" + name, response);
}
/**
* 查看缩略图
*/
@GetMapping("/thumbnail/{dir}/{name:.+}")
public void smFile(@PathVariable("dir") String dir, @PathVariable("name") String name, HttpServletResponse response) {
FileUploadUtil.thumbnail(dir + "/" + name, response);
}
/**
* 删除文件
*/
@OperLog(value = "文件管理", desc = "删除文件", result = true)
@RequiresPermissions("sys:file:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(String path) {
if (path == null || path.trim().isEmpty()) {
return JsonResult.error("参数不能为空");
}
if (FileUploadUtil.delete(path)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 查询文件列表
*/
@OperLog(value = "文件管理", desc = "查询全部")
@RequiresPermissions("sys:file:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(String dir) {
List<Map<String, Object>> list = FileUploadUtil.list(dir);
list.sort(new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
return ((Long) o2.get("updateTime")).compareTo((Long) o1.get("updateTime"));
}
});
return JsonResult.ok().setData(list);
}
}

View File

@@ -0,0 +1,75 @@
package com.bomaos.common.system.controller;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.common.system.entity.LoginRecord;
import com.bomaos.common.system.service.LoginRecordService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 登录日志
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/sys/loginRecord")
public class LoginRecordController extends BaseController {
@Autowired
private LoginRecordService loginRecordService;
@RequiresPermissions("sys:login_record:view")
@RequestMapping()
public String view() {
return "system/login-record.html";
}
/**
* 分页查询登录日志
*/
@OperLog(value = "登录日志", desc = "分页查询")
@RequiresPermissions("sys:login_record:view")
@ResponseBody
@RequestMapping("/page")
public PageResult<LoginRecord> page(HttpServletRequest request) {
PageParam<LoginRecord> pageParam = new PageParam<>(request);
pageParam.setDefaultOrder(null, new String[]{"create_time"});
return loginRecordService.listPage(pageParam);
}
/**
* 查询全部登录日志
*/
@OperLog(value = "登录日志", desc = "查询全部")
@RequiresPermissions("sys:login_record:view")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<LoginRecord> pageParam = new PageParam<>(request);
List<LoginRecord> records = loginRecordService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.sortRecords(records));
}
/**
* 根据id查询登录日志
*/
@OperLog(value = "登录日志", desc = "根据id查询")
@RequiresPermissions("sys:login_record:view")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
PageParam<LoginRecord> pageParam = new PageParam<>();
pageParam.put("id", id);
List<LoginRecord> records = loginRecordService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.getOne(records));
}
}

View File

@@ -0,0 +1,183 @@
package com.bomaos.common.system.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.system.entity.LoginRecord;
import com.bomaos.common.system.entity.Menu;
import com.bomaos.common.system.service.LoginRecordService;
import com.bomaos.common.system.service.MenuService;
import com.bomaos.settings.entity.Pays;
import com.bomaos.settings.service.PaysService;
import com.bomaos.website.entity.Website;
import com.bomaos.website.service.WebsiteService;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 首页、登录、验证码等
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
public class MainController extends BaseController implements ErrorController {
@Autowired
private MenuService menuService;
@Autowired
private LoginRecordService loginRecordService;
@Autowired
private WebsiteService websiteService;
@Autowired
private PaysService paysService;
/**
* 用户登录
*/
@ResponseBody
@PostMapping("/login")
public JsonResult login(String username, String password, String code, Boolean remember, HttpServletRequest request) {
if (username == null || username.trim().isEmpty()) return JsonResult.error("请输入账号");
if (!CaptchaUtil.ver(code, request)) {
CaptchaUtil.clear(request); // 清除session中的验证码
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, "验证码错误", request);
return JsonResult.error("验证码不正确");
}
try {
if (remember == null) remember = false;
SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));
loginRecordService.saveAsync(username, request);
return JsonResult.ok("登录成功");
} catch (IncorrectCredentialsException ice) {
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, "密码错误", request);
return JsonResult.error("密码错误");
} catch (UnknownAccountException uae) {
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, "账号不存在", request);
return JsonResult.error("账号不存在");
} catch (LockedAccountException e) {
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, "账号被锁定", request);
return JsonResult.error("账号被锁定");
} catch (ExcessiveAttemptsException eae) {
loginRecordService.saveAsync(username, LoginRecord.TYPE_ERROR, "操作频繁", request);
return JsonResult.error("操作频繁,请稍后再试");
}
}
/**
* 登录页
*/
@GetMapping("/login")
public String login(Model model) {
Website website = websiteService.getById(1);
model.addAttribute("website", website);
if (getLoginUser() != null) return "redirect:index";
return "login.html";
}
/**
* 主页
*/
@RequestMapping("/admin")
public String index(Model model) {
Pays paypal = paysService.getOne(new QueryWrapper<Pays>().eq("driver", "paypal"));
Pays zlqqpay = paysService.getOne(new QueryWrapper<Pays>().eq("driver", "epay_qqpay"));
if (ObjectUtils.isEmpty(paypal)) {
Pays pays1 = new Pays();
pays1.setName("Paypal");
pays1.setDriver("paypal");
Map<String, String> map = new HashMap<>();
map.put("clientId", "xxx");
map.put("clientSecret", "xxx");
map.put("return_url", "xxx");
String jsonString = JSON.toJSONString(map);
pays1.setConfig(jsonString);
pays1.setComment("Paypal 境外支付(默认美元交易)");
pays1.setIsMobile(0);
pays1.setIsPc(0);
pays1.setCreatedAt(new Date());
pays1.setUpdatedAt(new Date());
paysService.save(pays1);
}
if (ObjectUtils.isEmpty(zlqqpay)) {
Pays pays1 = new Pays();
pays1.setName("QQ钱包");
pays1.setDriver("epay_qqpay");
Map<String, String> map = new HashMap<>();
map.put("pid", "xxx");
map.put("key", "xxx");
map.put("notify_url", "xxx");
map.put("create_url", "xxx");
String jsonString = JSON.toJSONString(map);
pays1.setConfig(jsonString);
pays1.setComment("易支付 - QQ钱包");
pays1.setIsMobile(0);
pays1.setIsPc(0);
pays1.setCreatedAt(new Date());
pays1.setUpdatedAt(new Date());
paysService.save(pays1);
}
Website website = websiteService.getById(1);
model.addAttribute("website", website);
// 左侧菜单
List<Menu> menus = menuService.getUserMenu(getLoginUserId(), Menu.TYPE_MENU);
model.addAttribute("menus", menuService.toMenuTree(menus, 0));
return "main.html";
}
/**
* 图形验证码
*/
@RequestMapping("/assets/captcha")
public void captcha(HttpServletRequest request, HttpServletResponse response) {
try {
CaptchaUtil.out(5, request, response);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 主页弹窗页面
*/
@RequestMapping("/tpl/{name}")
public String tpl(@PathVariable("name") String name) {
return "index/" + name + ".html";
}
/**
* 错误页
*/
@RequestMapping("/error")
public String error() {
return "error/404.html";
}
}

View File

@@ -0,0 +1,154 @@
package com.bomaos.common.system.controller;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.*;
import com.bomaos.common.system.entity.Menu;
import com.bomaos.common.system.service.MenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 菜单管理
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/sys/menu")
public class MenuController extends BaseController {
@Autowired
private MenuService menuService;
@RequiresPermissions("sys:menu:view")
@RequestMapping()
public String view() {
return "system/menu.html";
}
/**
* 分页查询菜单
*/
@OperLog(value = "菜单管理", desc = "分页查询")
@RequiresPermissions("sys:menu:list")
@ResponseBody
@RequestMapping("/page")
public PageResult<Menu> page(HttpServletRequest request) {
PageParam<Menu> pageParam = new PageParam<>(request);
pageParam.setDefaultOrder(new String[]{"sort_number"}, null);
return menuService.listPage(pageParam);
}
/**
* 查询全部菜单
*/
@OperLog(value = "菜单管理", desc = "查询全部")
@RequiresPermissions("sys:menu:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<Menu> pageParam = new PageParam<>(request);
pageParam.setDefaultOrder(new String[]{"sort_number"}, null);
return JsonResult.ok().setData(menuService.list(pageParam.getOrderWrapper()));
}
/**
* 根据id查询菜单
*/
@OperLog(value = "菜单管理", desc = "根据id查询")
@RequiresPermissions("sys:menu:list")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
return JsonResult.ok().setData(menuService.getById(id));
}
/**
* 添加菜单
*/
@OperLog(value = "菜单管理", desc = "添加", param = false, result = true)
@RequiresPermissions("sys:menu:save")
@ResponseBody
@RequestMapping("/save")
public JsonResult save(Menu menu) {
if (menuService.save(menu)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改菜单
*/
@OperLog(value = "菜单管理", desc = "修改", param = false, result = true)
@RequiresPermissions("sys:menu:update")
@ResponseBody
@RequestMapping("/update")
public JsonResult update(Menu menu) {
if (menuService.updateById(menu)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除菜单
*/
@OperLog(value = "菜单管理", desc = "删除", result = true)
@RequiresPermissions("sys:menu:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (menuService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量添加菜单
*/
@OperLog(value = "菜单管理", desc = "批量添加", param = false, result = true)
@RequiresPermissions("sys:menu:save")
@ResponseBody
@RequestMapping("/saveBatch")
public JsonResult saveBatch(@RequestBody List<Menu> menuList) {
if (menuService.saveBatch(menuList)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 批量修改菜单
*/
@OperLog(value = "菜单管理", desc = "批量修改", result = true)
@RequiresPermissions("sys:menu:update")
@ResponseBody
@RequestMapping("/updateBatch")
public JsonResult updateBatch(@RequestBody BatchParam<Menu> batchParam) {
if (batchParam.update(menuService, "menu_id")) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 批量删除菜单
*/
@OperLog(value = "菜单管理", desc = "批量删除", result = true)
@RequiresPermissions("sys:menu:remove")
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (menuService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
}

View File

@@ -0,0 +1,75 @@
package com.bomaos.common.system.controller;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.common.system.entity.OperRecord;
import com.bomaos.common.system.service.OperRecordService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 操作日志
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/sys/operRecord")
public class OperRecordController extends BaseController {
@Autowired
private OperRecordService operLogService;
@RequiresPermissions("sys:oper_record:view")
@RequestMapping()
public String view() {
return "system/oper-record.html";
}
/**
* 分页查询操作日志
*/
@OperLog(value = "操作日志", desc = "分页查询")
@RequiresPermissions("sys:oper_record:view")
@ResponseBody
@RequestMapping("/page")
public PageResult<OperRecord> page(HttpServletRequest request) {
PageParam<OperRecord> pageParam = new PageParam<>(request);
pageParam.setDefaultOrder(null, new String[]{"create_time"});
return operLogService.listPage(pageParam);
}
/**
* 查询全部操作日志
*/
@OperLog(value = "操作日志", desc = "查询全部")
@RequiresPermissions("sys:oper_record:view")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<OperRecord> pageParam = new PageParam<>(request);
List<OperRecord> records = operLogService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.sortRecords(records));
}
/**
* 根据id查询操作日志
*/
@OperLog(value = "操作日志", desc = "根据id查询")
@RequiresPermissions("sys:oper_record:view")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
PageParam<OperRecord> pageParam = new PageParam<>();
pageParam.put("id", id);
List<OperRecord> records = operLogService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.getOne(records));
}
}

View File

@@ -0,0 +1,183 @@
package com.bomaos.common.system.controller;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.*;
import com.bomaos.common.system.entity.Organization;
import com.bomaos.common.system.service.DictionaryDataService;
import com.bomaos.common.system.service.OrganizationService;
import com.bomaos.common.system.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 组织机构管理
* Created by AutoGenerator on 2020-03-14 11:29:04
*/
@Controller
@RequestMapping("/sys/organization")
public class OrganizationController extends BaseController {
@Autowired
private OrganizationService organizationService;
@Autowired
private DictionaryDataService dictionaryDataService;
@Autowired
private RoleService roleService;
@RequiresPermissions("sys:org:view")
@RequestMapping()
public String view(Model model) {
model.addAttribute("sexList", dictionaryDataService.listByDictCode("sex"));
model.addAttribute("organizationTypeList", dictionaryDataService.listByDictCode("organization_type"));
model.addAttribute("rolesJson", JSON.toJSONString(roleService.list()));
return "system/organization.html";
}
/**
* 分页查询组织机构
*/
@OperLog(value = "机构管理", desc = "分页查询")
@RequiresPermissions("sys:org:list")
@ResponseBody
@RequestMapping("/page")
public PageResult<Organization> page(HttpServletRequest request) {
PageParam<Organization> pageParam = new PageParam<>(request);
return organizationService.listPage(pageParam);
}
/**
* 查询全部组织机构
*/
@OperLog(value = "机构管理", desc = "查询全部")
@RequiresPermissions("sys:org:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<Organization> pageParam = new PageParam<>(request);
List<Organization> records = organizationService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.sortRecords(records));
}
/**
* 根据id查询组织机构
*/
@OperLog(value = "机构管理", desc = "根据id查询")
@RequiresPermissions("sys:org:list")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
PageParam<Organization> pageParam = new PageParam<>();
pageParam.put("organizationId", id);
List<Organization> records = organizationService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.getOne(records));
}
/**
* 添加组织机构
*/
@OperLog(value = "机构管理", desc = "添加", param = false, result = true)
@RequiresPermissions("sys:org:save")
@ResponseBody
@RequestMapping("/save")
public JsonResult add(Organization organization) {
if (organization.getParentId() == null) organization.setParentId(0);
if (organizationService.count(new QueryWrapper<Organization>()
.eq("organization_name", organization.getOrganizationName())
.eq("parent_id", organization.getParentId())) > 0) {
return JsonResult.error("机构名称已存在");
}
if (organizationService.save(organization)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改组织机构
*/
@OperLog(value = "机构管理", desc = "修改", param = false, result = true)
@RequiresPermissions("sys:org:update")
@ResponseBody
@RequestMapping("/update")
public JsonResult update(Organization organization) {
if (organization.getOrganizationName() != null) {
if (organization.getParentId() == null) organization.setParentId(0);
if (organizationService.count(new QueryWrapper<Organization>()
.eq("organization_name", organization.getOrganizationName())
.eq("parent_id", organization.getParentId())
.ne("organization_id", organization.getOrganizationId())) > 0) {
return JsonResult.error("机构名称已存在");
}
}
if (organizationService.updateById(organization)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除组织机构
*/
@OperLog(value = "机构管理", desc = "删除", result = true)
@RequiresPermissions("sys:org:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (organizationService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量添加组织机构
*/
@OperLog(value = "机构管理", desc = "批量添加", param = false, result = true)
@RequiresPermissions("sys:org:save")
@ResponseBody
@RequestMapping("/saveBatch")
public JsonResult saveBatch(@RequestBody List<Organization> organizationList) {
if (organizationService.saveBatch(organizationList)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 批量修改组织机构
*/
@OperLog(value = "机构管理", desc = "批量修改", result = true)
@RequiresPermissions("sys:org:update")
@ResponseBody
@RequestMapping("/updateBatch")
public JsonResult updateBatch(@RequestBody BatchParam<Organization> batchParam) {
if (batchParam.update(organizationService, "organization_id")) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 批量删除组织机构
*/
@OperLog(value = "机构管理", desc = "批量删除", result = true)
@RequiresPermissions("sys:org:remove")
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (organizationService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
}

View File

@@ -0,0 +1,174 @@
package com.bomaos.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.utils.CoreUtil;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.core.web.PageParam;
import com.bomaos.common.core.web.PageResult;
import com.bomaos.common.system.entity.Role;
import com.bomaos.common.system.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
/**
* 角色管理
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/sys/role")
public class RoleController extends BaseController {
@Autowired
private RoleService roleService;
@RequiresPermissions("sys:role:view")
@RequestMapping()
public String view() {
return "system/role.html";
}
/**
* 分页查询角色
*/
@OperLog(value = "角色管理", desc = "分页查询")
@RequiresPermissions("sys:role:list")
@ResponseBody
@RequestMapping("/page")
public PageResult<Role> page(HttpServletRequest request) {
PageParam<Role> pageParam = new PageParam<>(request);
return new PageResult<>(roleService.page(pageParam, pageParam.getWrapper()).getRecords(), pageParam.getTotal());
}
/**
* 查询全部角色
*/
@OperLog(value = "角色管理", desc = "查询全部")
@RequiresPermissions("sys:role:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<Role> pageParam = new PageParam<>(request);
return JsonResult.ok().setData(roleService.list(pageParam.getOrderWrapper()));
}
/**
* 根据id查询角色
*/
@OperLog(value = "角色管理", desc = "根据id查询")
@RequiresPermissions("sys:role:list")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
return JsonResult.ok().setData(roleService.getById(id));
}
/**
* 添加角色
*/
@OperLog(value = "角色管理", desc = "添加", param = false, result = true)
@RequiresPermissions("sys:role:save")
@ResponseBody
@RequestMapping("/save")
public JsonResult save(Role role) {
if (roleService.count(new QueryWrapper<Role>().eq("role_code", role.getRoleCode())) > 0) {
return JsonResult.error("角色标识已存在");
}
if (roleService.count(new QueryWrapper<Role>().eq("role_name", role.getRoleName())) > 0) {
return JsonResult.error("角色名称已存在");
}
if (roleService.save(role)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改角色
*/
@OperLog(value = "角色管理", desc = "修改", param = false, result = true)
@RequiresPermissions("sys:role:update")
@ResponseBody
@RequestMapping("/update")
public JsonResult update(Role role) {
if (role.getRoleCode() != null && roleService.count(new QueryWrapper<Role>().eq("role_code", role.getRoleCode())
.ne("role_id", role.getRoleId())) > 0) {
return JsonResult.error("角色标识已存在");
}
if (role.getRoleName() != null && roleService.count(new QueryWrapper<Role>().eq("role_name", role.getRoleName())
.ne("role_id", role.getRoleId())) > 0) {
return JsonResult.error("角色名称已存在");
}
if (roleService.updateById(role)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除角色
*/
@OperLog(value = "角色管理", desc = "删除", result = true)
@RequiresPermissions("sys:role:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (roleService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量添加角色
*/
@OperLog(value = "角色管理", desc = "批量添加", param = false, result = true)
@RequiresPermissions("sys:role:save")
@ResponseBody
@RequestMapping("/saveBatch")
public JsonResult saveBatch(@RequestBody List<Role> list) {
// 对集合本身进行非空和重复校验
StringBuilder sb = new StringBuilder();
sb.append(CoreUtil.listCheckBlank(list, "roleCode", "角色标识"));
sb.append(CoreUtil.listCheckBlank(list, "roleName", "角色名称"));
sb.append(CoreUtil.listCheckRepeat(list, "roleCode", "角色标识"));
sb.append(CoreUtil.listCheckRepeat(list, "roleName", "角色名称"));
if (sb.length() != 0) return JsonResult.error(sb.toString());
// 数据库层面校验
if (roleService.count(new QueryWrapper<Role>().in("role_code",
list.stream().map(Role::getRoleCode).collect(Collectors.toList()))) > 0) {
return JsonResult.error("角色标识已存在");
}
if (roleService.count(new QueryWrapper<Role>().in("role_name",
list.stream().map(Role::getRoleName).collect(Collectors.toList()))) > 0) {
return JsonResult.error("角色名称已存在");
}
if (roleService.saveBatch(list)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 批量删除角色
*/
@OperLog(value = "角色管理", desc = "批量删除", result = true)
@RequiresPermissions("sys:role:remove")
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (roleService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
}

View File

@@ -0,0 +1,119 @@
package com.bomaos.common.system.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.exception.BusinessException;
import com.bomaos.common.core.web.BaseController;
import com.bomaos.common.core.web.JsonResult;
import com.bomaos.common.system.entity.Menu;
import com.bomaos.common.system.entity.RoleMenu;
import com.bomaos.common.system.service.MenuService;
import com.bomaos.common.system.service.RoleMenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
/**
* 角色菜单管理
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/sys/role/menu")
public class RoleMenuController extends BaseController {
@Autowired
private RoleMenuService roleMenuService;
@Autowired
private MenuService menuService;
/**
* 查询角色菜单
*/
@OperLog(value = "角色管理", desc = "查询角色菜单")
@RequiresPermissions("sys:role:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(Integer roleId) {
List<Menu> menus = menuService.list(new QueryWrapper<Menu>().orderByAsc("sort_number"));
List<RoleMenu> roleMenus = roleMenuService.list(new QueryWrapper<RoleMenu>().eq("role_id", roleId));
for (Menu menu : menus) {
menu.setOpen(true);
menu.setChecked(false);
for (RoleMenu roleMenu : roleMenus) {
if (menu.getMenuId().equals(roleMenu.getMenuId())) {
menu.setChecked(true);
break;
}
}
}
return JsonResult.ok().setData(menus);
}
/**
* 添加角色菜单
*/
@OperLog(value = "角色管理", desc = "添加角色菜单")
@RequiresPermissions("sys:role:update")
@ResponseBody
@RequestMapping("/save")
public JsonResult addRoleAuth(Integer roleId, Integer menuId) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
if (roleMenuService.save(roleMenu)) {
return JsonResult.ok();
}
return JsonResult.error();
}
/**
* 移除角色菜单
*/
@OperLog(value = "角色管理", desc = "移除角色菜单")
@RequiresPermissions("sys:role:update")
@ResponseBody
@RequestMapping("/remove")
public JsonResult removeRoleAuth(Integer roleId, Integer menuId) {
if (roleMenuService.remove(new UpdateWrapper<RoleMenu>()
.eq("role_id", roleId).eq("menuId", menuId))) {
return JsonResult.ok();
}
return JsonResult.error();
}
/**
* 批量修改角色菜单
*/
@OperLog(value = "角色管理", desc = "修改角色菜单")
@RequiresPermissions("sys:role:update")
@Transactional
@ResponseBody
@RequestMapping("/update/{id}")
public JsonResult setRoleAuth(@PathVariable("id") Integer roleId, @RequestBody List<Integer> menuIds) {
roleMenuService.remove(new UpdateWrapper<RoleMenu>().eq("role_id", roleId));
if (menuIds.size() > 0) {
List<RoleMenu> roleMenuList = new ArrayList<>();
for (Integer menuId : menuIds) {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenuList.add(roleMenu);
}
if (roleMenuService.saveBatch(roleMenuList)) {
return JsonResult.ok("保存成功");
} else {
throw new BusinessException("操作失败");
}
}
return JsonResult.ok("保存成功");
}
}

View File

@@ -0,0 +1,130 @@
package com.bomaos.common.system.controller;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.web.*;
import com.bomaos.common.system.entity.Supplier;
import com.bomaos.common.system.service.SupplierService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
/**
* 供应商管理
*/
@Controller
@RequestMapping("/sys/supplier")
public class SupplierController extends BaseController {
@Autowired
private SupplierService supplierService;
@RequiresPermissions("sys:supplier:view")
@RequestMapping()
public String view() {
return "system/supplier.html";
}
/**
* 分页查询供应商
*/
@RequiresPermissions("sys:supplier:list")
@OperLog(value = "供应商管理", desc = "分页查询")
@ResponseBody
@RequestMapping("/page")
public PageResult<Supplier> page(HttpServletRequest request) {
PageParam<Supplier> pageParam = new PageParam<>(request);
pageParam.setDefaultOrder(null, new String[]{"create_time"});
return supplierService.listPage(pageParam);
}
/**
* 查询全部供应商
*/
@RequiresPermissions("sys:supplier:list")
@OperLog(value = "供应商管理", desc = "查询全部")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<Supplier> pageParam = new PageParam<>(request);
List<Supplier> records = supplierService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.sortRecords(records));
}
/**
* 根据id查询供应商
*/
@RequiresPermissions("sys:supplier:list")
@OperLog(value = "供应商管理", desc = "根据id查询")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
return JsonResult.ok().setData(supplierService.getById(id));
}
/**
* 添加供应商
*/
@RequiresPermissions("sys:supplier:save")
@OperLog(value = "供应商管理", desc = "添加", param = false, result = true)
@ResponseBody
@RequestMapping("/save")
public JsonResult save(Supplier supplier) {
supplier.setCreateTime(new Date());
supplier.setUpdateTime(new Date());
if (supplierService.save(supplier)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改供应商
*/
@RequiresPermissions("sys:supplier:update")
@OperLog(value = "供应商管理", desc = "修改", param = false, result = true)
@ResponseBody
@RequestMapping("/update")
public JsonResult update(Supplier supplier) {
supplier.setUpdateTime(new Date());
if (supplierService.updateById(supplier)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除供应商
*/
@RequiresPermissions("sys:supplier:remove")
@OperLog(value = "供应商管理", desc = "删除", result = true)
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (supplierService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量删除供应商
*/
@RequiresPermissions("sys:supplier:remove")
@OperLog(value = "供应商管理", desc = "批量删除", result = true)
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (supplierService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
}

View File

@@ -0,0 +1,412 @@
package com.bomaos.common.system.controller;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bomaos.common.core.annotation.OperLog;
import com.bomaos.common.core.utils.CoreUtil;
import com.bomaos.common.core.web.*;
import com.bomaos.common.system.entity.DictionaryData;
import com.bomaos.common.system.entity.Organization;
import com.bomaos.common.system.entity.Role;
import com.bomaos.common.system.entity.User;
import com.bomaos.common.system.entity.Supplier;
import com.bomaos.common.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 用户管理
* Created by Panyoujie on 2018-12-24 16:10
*/
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {
@Autowired
private UserService userService;
@Autowired
private DictionaryDataService dictionaryDataService;
@Autowired
private RoleService roleService;
@Autowired
private OrganizationService organizationService;
@Autowired
private SupplierService supplierService;
@RequiresPermissions("sys:user:view")
@RequestMapping()
public String view(Model model) {
model.addAttribute("sexList", dictionaryDataService.listByDictCode("sex"));
model.addAttribute("organizationTypeList", dictionaryDataService.listByDictCode("organization_type"));
model.addAttribute("rolesJson", JSON.toJSONString(roleService.list()));
model.addAttribute("supplierListJson", JSON.toJSONString(supplierService.list()));
return "system/user.html";
}
/**
* 个人中心
*/
@RequestMapping("/info")
public String userInfo(Model model) {
model.addAttribute("user", userService.getFullById(getLoginUserId()));
model.addAttribute("sexList", dictionaryDataService.listByDictCode("sex"));
return "index/user-info.html";
}
/**
* 分页查询用户
*/
@OperLog(value = "用户管理", desc = "分页查询")
@RequiresPermissions("sys:user:list")
@ResponseBody
@RequestMapping("/page")
public PageResult<User> page(HttpServletRequest request) {
PageParam<User> pageParam = new PageParam<>(request);
pageParam.setDefaultOrder(null, new String[]{"create_time"});
return userService.listPage(pageParam);
}
/**
* 查询全部用户
*/
@OperLog(value = "用户管理", desc = "查询全部")
@RequiresPermissions("sys:user:list")
@ResponseBody
@RequestMapping("/list")
public JsonResult list(HttpServletRequest request) {
PageParam<User> pageParam = new PageParam<>(request);
List<User> records = userService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.sortRecords(records));
}
/**
* 根据id查询用户
*/
@OperLog(value = "用户管理", desc = "根据id查询")
@RequiresPermissions("sys:user:list")
@ResponseBody
@RequestMapping("/get")
public JsonResult get(Integer id) {
PageParam<User> pageParam = new PageParam<>();
pageParam.put("userId", id);
List<User> records = userService.listAll(pageParam.getNoPageParam());
return JsonResult.ok().setData(pageParam.getOne(records));
}
/**
* 添加用户
*/
@OperLog(value = "用户管理", desc = "添加", param = false, result = true)
@RequiresPermissions("sys:user:save")
@ResponseBody
@RequestMapping("/save")
public JsonResult save(@RequestBody User user) {
user.setState(0);
user.setPassword(userService.encodePsw(user.getPassword()));
if (userService.saveUser(user)) {
return JsonResult.ok("添加成功");
}
return JsonResult.error("添加失败");
}
/**
* 修改用户
*/
@OperLog(value = "用户管理", desc = "修改", param = false, result = true)
@RequiresPermissions("sys:user:update")
@ResponseBody
@RequestMapping("/update")
public JsonResult update(@RequestBody User user) {
user.setState(null); // 状态不能修改
user.setPassword(null); // 密码不能修改
user.setUsername(null); // 账号不能修改
if (userService.updateUser(user)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 删除用户
*/
@OperLog(value = "用户管理", desc = "删除", result = true)
@RequiresPermissions("sys:user:remove")
@ResponseBody
@RequestMapping("/remove")
public JsonResult remove(Integer id) {
if (userService.removeById(id)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 批量修改用户
*/
@OperLog(value = "用户管理", desc = "批量修改", param = false, result = true)
@RequiresPermissions("sys:user:update")
@ResponseBody
@RequestMapping("/updateBatch")
public JsonResult updateBatch(@RequestBody BatchParam<User> batchParam) {
// 不能修改的字段
batchParam.getData().setPassword(null);
batchParam.getData().setState(null);
batchParam.getData().setUsername(null);
batchParam.getData().setPhone(null);
batchParam.getData().setEmail(null);
if (batchParam.update(userService, "user_id")) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 批量删除用户
*/
@OperLog(value = "用户管理", desc = "批量删除", result = true)
@RequiresPermissions("sys:user:remove")
@ResponseBody
@RequestMapping("/removeBatch")
public JsonResult removeBatch(@RequestBody List<Integer> ids) {
if (userService.removeByIds(ids)) {
return JsonResult.ok("删除成功");
}
return JsonResult.error("删除失败");
}
/**
* 修改用户状态
*/
@OperLog(value = "用户管理", desc = "修改状态", result = true)
@RequiresPermissions("sys:user:update")
@ResponseBody
@RequestMapping("/state/update")
public JsonResult updateState(Integer id, Integer state) {
if (state == null || (state != 0 && state != 1)) {
return JsonResult.error("状态值不正确");
}
User user = new User();
user.setUserId(id);
user.setState(state);
if (userService.updateById(user)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 批量修改用户状态
*/
@OperLog(value = "用户管理", desc = "批量修改状态", result = true)
@RequiresPermissions("sys:user:update")
@ResponseBody
@RequestMapping("/state/updateBatch")
public JsonResult updateStateBatch(@RequestBody BatchParam<User> batchParam) {
User user = new User();
user.setState(batchParam.getData().getState());
if (user.getState() == null || (user.getState() != 0 && user.getState() != 1)) {
return JsonResult.error("状态值不正确");
}
if (batchParam.update(userService, "user_id")) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 重置密码
*/
@OperLog(value = "用户管理", desc = "重置密码", param = false, result = true)
@RequiresPermissions("sys:user:update")
@ResponseBody
@RequestMapping("/psw/reset")
public JsonResult resetPsw(Integer id, String password) {
User user = new User();
user.setUserId(id);
user.setPassword(userService.encodePsw(password));
if (userService.updateById(user)) {
return JsonResult.ok("重置成功");
} else {
return JsonResult.error("重置失败");
}
}
/**
* 批量重置密码
*/
@OperLog(value = "用户管理", desc = "批量重置密码", param = false, result = true)
@RequiresPermissions("sys:user:update")
@ResponseBody
@RequestMapping("/psw/resetBatch")
public JsonResult resetPswBatch(@RequestBody BatchParam<User> batchParam) {
User user = new User();
user.setPassword(userService.encodePsw(batchParam.getData().getPassword()));
if (batchParam.update(userService, "user_id")) {
return JsonResult.ok("重置成功");
} else {
return JsonResult.error("重置失败");
}
}
/**
* 修改自己密码
*/
@OperLog(value = "用户管理", desc = "修改自己密码", param = false, result = true)
@ResponseBody
@RequestMapping("/psw/update")
public JsonResult updatePsw(String oldPsw, String newPsw) {
if (StrUtil.hasBlank(oldPsw, newPsw)) {
return JsonResult.error("参数不能为空");
}
if (getLoginUserId() == null) {
return JsonResult.error("未登录");
}
if (!userService.comparePsw(userService.getById(getLoginUserId()).getPassword(), oldPsw)) {
return JsonResult.error("原密码输入不正确");
}
User user = new User();
user.setUserId(getLoginUserId());
user.setPassword(userService.encodePsw(newPsw));
if (userService.updateById(user)) {
return JsonResult.ok("修改成功");
}
return JsonResult.error("修改失败");
}
/**
* 修改自己资料
*/
@OperLog(value = "用户管理", desc = "修改个人信息", param = false, result = true)
@ResponseBody
@RequestMapping("/info/update")
public JsonResult updateInfo(User user) {
user.setUserId(getLoginUserId());
// 不能修改的字段
user.setState(null);
user.setPassword(null);
user.setUsername(null);
user.setOrganizationId(null);
if (userService.updateById(user)) {
User loginUser = getLoginUser();
if (user.getNickName() != null) loginUser.setNickName(user.getNickName());
if (user.getAvatar() != null) loginUser.setAvatar(user.getAvatar());
return JsonResult.ok("保存成功").setData(userService.getFullById(user.getUserId()));
}
return JsonResult.error("保存失败");
}
/**
* excel导入用户
*/
@Transactional
@OperLog(value = "用户管理", desc = "excel导入", param = false, result = true)
@RequiresPermissions("sys:user:save")
@ResponseBody
@RequestMapping("/import")
public JsonResult importBatch(MultipartFile file) {
StringBuilder sb = new StringBuilder();
try {
// 读取excel
int startRow = 1;
ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), 0);
List<List<Object>> list = reader.read(startRow);
// 进行非空和重复检查
sb.append(CoreUtil.excelCheckBlank(list, startRow, 0, 1, 2, 3, 4, 7));
sb.append(CoreUtil.excelCheckRepeat(list, startRow, 0, 5, 6));
if (!sb.toString().isEmpty()) return JsonResult.error(sb.toString());
// 进行数据库层面检查
List<User> users = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
List<Object> objects = list.get(i);
String username = String.valueOf(objects.get(0)); // 账号
String password = String.valueOf(objects.get(1)); // 密码
String nickName = String.valueOf(objects.get(2)); // 用户名
String sexName = String.valueOf(objects.get(3)); // 性别
String roleName = String.valueOf(objects.get(4)); // 角色名
String phone = String.valueOf(objects.get(5)); // 手机号
String email = String.valueOf(objects.get(6)); // 邮箱
String orgName = String.valueOf(objects.get(7)); // 组织机构
if (userService.count(new QueryWrapper<User>().eq("username", username)) > 0) {
sb.append("");
sb.append(i + startRow + 1);
sb.append("行第1");
sb.append("列账号已存在;\r\n");
}
if (StrUtil.isNotBlank(phone) && userService.count(new QueryWrapper<User>().eq("phone", phone)) > 0) {
sb.append("");
sb.append(i + startRow + 1);
sb.append("行第6");
sb.append("列手机号已存在;\r\n");
}
if (StrUtil.isNotBlank(email) && userService.count(new QueryWrapper<User>().eq("email", email)) > 0) {
sb.append("");
sb.append(i + startRow + 1);
sb.append("行第7");
sb.append("列邮箱已存在;\r\n");
}
User user = new User();
user.setUsername(username);
user.setNickName(nickName);
user.setPassword(userService.encodePsw(password));
user.setState(0);
user.setPhone(phone);
user.setEmail(email);
DictionaryData sexDictData = dictionaryDataService.listByDictCodeAndName("sex", sexName);
if (sexDictData == null) {
sb.append("");
sb.append(i + startRow + 1);
sb.append("行第4");
sb.append("列性别不存在;\r\n");
} else {
user.setSex(sexDictData.getDictDataId());
}
Role role = roleService.getOne(new QueryWrapper<Role>().eq("role_name", roleName), false);
if (role == null) {
sb.append("");
sb.append(i + startRow + 1);
sb.append("行第5");
sb.append("列角色不存在;\r\n");
} else {
user.setRoleIds(Collections.singletonList(role.getRoleId()));
}
Organization org = organizationService.getOne(new QueryWrapper<Organization>().eq("organization_full_name", orgName), false);
if (org == null) {
sb.append("");
sb.append(i + startRow + 1);
sb.append("行第8");
sb.append("列机构不存在;\r\n");
} else {
user.setOrganizationId(org.getOrganizationId());
}
users.add(user);
}
if (!sb.toString().isEmpty()) return JsonResult.error(sb.toString());
// 开始添加用户
int okNum = 0, errorNum = 0;
for (User user : users) {
if (userService.saveUser(user)) okNum++;
else errorNum++;
}
return JsonResult.ok("导入完成,成功" + okNum + "条,失败" + errorNum + "");
} catch (IOException e) {
e.printStackTrace();
}
return JsonResult.error("导入失败");
}
}

View File

@@ -0,0 +1,131 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* 字典
* Created by Panyoujie on 2020-03-14 11:29:03
*/
@TableName("sys_dictionary")
public class Dictionary implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 字典id
*/
@TableId(value = "dict_id", type = IdType.AUTO)
private Integer dictId;
/**
* 字典标识
*/
private String dictCode;
/**
* 字典名称
*/
private String dictName;
/**
* 排序号
*/
private Integer sortNumber;
/**
* 备注
*/
private String comments;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 是否删除,0否,1是
*/
@TableLogic
private Integer deleted;
public Integer getDictId() {
return dictId;
}
public void setDictId(Integer dictId) {
this.dictId = dictId;
}
public String getDictCode() {
return dictCode;
}
public void setDictCode(String dictCode) {
this.dictCode = dictCode;
}
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
public Integer getSortNumber() {
return sortNumber;
}
public void setSortNumber(Integer sortNumber) {
this.sortNumber = sortNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "Dictionary{" +
", dictId=" + dictId +
", dictCode=" + dictCode +
", dictName=" + dictName +
", sortNumber=" + sortNumber +
", comments=" + comments +
", createTime=" + createTime +
", updateTime=" + updateTime +
", deleted=" + deleted +
"}";
}
}

View File

@@ -0,0 +1,169 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.util.Date;
/**
* 字典项
* Created by Panyoujie on 2020-03-14 11:29:04
*/
@TableName("sys_dictionary_data")
public class DictionaryData implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 字典项id
*/
@TableId(value = "dict_data_id", type = IdType.AUTO)
private Integer dictDataId;
/**
* 字典id
*/
private Integer dictId;
/**
* 字典项标识
*/
private String dictDataCode;
/**
* 字典项名称
*/
private String dictDataName;
/**
* 排序号
*/
private Integer sortNumber;
/**
* 备注
*/
private String comments;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 是否删除,0否,1是
*/
@TableLogic
private Integer deleted;
/**
* 字典代码
*/
@TableField(exist = false)
private String dictCode;
/**
* 字典名称
*/
@TableField(exist = false)
private String dictName;
public Integer getDictDataId() {
return dictDataId;
}
public void setDictDataId(Integer dictDataId) {
this.dictDataId = dictDataId;
}
public Integer getDictId() {
return dictId;
}
public void setDictId(Integer dictId) {
this.dictId = dictId;
}
public String getDictDataCode() {
return dictDataCode;
}
public void setDictDataCode(String dictDataCode) {
this.dictDataCode = dictDataCode;
}
public String getDictDataName() {
return dictDataName;
}
public void setDictDataName(String dictDataName) {
this.dictDataName = dictDataName;
}
public Integer getSortNumber() {
return sortNumber;
}
public void setSortNumber(Integer sortNumber) {
this.sortNumber = sortNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public String getDictCode() {
return dictCode;
}
public void setDictCode(String dictCode) {
this.dictCode = dictCode;
}
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
@Override
public String toString() {
return "DictionaryData{" +
", dictDataId=" + dictDataId +
", dictId=" + dictId +
", dictDataCode=" + dictDataCode +
", dictDataName=" + dictDataName +
", sortNumber=" + sortNumber +
", comments=" + comments +
", createTime=" + createTime +
", updateTime=" + updateTime +
", deleted=" + deleted +
", dictCode=" + dictCode +
", dictName=" + dictName +
"}";
}
}

View File

@@ -0,0 +1,173 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* 登录日志
* Created by Panyoujie on 2018-12-24 16:10
*/
@TableName("sys_login_record")
public class LoginRecord implements Serializable {
private static final long serialVersionUID = 1L;
public static final int TYPE_LOGIN = 0; // 登录
public static final int TYPE_ERROR = 1; // 登录失败
public static final int TYPE_LOGOUT = 2; // 退出登录
public static final int TYPE_REFRESH = 3; // 刷新token
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户id
*/
private String username;
/**
* 操作系统
*/
private String os;
/**
* 设备名
*/
private String device;
/**
* 浏览器类型
*/
private String browser;
/**
* ip地址
*/
private String ip;
/**
* 操作类型,0登录成功,1登录失败,2退出登录,3刷新token
*/
private Integer operType;
/**
* 备注
*/
private String comments;
/**
* 操作时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 用户昵称
*/
@TableField(exist = false)
private String nickName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getBrowser() {
return browser;
}
public void setBrowser(String browser) {
this.browser = browser;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getOperType() {
return operType;
}
public void setOperType(Integer operType) {
this.operType = operType;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "LoginRecord{" +
", id=" + id +
", os=" + os +
", device=" + device +
", browser=" + browser +
", ip=" + ip +
", operType=" + operType +
", comments=" + comments +
", createTime=" + createTime +
", updateTime=" + updateTime +
", username=" + username +
", nickName=" + nickName +
"}";
}
}

View File

@@ -0,0 +1,259 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 菜单
* Created by AutoGenerator on 2018-12-24 16:10
*/
@TableName("sys_menu")
public class Menu implements Serializable {
private static final long serialVersionUID = 1L;
public static final int TYPE_MENU = 0; // 菜单类型
public static final int TYPE_BTN = 1; // 按钮类型
/**
* 菜单id
*/
@TableId(value = "menu_id", type = IdType.AUTO)
private Integer menuId;
/**
* 上级id,0是顶级
*/
private Integer parentId;
/**
* 菜单名称
*/
private String menuName;
/**
* 菜单图标
*/
private String menuIcon;
/**
* 图标颜色
*/
private String iconColor;
/**
* 菜单地址
*/
private String path;
/**
* 打开位置
*/
private String target;
/**
* 是否隐藏,0否,1是
*/
private Integer hide;
/**
* 排序号
*/
private Integer sortNumber;
/**
* 权限标识
*/
private String authority;
/**
* 菜单类型,0菜单,1按钮
*/
private Integer menuType;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 是否删除,0否,1是
*/
@TableLogic
private Integer deleted;
/**
* 上级菜单名称
*/
@TableField(exist = false)
private String parentName;
/**
* 子菜单
*/
@TableField(exist = false)
private List<Menu> children;
/**
* 回显选中状态,0未选中,1选中
*/
@TableField(exist = false)
private Boolean checked;
@TableField(exist = false)
private Boolean open;
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getIconColor() {
return iconColor;
}
public void setIconColor(String iconColor) {
this.iconColor = iconColor;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getMenuIcon() {
return menuIcon;
}
public void setMenuIcon(String menuIcon) {
this.menuIcon = menuIcon;
}
public Integer getSortNumber() {
return sortNumber;
}
public void setSortNumber(Integer sortNumber) {
this.sortNumber = sortNumber;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public Integer getHide() {
return hide;
}
public void setHide(Integer hide) {
this.hide = hide;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public Integer getMenuType() {
return menuType;
}
public void setMenuType(Integer menuType) {
this.menuType = menuType;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
@Override
public String toString() {
return "Menu{" +
", menuId=" + menuId +
", parentId=" + parentId +
", menuName=" + menuName +
", path=" + path +
", menuIcon=" + menuIcon +
", iconColor=" + iconColor +
", sortNumber=" + sortNumber +
", target=" + target +
", hide=" + hide +
", authority=" + authority +
", menuType=" + menuType +
", createTime=" + createTime +
", updateTime=" + updateTime +
", deleted=" + deleted +
", parentName=" + parentName +
"}";
}
}

View File

@@ -0,0 +1,247 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* 操作日志
* Created by Panyoujie on 2018-12-24 16:10
*/
@TableName("sys_oper_record")
public class OperRecord implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户id
*/
private Integer userId;
/**
* 模块
*/
private String model;
/**
* 方法
*/
private String description;
/**
* 请求地址
*/
private String url;
/**
* 请求方式
*/
private String requestMethod;
/**
* 调用方法
*/
private String operMethod;
/**
* 请求参数
*/
private String param;
/**
* 返回结果
*/
private String result;
/**
* ip地址
*/
private String ip;
/**
* 消耗时间,单位毫秒
*/
private Long spendTime;
/**
* 状态,0成功,1异常
*/
private Integer state;
/**
* 备注
*/
private String comments;
/**
* 操作时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 用户昵称
*/
@TableField(exist = false)
private String nickName;
/**
* 用户账号
*/
@TableField(exist = false)
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getOperMethod() {
return operMethod;
}
public void setOperMethod(String operMethod) {
this.operMethod = operMethod;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Long getSpendTime() {
return spendTime;
}
public void setSpendTime(Long spendTime) {
this.spendTime = spendTime;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "LoginRecord{" +
", id=" + id +
", userId=" + userId +
", model=" + model +
", description=" + description +
", url=" + url +
", requestMethod=" + requestMethod +
", operMethod=" + operMethod +
", param=" + param +
", result=" + result +
", ip=" + ip +
", spendTime=" + spendTime +
", state=" + state +
", comments=" + comments +
", createTime=" + createTime +
", updateTime=" + updateTime +
", nickName=" + nickName +
"}";
}
}

View File

@@ -0,0 +1,235 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.util.Date;
/**
* 组织机构
* Created by AutoGenerator on 2020-03-14 11:29:04
*/
@TableName("sys_organization")
public class Organization implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 机构id
*/
@TableId(value = "organization_id", type = IdType.AUTO)
private Integer organizationId;
/**
* 上级id,0是顶级
*/
private Integer parentId;
/**
* 机构名称
*/
private String organizationName;
/**
* 机构全称
*/
private String organizationFullName;
/**
* 机构代码
*/
private String organizationCode;
/**
* 机构类型
*/
private Integer organizationType;
/**
* 负责人id
*/
private Integer leaderId;
/**
* 排序号
*/
private Integer sortNumber;
/**
* 备注
*/
private String comments;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 是否删除,0否,1是
*/
@TableLogic
private Integer deleted;
/**
* 负责人姓名
*/
@TableField(exist = false)
private String leaderName;
/**
* 负责人账号
*/
@TableField(exist = false)
private String leaderAccount;
/**
* 上级名称
*/
@TableField(exist = false)
private String parentName;
/**
* 机构类型名称
*/
@TableField(exist = false)
private String organizationTypeName;
public Integer getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Integer organizationId) {
this.organizationId = organizationId;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
public String getOrganizationFullName() {
return organizationFullName;
}
public void setOrganizationFullName(String organizationFullName) {
this.organizationFullName = organizationFullName;
}
public String getOrganizationCode() {
return organizationCode;
}
public void setOrganizationCode(String organizationCode) {
this.organizationCode = organizationCode;
}
public Integer getOrganizationType() {
return organizationType;
}
public void setOrganizationType(Integer organizationType) {
this.organizationType = organizationType;
}
public Integer getLeaderId() {
return leaderId;
}
public void setLeaderId(Integer leaderId) {
this.leaderId = leaderId;
}
public Integer getSortNumber() {
return sortNumber;
}
public void setSortNumber(Integer sortNumber) {
this.sortNumber = sortNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public String getLeaderName() {
return leaderName;
}
public void setLeaderName(String leaderName) {
this.leaderName = leaderName;
}
public String getLeaderAccount() {
return leaderAccount;
}
public void setLeaderAccount(String leaderAccount) {
this.leaderAccount = leaderAccount;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getOrganizationTypeName() {
return organizationTypeName;
}
public void setOrganizationTypeName(String organizationTypeName) {
this.organizationTypeName = organizationTypeName;
}
@Override
public String toString() {
return "Organization{" +
", organizationId=" + organizationId +
", parentId=" + parentId +
", organizationName=" + organizationName +
", organizationFullName=" + organizationFullName +
", organizationType=" + organizationType +
", leaderId=" + leaderId +
", sortNumber=" + sortNumber +
", comments=" + comments +
", createTime=" + createTime +
", updateTime=" + updateTime +
", deleted=" + deleted +
", leaderName=" + leaderName +
", parentName=" + parentName +
", organizationTypeName=" + organizationTypeName +
"}";
}
}

View File

@@ -0,0 +1,140 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.util.Date;
/**
* 角色
* Created by AutoGenerator on 2018-12-24 16:10
*/
@TableName("sys_role")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 角色id
*/
@TableId(value = "role_id", type = IdType.AUTO)
private Integer roleId;
/**
* 角色名称
*/
private String roleName;
/**
* 角色标识
*/
private String roleCode;
/**
* 备注
*/
private String comments;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 是否删除,0否,1是
*/
@TableLogic
private Integer deleted;
/**
* 用户id
*/
@TableField(exist = false)
private Integer userId;
public Role() {
}
public Role(Integer roleId, String roleName) {
this(roleId, roleName, null);
}
public Role(Integer roleId, String roleName, String comments) {
this.roleId = roleId;
this.roleName = roleName;
this.comments = comments;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Override
public String toString() {
return "Role{" +
", roleId=" + roleId +
", roleName=" + roleName +
", comments=" + comments +
", createTime=" + createTime +
", updateTime=" + updateTime +
", deleted=" + deleted +
", userId=" + userId +
"}";
}
}

View File

@@ -0,0 +1,90 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* 角色权限
* Created by AutoGenerator on 2018-12-24 16:10
*/
@TableName("sys_role_menu")
public class RoleMenu implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 角色id
*/
private Integer roleId;
/**
* 菜单id
*/
private Integer menuId;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "RoleAuthorities{" +
", id=" + id +
", roleId=" + roleId +
", menuId=" + menuId +
", createTime=" + createTime +
", updateTime=" + updateTime +
"}";
}
}

View File

@@ -0,0 +1,52 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 供应商
*/
@Data
@ToString
@TableName("sys_supplier")
public class Supplier implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 自增ID
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 供应商名称
*/
private String name;
/**
* 联系方式
*/
private String contact;
/**
* 余额
*/
private BigDecimal balance;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}

View File

@@ -0,0 +1,350 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 用户
* Created by AutoGenerator on 2018-12-24 16:10
*/
@TableName("sys_user")
public class User implements Serializable {
private static final long serialVersionUID = 242146703513492331L;
/**
* 用户id
*/
@TableId(value = "user_id", type = IdType.AUTO)
private Integer userId;
/**
* 账号
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nickName;
/**
* 头像
*/
private String avatar;
/**
* 性别
*/
private Integer sex;
/**
* 手机号
*/
private String phone;
/**
* 邮箱
*/
private String email;
/**
* 邮箱是否验证,0否,1是
*/
private Integer emailVerified;
/**
* 真实姓名
*/
private String trueName;
/**
* 身份证号
*/
private String idCard;
/**
* 出生日期
*/
private Date birthday;
/**
* 个人简介
*/
private String introduction;
/**
* 机构id
*/
private Integer organizationId;
/**
* 供应商id
*/
private Integer supplierId;
/**
* 状态0正常1冻结
*/
private Integer state;
/**
* 注册时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 是否删除,0否,1是
*/
@TableLogic
private Integer deleted;
/**
* 权限列表
*/
@TableField(exist = false)
private List<String> authorities;
/**
* 角色列表
*/
@TableField(exist = false)
private List<Role> roles;
/**
* 角色id
*/
@TableField(exist = false)
private List<Integer> roleIds;
/**
* 机构名称
*/
@TableField(exist = false)
private String organizationName;
/**
* 性别名称
*/
@TableField(exist = false)
private String sexName;
/**
* 供应商名称
*/
@TableField(exist = false)
private String supplierName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getEmailVerified() {
return emailVerified;
}
public void setEmailVerified(Integer emailVerified) {
this.emailVerified = emailVerified;
}
public String getTrueName() {
return trueName;
}
public void setTrueName(String trueName) {
this.trueName = trueName;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public Integer getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Integer organizationId) {
this.organizationId = organizationId;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public List<String> getAuthorities() {
return authorities;
}
public void setAuthorities(List<String> authorities) {
this.authorities = authorities;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public List<Integer> getRoleIds() {
return roleIds;
}
public void setRoleIds(List<Integer> roleIds) {
this.roleIds = roleIds;
}
public String getOrganizationName() {
return organizationName;
}
public void setOrganizationName(String organizationName) {
this.organizationName = organizationName;
}
public String getSexName() {
return sexName;
}
public void setSexName(String sexName) {
this.sexName = sexName;
}
public Integer getSupplierId() {
return supplierId;
}
public void setSupplierId(Integer supplierId) {
this.supplierId = supplierId;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
@Override
public String toString() {
return "User{" +
", userId=" + userId +
", username=" + username +
", password=" + password +
", nickName=" + nickName +
", avatar=" + avatar +
", sex=" + sex +
", phone=" + phone +
", email=" + email +
", emailVerified=" + emailVerified +
", trueName=" + trueName +
", idCard=" + idCard +
", birthday=" + birthday +
", introduction=" + introduction +
", organizationId=" + organizationId +
", state=" + state +
", createTime=" + createTime +
", updateTime=" + updateTime +
", deleted=" + deleted +
", organizationName=" + organizationName +
"}";
}
}

View File

@@ -0,0 +1,104 @@
package com.bomaos.common.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* 用户角色
* Created by AutoGenerator on 2018-12-24 16:10
*/
@TableName("sys_user_role")
public class UserRole implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 用户id
*/
private Integer userId;
/**
* 角色id
*/
private Integer roleId;
/**
* 创建时间
*/
private Date createTime;
/**
* 修改时间
*/
private Date updateTime;
/**
* 角色名称
*/
@TableField(exist = false)
private String roleName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public String toString() {
return "UserRole{" +
", id=" + id +
", userId=" + userId +
", roleId=" + roleId +
", createTime=" + createTime +
", updateTime=" + updateTime +
", roleName=" + roleName +
"}";
}
}

Some files were not shown because too many files have changed in this diff Show More