This commit is contained in:
lu7213 committed 2025-12-02 23:07:47 +08:00
1 parent 81eca8933a
commit 345f906c35
540 files changed
+494222 -90

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.4.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>luqj-common</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<!--七牛云上传相关-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.11</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>happy-dns-java</artifactId>
<version>0.1.4</version>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,64 @@
package com.luqj.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 邮件系统属性信息
*/
@Component
@ConfigurationProperties(prefix = "lu.admin.mail")
public class EmailProperties {
/**
* 是否smtp授权
*/
private Boolean smtpAuth = true;
/**
* 邮件系统smtp
*/
private String smtpHost = "smtp.163.com";
/**
* 默认用户
*/
private String user;
/**
* 用户密码
*/
private String password;
public Boolean getSmtpAuth() {
return smtpAuth;
}
public void setSmtpAuth(Boolean smtpAuth) {
this.smtpAuth = smtpAuth;
}
public String getSmtpHost() {
return smtpHost;
}
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,109 @@
package com.luqj.common.controller;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.luqj.common.domain.ComCategory;
import com.luqj.common.service.IComCategoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
* 类别Controller
*
* @author luqj
* @date 2021-07-24
*/
@RestController
@RequestMapping("/common/category")
public class ComCategoryController extends BaseController
{
@Autowired
private IComCategoryService comCategoryService;
@GetMapping("/treeselect")
public AjaxResult treeselect(ComCategory comCategory)
{
List<ComCategory> depts = comCategoryService.selectComCategoryList(comCategory);
return AjaxResult.success(comCategoryService.buildCategoryTreeSelect(depts));
}
/**
* 查询类别列表
*/
@PreAuthorize("@ss.hasPermi('common:category:list')")
@GetMapping("/list")
public TableDataInfo list(ComCategory comCategory)
{
startPage();
List<ComCategory> list = comCategoryService.selectComCategoryList(comCategory);
return getDataTable(list);
}
/**
* 导出类别列表
*/
@PreAuthorize("@ss.hasPermi('common:category:export')")
@Log(title = "类别", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(ComCategory comCategory)
{
List<ComCategory> list = comCategoryService.selectComCategoryList(comCategory);
ExcelUtil<ComCategory> util = new ExcelUtil<ComCategory>(ComCategory.class);
return util.exportExcel(list, "category");
}
/**
* 获取类别详细信息
*/
@PreAuthorize("@ss.hasPermi('common:category:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(comCategoryService.selectComCategoryById(id));
}
/**
* 新增类别
*/
@PreAuthorize("@ss.hasPermi('common:category:add')")
@Log(title = "类别", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody ComCategory comCategory)
{
return toAjax(comCategoryService.insertComCategory(comCategory));
}
/**
* 修改类别
*/
@PreAuthorize("@ss.hasPermi('common:category:edit')")
@Log(title = "类别", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody ComCategory comCategory)
{
return toAjax(comCategoryService.updateComCategory(comCategory));
}
/**
* 删除类别
*/
@PreAuthorize("@ss.hasPermi('common:category:remove')")
@Log(title = "类别", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(comCategoryService.deleteComCategoryByIds(ids));
}
}
@@ -0,0 +1,28 @@
package com.luqj.common.controller;
import com.luqj.common.domain.SelectItem;
import com.luqj.common.service.ICommonService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/common")
public class SelectCommonController extends BaseController {
@Autowired
private ICommonService comCategory;
@GetMapping("/select/search")
public AjaxResult selectSearch(String tableName, String keyword, String fieldId, String fieldName) {
if(tableName.contains(" ") || fieldId.contains(" ") || fieldName.contains(" ")){
return AjaxResult.error("注入嫌疑");
}
List<SelectItem> searchs = comCategory.search(tableName, fieldId, fieldName, keyword);
return AjaxResult.success(searchs);
}
}
@@ -0,0 +1,14 @@
package com.luqj.common.domain;
import com.ruoyi.common.core.domain.TreeSelect;
import java.util.stream.Collectors;
public class CategoryTreeSelect extends TreeSelect {
public CategoryTreeSelect(ComCategory comCategory)
{
this.id = comCategory.getId();
this.label = comCategory.getName();
this.children = comCategory.getChildren().stream().map(CategoryTreeSelect::new).collect(Collectors.toList());
}
}
@@ -0,0 +1,233 @@
package com.luqj.common.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 类别对象 com_category
*
* @author luqj
* @date 2021-07-24
*/
public class ComCategory extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** id */
private Long id;
/** 名称 */
@Excel(name = "名称")
private String name;
/** 父id */
@Excel(name = "父id")
private Long parentId;
/** 所有父级id组合,以逗号隔开 */
@Excel(name = "所有父级id组合,以逗号隔开")
private String parentIds;
/** 系统层级类目 */
@Excel(name = "系统层级类目")
private Long projectType;
/** 排序 */
@Excel(name = "排序")
private Long sortNum;
/** 图标地址 */
@Excel(name = "图标地址")
private String iconUrl;
/** 图片地址 */
@Excel(name = "图片地址")
private String picUrl;
/** 是否叶子节点(0否,1是) */
@Excel(name = "是否叶子节点(0否,1是)")
private Integer hasLeaf;
/** 是否前台首页展示(0否,1是) */
@Excel(name = "是否前台首页展示(0否,1是)")
private Integer homeShow;
/** 类目级别,1:一级类目;2:二级类目;3:三级类目,目前只支持三级类目 */
@Excel(name = "类目级别,1:一级类目;2:二级类目;3:三级类目,目前只支持三级类目")
private Integer level;
/** 标示位:例如热门分类等 */
@Excel(name = "标示位:例如热门分类等")
private Long flag;
/** 描述 */
@Excel(name = "描述")
private String description;
/** 状态 0-禁用,1-启用,2-删除 */
@Excel(name = "状态 0-禁用,1-启用,2-删除")
private Integer status;
private List<ComCategory> children = new ArrayList<>();
public void setId(Long id)
{
this.id = id;
}
public List<ComCategory> getChildren() {
return children;
}
public void setChildren(List<ComCategory> children) {
this.children = children;
}
public Long getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public Long getParentId()
{
return parentId;
}
public void setParentIds(String parentIds)
{
this.parentIds = parentIds;
}
public String getParentIds()
{
return parentIds;
}
public void setProjectType(Long projectType)
{
this.projectType = projectType;
}
public Long getProjectType()
{
return projectType;
}
public void setSortNum(Long sortNum)
{
this.sortNum = sortNum;
}
public Long getSortNum()
{
return sortNum;
}
public void setIconUrl(String iconUrl)
{
this.iconUrl = iconUrl;
}
public String getIconUrl()
{
return iconUrl;
}
public void setPicUrl(String picUrl)
{
this.picUrl = picUrl;
}
public String getPicUrl()
{
return picUrl;
}
public void setHasLeaf(Integer hasLeaf)
{
this.hasLeaf = hasLeaf;
}
public Integer getHasLeaf()
{
return hasLeaf;
}
public void setHomeShow(Integer homeShow)
{
this.homeShow = homeShow;
}
public Integer getHomeShow()
{
return homeShow;
}
public void setLevel(Integer level)
{
this.level = level;
}
public Integer getLevel()
{
return level;
}
public void setFlag(Long flag)
{
this.flag = flag;
}
public Long getFlag()
{
return flag;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Integer getStatus()
{
return status;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("name", getName())
.append("parentId", getParentId())
.append("parentIds", getParentIds())
.append("projectType", getProjectType())
.append("sortNum", getSortNum())
.append("iconUrl", getIconUrl())
.append("picUrl", getPicUrl())
.append("hasLeaf", getHasLeaf())
.append("homeShow", getHomeShow())
.append("level", getLevel())
.append("flag", getFlag())
.append("description", getDescription())
.append("createTime", getCreateTime())
.append("updateTime", getUpdateTime())
.append("status", getStatus())
.toString();
}
}
@@ -0,0 +1,232 @@
package com.luqj.common.domain;
import com.baomidou.mybatisplus.annotation.TableName;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import java.io.Serializable;
import java.util.Date;
/**
* 类别对象 com_category
*
* @author luqj
* @date 2021-07-24
*/
@TableName(value = "com_category")
public class ComCategoryPlus implements Serializable
{
private static final long serialVersionUID = 1L;
/** id */
private Long id;
/** 名称 */
@Excel(name = "名称")
private String name;
/** 父id */
@Excel(name = "父id")
private Long parentId;
/** 所有父级id组合,以逗号隔开 */
@Excel(name = "所有父级id组合,以逗号隔开")
private String parentIds;
/** 系统层级类目 */
@Excel(name = "系统层级类目")
private Long projectType;
/** 排序 */
@Excel(name = "排序")
private Long sortNum;
/** 图标地址 */
@Excel(name = "图标地址")
private String iconUrl;
/** 图片地址 */
@Excel(name = "图片地址")
private String picUrl;
/** 是否叶子节点(0否,1是) */
@Excel(name = "是否叶子节点(0否,1是)")
private Integer hasLeaf;
/** 是否前台首页展示(0否,1是) */
@Excel(name = "是否前台首页展示(0否,1是)")
private Integer homeShow;
/** 类目级别,1:一级类目;2:二级类目;3:三级类目,目前只支持三级类目 */
@Excel(name = "类目级别,1:一级类目;2:二级类目;3:三级类目,目前只支持三级类目")
private Integer level;
/** 标示位:例如热门分类等 */
@Excel(name = "标示位:例如热门分类等")
private Long flag;
/** 描述 */
@Excel(name = "描述")
private String description;
/** 创建时间 */
private Date createTime;
/** 修改时间 */
private Date updateTime;
/** 状态 0-禁用,1-启用,2-删除 */
@Excel(name = "状态 0-禁用,1-启用,2-删除")
private Integer status;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setParentId(Long parentId)
{
this.parentId = parentId;
}
public Long getParentId()
{
return parentId;
}
public void setParentIds(String parentIds)
{
this.parentIds = parentIds;
}
public String getParentIds()
{
return parentIds;
}
public void setProjectType(Long projectType)
{
this.projectType = projectType;
}
public Long getProjectType()
{
return projectType;
}
public void setSortNum(Long sortNum)
{
this.sortNum = sortNum;
}
public Long getSortNum()
{
return sortNum;
}
public void setIconUrl(String iconUrl)
{
this.iconUrl = iconUrl;
}
public String getIconUrl()
{
return iconUrl;
}
public void setPicUrl(String picUrl)
{
this.picUrl = picUrl;
}
public String getPicUrl()
{
return picUrl;
}
public void setHasLeaf(Integer hasLeaf)
{
this.hasLeaf = hasLeaf;
}
public Integer getHasLeaf()
{
return hasLeaf;
}
public void setHomeShow(Integer homeShow)
{
this.homeShow = homeShow;
}
public Integer getHomeShow()
{
return homeShow;
}
public void setLevel(Integer level)
{
this.level = level;
}
public Integer getLevel()
{
return level;
}
public void setFlag(Long flag)
{
this.flag = flag;
}
public Long getFlag()
{
return flag;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public Date getCreateTime()
{
return createTime;
}
public void setUpdateTime(Date updateTime)
{
this.updateTime = updateTime;
}
public Date getUpdateTime()
{
return updateTime;
}
public void setStatus(Integer status)
{
this.status = status;
}
public Integer getStatus()
{
return status;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("name", getName())
.append("parentId", getParentId())
.append("parentIds", getParentIds())
.append("projectType", getProjectType())
.append("sortNum", getSortNum())
.append("iconUrl", getIconUrl())
.append("picUrl", getPicUrl())
.append("hasLeaf", getHasLeaf())
.append("homeShow", getHomeShow())
.append("level", getLevel())
.append("flag", getFlag())
.append("description", getDescription())
.append("createTime", getCreateTime())
.append("updateTime", getUpdateTime())
.append("status", getStatus())
.toString();
}
}
@@ -0,0 +1,17 @@
package com.luqj.common.domain;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ContactItem<T> implements Serializable,Comparable<ContactItem> {
private String letter;
private List<T> data;
@Override
public int compareTo(ContactItem o) {
return this.getLetter().compareTo(o.getLetter());
}
}
@@ -0,0 +1,75 @@
package com.luqj.common.domain;
import com.ruoyi.common.utils.StringUtils;
import java.math.BigDecimal;
import java.util.Date;
public class RedisKey {
private StringBuffer stringBuffer = new StringBuffer("");
public RedisKey() {
}
public RedisKey(String key) {
stringBuffer = new StringBuffer(key);
}
public RedisKey add(String key) {
if (StringUtils.isNotBlank(key)) {
stringBuffer.append(key).append("_");
} else {
stringBuffer.append("NULL_");
}
return this;
}
public RedisKey add(BigDecimal key) {
if (key != null) {
stringBuffer.append(key).append("_");
} else {
stringBuffer.append("NULL_");
}
return this;
}
public RedisKey add(Boolean key) {
if (key != null) {
stringBuffer.append(key).append("_");
} else {
stringBuffer.append("NULL_");
}
return this;
}
public RedisKey add(Long key) {
if (key != null) {
stringBuffer.append(key).append("_");
} else {
stringBuffer.append("NULL_");
}
return this;
}
public RedisKey add(Date key) {
if (key != null) {
stringBuffer.append(key.getTime()).append("_");
} else {
stringBuffer.append("_NULL");
}
return this;
}
public RedisKey add(Integer key) {
if (key != null) {
stringBuffer.append(key).append("_");
} else {
stringBuffer.append("_NULL");
}
return this;
}
public String key() {
return this.stringBuffer.toString();
}
}
@@ -0,0 +1,11 @@
package com.luqj.common.domain;
import lombok.Data;
import java.io.Serializable;
@Data
public class SelectItem implements Serializable {
private String id;
private String name;
}
@@ -0,0 +1,65 @@
package com.luqj.common.mapper;
import java.util.List;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import com.luqj.common.domain.ComCategory;
import com.luqj.common.domain.ComCategoryPlus;
/**
* 类别Mapper接口
*
* @author luqj
* @date 2021-07-24
*/
public interface ComCategoryMapper extends BaseMapper<ComCategoryPlus>
{
/**
* 查询类别
*
* @param id 类别ID
* @return 类别
*/
public ComCategory selectComCategoryById(Long id);
/**
* 查询类别列表
*
* @param comCategory 类别
* @return 类别集合
*/
public List<ComCategory> selectComCategoryList(ComCategory comCategory);
/**
* 新增类别
*
* @param comCategory 类别
* @return 结果
*/
public int insertComCategory(ComCategory comCategory);
/**
* 修改类别
*
* @param comCategory 类别
* @return 结果
*/
public int updateComCategory(ComCategory comCategory);
/**
* 删除类别
*
* @param id 类别ID
* @return 结果
*/
public int deleteComCategoryById(Long id);
/**
* 批量删除类别
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteComCategoryByIds(Long[] ids);
}
@@ -0,0 +1,90 @@
package com.luqj.common.service;
import java.util.Map;
import java.util.List;
import com.luqj.common.domain.CategoryTreeSelect;
import com.luqj.common.domain.ComCategory;
import com.luqj.common.domain.ComCategoryPlus;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
/**
* 类别Service接口
*
* @author luqj
* @date 2021-07-24
*/
public interface IComCategoryService extends IService<ComCategoryPlus>
{
/**
* 查询类别
*
* @param id 类别ID
* @return 类别
*/
public ComCategory selectComCategoryById(Long id);
/**
* 查询类别列表
*
* @param comCategory 类别
* @return 类别集合
*/
public List<ComCategory> selectComCategoryList(ComCategory comCategory);
/**
* 新增类别
*
* @param comCategory 类别
* @return 结果
*/
public int insertComCategory(ComCategory comCategory);
/**
* 修改类别
*
* @param comCategory 类别
* @return 结果
*/
public int updateComCategory(ComCategory comCategory);
/**
* 批量删除类别
*
* @param ids 需要删除的类别ID
* @return 结果
*/
public int deleteComCategoryByIds(Long[] ids);
/**
* 删除类别信息
*
* @param id 类别ID
* @return 结果
*/
public int deleteComCategoryById(Long id);
List<ComCategoryPlus> getByIds(List<Long> ids, SFunction<ComCategoryPlus, ?>... columns);
ComCategoryPlus getById(Long id, SFunction<ComCategoryPlus, ?>... columns);
Map<Long, ComCategoryPlus> getMapByIds(List<Long> ids, SFunction<ComCategoryPlus, ?>... columns);
List<CategoryTreeSelect> buildCategoryTreeSelect(List<ComCategory> comCategory);
List<ComCategoryPlus> getByIds(List<Long> ids);
Map<Long, ComCategoryPlus> getMapByIds(List<Long> ids);
/**
* @param field sum 字段
* @param where 条件
* @param tClass 返回类型
* @param <T>
* @return
*/
<T> T sum(String field, String where, Class<T> tClass);
Long count(String where);
<T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass);
}
@@ -0,0 +1,9 @@
package com.luqj.common.service;
import com.luqj.common.domain.SelectItem;
import java.util.List;
public interface ICommonService {
List<SelectItem> search(String tableName, String fieldId, String fieldName, String keyword);
}
@@ -0,0 +1,8 @@
package com.luqj.common.service;
import javax.mail.MessagingException;
import java.security.GeneralSecurityException;
public interface ISendEmailService {
boolean send(String email, String subject, String content) throws MessagingException, GeneralSecurityException;
}
@@ -0,0 +1,275 @@
package com.luqj.common.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import java.util.*;
import com.luqj.common.domain.CategoryTreeSelect;
import com.ruoyi.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
import java.util.stream.Collectors;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.luqj.common.mapper.ComCategoryMapper;
import com.luqj.common.domain.ComCategory;
import com.luqj.common.domain.ComCategoryPlus;
import com.luqj.common.service.IComCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 类别Service业务层处理
*
* @author luqj
* @date 2021-07-24
*/
@Service
public class ComCategoryServiceImpl extends ServiceImpl<ComCategoryMapper, ComCategoryPlus> implements IComCategoryService
{
@Autowired
private ComCategoryMapper comCategoryMapper;
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<ComCategoryPlus> getByIds(List<Long> ids, SFunction<ComCategoryPlus, ?>... columns) {
LambdaQueryWrapper<ComCategoryPlus> lambdaQueryWrapper = new LambdaQueryWrapper<ComCategoryPlus>()
.select(columns).in(ComCategoryPlus::getId, ids);
return this.list(lambdaQueryWrapper);
}
@Override
public ComCategoryPlus getById(Long id, SFunction<ComCategoryPlus, ?>... columns) {
LambdaQueryWrapper<ComCategoryPlus> lambdaQueryWrapper = new LambdaQueryWrapper<ComCategoryPlus>()
.select(columns).eq(ComCategoryPlus::getId, id);
return baseMapper.selectOne(lambdaQueryWrapper);
}
@Override
public Map<Long, ComCategoryPlus> getMapByIds(List<Long> ids, SFunction<ComCategoryPlus, ?>... columns) {
List<ComCategoryPlus> list = this.getByIds(ids, columns);
Map<Long, ComCategoryPlus> map = new HashMap<>();
for (ComCategoryPlus item : list) {
map.put(item.getId(), item);
}
return map;
}
public List<CategoryTreeSelect> buildCategoryTreeSelect(List<ComCategory> comCategory)
{
List<ComCategory> deptTrees = buildCategoryTree(comCategory);
ComCategory com =new ComCategory();
com.setId(0L);
com.setName("根目录");
com.setChildren(deptTrees);
List<ComCategory> pc = new ArrayList<>();
for(ComCategory c:deptTrees){
if(c.getParentId() == 0L){
pc.add(c);
}
}
com.setChildren(pc);
return Arrays.asList(com).stream().map(CategoryTreeSelect::new).collect(Collectors.toList());
}
/**
* 递归列表
*/
private void recursionFn(List<ComCategory> list, ComCategory t)
{
// 得到子节点列表
List<ComCategory> childList = getChildList(list, t);
t.setChildren(childList);
for (ComCategory tChild : childList)
{
if (hasChild(list, tChild))
{
recursionFn(list, tChild);
}
}
}
/**
* 得到子节点列表
*/
private List<ComCategory> getChildList(List<ComCategory> list, ComCategory t)
{
List<ComCategory> tlist = new ArrayList<ComCategory>();
Iterator<ComCategory> it = list.iterator();
while (it.hasNext())
{
ComCategory n = (ComCategory) it.next();
if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
{
tlist.add(n);
}
}
return tlist;
}
/**
* 判断是否有子节点
*/
private boolean hasChild(List<ComCategory> list, ComCategory t)
{
return getChildList(list, t).size() > 0 ? true : false;
}
public List<ComCategory> buildCategoryTree(List<ComCategory> depts)
{
List<ComCategory> returnList = new ArrayList<ComCategory>();
List<Long> tempList = new ArrayList<Long>();
for (ComCategory dept : depts)
{
tempList.add(dept.getId());
}
for (Iterator<ComCategory> iterator = depts.iterator(); iterator.hasNext();)
{
ComCategory dept = (ComCategory) iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(dept.getParentId()))
{
recursionFn(depts, dept);
returnList.add(dept);
}
}
if (returnList.isEmpty())
{
returnList = depts;
}
return returnList;
}
@Override
public Map<Long, ComCategoryPlus> getMapByIds(List<Long> ids) {
List<ComCategoryPlus> list = this.getByIds(ids);
Map<Long, ComCategoryPlus> map = new HashMap<>();
for (ComCategoryPlus item : list) {
map.put(item.getId(), item);
}
return map;
}
@Override
public List<ComCategoryPlus> getByIds(List<Long> ids) {
LambdaQueryWrapper<ComCategoryPlus> lambdaQueryWrapper = new LambdaQueryWrapper<ComCategoryPlus>().in(ComCategoryPlus::getId, ids);
return this.list(lambdaQueryWrapper);
}
public <T> T sum(String field, String where, Class<T> tClass) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(" sum(" + field + ") as total ");
stringBuffer.append(" from com_category ");
if (StringUtils.isNotBlank(where)) {
stringBuffer.append(" where ");
stringBuffer.append(where);
}
T result = jdbcTemplate.queryForObject(stringBuffer.toString(), tClass);
return result;
}
public Long count(String where) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(" count(1)");
stringBuffer.append(" from ");
stringBuffer.append(" com_category ");
if (StringUtils.isNotBlank(where)) {
stringBuffer.append(" where ");
stringBuffer.append(where);
}
Long result = jdbcTemplate.queryForObject(stringBuffer.toString(), Long.class);
return result;
}
public <T> List<T> countByGroupBy(String select, String where, String groupby, Class<T> tClass) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(select);
stringBuffer.append(" from ");
stringBuffer.append(" com_category ");
if (StringUtils.isNotBlank(where)) {
stringBuffer.append(" where ");
stringBuffer.append(where);
}
stringBuffer.append(" group by ");
stringBuffer.append(groupby);
List result = jdbcTemplate.queryForList(stringBuffer.toString());
List<T> tList = JSONArray.parseArray(JSONArray.toJSONString(result), tClass);
return tList;
}
/**
* 查询类别
*
* @param id 类别ID
* @return 类别
*/
@Override
public ComCategory selectComCategoryById(Long id)
{
return comCategoryMapper.selectComCategoryById(id);
}
/**
* 查询类别列表
*
* @param comCategory 类别
* @return 类别
*/
@Override
public List<ComCategory> selectComCategoryList(ComCategory comCategory)
{
return comCategoryMapper.selectComCategoryList(comCategory);
}
/**
* 新增类别
*
* @param comCategory 类别
* @return 结果
*/
@Override
public int insertComCategory(ComCategory comCategory)
{
comCategory.setCreateTime(DateUtils.getNowDate());
return comCategoryMapper.insertComCategory(comCategory);
}
/**
* 修改类别
*
* @param comCategory 类别
* @return 结果
*/
@Override
public int updateComCategory(ComCategory comCategory)
{
comCategory.setUpdateTime(DateUtils.getNowDate());
return comCategoryMapper.updateComCategory(comCategory);
}
/**
* 批量删除类别
*
* @param ids 需要删除的类别ID
* @return 结果
*/
@Override
public int deleteComCategoryByIds(Long[] ids)
{
return comCategoryMapper.deleteComCategoryByIds(ids);
}
/**
* 删除类别信息
*
* @param id 类别ID
* @return 结果
*/
@Override
public int deleteComCategoryById(Long id)
{
return comCategoryMapper.deleteComCategoryById(id);
}
}
@@ -0,0 +1,39 @@
package com.luqj.common.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.luqj.common.domain.SelectItem;
import com.luqj.common.service.ICommonService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class CommonServiceImpl implements ICommonService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<SelectItem> search(String tableName, String fieldId, String fieldName, String keyword) {
if (StringUtils.isEmpty(tableName)) {
return new ArrayList<>();
}
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("select ");
stringBuffer.append(fieldId + " as id,");
stringBuffer.append(fieldName + " as name");
stringBuffer.append(" from ");
stringBuffer.append(" " + tableName + " ");
if (StringUtils.isNotBlank(keyword)) {
stringBuffer.append(" where ");
stringBuffer.append(fieldName + " like '%" + keyword + "%'");
}
stringBuffer.append(" limit 0,100 ");
List result = jdbcTemplate.queryForList(stringBuffer.toString());
List<SelectItem> tList = JSONArray.parseArray(JSONArray.toJSONString(result), SelectItem.class);
return tList;
}
}
@@ -0,0 +1,65 @@
package com.luqj.common.service.impl;
import com.luqj.common.config.EmailProperties;
import com.luqj.common.service.ISendEmailService;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
@Service
public class SendEmailServiceImpl implements ISendEmailService {
@Autowired
private EmailProperties emailProperties;
private final Properties props = new Properties();
@Override
public boolean send(String email, String subject, String content) throws MessagingException, GeneralSecurityException {
// qq邮件
// 设置邮件服务器主机名
props.setProperty("mail.host", emailProperties.getSmtpHost());
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", emailProperties.getSmtpAuth() + "");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
// 创建session
Session session = Session.getInstance(props);
// 通过session得到transport对象
Transport ts = session.getTransport();
ts.connect(emailProperties.getSmtpHost(), emailProperties.getUser(), emailProperties.getPassword());// 后面的字符是授权码
// 创建邮件对象
Message message = new MimeMessage(session);
// 指明邮件的发件人
message.setFrom(new InternetAddress(emailProperties.getUser()));
// 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 邮件的标题
message.setSubject(subject);
// 邮件的文本内容
message.setContent(content, "text/html;charset=UTF-8");
// 发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
return true;
}
public static void main(String[] args) {
}
}
@@ -0,0 +1,41 @@
package com.luqj.qiniu.controller;
import com.luqj.qiniu.entity.QiNiu;
import com.luqj.qiniu.service.IQiniuService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: qiniu_config
* @Author: jeecg-boot
* @Date: 2020-08-15
* @Version: V1.0
*/
@Api(tags = "qiniu")
@RestController
@RequestMapping("/common/qiniu")
@Slf4j
public class QiniuController extends BaseController {
@Autowired
private IQiniuService qiniuService;
@ApiOperation(value = "获取客户端上传认证信息", notes = "获取客户端上传认证信息")
@GetMapping(value = "/config")
@ResponseBody
public AjaxResult config() {
try {
QiNiu qiNiu = qiniuService.buildToken();
return AjaxResult.success(qiNiu);
} catch (Exception ex) {
return AjaxResult.error(ex.getMessage());
}
}
}
@@ -0,0 +1,16 @@
package com.luqj.qiniu.entity;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import java.io.Serializable;
@Data
@ApiModel(value = "QiNiu",description = "七牛配置")
public class QiNiu implements Serializable {
private String token;
private String key;
private int zone;
}
@@ -0,0 +1,81 @@
package com.luqj.qiniu.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* @Description: qiniu_config
* @Author: jeecg-boot
* @Date: 2020-08-15
* @Version: V1.0
*/
@Data
@TableName("com_qiniu_config")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "qiniu_config对象", description = "qiniu_config")
public class QiniuConfig implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.ID_WORKER_STR)
@ApiModelProperty(value = "主键")
private String id;
/**
* access_key
*/
@Excel(name = "access_key", width = 15)
@ApiModelProperty(value = "access_key")
private String accessKey;
/**
* secret_key
*/
@Excel(name = "secret_key", width = 15)
@ApiModelProperty(value = "secret_key")
private String secretKey;
/**
* 编码
*/
@Excel(name = "编码", width = 15)
@ApiModelProperty(value = "编码")
private String code;
/**
* bucket
*/
@Excel(name = "bucket", width = 15)
@ApiModelProperty(value = "bucket")
private String bucket;
/**
* token有效时间
*/
@Excel(name = "token有效时间", width = 15)
@ApiModelProperty(value = "token有效时间")
private Integer tokenExpireSeconds;
/**
* zone类型
*/
@Excel(name = "zone类型", width = 15)
@ApiModelProperty(value = "zone类型")
private Integer zoneType;
/**
* 创建时间
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建时间")
private Date createTime;
}
@@ -0,0 +1,16 @@
package com.luqj.qiniu.mapper;
import java.util.List;
import com.luqj.qiniu.entity.QiniuConfig;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @Description: qiniu_config
* @Author: jeecg-boot
* @Date: 2020-08-15
* @Version: V1.0
*/
public interface QiniuConfigMapper extends BaseMapper<QiniuConfig> {
}
@@ -0,0 +1,14 @@
package com.luqj.qiniu.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.luqj.qiniu.entity.QiniuConfig;
/**
* @Description: qiniu_config
* @Author: jeecg-boot
* @Date: 2020-08-15
* @Version: V1.0
*/
public interface IQiniuConfigService extends IService<QiniuConfig> {
QiniuConfig getFirstOne();
}
@@ -0,0 +1,14 @@
package com.luqj.qiniu.service;
import com.luqj.qiniu.entity.QiNiu;
import org.springframework.web.multipart.MultipartFile;
public interface IQiniuService {
QiNiu buildToken() throws Exception;
void refreshQiniuToken();
String upload(String localFilePath, String key);
String upload(MultipartFile file, String fileDir);
}
@@ -0,0 +1,55 @@
package com.luqj.qiniu.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luqj.qiniu.entity.QiniuConfig;
import com.luqj.qiniu.mapper.QiniuConfigMapper;
import com.luqj.qiniu.service.IQiniuConfigService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.Collection;
/**
* @Description: qiniu_config
* @Author: jeecg-boot
* @Date: 2020-08-15
* @Version: V1.0
*/
@Service
public class QiniuConfigServiceImpl extends ServiceImpl<QiniuConfigMapper, QiniuConfig> implements IQiniuConfigService {
@Cacheable(value = "sys:qiniu:config", key = "'one'")
@Override
public QiniuConfig getFirstOne() {
LambdaQueryWrapper queryWrapper = new QueryWrapper<QiniuConfig>().lambda();
QiniuConfig qiniuConfig = getOne(queryWrapper);
return qiniuConfig;
}
@CacheEvict(value = "sys:qiniu:config", key = "'one'")
@Override
public boolean save(QiniuConfig entity) {
return super.save(entity);
}
@CacheEvict(value = "sys:qiniu:config", key = "'one'")
@Override
public boolean updateById(QiniuConfig entity) {
return super.updateById(entity);
}
@CacheEvict(value = "sys:qiniu:config", key = "'one'")
@Override
public boolean removeByIds(Collection<? extends Serializable> idList) {
return super.removeByIds(idList);
}
@CacheEvict(value = "sys:qiniu:config", key = "'one'")
@Override
public boolean removeById(Serializable id) {
return super.removeById(id);
}
}
@@ -0,0 +1,125 @@
package com.luqj.qiniu.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.luqj.qiniu.entity.QiNiu;
import com.luqj.qiniu.entity.QiniuConfig;
import com.luqj.qiniu.service.IQiniuConfigService;
import com.luqj.qiniu.service.IQiniuService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.ruoyi.common.CacheConstant;
import com.ruoyi.common.redis.RedisUtil;
import com.ruoyi.common.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class QiniuServiceImpl implements IQiniuService {
private final static Logger logger = LoggerFactory.getLogger(QiniuServiceImpl.class);
@Autowired
private IQiniuConfigService qiniuConfigService;
@Autowired
private RedisUtil redisUtil;
@Value("${lu.admin.qiniu.addr:http://img.hy-vip.cn}")
private String qiniuAddr;
@Override
public QiNiu buildToken() throws Exception {
LambdaQueryWrapper queryWrapper = new QueryWrapper<QiniuConfig>().lambda();
QiniuConfig qiniuConfig = qiniuConfigService.getOne(queryWrapper);
if (null == qiniuConfig) {
throw new Exception("请配置七牛存储配置");
}
QiNiu qiNiu = new QiNiu();
qiNiu.setKey(UUID.randomUUID().toString().replaceAll("\\-", ""));
String token = redisUtil.get(CacheConstant.QI_NIU_TOKEN, "");
qiNiu.setToken(token);
qiNiu.setZone(qiNiu.getZone());
return qiNiu;
}
public String upload(MultipartFile file, String fileDir) {
Configuration cfg = new Configuration(new Zone.Builder().autoZone());
UploadManager uploadManager = new UploadManager(cfg);
StringBuilder fileUrl = new StringBuilder();
// 获取文件名
String orgName = file.getOriginalFilename();
orgName = CommonUtils.getFileName(orgName);
String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
fileDir = fileDir.replace("/", "/");
fileUrl = fileUrl.append(fileDir + fileName);
String upToken = redisUtil.get(CacheConstant.QI_NIU_TOKEN, "");
try {
Response response = uploadManager.put(file.getBytes(), fileUrl.toString(), upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return qiniuAddr + File.separator + putRet.key;
} catch (QiniuException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void refreshQiniuToken() {
QiniuConfig qiniuConfig = qiniuConfigService.getFirstOne();
if (null == qiniuConfig) {
logger.error("请配置七牛存储配置");
return;
}
String accessKey = qiniuConfig.getAccessKey();
String secretKey = qiniuConfig.getSecretKey();
String bucket = qiniuConfig.getBucket();
long expireSeconds = qiniuConfig.getTokenExpireSeconds(); //过期时间
if (!redisUtil.hasKey(CacheConstant.QI_NIU_TOKEN, "")) {
StringMap putPolicy = new StringMap();
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
redisUtil.set(CacheConstant.QI_NIU_TOKEN, "", upToken, expireSeconds, TimeUnit.SECONDS);
}
}
public String upload(String localFilePath, String key) {
//构造一个带指定 Region
Configuration cfg = new Configuration(new Zone.Builder().autoZone());
UploadManager uploadManager = new UploadManager(cfg);
try {
String[] strings = localFilePath.split("\\.");
Response response = uploadManager.put(localFilePath, key + "." + strings[strings.length - 1], redisUtil.get(CacheConstant.QI_NIU_TOKEN, ""));
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return qiniuAddr + File.separator + putRet.key;
} catch (QiniuException ex) {
ex.printStackTrace();
}
return null;
}
}
@@ -0,0 +1,28 @@
package com.luqj.qiniu.task;
import com.luqj.qiniu.service.IQiniuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* Created by luqj on 2018/8/24.
* 书信七牛token
*/
@Component
@EnableScheduling // 2.开启定时任务
public class QiNiuRefreshTokenTask {
private final static Logger logger = LoggerFactory.getLogger(QiNiuRefreshTokenTask.class);
@Autowired
private IQiniuService qiniuService;
// @Scheduled(cron = "0/10 * * * * ?")
@Scheduled(cron = "* 0/10 * * * ?")
public void refreshQiniuToken() {
qiniuService.refreshQiniuToken();
}
}
@@ -0,0 +1,127 @@
package com.luqj.qiniu.util;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import java.io.File;
/**
* 七牛 java sdk 简单上传,覆盖上传,文件上传
*
* @author luqj
*/
public class SimpleUpload {
private Auth auth;
private UploadManager uploadManager;
public void init(String accessKey, String secretKey) {
// Configuration cfg = new Configuration(Zone.zone0());
Configuration cfg = new Configuration(Zone.zone2());
uploadManager = new UploadManager(cfg);
auth = Auth.create(accessKey, secretKey);
}
/**
* 获取凭证
*
* @param bucketName 空间名称
* @param key 如果需要覆盖上传则设置此参数
* @return
*/
public String getUpToken(String bucketName, String key) {
return auth.uploadToken(bucketName);
}
/**
* 上传方法1
*
* @param filePath 文件路径 (也可以是字节数组、或者File对象)
* @param key 上传到七牛上的文件的名称 (同一个空间下,名称【key】是唯一的)
* @param bucketName 空间名称 (这里是为了获取上传凭证)
*/
public void upload(String filePath, String key, String bucketName) {
try {
// 调用put方法上传
Response res = uploadManager.put(filePath, key, getUpToken(bucketName, key));
// 打印返回的信息
System.out.println(res.bodyString());
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
// 响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException qe) {
// ignore
}
}
}
/**
* 上传方法2
*
* @param file 文件
* @param key 上传到七牛上的文件的名称 (同一个空间下,名称【key】是唯一的)
* @param bucketName 空间名称 (这里是为了获取上传凭证)
*/
public void upload(File file, String key, String bucketName) {
try {
// 调用put方法上传
Response res = uploadManager.put(file, key, getUpToken(bucketName, key));
// 打印返回的信息
System.out.println(res.bodyString());
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
// 响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException qe) {
// ignore
}
}
}
/**
* 上传方法3 覆盖上传
*
* @param path 上传文件路径
* @param bucketName 空间名
* @param key 文件名
*/
public void overrideUpload(String path, String key, String bucketName) {
try {
String token = getUpToken(bucketName, key);//获取 token
Response response = uploadManager.put(path, key, token);//执行上传,通过token来识别 该上传是“覆盖上传”
System.out.println(response.toString());
} catch (QiniuException e) {
System.out.println(e.response.statusCode);
e.printStackTrace();
}
}
/**
* 主函数:程序入口,测试功能
*
* @param args
*/
public static void main(String[] args) {
// 上传文件的路径,因为在Mac下,所以路径和windows下不同
String filePath = "D:\\test.txt";
// 要上传的空间
String bucketName = "test";
// 上传到七牛后保存的文件名
String key = "sometext.txt";
// 这里的filepath可以直接替换成File如下注释所示
// File file=new File(filePath);
// new SimpleUpload().upload(file, key, bucketName);
new SimpleUpload().upload(filePath, key, bucketName);
}
}
@@ -0,0 +1,230 @@
package com.luqj.qiniu.util;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.util.StringMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* 七牛文件上传管理器,通过该类上传文件时,会自动根据定义的{@link Configuration#putThreshold}
* 来判断是采用表单上传还是分片上传的方法,超过了定义的{@link Configuration#putThreshold}就会采用
* 分片上传的方法,可以在构造该类对象的时候,通过{@link Configuration}类来自定义这个值。
* 一般默认可以使用这个类的方法来上传数据和文件。这个类自动检测文件的大小,
*/
public final class UploadManager {
private final Client client;
private final Recorder recorder;
private final Configuration configuration;
/**
* 构建一个非断点续传的上传对象
*
* @param config 配置类对象
*/
public UploadManager(Configuration config) {
this(config, null);
}
/**
* 构建一个支持断点续传的上传对象。只在文件采用分片上传时才会有效。
* 分块上传中,将每一块上传的记录保存下来。上传中断后可在上一次断点记录基础上上传剩余部分。
* 对于不同的文件上传需要支持断点续传的情况,请定义不同的UploadManager对象,而不要共享。
*
* @param config 配置类对象
* @param recorder 断点记录对象
*/
public UploadManager(Configuration config, Recorder recorder) {
configuration = config.clone();
client = new Client(configuration);
this.recorder = recorder;
}
private static void checkArgs(final String key, byte[] data, File f, String token) {
String message = null;
if (f == null && data == null) {
message = "no input data";
} else if (token == null || token.equals("")) {
message = "no token";
}
if (message != null) {
throw new IllegalArgumentException(message);
}
}
/**
* 过滤用户自定义参数,只有参数名以<code>x:</code>开头的参数才会被使用
*
* @param params 待过滤的用户自定义参数
* @return 过滤后的用户自定义参数
*/
private static StringMap filterParam(StringMap params) {
final StringMap ret = new StringMap();
if (params == null) {
return ret;
}
params.forEach(new StringMap.Consumer() {
@Override
public void accept(String key, Object value) {
if (value == null) {
return;
}
String val = value.toString();
if (key.startsWith("x:") && !val.equals("")) {
ret.put(key, val);
}
}
});
return ret;
}
/**
* 上传字节数组
*
* @param data 上传的数据
* @param key 上传数据保存的文件名
* @param token 上传凭证
*/
public Response put(final byte[] data, final String key, final String token) throws QiniuException {
return put(data, key, token, null, null, false);
}
/**
* 上传字节数组
*
* @param data 上传的数据
* @param key 上传数据保存的文件名
* @param token 上传凭证
* @param params 自定义参数,如 params.put("x:foo", "foo")
* @param mime 指定文件mimetype
* @param checkCrc 是否验证crc32
* @return
* @throws QiniuException
*/
public Response put(final byte[] data, final String key, final String token, StringMap params,
String mime, boolean checkCrc) throws QiniuException {
checkArgs(key, data, null, token);
if (mime == null) {
mime = Client.DefaultMime;
}
params = filterParam(params);
return new FormUploader(client, token, key, data, params, mime, checkCrc, configuration).upload();
}
/**
* 上传文件
*
* @param filePath 上传的文件路径
* @param key 上传文件保存的文件名
* @param token 上传凭证
*/
public Response put(String filePath, String key, String token) throws QiniuException {
return put(filePath, key, token, null, null, false);
}
/**
* 上传文件
*
* @param filePath 上传的文件路径
* @param key 上传文件保存的文件名
* @param token 上传凭证
* @param params 自定义参数,如 params.put("x:foo", "foo")
* @param mime 指定文件mimetype
* @param checkCrc 是否验证crc32
*/
public Response put(String filePath, String key, String token, StringMap params,
String mime, boolean checkCrc) throws QiniuException {
return put(new File(filePath), key, token, params, mime, checkCrc);
}
/**
* 上传文件
*
* @param file 上传的文件对象
* @param key 上传文件保存的文件名
* @param token 上传凭证
*/
public Response put(File file, String key, String token) throws QiniuException {
return put(file, key, token, null, null, false);
}
/**
* 上传文件
*
* @param file 上传的文件对象
* @param key 上传文件保存的文件名
* @param token 上传凭证
* @param mime 指定文件mimetype
* @param checkCrc 是否验证crc32
*/
public Response put(File file, String key, String token, StringMap params,
String mime, boolean checkCrc) throws QiniuException {
checkArgs(key, null, file, token);
if (mime == null) {
mime = Client.DefaultMime;
}
params = filterParam(params);
long size = file.length();
if (size <= configuration.putThreshold) {
return new FormUploader(client, token, key, file, params, mime, checkCrc, configuration).upload();
}
ResumeUploader uploader = new ResumeUploader(client, token, key, file,
params, mime, recorder, configuration);
return uploader.upload();
}
/**
* 异步上传数据
*
* @param data 上传的数据
* @param key 上传数据保存的文件名
* @param token 上传凭证
* @param params 自定义参数,如 params.put("x:foo", "foo")
* @param mime 指定文件mimetype
* @param checkCrc 是否验证crc32
* @param handler 上传完成的回调函数
*/
public void asyncPut(final byte[] data, final String key, final String token, StringMap params,
String mime, boolean checkCrc, UpCompletionHandler handler) throws IOException {
checkArgs(key, data, null, token);
if (mime == null) {
mime = Client.DefaultMime;
}
params = filterParam(params);
new FormUploader(client, token, key, data, params, mime, checkCrc, configuration).asyncUpload(handler);
}
/**
* 流式上传,通常情况建议文件上传,可以使用持久化的断点记录。
*
* @param stream sha
* @param key 上传文件保存的文件名
* @param token 上传凭证
* @param params 自定义参数,如 params.put("x:foo", "foo")
* @param mime 指定文件mimetype
*/
public Response put(InputStream stream, String key, String token, StringMap params,
String mime) throws QiniuException {
String message = null;
if (stream == null) {
message = "no input data";
} else if (token == null || token.equals("")) {
message = "no token";
}
if (message != null) {
throw new IllegalArgumentException(message);
}
StreamUploader uploader = new StreamUploader(client, token, key, stream,
params, mime, configuration);
return uploader.upload();
}
}
@@ -0,0 +1,23 @@
package com.luqj.sso.config;
import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by luqj on 2018/5/17.
*/
@Configuration
public class OssConfig {
@Value("${luqj.oss.endpoint}")
private String ALIYUN_OSS_ENDPOINT;
@Value("${luqj.oss.accessKey}")
private String ALIYUN_OSS_ACCESSKEYID;
@Value("${luqj.oss.secretKey}")
private String ALIYUN_OSS_ACCESSKEYSECRET;
@Bean
public OSSClient ossClient(){
return new OSSClient(ALIYUN_OSS_ENDPOINT,ALIYUN_OSS_ACCESSKEYID,ALIYUN_OSS_ACCESSKEYSECRET);
}
}
@@ -0,0 +1,45 @@
package com.luqj.sso.controller;
import com.luqj.sso.entity.OssCallbackResult;
import com.luqj.sso.entity.OssPolicyResult;
import com.luqj.sso.service.OssService;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* Oss相关操作接口
* Created by luqj on 2018/4/26.
*/
@Controller
@Api(tags = "Oss管理-后台", description = "Oss管理")
@RequestMapping("/common/oss")
public class OssController {
@Autowired
private OssService ossService;
@ApiOperation(value = "oss上传签名生成")
@RequestMapping(value = "/policy", method = RequestMethod.GET)
@ResponseBody
public AjaxResult policy() {
OssPolicyResult result = ossService.policy();
return AjaxResult.success(result);
}
@ApiOperation(value = "oss上传成功回调")
@RequestMapping(value = "callback", method = RequestMethod.POST)
@ResponseBody
public AjaxResult callback(HttpServletRequest request) {
OssCallbackResult ossCallbackResult = ossService.callback(request);
return AjaxResult.success(ossCallbackResult);
}
}
@@ -0,0 +1,20 @@
package com.luqj.sso.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* oss上传成功后的回调参数
* Created by luqj on 2018/5/17.
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class OssCallbackParam {
@ApiModelProperty("请求的回调地址")
private String callbackUrl;
@ApiModelProperty("回调是传入request中的参数")
private String callbackBody;
@ApiModelProperty("回调时传入参数的格式,比如表单提交形式")
private String callbackBodyType;
}
@@ -0,0 +1,24 @@
package com.luqj.sso.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* oss上传文件的回调结果
* Created by luqj on 2018/5/17.
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class OssCallbackResult {
@ApiModelProperty("文件名称")
private String filename;
@ApiModelProperty("文件大小")
private String size;
@ApiModelProperty("文件的mimeType")
private String mimeType;
@ApiModelProperty("图片文件的宽")
private String width;
@ApiModelProperty("图片文件的高")
private String height;
}
@@ -0,0 +1,26 @@
package com.luqj.sso.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 获取OSS上传文件授权返回结果
* Created by luqj on 2018/5/17.
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class OssPolicyResult {
@ApiModelProperty("访问身份验证中用到用户标识")
private String accessKeyId;
@ApiModelProperty("用户表单上传的策略,经过base64编码过的字符串")
private String policy;
@ApiModelProperty("对policy签名后的字符串")
private String signature;
@ApiModelProperty("上传文件夹路径前缀")
private String dir;
@ApiModelProperty("oss对外服务的访问域名")
private String host;
@ApiModelProperty("上传成功后的回调设置")
private String callback;
}
@@ -0,0 +1,21 @@
package com.luqj.sso.service;
import com.luqj.sso.entity.OssCallbackResult;
import com.luqj.sso.entity.OssPolicyResult;
import javax.servlet.http.HttpServletRequest;
/**
* oss上传管理Service
* Created by luqj on 2018/5/17.
*/
public interface OssService {
/**
* oss上传策略生成
*/
OssPolicyResult policy();
/**
* oss上传成功回调
*/
OssCallbackResult callback(HttpServletRequest request);
}
@@ -0,0 +1,102 @@
package com.luqj.sso.service.impl;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.luqj.sso.entity.OssCallbackParam;
import com.luqj.sso.entity.OssCallbackResult;
import com.luqj.sso.entity.OssPolicyResult;
import com.luqj.sso.service.OssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* oss上传管理Service实现类
* Created by luqj on 2018/5/17.
*/
@Service
public class OssServiceImpl implements OssService {
private static final Logger LOGGER = LoggerFactory.getLogger(OssServiceImpl.class);
@Value("${luqj.oss.policy.expire}")
private int ALIYUN_OSS_EXPIRE;
@Value("${luqj.oss.maxSize}")
private int ALIYUN_OSS_MAX_SIZE;
@Value("${luqj.oss.callback}")
private String ALIYUN_OSS_CALLBACK;
@Value("${luqj.oss.bucketName}")
private String ALIYUN_OSS_BUCKET_NAME;
@Value("${luqj.oss.endpoint}")
private String ALIYUN_OSS_ENDPOINT;
@Value("${luqj.oss.dir.prefix}")
private String ALIYUN_OSS_DIR_PREFIX;
@Autowired
private OSSClient ossClient;
/**
* 签名生成
*/
@Override
public OssPolicyResult policy() {
OssPolicyResult result = new OssPolicyResult();
// 存储目录
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dir = ALIYUN_OSS_DIR_PREFIX + sdf.format(new Date());
// 签名有效期
long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_EXPIRE * 1000;
Date expiration = new Date(expireEndTime);
// 文件大小
long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024;
// 回调
OssCallbackParam callback = new OssCallbackParam();
callback.setCallbackUrl(ALIYUN_OSS_CALLBACK);
callback.setCallbackBody("filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
callback.setCallbackBodyType("application/x-www-form-urlencoded");
// 提交节点
String action = "http://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT;
try {
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String policy = BinaryUtil.toBase64String(binaryData);
String signature = ossClient.calculatePostSignature(postPolicy);
String callbackData = BinaryUtil.toBase64String(JSONUtil.parse(callback).toString().getBytes("utf-8"));
// 返回结果
result.setAccessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId());
result.setPolicy(policy);
result.setSignature(signature);
result.setDir(dir);
result.setCallback(callbackData);
result.setHost(action);
} catch (Exception e) {
LOGGER.error("签名生成失败", e);
}
return result;
}
@Override
public OssCallbackResult callback(HttpServletRequest request) {
OssCallbackResult result = new OssCallbackResult();
String filename = request.getParameter("filename");
filename = "http://".concat(ALIYUN_OSS_BUCKET_NAME).concat(".").concat(ALIYUN_OSS_ENDPOINT).concat("/").concat(filename);
result.setFilename(filename);
result.setSize(request.getParameter("size"));
result.setMimeType(request.getParameter("mimeType"));
result.setWidth(request.getParameter("width"));
result.setHeight(request.getParameter("height"));
return result;
}
}
@@ -0,0 +1,578 @@
package com.luqj.util;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.CertificateException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
@Slf4j
public class HttpHelper {
private String proxyHost;
private Integer proxyPort;
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public Integer getProxyPort() {
return proxyPort;
}
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}
public static void main(String[] args) throws Exception {
BigDecimal decimal = new BigDecimal("1").divide(new BigDecimal(100));
esListense();
}
/**
* 读取网络文本
*
* @param sourcePath
* @return
*/
public List<String> readHttpFile(String sourcePath) {
String line;
int lineNum = 0;
List<String> list = new ArrayList<>();
BufferedReader reader = null;
try {
URL url = new URL(sourcePath);
reader = new BufferedReader(new InputStreamReader(url.openStream(), "gbk"));
while ((line = reader.readLine()) != null) {
lineNum++;
list.add(line);
}
} catch (Exception ie) {
ie.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public List<String> readGzFile(String url) throws IOException {
InputStream in = new GZIPInputStream(new FileInputStream(url));
List<String> list = IOUtils.readLines(in, "UTF-8");
return list;
}
public List<String> readHttpGzFile(String sourcePath) {
List<String> list = new ArrayList<>();
BufferedReader reader = null;
try {
URL url = new URL(sourcePath);
InputStream in = new GZIPInputStream(url.openStream());
list = IOUtils.readLines(in, "UTF-8");
} catch (Exception ie) {
ie.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public CloseableHttpClient getHttpsClient() throws Exception {
SSLContext sslcontext = SSLContexts.custom().useSSL().build();
sslcontext.init(null, new X509TrustManager[]{new HttpsTrustManager()}, new SecureRandom());
SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(500000)
.setStaleConnectionCheckEnabled(true)
.build();
RequestConfig requestConfig = null;
if (StringUtils.isNotBlank(proxyHost) && null != proxyPort) {
// setProxy(new HttpHost("lu7213.6655.la", 57301))
// setProxy(new HttpHost("127.0.0.1", 19180))
requestConfig = RequestConfig.copy(defaultRequestConfig).setProxy(new HttpHost(proxyHost, proxyPort))
.build();
} else {
requestConfig = RequestConfig.copy(defaultRequestConfig).build();
}
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(factory).setDefaultRequestConfig(requestConfig).build();
return client;
}
/**
* 导入证书
*
* @return
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws IOException
* @throws KeyManagementException
*/
private SSLContext getSSLContext() throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
instream.close();
}
return SSLContexts.custom()
.loadTrustMaterial(trustStore)
.build();
}
// es 7.4 白嫖命令
private static boolean esListense() throws Exception {
HttpHelper httpHelper = new HttpHelper();
HashMap<String, Object> headers = new HashMap<>();
// headers.put("Content-Type", "application/json");
HashMap<String, Object> map = new HashMap<>();
map.put("access_token", "1278491352545154|4fa79654c00caab794a70afee2d769c2");
map.put("input_token", "EAASKxZCbqt4IBAOwxuyFEZCynraaVQtOrMnwkj301sxydRYZBiZBUe1REIV1zcrXvSC6nsnPVMG1YpB645OsRACOjQ9C9T4lFJxQI1rPon2p2Ww8onXsKytaOcqaKFf2f4EZAA4doPxGcJoBiCnKh0g7EdhjZBQrfpC1Q05N87fLUlKHE3ZAQddLeZAIKBaXcoyDVhqTSWVGoKlghLQvMpnJNeXmRyQTSIAZD");
// ResponseWrapper result = httpHelper.sendGet("https://graph.facebook.com/debug_token", map);
// httpHelper.setProxyHost("192.168.2.4");
// httpHelper.setProxyPort(29180);
// String result = httpHelper.getlHttpResult("https://graph.facebook.com/debug_token", "GET", headers, map);
// System.out.println(result);
// HashMap headers = new HashMap<>();
//// headers.put("Content-Type", "application/json");
String data = "{\"license\":{\"uid\":\"64311a78-1da8-4242-801d-1919b2ee6373\",\"type\":\"platinum\",\"issue_date_in_millis\":1591660800000,\"expiry_date_in_millis\":2516630400000,\"max_nodes\":100,\"issued_to\":\"qungjie lu (dragon)\",\"issuer\":\"Web Form\",\"signature\":\"AAAAAwAAAA3TbuzQUBHKydhRaMl8AAABmC9ZN0hjZDBGYnVyRXpCOW5Bb3FjZDAxOWpSbTVoMVZwUzRxVk1PSmkxaktJRVl5MUYvUWh3bHZVUTllbXNPbzBUemtnbWpBbmlWRmRZb25KNFlBR2x0TXc2K2p1Y1VtMG1UQU9TRGZVSGRwaEJGUjE3bXd3LzRqZ05iLzRteWFNekdxRGpIYlFwYkJiNUs0U1hTVlJKNVlXekMrSlVUdFIvV0FNeWdOYnlESDc3MWhlY3hSQmdKSjJ2ZTcvYlBFOHhPQlV3ZHdDQ0tHcG5uOElCaDJ4K1hob29xSG85N0kvTWV3THhlQk9NL01VMFRjNDZpZEVXeUtUMXIyMlIveFpJUkk2WUdveEZaME9XWitGUi9WNTZVQW1FMG1DenhZU0ZmeXlZakVEMjZFT2NvOWxpZGlqVmlHNC8rWVVUYzMwRGVySHpIdURzKzFiRDl4TmM1TUp2VTBOUlJZUlAyV0ZVL2kvVk10L0NsbXNFYVZwT3NSU082dFNNa2prQ0ZsclZ4NTltbU1CVE5lR09Bck93V2J1Y3c9PQAAAQBCUpzI7WOa8sBex3uA0Ag2ELeK9+bTX/GPpqKFEoEU6tdWyxxXsfwC1a8+FTkDmm/96jAm7x86wlgu3vimq7nK2ddMjNub3zZd4TAa3pRZfyNnJrlWzDIzyKwHI1N13YB4cEnrSgf+Hj/czIcLcFjTr7IEgXIuc1kfeEmghGLWVKZkHaoeTStWt5+3w/xwzs0ieacWp+FFkJv06ywEf96HusMSc1ExrRL/4JRY+zJiMjupxvrNSm3VP6K2I1RhR+XLXM/9d71jxPXFtFbY1IyAjHOviie7baszbR+eD3F1uHFOoR7WpKNYkXxVF+002HYtoKI4OEN2t6PXx12yAlXM\",\"start_date_in_millis\":1591660800000}}";
String result = httpHelper.playLoad("put", "http://192.168.2.176:9200/_xpack/license", headers, data, "application/json", "utf-8");
System.out.println(result);
return true;
}
private PoolingHttpClientConnectionManager cm;
public HttpHelper() {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(500); // 整个连接池最大连接数
cm.setDefaultMaxPerRoute(5); // 每路由最大连接数,默认值是2
}
/**
* 通过连接池获取HttpClient
*
* @return
*/
private CloseableHttpClient getHttpClient() {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000000)
.setStaleConnectionCheckEnabled(true)
.build();
RequestConfig requestConfig = null;
if (StringUtils.isNotBlank(proxyHost) && null != proxyPort) {
// setProxy(new HttpHost("lu7213.6655.la", 57301))
// setProxy(new HttpHost("127.0.0.1", 19180))
requestConfig = RequestConfig.copy(defaultRequestConfig).setProxy(new HttpHost(proxyHost, proxyPort))
.build();
} else {
requestConfig = RequestConfig.copy(defaultRequestConfig).build();
}
return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
}
private ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
return pairs;
}
/**
* 发送http
*
* @param url
* @param method
* @param headers
* @return
* @throws Exception
*/
public CloseableHttpResponse send(CloseableHttpClient httpClient, String url, String method, Map<String, Object> headers) throws Exception {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
HttpRequestBase http = null;
if (method.toLowerCase().equals("put")) {
http = new HttpPut(ub.build());
}
if (method.toLowerCase().equals("post")) {
http = new HttpPost(ub.build());
}
if (method.toLowerCase().equals("get")) {
http = new HttpGet(ub.build());
}
if (method.toLowerCase().equals("delete")) {
http = new HttpDelete(ub.build());
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
try {
return httpClient.execute(http);
} catch (Exception e) {
throw e;
}
}
public CloseableHttpResponse send(CloseableHttpClient httpClient, String url, String method) throws Exception {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
HttpRequestBase http = null;
if (method.toLowerCase().equals("put")) {
http = new HttpPut(ub.build());
}
if (method.toLowerCase().equals("post")) {
http = new HttpPost(ub.build());
}
if (method.toLowerCase().equals("get")) {
http = new HttpGet(ub.build());
}
if (method.toLowerCase().equals("delete")) {
http = new HttpDelete(ub.build());
}
try {
return httpClient.execute(http);
} catch (Exception e) {
throw e;
}
}
/**
* 发送http
*
* @param url
* @param method
* @param headers
* @param params
* @return
* @throws Exception
*/
public CloseableHttpResponse send(CloseableHttpClient httpClient, String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
if (method.toLowerCase().equals("put")) {
ub.setParameters(pairs);
HttpPut http = null;
if (pairs.size() > 0) {
http = new HttpPut(ub.build());
} else {
http = new HttpPut(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return httpClient.execute(http);
}
if (method.toLowerCase().equals("post")) {
ub.setParameters(pairs);
HttpPost http = null;
if (pairs.size() > 0) {
http = new HttpPost(ub.build());
} else {
http = new HttpPost(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
return httpClient.execute(http);
}
if (method.toLowerCase().equals("get")) {
HttpGet http = null;
if (pairs.size() > 0) {
ub.setParameters(pairs);
String path = ub.toString();
if(path.startsWith("/")) {
http = new HttpGet(path.substring(1));
}else{
http = new HttpGet(ub.build());
}
} else {
http = new HttpGet(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
// HttpHost target = new HttpHost(InetAddress.,ub.getHost(),ub.getPort(),ub.getScheme());
return httpClient.execute(http);
}
if (method.toLowerCase().equals("delete")) {
ub.setParameters(pairs);
HttpDelete http = null;
if (pairs.size() > 0) {
http = new HttpDelete(ub.build());
} else {
http = new HttpDelete(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return httpClient.execute(http);
}
if (method.toLowerCase().equals("options")) {
ub.setParameters(pairs);
HttpOptions http = null;
if (pairs.size() > 0) {
http = new HttpOptions(ub.build());
} else {
http = new HttpOptions(url);
}
for (Map.Entry<String, Object> param : headers.entrySet()) {
http.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
return httpClient.execute(http);
}
return null;
}
public ResponseWrapper sendGet(String apiUrl, Map<String, Object> allParams) throws Exception {
URL url = new URL(RequestHelper.constructUrlString(apiUrl, allParams));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "fbbizsdk-java-v3.3");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return readResponse(con);
}
private ResponseWrapper readResponse(HttpsURLConnection con) throws Exception {
try {
int responseCode = con.getResponseCode();
String header = convertToString(con.getHeaderFields());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return new ResponseWrapper(response.toString(), header);
} catch (Exception e) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
throw new Exception(response.toString(), e);
}
}
private String convertToString(Object input) {
if (input == null) {
return "null";
} else if (input instanceof Map) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.disableHtmlEscaping()
.create();
return gson.toJson((Map) input);
} else if (input instanceof List) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.disableHtmlEscaping()
.create();
return gson.toJson((List) input);
} else {
return input.toString();
}
}
/**
* 处理Http请求
*
* @return
*/
public String getlHttpResult(String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
CloseableHttpResponse response = this.send(httpClient, url, method, headers, params);
if (method.toLowerCase().equals("options")) {
return response.getStatusLine().getStatusCode() + "";
} else {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
// httpClient.close();
response.close();
return result;
}
return "";
}
}
public String getlHttpResultCode(String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
CloseableHttpResponse response = this.send(httpClient, url, method, headers, params);
return response.getStatusLine().getStatusCode() + "";
}
public Boolean testHttp(String url, String method, Map<String, Object> headers, Map<String, Object> params) throws Exception {
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
CloseableHttpResponse response = this.send(httpClient, url, method, headers, params);
boolean result = response.getStatusLine().getStatusCode() == 200;
response.close();
return result;
}
public void clear() {
cm.close();
}
public String playLoad(String method, String url, Map<String, Object> headersMap, Object data, String contentType, String charset) throws Exception {
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
httpClient = getHttpsClient();
} else {
httpClient = getHttpClient();
}
String result = null;
HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase = null;
if ("post".equalsIgnoreCase(method)) {
httpEntityEnclosingRequestBase = new HttpPost(url);
} else if ("put".equalsIgnoreCase(method)) {
httpEntityEnclosingRequestBase = new HttpPut(url);
} else if ("get".equalsIgnoreCase(method)) {
httpEntityEnclosingRequestBase = new HttpEntityEnclosingRequestBase() {
@Override
public String getMethod() {
return "GET";
}
};
httpEntityEnclosingRequestBase.setURI(new URI(url));
}
for (Map.Entry<String, Object> param : headersMap.entrySet()) {
httpEntityEnclosingRequestBase.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
httpEntityEnclosingRequestBase.addHeader("Content-Type", contentType);
String json = "";
if (data instanceof String) {
json = String.valueOf(data);
} else {
json = JSONObject.toJSONString(data);
}
StringEntity entity = new StringEntity(json, charset);
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpEntityEnclosingRequestBase.setEntity(entity);
// 响应模型
CloseableHttpResponse response = null;
try {
// 由客户端执行(发送)Post请求
response = (CloseableHttpResponse) httpClient.execute(httpEntityEnclosingRequestBase);
// 从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity);
}
} catch (Exception e) {
log.error(e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
return result;
}
/**
* 替换指定格式的日期
*
* @param value
* @return
*/
public String replaceCurDate(String value) {
String cur = formatDate(new Date(), "yyyyMMddHHmm");
String result = value.replaceAll("\\$\\{yyyyMMddHHmm\\}", cur);
cur = formatDate(new Date(), "yyyyMMddHH");
result = result.replaceAll("\\$\\{yyyyMMddHH\\}", cur);
cur = formatDate(new Date(), "yyyyMMdd");
result = result.replaceAll("\\$\\{yyyyMMdd\\}", cur);
cur = formatDate(new Date(), "yyyyMM");
result = result.replaceAll("\\$\\{yyyyMM\\}", cur);
return result;
}
public String formatDate(final Date date, final String pattern) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
return formatter.format(date);
}
}
@@ -0,0 +1,28 @@
package com.luqj.util;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class HttpsTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
@@ -0,0 +1,129 @@
package com.luqj.util;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RequestHelper {
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
public static Map<String, String> fileToContentTypeMap = new HashMap<String, String>();
static {
fileToContentTypeMap.put(".atom", "application/atom+xml");
fileToContentTypeMap.put(".rss", "application/rss+xml");
fileToContentTypeMap.put(".xml", "application/xml");
fileToContentTypeMap.put(".csv", "text/csv");
fileToContentTypeMap.put(".txt", "text/plain");
}
public static String getContentTypeForFile(File file) {
String contentType = fileToContentTypeMap.get(getFileExtension(file));
if (contentType != null) return contentType;
try {
contentType = Files.probeContentType(file.toPath());
} catch (IOException ignored) {
}
return contentType != null ? contentType : DEFAULT_CONTENT_TYPE;
}
private static String getFileExtension(File file) {
String fileName = file.getName();
int index = fileName.lastIndexOf('.');
if (index == -1) return "";
return fileName.substring(index, fileName.length());
}
private static String convertToString(Object input) {
if (input == null) {
return "null";
} else if (input instanceof Map) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.disableHtmlEscaping()
.create();
return gson.toJson((Map) input);
} else if (input instanceof List) {
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.STATIC)
.excludeFieldsWithModifiers(Modifier.PROTECTED)
.disableHtmlEscaping()
.create();
return gson.toJson((List) input);
} else {
return input.toString();
}
}
public static int getContentLength(Map<String, Object> allParams, String boundary) throws IOException {
int contentLength = 0;
for (Map.Entry entry : allParams.entrySet()) {
contentLength += ("--" + boundary + "\r\n").length();
if (entry.getValue() instanceof File) {
File file = (File) entry.getValue();
String contentType = getContentTypeForFile(file);
contentLength += getLengthAndLog( "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + file.getName() + "\"\r\n");
if (contentType != null) {
contentLength += getLengthAndLog( "Content-Type: " + contentType + "\r\n");
}
contentLength += getLengthAndLog( "\r\n");
contentLength += file.length();
contentLength += getLengthAndLog( "\r\n");
} else if (entry.getValue() instanceof byte[]) {
byte[] bytes = (byte[]) entry.getValue();
contentLength += getLengthAndLog( "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + "chunkfile" + "\"\r\n");
contentLength += bytes.length;
contentLength += getLengthAndLog( "\r\n");
} else {
contentLength += getLengthAndLog( "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
contentLength += getLengthAndLog( convertToString(entry.getValue()));
contentLength += getLengthAndLog( "\r\n");
}
}
contentLength += getLengthAndLog( "--" + boundary + "--\r\n");
return contentLength;
}
private static int getLengthAndLog(String input) throws IOException {
return input.getBytes("UTF-8").length;
}
public static String constructUrlString(String apiUrl, Map<String, Object> allParams) throws IOException {
StringBuilder urlString = new StringBuilder(apiUrl);
boolean firstEntry = true;
for (Map.Entry entry : allParams.entrySet()) {
urlString.append((firstEntry ? "?" : "&") + URLEncoder.encode(entry.getKey().toString(), "UTF-8") + "=" + URLEncoder.encode(convertToString(entry.getValue()), "UTF-8"));
firstEntry = false;
}
return urlString.toString();
}
public static ListenableFuture<ResponseWrapper> invoke(okhttp3.OkHttpClient client, okhttp3.Request request) {
final SettableFuture<ResponseWrapper> future = SettableFuture.create();
client.newCall(request).enqueue(
new okhttp3.Callback() {
@Override
public void onFailure(final okhttp3.Call call, IOException e) {
future.setException(
new Exception(e)
);
}
@Override
public void onResponse(okhttp3.Call call, final okhttp3.Response response) throws IOException {
future.set(new ResponseWrapper(response.body().string(), convertToString(response.headers())));
}
});
return future;
}
}
@@ -0,0 +1,19 @@
package com.luqj.util;
public class ResponseWrapper {
private String body;
private String header;
public ResponseWrapper(String body, String header) {
this.body = body;
this.header = header;
}
public String getBody() {
return this.body;
}
public String getHeader() {
return this.header;
}
}
@@ -0,0 +1,92 @@
package com.luqj.util;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
public class SignatureUtil {
/**
* 生成签名
* @param params 业务参数(不包含signature)
* @param apiToken API认证密钥(例如 epusdt_password_xasddawqe)
* @return 生成的MD5签名(32位小写)
*/
public static String generateSignature(Map<String, Object> params, String apiToken) {
// 1. 按 ASCII 排序
SortedMap<String, Object> sortedParams = new TreeMap<>(params);
// 2. 拼接成 key=value&key=value
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
// if(entry.getValue() instanceof Double){
// Double val = (Double) entry.getValue();
// BigDecimal amount = new BigDecimal(val);
// if (entry.getValue() != null) {
// sb.append(entry.getKey()).append("=").append( amount.setScale(2, RoundingMode.DOWN).toPlainString()).append("&");
// }
// }else if(entry.getValue() instanceof BigDecimal){
// BigDecimal amount = (BigDecimal) entry.getValue();
// if (entry.getValue() != null) {
// sb.append(entry.getKey()).append("=").append( amount.setScale(2, RoundingMode.DOWN).toPlainString()).append("&");
// }
// }else {
// if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
// sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
// }
// }
if (entry.getValue() != null && !entry.getValue().toString().isEmpty()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
// 去掉最后一个 & 符号
sb.setLength(sb.length() - 1);
// 3. 拼接密钥
sb.append(apiToken); // 注意:不是加 &,是直接拼接密钥!!!
// 4. MD5加密
return md5(sb.toString()).toLowerCase();
}
// MD5算法实现
private static String md5(String text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(text.getBytes("UTF-8"));
StringBuilder hexString = new StringBuilder();
for (byte b : digest) {
hexString.append(String.format("%02x", b & 0xff));
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException("MD5 error: " + e.getMessage(), e);
}
}
// 测试方法
public static void main(String[] args) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("order_id", System.currentTimeMillis()+"");
params.put("app_id", "1");
params.put("amount", "64.01");
params.put("notify_url", "http://127.0.0.1:5005/transfer/trc/notify");
params.put("redirect_url", "http://example.com/redirect"); //pay/checkout-counter/xxx 支付成功后得回调地址
String token = "lqj";
String signature = generateSignature(params, token);
//c50576484554b282f6c2b53097217464
System.out.println("Signature = " + signature);
HttpHelper httpHelper = new HttpHelper();
HashMap<String, Object> headers = new HashMap<>();
// headers.put("Content-Type", "application/json");
params.put("signature", signature);
String result =httpHelper.playLoad("post","https://yougc.com/usdt/api/v1/order/create-transaction"
,headers,params,"application/json","utf-8");
System.out.println(result);
}
}
@@ -0,0 +1,124 @@
<?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.luqj.common.mapper.ComCategoryMapper">
<resultMap type="ComCategory" id="ComCategoryResult">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="parentId" column="parent_id" />
<result property="parentIds" column="parent_ids" />
<result property="projectType" column="project_type" />
<result property="sortNum" column="sort_num" />
<result property="iconUrl" column="icon_url" />
<result property="picUrl" column="pic_url" />
<result property="hasLeaf" column="has_leaf" />
<result property="homeShow" column="home_show" />
<result property="level" column="level" />
<result property="flag" column="flag" />
<result property="description" column="description" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
<result property="status" column="status" />
</resultMap>
<sql id="selectComCategoryVo">
select id, name, parent_id, parent_ids, project_type, sort_num, icon_url, pic_url, has_leaf, home_show, level, flag, description, create_time, update_time, status from com_category
</sql>
<select id="selectComCategoryList" parameterType="ComCategory" resultMap="ComCategoryResult">
<include refid="selectComCategoryVo"/>
<where>
<if test="name != null and name != ''"> and name like concat('%', #{name}, '%')</if>
<if test="parentId != null "> and parent_id = #{parentId}</if>
<if test="parentIds != null and parentIds != ''"> and parent_ids = #{parentIds}</if>
<if test="projectType != null "> and project_type = #{projectType}</if>
<if test="sortNum != null "> and sort_num = #{sortNum}</if>
<if test="iconUrl != null and iconUrl != ''"> and icon_url = #{iconUrl}</if>
<if test="picUrl != null and picUrl != ''"> and pic_url = #{picUrl}</if>
<if test="hasLeaf != null "> and has_leaf = #{hasLeaf}</if>
<if test="homeShow != null "> and home_show = #{homeShow}</if>
<if test="level != null "> and level = #{level}</if>
<if test="flag != null "> and flag = #{flag}</if>
<if test="description != null and description != ''"> and description = #{description}</if>
<if test="status != null "> and status = #{status}</if>
</where>
</select>
<select id="selectComCategoryById" parameterType="Long" resultMap="ComCategoryResult">
<include refid="selectComCategoryVo"/>
where id = #{id}
</select>
<insert id="insertComCategory" parameterType="ComCategory" useGeneratedKeys="true" keyProperty="id">
insert into com_category
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">name,</if>
<if test="parentId != null">parent_id,</if>
<if test="parentIds != null">parent_ids,</if>
<if test="projectType != null">project_type,</if>
<if test="sortNum != null">sort_num,</if>
<if test="iconUrl != null">icon_url,</if>
<if test="picUrl != null">pic_url,</if>
<if test="hasLeaf != null">has_leaf,</if>
<if test="homeShow != null">home_show,</if>
<if test="level != null">level,</if>
<if test="flag != null">flag,</if>
<if test="description != null">description,</if>
<if test="createTime != null">create_time,</if>
<if test="updateTime != null">update_time,</if>
<if test="status != null">status,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">#{name},</if>
<if test="parentId != null">#{parentId},</if>
<if test="parentIds != null">#{parentIds},</if>
<if test="projectType != null">#{projectType},</if>
<if test="sortNum != null">#{sortNum},</if>
<if test="iconUrl != null">#{iconUrl},</if>
<if test="picUrl != null">#{picUrl},</if>
<if test="hasLeaf != null">#{hasLeaf},</if>
<if test="homeShow != null">#{homeShow},</if>
<if test="level != null">#{level},</if>
<if test="flag != null">#{flag},</if>
<if test="description != null">#{description},</if>
<if test="createTime != null">#{createTime},</if>
<if test="updateTime != null">#{updateTime},</if>
<if test="status != null">#{status},</if>
</trim>
</insert>
<update id="updateComCategory" parameterType="ComCategory">
update com_category
<trim prefix="SET" suffixOverrides=",">
<if test="name != null">name = #{name},</if>
<if test="parentId != null">parent_id = #{parentId},</if>
<if test="parentIds != null">parent_ids = #{parentIds},</if>
<if test="projectType != null">project_type = #{projectType},</if>
<if test="sortNum != null">sort_num = #{sortNum},</if>
<if test="iconUrl != null">icon_url = #{iconUrl},</if>
<if test="picUrl != null">pic_url = #{picUrl},</if>
<if test="hasLeaf != null">has_leaf = #{hasLeaf},</if>
<if test="homeShow != null">home_show = #{homeShow},</if>
<if test="level != null">level = #{level},</if>
<if test="flag != null">flag = #{flag},</if>
<if test="description != null">description = #{description},</if>
<if test="createTime != null">create_time = #{createTime},</if>
<if test="updateTime != null">update_time = #{updateTime},</if>
<if test="status != null">status = #{status},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteComCategoryById" parameterType="Long">
delete from com_category where id = #{id}
</delete>
<delete id="deleteComCategoryByIds" parameterType="String">
delete from com_category where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
@@ -0,0 +1,5 @@
<?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="org.code.modules.qiniu.mapper.QiniuConfigMapper">
</mapper>