优化文件上传逻辑,增加OSS,修改请求返回为ruoyi风格 code=200,msg="消息内容",增加Vben动态菜单适配

This commit is contained in:
xiaoyoutai
2022-08-14 00:48:51 +08:00
parent 4a188f255d
commit 89d86f2698
121 changed files with 6250 additions and 1484 deletions
+6 -6
View File
@@ -4,9 +4,9 @@
/vboot-extend/target/
/vboot-web/target/
/.idea/
/vboot-web/src/main/resources/application.properties
/vboot-web/src/main/resources/application.yml
/vboot-extend/src/main/java/vboot/extend/bi/
/vboot-extend/src/main/java/vboot/extend/sa/
/vboot-extend/src/main/java/vboot/extend/te/
/vboot-extend/src/main/java/vboot/extend/wc/
#/vboot-web/src/main/resources/application.properties
#/vboot-web/src/main/resources/application.yml
#/vboot-extend/src/main/java/vboot/extend/bi/
#/vboot-extend/src/main/java/vboot/extend/sa/
#/vboot-extend/src/main/java/vboot/extend/te/
#/vboot-extend/src/main/java/vboot/extend/wc/
+8
View File
@@ -76,6 +76,14 @@
<!--Maven远程仓库设置 非必要,可以删除-->
<repositories>
<!-- <repository>-->
<!-- <id>q3z3-boot-temp-maven</id>-->
<!-- <name>maven</name>-->
<!-- <url>https://q3z3-maven.pkg.coding.net/repository/boot-temp/maven/</url>-->
<!-- <releases>-->
<!-- <enabled>true</enabled>-->
<!-- </releases>-->
<!-- </repository>-->
<repository>
<id>public</id>
<name>aliyun nexus</name>
@@ -1,9 +0,0 @@
package vboot.app.de.supp.cate;
import org.springframework.data.jpa.repository.JpaRepository;
//供应商分类JPA仓储
public interface DeSuppCateRepo extends JpaRepository<DeSuppCate,String> {
}
@@ -1,51 +0,0 @@
package vboot.app.de.supp.main;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
//主记录OneToMany
@Entity
@Data
@ApiModel("供应商附件")
public class DeSuppAtt
{
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
@Column(length = 32)
@ApiModelProperty("存储地址")
private String addre;
@Column(length = 128)
@ApiModelProperty("文件前缀名")
private String pname;
@Column(length = 128)
@ApiModelProperty("文件后缀名")
private String sname;
@Column(length = 16)
@ApiModelProperty("文件大小")
private String zsize;
@Transient
@ApiModelProperty("图片缩略图")
private String zimg;
@Column(length = 256)
@ApiModelProperty("文件全名")
private String name;
@Column(length = 256)
@ApiModelProperty("文件链接地址")
private String link;
}
@@ -1,63 +0,0 @@
package vboot.app.de.supp.main;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.Sqler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vboot.core.module.ass.num.main.AssNumMainService;
import vboot.core.module.mon.log.oper.Oplog;
@RestController
@RequestMapping("de/supp/main")
@Api(tags = {"供应商管理"})
public class DeSuppMainApi {
@Oplog("查询供应商分页")
@GetMapping
@ApiOperation("查询供应商分页")
public R get(String name) {
Sqler sqler = new Sqler("de_supp_main");
sqler.addLike("t.name", name);
sqler.addSelect("t.addre,t.senum,t.notes");
return R.ok(service.findPageData(sqler));
}
@Oplog("查询供应商详情")
@GetMapping("one/{id}")
@ApiOperation("查询供应商详情")
public R getOne(@PathVariable String id) {
DeSuppMain main = service.findOne(id);
return R.ok(main);
}
@Oplog("新增供应商")
@PostMapping
@ApiOperation("新增供应商")
public R post(@RequestBody DeSuppMain main) {
main.setSenum(numService.getNum("SUPP"));//设置供应商流水号
return R.ok(service.insert(main));
}
@Oplog("更新供应商")
@PutMapping
@ApiOperation("更新供应商")
public R put(@RequestBody DeSuppMain main) {
return R.ok(service.update(main));
}
@Oplog("删除供应商")
@DeleteMapping("{ids}")
@ApiOperation("删除供应商")
public R delete(@PathVariable String[] ids) {
return R.ok(service.delete(ids));
}
@Autowired
private DeSuppMainService service;
@Autowired
private AssNumMainService numService;
}
@@ -1,10 +0,0 @@
package vboot.app.de.supp.main;
import org.springframework.data.jpa.repository.JpaRepository;
//供应商JPA仓储
public interface DeSuppMainRepo extends JpaRepository<DeSuppMain,String> {
}
@@ -1,4 +1,4 @@
package vboot.app.de.supp.cate;
package vboot.app.my.demo.cate;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -11,12 +11,12 @@ import javax.persistence.*;
@Entity
@Getter
@Setter
@ApiModel("供应商分类")
public class DeSuppCate extends BaseCateEntity {
@ApiModel("DEMO分类")
public class MyDemoCate extends BaseCateEntity {
@ManyToOne(fetch= FetchType.EAGER)
@JoinColumn(name = "pid")
@ApiModelProperty("父类别")
private DeSuppCate parent;
private MyDemoCate parent;
}
@@ -1,4 +1,4 @@
package vboot.app.de.supp.cate;
package vboot.app.my.demo.cate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -11,40 +11,40 @@ import vboot.core.common.mvc.pojo.Ztree;
import java.util.List;
@RestController
@RequestMapping("de/supp/cate")
@Api(tags = {"供应商分类管理"})
public class DeSuppCateApi {
@RequestMapping("my/demo/cate")
@Api(tags = {"DEMO分类管理"})
public class MyDemoCateApi {
private String table = "de_supp_cate";
private String table = "my_demo_cate";
@GetMapping("treez")
@ApiOperation("查询供应商除自身外的分类树")
@ApiOperation("查询DEMO除自身外的分类树")
public R getTreez(String name, String id) {
List<Ztree> list = service.tier2Choose(table, id, name);
return R.ok(list);
}
@GetMapping("treea")
@ApiOperation("查询供应商分类树")
@ApiOperation("查询DEMO分类树")
public R getTreea(String name) {
List<Ztree> list = service.findTreeList(table, name);
return R.ok(list);
}
@GetMapping("tree")
@ApiOperation("查询供应商分类列表")
@ApiOperation("查询DEMO分类列表")
public R getTree(String name) {
Sqler sqler = new Sqler(table);
sqler.addLike("t.name", name);
sqler.addOrder("t.ornum");
sqler.addWhere("t.avtag=1");
sqler.addSelect("t.crtim,t.uptim,t.pid,t.notes");
List<DeSuppCate> list = service.findTree(sqler);
List<MyDemoCate> list = service.findTree(sqler);
return R.ok(list);
}
@GetMapping
@ApiOperation("查询供应商分类分页")
@ApiOperation("查询DEMO分类分页")
public R get(String name) {
Sqler sqler = new Sqler(table);
sqler.addLike("t.name", name);
@@ -53,30 +53,30 @@ public class DeSuppCateApi {
}
@GetMapping("one/{id}")
@ApiOperation("查询供应商分类详情")
@ApiOperation("查询DEMO分类详情")
public R getOne(@PathVariable String id) {
return R.ok(service.findOne(id));
}
@PostMapping
@ApiOperation("新增供应商分类")
public R post(@RequestBody DeSuppCate main) {
@ApiOperation("新增DEMO分类")
public R post(@RequestBody MyDemoCate main) {
return R.ok(service.insert(main));
}
@PutMapping
@ApiOperation("更新供应商分类")
public R put(@RequestBody DeSuppCate main) {
@ApiOperation("更新DEMO分类")
public R put(@RequestBody MyDemoCate main) {
return R.ok(service.update(main, table));
}
@DeleteMapping("{ids}")
@ApiOperation("删除供应商分类")
@ApiOperation("删除DEMO分类")
public R delete(@PathVariable String[] ids) {
return R.ok(service.delete(ids));
}
@Autowired
private DeSuppCateService service;
private MyDemoCateService service;
}
@@ -0,0 +1,9 @@
package vboot.app.my.demo.cate;
import org.springframework.data.jpa.repository.JpaRepository;
//DEMO分类JPA仓储
public interface MyDemoCateRepo extends JpaRepository<MyDemoCate,String> {
}
@@ -1,4 +1,4 @@
package vboot.app.de.supp.cate;
package vboot.app.my.demo.cate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
@@ -9,19 +9,19 @@ import vboot.core.common.mvc.service.BaseCateService;
import javax.annotation.PostConstruct;
import java.util.List;
//供应商分类服务
//DEMO分类服务
@Service
public class DeSuppCateService extends BaseCateService<DeSuppCate> {
public class MyDemoCateService extends BaseCateService<MyDemoCate> {
//获取分类treeTable数据
public List<DeSuppCate> findTree(Sqler sqler) {
List<DeSuppCate> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(),
new BeanPropertyRowMapper<>(DeSuppCate.class));
public List<MyDemoCate> findTree(Sqler sqler) {
List<MyDemoCate> list = jdbcDao.getTp().query(sqler.getSql(), sqler.getParams(),
new BeanPropertyRowMapper<>(MyDemoCate.class));
return buildByRecursive(list);
}
@Autowired
private DeSuppCateRepo repo;
private MyDemoCateRepo repo;
@PostConstruct
public void initDao() {
@@ -0,0 +1,41 @@
package vboot.app.my.demo.main;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
@Data
@ApiModel("DEMO附件")
public class MyDemoAtt
{
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
@ApiModelProperty("附件名称")
private String name;
@ApiModelProperty("附件大小")
private String size;
@ApiModelProperty("存储地址")
private String path;
@ApiModelProperty("文件ID")
@Column(length = 32)
private String filid;
@ApiModelProperty("业务ID")
@Column(length = 32)
private String busid;
@ApiModelProperty("排序号")
private Integer ornum;
}
@@ -1,4 +1,4 @@
package vboot.app.de.supp.main;
package vboot.app.my.demo.main;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -11,8 +11,8 @@ import javax.persistence.Id;
//主记录OneToMany
@Data
@Entity
@ApiModel("供应商联系人")
public class DeSuppContact {
@ApiModel("DEMO明细行")
public class MyDemoItem {
@Id
@Column(length = 36)
@ApiModelProperty("主键ID")
@@ -1,4 +1,4 @@
package vboot.app.de.supp.main;
package vboot.app.my.demo.main;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -14,12 +14,12 @@ import java.util.List;
@Entity
@Getter
@Setter
@ApiModel("供应商信息")
public class DeSuppMain extends BaseMainEntity {
@ApiModel("DEMO主数据")
public class MyDemoMain extends BaseMainEntity {
//关联分类表示例
//分类关联示例
@Column(length = 32)
@ApiModelProperty("供应商分类")
@ApiModelProperty("分类ID")
private String catid;
//流水号示例
@@ -29,7 +29,7 @@ public class DeSuppMain extends BaseMainEntity {
//数据字典示例
@Column(length = 32)
@ApiModelProperty("供应商资质")
@ApiModelProperty("等级")
private String grade;
//ManyToOne示例
@@ -40,14 +40,14 @@ public class DeSuppMain extends BaseMainEntity {
//ManyToMany示例
@ManyToMany
@JoinTable(name = "de_supp_viewer", joinColumns = {@JoinColumn(name = "mid")},
@JoinTable(name = "my_demo_viewer", joinColumns = {@JoinColumn(name = "mid")},
inverseJoinColumns = {@JoinColumn(name = "oid")})
@ApiModelProperty("可查看者")
private List<SysOrg> viewers;
//ManyToMany示例
@ManyToMany
@JoinTable(name = "de_supp_editor", joinColumns = {@JoinColumn(name = "mid")},
@JoinTable(name = "my_demo_editor", joinColumns = {@JoinColumn(name = "mid")},
inverseJoinColumns = {@JoinColumn(name = "oid")})
@ApiModelProperty("可编辑者")
private List<SysOrg> editors;
@@ -56,15 +56,15 @@ public class DeSuppMain extends BaseMainEntity {
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "maiid")
@OrderBy("ornum ASC")
@ApiModelProperty("联系人清单")
private List<DeSuppContact> contacts = new ArrayList<>();
@ApiModelProperty("明细行")
private List<MyDemoItem> items = new ArrayList<>();
//附件示例
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "maiid")
@JoinColumn(name = "busid")
@OrderBy("ornum ASC")
@ApiModelProperty("附件清单")
private List<DeSuppAtt> atts = new ArrayList<>();
private List<MyDemoAtt> atts = new ArrayList<>();
//地址选择示例,可根据实际情况存想要的字段
//region-----地址相关信息-----
@@ -0,0 +1,70 @@
package vboot.app.my.demo.main;
import cn.hutool.core.lang.Dict;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.Sqler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vboot.core.common.utils.ruoyi.JsonUtils;
import vboot.core.module.ass.num.main.AssNumMainService;
import vboot.core.module.mon.log.oper.Oplog;
@RestController
@RequestMapping("my/demo/main")
@Api(tags = {"DEMO管理"})
public class MyDemoMainApi {
@Oplog("查询DEMO分页")
@GetMapping
@ApiOperation("查询DEMO分页")
public R get(String name) {
Sqler sqler = new Sqler("my_demo_main");
sqler.addLike("t.name", name);
sqler.addSelect("t.addre,t.senum,t.notes");
return R.ok(service.findPageData(sqler));
}
@Oplog("查询DEMO详情")
@GetMapping("one/{id}")
@ApiOperation("查询DEMO详情")
public R getOne(@PathVariable String id) throws ApiException {
MyDemoMain main = service.findOne(id);
return R.ok(main);
}
@Oplog("新增DEMO")
@PostMapping
@ApiOperation("新增DEMO")
public R post(@RequestBody MyDemoMain main) {
main.setSenum(numService.getNum("DEMO"));//设置供应商流水号
return R.ok(service.insert(main));
}
@Oplog("更新DEMO")
@PutMapping
@ApiOperation("更新DEMO")
public R put(@RequestBody MyDemoMain main) {
return R.ok(service.update(main));
}
@Oplog("删除DEMO")
@DeleteMapping("{ids}")
@ApiOperation("删除DEMO")
public R delete(@PathVariable String[] ids) {
return R.ok(service.delete(ids));
}
@Autowired
private MyDemoMainService service;
@Autowired
private AssNumMainService numService;
}
@@ -0,0 +1,10 @@
package vboot.app.my.demo.main;
import org.springframework.data.jpa.repository.JpaRepository;
//DEMO主数据JPA仓储
public interface MyDemoMainRepo extends JpaRepository<MyDemoMain,String> {
}
@@ -1,4 +1,4 @@
package vboot.app.de.supp.main;
package vboot.app.my.demo.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -6,12 +6,12 @@ import vboot.core.common.mvc.service.BaseMainService;
import javax.annotation.PostConstruct;
//供应商服务
//DEMO主数据服务
@Service
public class DeSuppMainService extends BaseMainService<DeSuppMain> {
public class MyDemoMainService extends BaseMainService<MyDemoMain> {
@Autowired
private DeSuppMainRepo repo;
private MyDemoMainRepo repo;
@PostConstruct
public void initDao() {
+101 -50
View File
@@ -50,10 +50,10 @@
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-ldap</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -88,17 +88,17 @@
</dependency>
<!--自动生成API文档开始-->
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger2</artifactId>-->
<!-- <version>2.7.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger2</artifactId>-->
<!-- <version>2.7.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
<!-- <version>2.7.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>io.springfox</groupId>-->
<!-- <artifactId>springfox-swagger-ui</artifactId>-->
<!-- <version>2.7.0</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
@@ -113,7 +113,6 @@
</dependency>
<!--自动生成API文档结束-->
<dependency>
@@ -137,10 +136,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.session</groupId>-->
<!-- <artifactId>spring-session-data-redis</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.session</groupId>-->
<!-- <artifactId>spring-session-data-redis</artifactId>-->
<!-- </dependency>-->
<!--AUTH权限相关结束-->
<!--定时调度开始-->
@@ -182,38 +181,35 @@
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi</artifactId>-->
<!-- <version>3.17</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi-ooxml</artifactId>-->
<!-- <version>3.17</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi-ooxml-schemas</artifactId>-->
<!-- <version>3.17</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi</artifactId>-->
<!-- <version>3.17</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi-ooxml</artifactId>-->
<!-- <version>3.17</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.apache.poi</groupId>-->
<!-- <artifactId>poi-ooxml-schemas</artifactId>-->
<!-- <version>3.17</version>-->
<!-- </dependency>-->
<!--word,excel处理结束-->
<!--浏览器客户端识别开始-->
<!--服务器连接与监控开始-->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<!--浏览器客户端识别结束-->
<!--服务器监控开始-->
<!-- <dependency>-->
<!-- <groupId>ch.ethz.ganymed</groupId>-->
<!-- <artifactId>ganymed-ssh2</artifactId>-->
<!-- <version>262</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>com.github.oshi</groupId>
@@ -226,7 +222,7 @@
<artifactId>snmp4j</artifactId>
<version>2.6.3</version>
</dependency>
<!--服务器监控结束-->
<!--服务器连接与监控结束-->
<!--json包开始-->
<dependency>
@@ -274,10 +270,25 @@
</dependency>
<!--webservice-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.2.7</version>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.2.4</version>
</dependency>
@@ -309,13 +320,20 @@
<version>1.7.2</version>
</dependency>
<!-- 解析客户端操作系统、浏览器信息 -->
<!-- 浏览器客户端识别开始 -->
<dependency>
<groupId>nl.basjes.parse.useragent</groupId>
<artifactId>yauaa</artifactId>
<version>5.23</version>
</dependency>
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
<!--浏览器客户端识别结束-->
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
@@ -349,6 +367,39 @@
<version>1.14.3</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.q3z3</groupId>-->
<!-- <artifactId>core-upload</artifactId>-->
<!-- <version>1.0.0</version>-->
<!--&lt;!&ndash; <scope>system</scope>&ndash;&gt;-->
<!--&lt;!&ndash; <systemPath>${pom.basedir}/lib/core-upload.jar</systemPath>&ndash;&gt;-->
<!--&lt;!&ndash; <exclusions>&ndash;&gt;-->
<!--&lt;!&ndash; <exclusion>&ndash;&gt;-->
<!--&lt;!&ndash; <groupId>org.slf4j</groupId>&ndash;&gt;-->
<!--&lt;!&ndash; <artifactId>slf4j-log4j12</artifactId>&ndash;&gt;-->
<!--&lt;!&ndash; </exclusion>&ndash;&gt;-->
<!--&lt;!&ndash; </exclusions>&ndash;&gt;-->
<!-- </dependency>-->
<!-- tencent -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.473</version>
</dependency>
<!--redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.17.4</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.248</version>
</dependency>
</dependencies>
@@ -0,0 +1,75 @@
package vboot.core.common.exception.base;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import vboot.core.common.utils.MessageUtils;
import vboot.core.common.utils.ruoyi.StringUtils;
/**
* 基础异常
*
* @author ruoyi
*/
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class BaseException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 所属模块
*/
private String module;
/**
* 错误码
*/
private String code;
/**
* 错误码对应的参数
*/
private Object[] args;
/**
* 错误消息
*/
private String defaultMessage;
public BaseException(String module, String code, Object[] args, String defaultMessage) {
this.module = module;
this.code = code;
this.args = args;
this.defaultMessage = defaultMessage;
}
public BaseException(String module, String code, Object[] args) {
this(module, code, args, null);
}
public BaseException(String module, String defaultMessage) {
this(module, null, null, defaultMessage);
}
public BaseException(String code, Object[] args) {
this(null, code, args, null);
}
public BaseException(String defaultMessage) {
this(null, null, null, defaultMessage);
}
@Override
public String getMessage() {
String message = null;
if (!StringUtils.isEmpty(code)) {
message = MessageUtils.message(code, args);
}
if (message == null) {
message = defaultMessage;
}
return message;
}
}
@@ -8,10 +8,10 @@ import java.time.LocalDateTime;
@Data
class ApiError {
private Integer status = 500;
private Integer code = 500;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timestamp;
private String message;
private String msg;
private ApiError() {
timestamp = LocalDateTime.now();
@@ -19,14 +19,14 @@ class ApiError {
public static ApiError error(String message){
ApiError apiError = new ApiError();
apiError.setMessage(message);
apiError.setMsg(message);
return apiError;
}
public static ApiError error(Integer status, String message){
ApiError apiError = new ApiError();
apiError.setStatus(status);
apiError.setMessage(message);
apiError.setCode(status);
apiError.setMsg(message);
return apiError;
}
}
@@ -91,6 +91,6 @@ public class GlobalExceptionHandler {
* 统一返回
*/
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
return new ResponseEntity<>(apiError, HttpStatus.valueOf(200));
}
}
@@ -9,9 +9,11 @@ public class R extends HashMap<String, Object> {
public static final String CODE_TAG = "code";
public static final String MSG_TAG = "message";
// public static final String MSG_TAG = "message";
public static final String MSG_TAG = "msg";
public static final String DATA_TAG = "result";
// public static final String DATA_TAG = "result";
public static final String DATA_TAG = "data";
public R() {
@@ -40,8 +42,11 @@ public class R extends HashMap<String, Object> {
return R.ok("操作成功", new ArrayList<>());
}
// public static R ok(String msg, Object data) {
// return new R(0, msg, data);
// }
public static R ok(String msg, Object data) {
return new R(0, msg, data);
return new R(200, msg, data);
}
public static R error(Object data) {
@@ -1,5 +1,6 @@
package vboot.core.common.mvc.dao;
import vboot.core.common.utils.db.DbType;
import vboot.core.module.sys.org.root.SysOrg;
import vboot.core.common.mvc.api.PageData;
import vboot.core.common.mvc.pojo.ZidName;
@@ -31,11 +32,11 @@ public class JdbcDao {
return new PageData(0, new ArrayList<>());
}
List<Map<String, Object>> list;
if ("mysql".equals(DB_TYPE)) {
if (DbType.MYSQL.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getMysqlPagingSql(), sqler.getParams());
} else if ("oracle".equals(DB_TYPE)) {
} else if (DbType.ORACLE.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getOraclePagingLowerCaseSql(), sqler.getParams());
} else if ("sqlserver".equals(DB_TYPE)) {
} else if (DbType.SQL_SERVER.equals(DB_TYPE)) {
System.out.println(sqler.getSqlserverPagingSql());
list = jdbcTemplate.queryForList(sqler.getSqlserverPagingSql(), sqler.getParams());
} else {
@@ -51,11 +52,11 @@ public class JdbcDao {
return null;
}
List<Map<String, Object>> list;
if ("mysql".equals(DB_TYPE)) {
if (DbType.MYSQL.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getMysqlPagingSql(), sqler.getParams());
} else if ("oracle".equals(DB_TYPE)) {
} else if (DbType.ORACLE.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getOraclePagingLowerCaseSql(), sqler.getParams());
} else if ("sqlserver".equals(DB_TYPE)) {
} else if (DbType.SQL_SERVER.equals(DB_TYPE)) {
System.out.println(sqler.getSqlserverPagingSql());
list = jdbcTemplate.queryForList(sqler.getSqlserverPagingSql(), sqler.getParams());
} else {
@@ -191,7 +192,7 @@ public class JdbcDao {
}
public List<Map<String, Object>> findMapList(Sqler sqler) {
if ("oracle".equals(DB_TYPE)) {
if (DbType.ORACLE.equals(DB_TYPE)) {
return jdbcTemplate.queryForList(sqler.getLowerCaseSql(), sqler.getParams());
} else{
return jdbcTemplate.queryForList(sqler.getSql(), sqler.getParams());
@@ -1,6 +1,7 @@
package vboot.core.common.mvc.dao;
import vboot.core.common.utils.db.DbType;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.framework.security.pojo.Zuser;
@@ -169,7 +170,7 @@ public class Sqler
public Sqler addGtDate(String name, Object value, String dbType)
{
if("oracle".equals(dbType)){
if(DbType.ORACLE.equals(dbType)){
if (XstrUtil.isNotBlank(value + ""))
{
if (whereClause.length() == 0)
@@ -181,7 +182,7 @@ public class Sqler
}
parameters.add(value);
}
}else if("mysql".equals(dbType)){
}else if(DbType.MYSQL.equals(dbType)){
if (XstrUtil.isNotBlank(value + ""))
{
if (whereClause.length() == 0)
@@ -200,7 +201,7 @@ public class Sqler
public Sqler addLtDate(String name, Object value, String dbType)
{
if("oracle".equals(dbType)) {
if(DbType.ORACLE.equals(dbType)) {
if (XstrUtil.isNotBlank(value + "")) {
if (whereClause.length() == 0) {
whereClause = " WHERE " + name + "<to_date(?,'yyyy-MM-dd')+1";
@@ -352,8 +353,6 @@ public class Sqler
// return " SELECT * FROM (SELECT PPGG.*, ROWNUM RN FROM (" + changeSelectClause.toString() + fromClause + whereClause+groupClause + orderClause + ") PPGG WHERE ROWNUM <= " + rownum + ") WHERE RN > " + rn;
}
public String getOraclePagingSql()
{
int rownum = panum * pasiz;
@@ -1,6 +1,7 @@
package vboot.core.common.mvc.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.experimental.Accessors;
import vboot.core.module.sys.org.root.SysOrg;
import lombok.Getter;
import lombok.Setter;
@@ -37,7 +38,6 @@ public class BaseCateEntity {
@ApiModelProperty("子分类列表")
protected List<BaseCateEntity> children = new ArrayList<>();
//----------------------通用属性-----------------------
@Column(length = 100)
@ApiModelProperty("名称")
protected String name;
@@ -0,0 +1,47 @@
package vboot.core.common.mvc.vo;
import java.util.List;
public class BaseTreeVo {
private String id;
private String name;
private String pid;
private List<BaseTreeVo> children;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public List<BaseTreeVo> getChildren() {
return children;
}
public void setChildren(List<BaseTreeVo> children) {
this.children = children;
}
}
@@ -0,0 +1,42 @@
package vboot.core.common.mvc.vo;
import java.util.ArrayList;
import java.util.List;
public class BaseTreeVoHand<T extends BaseTreeVo> {
public List<T> buildTreeByRecursive(List<T> nodes) {
List<T> list = new ArrayList<>();
for (T node : nodes) {
if (node.getPid() == null) {
list.add(findTreeChildrenByTier(node, nodes));
} else {
boolean flag = false;
for (T node2 : nodes) {
if (node.getPid().equals(node2.getId())) {
flag = true;
break;
}
}
if (!flag) {
list.add(findTreeChildrenByTier(node, nodes));
}
}
}
return list;
}
//递归查找子节点
private T findTreeChildrenByTier(T node, List<T> nodes) {
for (T item : nodes) {
if (node.getId().equals(item.getPid())) {
if (node.getChildren() == null) {
node.setChildren(new ArrayList<>());
}
node.getChildren().add(findTreeChildrenByTier(item, nodes));
}
}
return node;
}
}
@@ -0,0 +1,29 @@
package vboot.core.common.utils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import vboot.core.common.utils.web.SpringUtils;
/**
* 获取i18n资源文件
*
* @author Lion Li
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MessageUtils {
private static final MessageSource MESSAGE_SOURCE = SpringUtils.getBean(MessageSource.class);
/**
* 根据消息键和参数 获取消息 委托给spring messageSource
*
* @param code 消息键
* @param args 参数
* @return 获取国际化翻译值
*/
public static String message(String code, Object... args) {
return MESSAGE_SOURCE.getMessage(code, args, LocaleContextHolder.getLocale());
}
}
@@ -0,0 +1,139 @@
/*
* <<
* Davinci
* ==
* Copyright (C) 2016 - 2019 EDP
* ==
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* >>
*
*/
package vboot.core.common.utils.db;
import lombok.extern.slf4j.Slf4j;
/**
* @author /
*/
@Slf4j
@SuppressWarnings({"unchecked","all"})
public enum DataTypeEnum {
/** mysql */
MYSQL("mysql", "mysql", "com.mysql.jdbc.Driver", "`", "`", "'", "'"),
/** oracle */
ORACLE("oracle", "oracle", "oracle.jdbc.driver.OracleDriver", "\"", "\"", "\"", "\""),
/** sql server */
SQLSERVER("sqlserver", "sqlserver", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "\"", "\"", "\"", "\""),
/** h2 */
H2("h2", "h2", "org.h2.Driver", "`", "`", "\"", "\""),
/** phoenix */
PHOENIX("phoenix", "hbase phoenix", "org.apache.phoenix.jdbc.PhoenixDriver", "", "", "\"", "\""),
/** mongo */
MONGODB("mongo", "mongodb", "mongodb.jdbc.MongoDriver", "`", "`", "\"", "\""),
/** sql4es */
ELASTICSEARCH("sql4es", "elasticsearch", "nl.anchormen.sql4es.jdbc.ESDriver", "", "", "'", "'"),
/** presto */
PRESTO("presto", "presto", "com.facebook.presto.jdbc.PrestoDriver", "", "", "\"", "\""),
/** moonbox */
MOONBOX("moonbox", "moonbox", "moonbox.jdbc.MbDriver", "`", "`", "`", "`"),
/** cassandra */
CASSANDRA("cassandra", "cassandra", "com.github.adejanovski.cassandra.jdbc.CassandraDriver", "", "", "'", "'"),
/** click house */
CLICKHOUSE("clickhouse", "clickhouse", "ru.yandex.clickhouse.ClickHouseDriver", "", "", "\"", "\""),
/** kylin */
KYLIN("kylin", "kylin", "org.apache.kylin.jdbc.Driver", "\"", "\"", "\"", "\""),
/** vertica */
VERTICA("vertica", "vertica", "com.vertica.jdbc.Driver", "", "", "'", "'"),
/** sap */
HANA("sap", "sap hana", "com.sap.db.jdbc.Driver", "", "", "'", "'"),
/** impala */
IMPALA("impala", "impala", "com.cloudera.impala.jdbc41.Driver", "", "", "'", "'");
private String feature;
private String desc;
private String driver;
private String keywordPrefix;
private String keywordSuffix;
private String aliasPrefix;
private String aliasSuffix;
private static final String JDBC_URL_PREFIX = "jdbc:";
DataTypeEnum(String feature, String desc, String driver, String keywordPrefix, String keywordSuffix, String aliasPrefix, String aliasSuffix) {
this.feature = feature;
this.desc = desc;
this.driver = driver;
this.keywordPrefix = keywordPrefix;
this.keywordSuffix = keywordSuffix;
this.aliasPrefix = aliasPrefix;
this.aliasSuffix = aliasSuffix;
}
public static DataTypeEnum urlOf(String jdbcUrl) {
String url = jdbcUrl.toLowerCase().trim();
for (DataTypeEnum dataTypeEnum : values()) {
if (url.startsWith(JDBC_URL_PREFIX + dataTypeEnum.feature)) {
try {
Class<?> aClass = Class.forName(dataTypeEnum.getDriver());
if (null == aClass) {
throw new RuntimeException("Unable to get driver instance for jdbcUrl: " + jdbcUrl);
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to get driver instance: " + jdbcUrl);
}
return dataTypeEnum;
}
}
return null;
}
public String getFeature() {
return feature;
}
public String getDesc() {
return desc;
}
public String getDriver() {
return driver;
}
public String getKeywordPrefix() {
return keywordPrefix;
}
public String getKeywordSuffix() {
return keywordSuffix;
}
public String getAliasPrefix() {
return aliasPrefix;
}
public String getAliasSuffix() {
return aliasSuffix;
}
}
@@ -0,0 +1,15 @@
package vboot.core.common.utils.db;
public class DbType {
public static final String MYSQL = "mysql";
public static final String MYSQL8 = "mysql8";
public static final String ORACLE = "oracle";
public static final String SQL_SERVER = "sqlserver";
public static final String DB2 = "db2";
}
@@ -0,0 +1,244 @@
package vboot.core.common.utils.db;
import org.springframework.jdbc.core.JdbcTemplate;
import vboot.core.common.mvc.api.PageData;
import vboot.core.common.mvc.dao.BaseSqler;
import vboot.core.common.mvc.dao.Sqler;
import vboot.core.common.mvc.pojo.ZidName;
import vboot.core.common.mvc.pojo.Zinp;
import vboot.core.common.mvc.pojo.Ztree;
import vboot.core.common.utils.lang.XjsonUtil;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.common.utils.web.XreqUtil;
import vboot.core.module.sys.org.root.SysOrg;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Jdao {
public Jdao(JdbcTemplate jdbcTemplate, String dbType){
this.jdbcTemplate=jdbcTemplate;
this.DB_TYPE=dbType;
}
private JdbcTemplate jdbcTemplate;
private String DB_TYPE;
public PageData findPageData(Sqler sqler) {
XreqUtil.setPageParam(sqler);
Integer count = jdbcTemplate.queryForObject(sqler.getSizeSql(), sqler.getParams(), Integer.class);
if (count == null || count == 0) {
return new PageData(0, new ArrayList<>());
}
List<Map<String, Object>> list;
if (DbType.MYSQL.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getMysqlPagingSql(), sqler.getParams());
} else if (DbType.ORACLE.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getOraclePagingLowerCaseSql(), sqler.getParams());
} else if (DbType.SQL_SERVER.equals(DB_TYPE)) {
System.out.println(sqler.getSqlserverPagingSql());
list = jdbcTemplate.queryForList(sqler.getSqlserverPagingSql(), sqler.getParams());
} else {
System.err.println("目前只支持mysql,oracle与sqlserver");
list = new ArrayList<>();
}
return new PageData(count, list);
}
public List<Map<String, Object>> findPageMapList(Sqler sqler) {
Integer count = jdbcTemplate.queryForObject(sqler.getSizeSql(), sqler.getParams(), Integer.class);
if (count == null || count == 0) {
return null;
}
List<Map<String, Object>> list;
if (DbType.MYSQL.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getMysqlPagingSql(), sqler.getParams());
} else if (DbType.ORACLE.equals(DB_TYPE)) {
list = jdbcTemplate.queryForList(sqler.getOraclePagingLowerCaseSql(), sqler.getParams());
} else if (DbType.SQL_SERVER.equals(DB_TYPE)) {
System.out.println(sqler.getSqlserverPagingSql());
list = jdbcTemplate.queryForList(sqler.getSqlserverPagingSql(), sqler.getParams());
} else {
System.err.println("目前只支持mysql,oracle与sqlserver");
list = new ArrayList<>();
}
return list;
}
//--------------------------------------------------------------------------------
public List<Ztree> findTreeList(Sqler sqler) {
List<Ztree> list = jdbcTemplate.query(sqler.getSql(), sqler.getParams(), (rs, rowNum) -> {
Ztree ztree = new Ztree();
ztree.setId(rs.getString("id"));
ztree.setName(rs.getString("name"));
ztree.setPid(rs.getString("pid"));
return ztree;
});
return XjsonUtil.buildTreeByRecursive(list);
}
public List<ZidName> findIdNameList(String sql, Object... args) {
return jdbcTemplate.query(sql, args, (rs, rowNum) -> {
ZidName ztwo = new ZidName();
ztwo.setId(rs.getString("id"));
ztwo.setName(rs.getString("name"));
return ztwo;
});
}
public List<ZidName> getIdNameListByTable(String table, String name) {
String sql = "select id,name from " + table + " where avtag = 1";
if (XstrUtil.isBlank(name)) {
return findIdNameList(sql);
} else {
return jdbcTemplate.query(sql + " and name like ?", new Object[]{"%" + name + "%"}, (rs, rowNum) -> {
ZidName ztwo = new ZidName();
ztwo.setId(rs.getString("id"));
ztwo.setName(rs.getString("name"));
return ztwo;
});
}
}
public List<ZidName> findIdNameList(Sqler sqlHelper) {
return findIdNameList((sqlHelper.getSql()), sqlHelper.getParams());
}
public List<SysOrg> findOrgList(String sql, Object... args) {
return jdbcTemplate.query(sql, args, (rs, rowNum) -> {
SysOrg sysOrg = new SysOrg();
sysOrg.setId(rs.getString("id"));
sysOrg.setName(rs.getString("name"));
return sysOrg;
});
}
public List<Zinp> findInpList(String sql, Object... args) {
return jdbcTemplate.query(sql, args, (rs, rowNum) -> {
Zinp zinp = new Zinp();
zinp.setId(rs.getString("id"));
zinp.setName(rs.getString("name"));
zinp.setPid(rs.getString("pid"));
return zinp;
});
}
public List<Zinp> findInpList(Sqler sqlHelper) {
return findInpList(sqlHelper.getSql(), sqlHelper.getParams());
}
public List<Zinp> findInpListByTable(String table) {
String sql = "select id,name,pid from " + table + " where avtag = 1";
return findInpList(sql);
}
public List<Zinp> findInpListByTable(String table, String name) {
String sql = "select id,name,pid from " + table + " where avtag = 1";
if (XstrUtil.isBlank(name)) {
return findInpList(sql);
} else {
return jdbcTemplate.query(sql + " and name like ?", new Object[]{"%" + name + "%"}, (rs, rowNum) -> new Zinp(rs.getString("id"), rs.getString("name"), rs.getString("pid")));
}
}
public List<String> findStringList(String sql, Object... args) {
return jdbcTemplate.query(sql, args, (rs, rowNum) -> rs.getString("id"));
}
public List<String> findStringList(Sqler sqler) {
return jdbcTemplate.query(sqler.getSql(), sqler.getParams(), (rs, rowNum) -> rs.getString("id"));
}
public Integer findSize(Sqler sqler) {
return jdbcTemplate.queryForObject(sqler.getSizeSql(), sqler.getParams(), Integer.class);
}
public String findOneString(String sql, Object... args) {
String str = null;
try {
str = jdbcTemplate.queryForObject(sql, args, String.class);
} catch (Exception ignored) {
}
return str;
}
public String findOneString(Sqler sqler) {
return findOneString(sqler.getSql(), sqler.getParams());
}
public Map<String, Object> findMap(Sqler sqler) {
List<Map<String, Object>> list = jdbcTemplate.queryForList(sqler.getSql(), sqler.getParams());
if (list.size() > 0) {
return list.get(0);
} else {
return null;
}
// return jdbcTemplate.queryForMap(sqler.getSql(), sqler.getParams());
}
public Map<String, Object> findMap(String sql, Object... args) {
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, args);
if (list.size()==0) {
return null;
} else {
return list.get(0);
}
}
public List<Map<String, Object>> findMapList(Sqler sqler) {
if (DbType.ORACLE.equals(DB_TYPE)) {
return jdbcTemplate.queryForList(sqler.getLowerCaseSql(), sqler.getParams());
} else{
return jdbcTemplate.queryForList(sqler.getSql(), sqler.getParams());
}
}
public List<Map<String, Object>> findMapList(String sql, Object... args) {
return jdbcTemplate.queryForList(sql, args);
}
public String findOneName(String table, String id) {
if (XstrUtil.isBlank(id)) {
return null;
} else {
return jdbcTemplate.queryForObject("select name from " + table + " where id = ?", new Object[]{id}, String.class);
}
}
//queryForObject 如果返回没结果会报错
//增删改----------------------------------------------------------------------------------
public int update(String sql, Object... args) {
return jdbcTemplate.update(sql, args);
}
public int update(BaseSqler sqler) throws SQLException {
return jdbcTemplate.update(sqler.getSql(), sqler.getParams());
}
public int[] batch(String sql, List<Object[]> list) {
return jdbcTemplate.batchUpdate(sql, list);
}
public String getDbType() {
return DB_TYPE;
}
public JdbcTemplate getTp() {
// jdbcDao.getTp().query(sql, new Object[]{}, new BeanPropertyRowMapper<>(Qmarg.class));
return jdbcTemplate;
}
}
@@ -0,0 +1,275 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vboot.core.common.utils.db;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.module.mon.server.main.CloseUtil;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author /
*/
@Slf4j
public class SqlUtils {
private static Map<String, DruidDataSource> dataSourceMap = new HashMap<>();
private static Map<String, Jdao> jdaoMap = new HashMap<>();
private static DataSource getDataSource(Zconn zconn) {
if (XstrUtil.isNotBlank(zconn.getName())) {
DruidDataSource ds = dataSourceMap.get(zconn.getName());
if (ds != null) {
return ds;
}
}
DruidDataSource druidDataSource = new DruidDataSource();
String className;
try {
className = DriverManager.getDriver(zconn.getUrl().trim()).getClass().getName();
} catch (SQLException e) {
throw new RuntimeException("Get class name error: =" + zconn.getUrl());
}
if (StringUtils.isEmpty(className)) {
DataTypeEnum dataTypeEnum = DataTypeEnum.urlOf(zconn.getUrl());
if (null == dataTypeEnum) {
throw new RuntimeException("Not supported data type: jdbcUrl=" + zconn.getUrl());
}
druidDataSource.setDriverClassName(dataTypeEnum.getDriver());
} else {
druidDataSource.setDriverClassName(className);
}
if (XstrUtil.isNotBlank(zconn.getName())) {
druidDataSource.setName(zconn.getName());
}
druidDataSource.setUrl(zconn.getUrl());
druidDataSource.setUsername(zconn.getUsername());
druidDataSource.setPassword(zconn.getPasscode());
// 配置获取连接等待超时的时间
druidDataSource.setMaxWait(3000);
// 配置初始化大小、最小、最大
druidDataSource.setInitialSize(1);
druidDataSource.setMinIdle(1);
druidDataSource.setMaxActive(5);
if(DbType.SQL_SERVER.equals(zconn.getType())){
druidDataSource.setValidationQuery("SELECT 1");
}
// 如果链接出现异常则直接判定为失败而不是一直重试
druidDataSource.setBreakAfterAcquireFailure(true);
try {
druidDataSource.init();
} catch (SQLException e) {
log.error("Exception during pool initialization", e);
throw new RuntimeException(e.getMessage());
}
if(XstrUtil.isNotBlank(zconn.getName())){
dataSourceMap.put(zconn.getName(), druidDataSource);
}
return druidDataSource;
}
public static Jdao getJdao(Zconn zconn) {
Jdao jdao = jdaoMap.get(zconn.getName());
if (jdao != null) {
return jdao;
} else {
DataSource druidDataSource = getDataSource(zconn);
JdbcTemplate jdbcTemplate = new JdbcTemplate(druidDataSource);
jdao = new Jdao(jdbcTemplate, zconn.getType());
jdaoMap.put(zconn.getName(), jdao);
return jdao;
}
}
private static Connection getConnection(Zconn zconn) {
DataSource dataSource = getDataSource(zconn);
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (Exception ignored) {
}
try {
int timeOut = 5;
if (null == connection || connection.isClosed() || !connection.isValid(timeOut)) {
log.info("connection is closed or invalid, retry get connection!");
connection = dataSource.getConnection();
}
} catch (Exception e) {
log.error("create connection error, jdbcUrl: {}", zconn.getUrl());
throw new RuntimeException("create connection error, jdbcUrl: " + zconn.getUrl());
} finally {
CloseUtil.close(connection);
}
return connection;
}
private static void releaseConnection(Connection connection) {
if (null != connection) {
try {
connection.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
log.error("connection close error:" + e.getMessage());
}
}
}
public static boolean testConnection(Zconn zconn) {
Connection connection = null;
DataSource dataSource = null;
try {
dataSource = getDataSource(zconn);
connection = dataSource.getConnection();
int timeOut = 5;
if (null == connection || connection.isClosed() || !connection.isValid(timeOut)) {
log.info("connection is closed or invalid, retry get connection!");
connection = dataSource.getConnection();
}
if (null != connection) {
return true;
}
} catch (Exception e) {
log.info("Get connection failed:" + e.getMessage());
} finally {
CloseUtil.close(connection);
releaseConnection(connection);
assert dataSource != null;
((DruidDataSource) dataSource).close();
}
return false;
}
// public static boolean testConnection(String name,String jdbcUrl, String userName, String password) {
// Connection connection = null;
// try {
// connection = getConnection(name,jdbcUrl, userName, password);
// if (null != connection) {
// return true;
// }
// } catch (Exception e) {
// log.info("Get connection failed:" + e.getMessage());
// } finally {
// releaseConnection(connection);
// }
// return false;
// }
// public static boolean execSql(String name, String jdbcUrl, String userName, String password) {
// Connection connection = null;
// try {
// connection = getConnection(name, jdbcUrl, userName, password);
// if (null != connection) {
// return true;
// }
// } catch (Exception e) {
// log.info("Get connection failed:" + e.getMessage());
// } finally {
// releaseConnection(connection);
// }
// return false;
// }
// public static String executeFile(String name, String jdbcUrl, String userName, String password, File sqlFile) {
// Connection connection = getConnection(name, jdbcUrl, userName, password);
// try {
// batchExecute(connection, readSqlList(sqlFile));
// } catch (Exception e) {
// log.error("sql脚本执行发生异常:{}", e.getMessage());
// return e.getMessage();
// } finally {
// releaseConnection(connection);
// }
// return "success";
// }
/**
* 批量执行sql
*
* @param connection /
* @param sqlList /
*/
// public static void batchExecute(Connection connection, List<String> sqlList) {
// Statement st = null;
// try {
// st = connection.createStatement();
// for (String sql : sqlList) {
// if (sql.endsWith(";")) {
// sql = sql.substring(0, sql.length() - 1);
// }
// st.addBatch(sql);
// }
// st.executeBatch();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// } finally {
// CloseUtil.close(st);
// }
// }
/**
* 将文件中的sql语句以;为单位读取到列表中
*
* @param sqlFile /
* @return /
* @throws Exception e
*/
// private static List<String> readSqlList(File sqlFile) throws Exception {
// List<String> sqlList = Lists.newArrayList();
// StringBuilder sb = new StringBuilder();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(
// new FileInputStream(sqlFile), StandardCharsets.UTF_8))) {
// String tmp;
// while ((tmp = reader.readLine()) != null) {
// log.info("line:{}", tmp);
// if (tmp.endsWith(";")) {
// sb.append(tmp);
// sqlList.add(sb.toString());
// sb.delete(0, sb.length());
// } else {
// sb.append(tmp);
// }
// }
// if (!"".endsWith(sb.toString().trim())) {
// sqlList.add(sb.toString());
// }
// }
//
// return sqlList;
// }
}
@@ -1,4 +1,4 @@
package vboot.core.common.mvc.pojo;
package vboot.core.common.utils.db;
import lombok.AllArgsConstructor;
import lombok.Data;
@@ -9,6 +9,8 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
public class Zconn {
private String name;
private String type;
private String url;
@@ -21,13 +23,22 @@ public class Zconn {
{
if(isMysql())
{
return url.substring(url.lastIndexOf("/")+1).replaceAll("/","");
String lasturl=url.split("\\?")[0];
return lasturl.substring(lasturl.lastIndexOf("/")+1);
}
else if (isOracle())
{
return url.substring(url.lastIndexOf(":")+1);
if(url.indexOf("/")>0){
return url.substring(url.lastIndexOf("/")+1);
}else{
return url.substring(url.lastIndexOf(":")+1);
}
}
else if (isDB2())
else if (isSqlserver())
{
return url.substring(url.lastIndexOf("Name=")+5);
}
else if (isDb2())
{
return url.substring(url.lastIndexOf("/")+1);
}
@@ -43,7 +54,7 @@ public class Zconn {
return "com.mysql.jdbc.Driver";
}else if(isMysql8()){
return "com.mysql.cj.jdbc.Driver";
}else if(isDB2()){
}else if(isDb2()){
return "com.ibm.db2.jcc.DB2Driver";
}else{
return "暂不支持";
@@ -52,18 +63,24 @@ public class Zconn {
public boolean isOracle()
{
return "oracle".equals(type);
return DbType.ORACLE.equals(type);
}
public boolean isMysql()
{
return "mysql".equals(type);
return DbType.MYSQL.equals(type);
}
public boolean isMysql8()
{
return "mysql8".equals(type);
return DbType.MYSQL8.equals(type);
}
public boolean isDB2()
public boolean isDb2()
{
return "DB2".equals(type);
return DbType.DB2.equals(type);
}
public boolean isSqlserver()
{
return DbType.SQL_SERVER.equals(type);
}
}
@@ -4,10 +4,14 @@ import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import vboot.core.common.utils.file.excel.DefaultExcelListener;
import vboot.core.common.utils.file.excel.ExcelBigNumberConvert;
import vboot.core.common.utils.file.excel.ExcelListener;
import vboot.core.common.utils.file.excel.ExcelResult;
import vboot.core.common.utils.lang.XdateUtil;
import vboot.core.common.utils.ruoyi.StringUtils;
import javax.servlet.ServletOutputStream;
@@ -16,6 +20,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.apache.poi.ss.usermodel.CellType.BLANK;
/**
* Excel相关处理
*
@@ -4,7 +4,12 @@ import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.utils.lang.XdateUtil;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
@SuppressWarnings("unchecked")
@@ -101,5 +106,80 @@ public class XexcelUtil
return style;
}
public static Object getCellValue(Cell cell)
{
Object back = null;
if (null != cell)
{
switch (cell.getCellType())
{
case BLANK:
back = null;
break;
case BOOLEAN:
back = Boolean.toString(cell.getBooleanCellValue());
break;
//数值
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell))
{
back = XdateUtil.getDate(cell.getDateCellValue());
} else
{
cell.setCellType(CellType.STRING);
String temp = cell.getStringCellValue();
//判断是否包含小数点,如果不含小数点,则以字符串读取,如果含小数点,则转换为Double类型的字符串
if (temp.indexOf(".") > -1)
{
back = String.valueOf(new Double(temp)).trim();
} else
{
back = temp.trim();
}
}
break;
case STRING:
back = cell.getStringCellValue().trim();
if ("".equals(back))
{
back = null;
}
break;
case ERROR:
back = null;
break;
case FORMULA:
cell.setCellType(CellType.STRING);
back = cell.getStringCellValue();
break;
default:
back = null;
break;
}
}
return back;
}
public static Workbook getWorkbook(MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
String fileName = file.getOriginalFilename();
if (fileName.toLowerCase().endsWith("xls")) {
return new HSSFWorkbook(in);
}
if (fileName.toLowerCase().endsWith("xlsx")) {
return new XSSFWorkbook(in);
}
return null;
}
public static void closeWorkBook(Workbook workbook) {
if(workbook!=null){
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@@ -1,78 +0,0 @@
package vboot.core.common.utils.lang;
import cn.hutool.core.util.ArrayUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import vboot.core.common.utils.web.XspringUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtils {
private static ObjectMapper objectMapper = XspringUtil.getBean(ObjectMapper.class);
public static <T> T parseObject(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text)) {
return null;
}
try {
return objectMapper.readValue(text, clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
if (ArrayUtil.isEmpty(bytes)) {
return null;
}
try {
return objectMapper.readValue(bytes, clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return objectMapper.readValue(text, typeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> Map<String, T> parseMap(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return objectMapper.readValue(text, new TypeReference<Map<String, T>>() {
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> parseArray(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text)) {
return new ArrayList<>();
}
try {
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -33,6 +33,12 @@ public class XdateUtil {
return cal.toGregorianCalendar().getTime();
}
public static String getYYYYMMDDPath() {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
return format.format(new Date());
}
public static String getYYYY() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
return dateFormat.format(new Date());
@@ -63,6 +69,7 @@ public class XdateUtil {
return strtodate;
}
public static Date strToDateBySap(String strDate) {
if (XstrUtil.isBlank(strDate)) {
return null;
@@ -5,9 +5,19 @@ import vboot.core.common.mvc.pojo.Ztree;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class XjsonUtil {
//高性能转换,但是要求顶层有pid,这里假设为0
public static List<Ztree> buildTree(List<Ztree> pidList) {
Map<String, List<Ztree>> pidListMap = pidList.stream().collect(Collectors.groupingBy(Ztree::getPid));
pidList.stream().forEach(item -> item.setChildren(pidListMap.get(item.getId())));
//返回结果也改为返回顶层节点的list
return pidListMap.get("0");
}
public static List<Ztree> buildTreeByRecursive(List<Ztree> nodes) {
List<Ztree> list = new ArrayList<>();
for (Ztree node : nodes) {
@@ -30,6 +40,7 @@ public class XjsonUtil {
}
//递归查找子节点
private static Ztree findTreeChildrenByTier(Ztree node, List<Ztree> nodes) {
for (Ztree item : nodes) {
@@ -1,5 +1,6 @@
package vboot.core.common.utils.lang;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
@@ -14,6 +15,16 @@ public class XtimeUtil
return sdf.format(new Date());
}
public static Date strToDate(String strDate) {
if (XstrUtil.isBlank(strDate)) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
public static void calStart()
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss SSS");
@@ -0,0 +1,108 @@
package vboot.core.common.utils.ruoyi;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import vboot.core.common.utils.web.SpringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* JSON 工具类
*
* @author 芋道源码
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtils {
private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class);
public static ObjectMapper getObjectMapper() {
return OBJECT_MAPPER;
}
public static String toJsonString(Object object) {
if (ObjectUtil.isNull(object)) {
return null;
}
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(text, clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
if (ArrayUtil.isEmpty(bytes)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(bytes, clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(text, typeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Dict parseMap(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static List<Dict> parseArrayMap(String text) {
if (StringUtils.isBlank(text)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> parseArray(String text, Class<T> clazz) {
if (StringUtils.isEmpty(text)) {
return new ArrayList<>();
}
try {
return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,431 @@
package vboot.core.common.utils.ruoyi;
import cn.hutool.core.collection.IterUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.redisson.api.*;
import vboot.core.common.utils.web.SpringUtils;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
/**
* redis 工具类
*
* @author Lion Li
* @version 3.1.0 新增
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings(value = {"unchecked", "rawtypes"})
public class RedisUtils {
private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);
/**
* 限流
*
* @param key 限流key
* @param rateType 限流类型
* @param rate 速率
* @param rateInterval 速率间隔
* @return -1 表示失败
*/
public static long rateLimiter(String key, RateType rateType, int rate, int rateInterval) {
RRateLimiter rateLimiter = CLIENT.getRateLimiter(key);
rateLimiter.trySetRate(rateType, rate, rateInterval, RateIntervalUnit.SECONDS);
if (rateLimiter.tryAcquire()) {
return rateLimiter.availablePermits();
} else {
return -1L;
}
}
/**
* 获取客户端实例
*/
public static RedissonClient getClient() {
return CLIENT;
}
/**
* 发布通道消息
*
* @param channelKey 通道key
* @param msg 发送数据
* @param consumer 自定义处理
*/
public static <T> void publish(String channelKey, T msg, Consumer<T> consumer) {
RTopic topic = CLIENT.getTopic(channelKey);
topic.publish(msg);
consumer.accept(msg);
}
public static <T> void publish(String channelKey, T msg) {
RTopic topic = CLIENT.getTopic(channelKey);
topic.publish(msg);
}
/**
* 订阅通道接收消息
*
* @param channelKey 通道key
* @param clazz 消息类型
* @param consumer 自定义处理
*/
public static <T> void subscribe(String channelKey, Class<T> clazz, Consumer<T> consumer) {
RTopic topic = CLIENT.getTopic(channelKey);
topic.addListener(clazz, (channel, msg) -> consumer.accept(msg));
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
*/
public static <T> void setCacheObject(final String key, final T value) {
setCacheObject(key, value, false);
}
/**
* 缓存基本的对象,保留当前对象 TTL 有效期
*
* @param key 缓存的键值
* @param value 缓存的值
* @param isSaveTtl 是否保留TTL有效期(例如: set之前ttl剩余90 set之后还是为90)
* @since Redis 6.X 以上使用 setAndKeepTTL 兼容 5.X 方案
*/
public static <T> void setCacheObject(final String key, final T value, final boolean isSaveTtl) {
RBucket<Object> bucket = CLIENT.getBucket(key);
if (isSaveTtl) {
try {
bucket.setAndKeepTTL(value);
} catch (Exception e) {
long timeToLive = bucket.remainTimeToLive();
bucket.set(value);
bucket.expire(Duration.ofMillis(timeToLive));
}
} else {
bucket.set(value);
}
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param duration 时间
*/
public static <T> void setCacheObject(final String key, final T value, final Duration duration) {
RBucket<T> result = CLIENT.getBucket(key);
result.set(value);
result.expire(duration);
}
/**
* 注册对象监听器
* <p>
* key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
*
* @param key 缓存的键值
* @param listener 监听器配置
*/
public static <T> void addObjectListener(final String key, final ObjectListener listener) {
RBucket<T> result = CLIENT.getBucket(key);
result.addListener(listener);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @return true=设置成功;false=设置失败
*/
public static boolean expire(final String key, final long timeout) {
return expire(key, Duration.ofSeconds(timeout));
}
/**
* 设置有效时间
*
* @param key Redis键
* @param duration 超时时间
* @return true=设置成功;false=设置失败
*/
public static boolean expire(final String key, final Duration duration) {
RBucket rBucket = CLIENT.getBucket(key);
return rBucket.expire(duration);
}
/**
* 获得缓存的基本对象。
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public static <T> T getCacheObject(final String key) {
RBucket<T> rBucket = CLIENT.getBucket(key);
return rBucket.get();
}
/**
* 获得key剩余存活时间
*
* @param key 缓存键值
* @return 剩余存活时间
*/
public static <T> long getTimeToLive(final String key) {
RBucket<T> rBucket = CLIENT.getBucket(key);
return rBucket.remainTimeToLive();
}
/**
* 删除单个对象
*
* @param key 缓存的键值
*/
public static boolean deleteObject(final String key) {
return CLIENT.getBucket(key).delete();
}
/**
* 删除集合对象
*
* @param collection 多个对象
*/
public static void deleteObject(final Collection collection) {
RBatch batch = CLIENT.createBatch();
collection.forEach(t -> {
batch.getBucket(t.toString()).deleteAsync();
});
batch.execute();
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public static <T> boolean setCacheList(final String key, final List<T> dataList) {
RList<T> rList = CLIENT.getList(key);
return rList.addAll(dataList);
}
/**
* 注册List监听器
* <p>
* key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
*
* @param key 缓存的键值
* @param listener 监听器配置
*/
public static <T> void addListListener(final String key, final ObjectListener listener) {
RList<T> rList = CLIENT.getList(key);
rList.addListener(listener);
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public static <T> List<T> getCacheList(final String key) {
RList<T> rList = CLIENT.getList(key);
return rList.readAll();
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public static <T> boolean setCacheSet(final String key, final Set<T> dataSet) {
RSet<T> rSet = CLIENT.getSet(key);
return rSet.addAll(dataSet);
}
/**
* 注册Set监听器
* <p>
* key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
*
* @param key 缓存的键值
* @param listener 监听器配置
*/
public static <T> void addSetListener(final String key, final ObjectListener listener) {
RSet<T> rSet = CLIENT.getSet(key);
rSet.addListener(listener);
}
/**
* 获得缓存的set
*
* @param key 缓存的key
* @return set对象
*/
public static <T> Set<T> getCacheSet(final String key) {
RSet<T> rSet = CLIENT.getSet(key);
return rSet.readAll();
}
/**
* 缓存Map
*
* @param key 缓存的键值
* @param dataMap 缓存的数据
*/
public static <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
RMap<String, T> rMap = CLIENT.getMap(key);
rMap.putAll(dataMap);
}
}
/**
* 注册Map监听器
* <p>
* key 监听器需开启 `notify-keyspace-events` 等 redis 相关配置
*
* @param key 缓存的键值
* @param listener 监听器配置
*/
public static <T> void addMapListener(final String key, final ObjectListener listener) {
RMap<String, T> rMap = CLIENT.getMap(key);
rMap.addListener(listener);
}
/**
* 获得缓存的Map
*
* @param key 缓存的键值
* @return map对象
*/
public static <T> Map<String, T> getCacheMap(final String key) {
RMap<String, T> rMap = CLIENT.getMap(key);
return rMap.getAll(rMap.keySet());
}
/**
* 往Hash中存入数据
*
* @param key Redis键
* @param hKey Hash键
* @param value 值
*/
public static <T> void setCacheMapValue(final String key, final String hKey, final T value) {
RMap<String, T> rMap = CLIENT.getMap(key);
rMap.put(hKey, value);
}
/**
* 获取Hash中的数据
*
* @param key Redis键
* @param hKey Hash键
* @return Hash中的对象
*/
public static <T> T getCacheMapValue(final String key, final String hKey) {
RMap<String, T> rMap = CLIENT.getMap(key);
return rMap.get(hKey);
}
/**
* 删除Hash中的数据
*
* @param key Redis键
* @param hKey Hash键
* @return Hash中的对象
*/
public static <T> T delCacheMapValue(final String key, final String hKey) {
RMap<String, T> rMap = CLIENT.getMap(key);
return rMap.remove(hKey);
}
/**
* 获取多个Hash中的数据
*
* @param key Redis键
* @param hKeys Hash键集合
* @return Hash对象集合
*/
public static <K, V> Map<K, V> getMultiCacheMapValue(final String key, final Set<K> hKeys) {
RMap<K, V> rMap = CLIENT.getMap(key);
return rMap.getAll(hKeys);
}
/**
* 设置原子值
*
* @param key Redis键
* @param value 值
*/
public static void setAtomicValue(String key, long value) {
RAtomicLong atomic = CLIENT.getAtomicLong(key);
atomic.set(value);
}
/**
* 获取原子值
*
* @param key Redis键
* @return 当前值
*/
public static long getAtomicValue(String key) {
RAtomicLong atomic = CLIENT.getAtomicLong(key);
return atomic.get();
}
/**
* 递增原子值
*
* @param key Redis键
* @return 当前值
*/
public static long incrAtomicValue(String key) {
RAtomicLong atomic = CLIENT.getAtomicLong(key);
return atomic.incrementAndGet();
}
/**
* 递减原子值
*
* @param key Redis键
* @return 当前值
*/
public static long decrAtomicValue(String key) {
RAtomicLong atomic = CLIENT.getAtomicLong(key);
return atomic.decrementAndGet();
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public static Collection<String> keys(final String pattern) {
Iterable<String> iterable = CLIENT.getKeys().getKeysByPattern(pattern);
return IterUtil.toList(iterable);
}
/**
* 检查redis中是否存在key
*
* @param key 键
*/
public static Boolean hasKey(String key) {
RKeys rKeys = CLIENT.getKeys();
return rKeys.countExists(key) > 0;
}
}
@@ -0,0 +1,165 @@
package vboot.core.framework.cache;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.redisson.config.ReadMode;
import org.redisson.config.SubscriptionMode;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Redisson 配置属性
*
* @author Lion Li
*/
@Data
@Component
@ConfigurationProperties(prefix = "redisson")
public class RedissonProperties {
/**
* 线程池数量,默认值 = 当前处理核数量 * 2
*/
private int threads;
/**
* Netty线程池数量,默认值 = 当前处理核数量 * 2
*/
private int nettyThreads;
/**
* 单机服务配置
*/
private SingleServerConfig singleServerConfig;
/**
* 集群服务配置
*/
private ClusterServersConfig clusterServersConfig;
/**
* 缓存组
*/
private List<CacheGroup> cacheGroup;
@Data
@NoArgsConstructor
public static class SingleServerConfig {
/**
* 客户端名称
*/
private String clientName;
/**
* 最小空闲连接数
*/
private int connectionMinimumIdleSize;
/**
* 连接池大小
*/
private int connectionPoolSize;
/**
* 连接空闲超时,单位:毫秒
*/
private int idleConnectionTimeout;
/**
* 命令等待超时,单位:毫秒
*/
private int timeout;
/**
* 发布和订阅连接池大小
*/
private int subscriptionConnectionPoolSize;
}
@Data
@NoArgsConstructor
public static class ClusterServersConfig {
/**
* 客户端名称
*/
private String clientName;
/**
* master最小空闲连接数
*/
private int masterConnectionMinimumIdleSize;
/**
* master连接池大小
*/
private int masterConnectionPoolSize;
/**
* slave最小空闲连接数
*/
private int slaveConnectionMinimumIdleSize;
/**
* slave连接池大小
*/
private int slaveConnectionPoolSize;
/**
* 连接空闲超时,单位:毫秒
*/
private int idleConnectionTimeout;
/**
* 命令等待超时,单位:毫秒
*/
private int timeout;
/**
* 发布和订阅连接池大小
*/
private int subscriptionConnectionPoolSize;
/**
* 读取模式
*/
private ReadMode readMode;
/**
* 订阅模式
*/
private SubscriptionMode subscriptionMode;
}
@Data
@NoArgsConstructor
public static class CacheGroup {
/**
* 组id
*/
private String groupId;
/**
* 组过期时间
*/
private long ttl;
/**
* 组最大空闲时间
*/
private long maxIdleTime;
/**
* 组最大长度
*/
private int maxSize;
}
}
@@ -1,320 +0,0 @@
package vboot.core.framework.init;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.module.sys.org.dept.SysOrgDept;
import vboot.core.module.sys.org.dept.SysOrgDeptService;
import vboot.core.module.sys.org.root.SysOrg;
import vboot.core.module.sys.org.user.SysOrgUser;
import vboot.core.module.sys.org.user.SysOrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
//组织架构初始化,可根据application.properties的app.init.type配置生成不同的基础数据
@Component
public class SysOrgInit {
//公司及子公司初始化
protected void initCorp() throws Exception {
List<SysOrgDept> deptList = new ArrayList<>();
initDept(deptList,"刘", "LIU",1);
initDept(deptList,"陈", "CHEN",2);
initDept(deptList,"张", "ZHANG",3);
initDept(deptList,"李", "LI",4);
initDept(deptList,"王", "WANG",5);
initDept(deptList,"赵", "ZHAO",6);
initDept(deptList,"孙", "SUN",7);
initDept(deptList,"周", "ZHOU",8);
initDept(deptList,"吴", "WU",9);
initDept(deptList,"郑", "ZHENG",10);
deptService.insertAll(deptList);
}
//部门初始化
private void initDept(List<SysOrgDept> deptList,String name, String id,Integer ornum) throws Exception {
SysOrgDept corp = new SysOrgDept();
corp.setType(1);
corp.setId(id);
corp.setName(name + "家科技");
corp.setLabel(id);
corp.setOrnum(ornum);
corp.setAvtag(true);
corp.setTier("x"+id+"x");
deptList.add(corp);
SysOrgDept dept1 = new SysOrgDept();
dept1.setType(2);
dept1.setId(id + "-1");
dept1.setName(name + "一总金办");
dept1.setLabel(id);
dept1.setParent(new SysOrg(id));
dept1.setOrnum(1);
dept1.setAvtag(true);
dept1.setTier("x"+id+"x"+id + "-1"+"x");
deptList.add(dept1);
SysOrgDept dept2 = new SysOrgDept();
dept2.setType(2);
dept2.setId(id + "-2");
dept2.setName(name + "二人事部");
dept2.setLabel(id);
dept2.setParent(new SysOrg(id));
dept2.setOrnum(2);
dept2.setAvtag(true);
dept2.setTier("x"+id+"x"+id + "-2"+"x");
deptList.add(dept2);
SysOrgDept dept3 = new SysOrgDept();
dept3.setType(2);
dept3.setId(id + "-3");
dept3.setName(name + "三销售部");
dept3.setLabel(id);
dept3.setParent(new SysOrg(id));
dept3.setOrnum(3);
dept3.setAvtag(true);
dept3.setTier("x"+id+"x"+id + "-3"+"x");
deptList.add(dept3);
SysOrgDept dept4 = new SysOrgDept();
dept4.setType(2);
dept4.setId(id + "-4");
dept4.setName(name + "四财务部");
dept4.setLabel(id);
dept4.setParent(new SysOrg(id));
dept4.setOrnum(4);
dept4.setAvtag(true);
dept4.setTier("x"+id+"x"+id + "-4"+"x");
deptList.add(dept4);
SysOrgDept dept5 = new SysOrgDept();
dept5.setType(2);
dept5.setId(id + "-5");
dept5.setName(name + "五采购部");
dept5.setLabel(id);
dept5.setParent(new SysOrg(id));
dept5.setOrnum(5);
dept5.setAvtag(true);
dept5.setTier("x"+id+"x"+id + "-5"+"x");
deptList.add(dept5);
SysOrgDept dept6 = new SysOrgDept();
dept6.setType(2);
dept6.setId(id + "-6");
dept6.setName(name + "六技术部");
dept6.setLabel(id);
dept6.setParent(new SysOrg(id));
dept6.setOrnum(6);
dept6.setAvtag(true);
dept6.setTier("x"+id+"x"+id + "-6"+"x");
deptList.add(dept6);
SysOrgDept dept7 = new SysOrgDept();
dept7.setType(2);
dept7.setId(id + "-7");
dept7.setName(name + "七制造部");
dept7.setLabel(id);
dept7.setParent(new SysOrg(id));
dept7.setOrnum(7);
dept7.setAvtag(true);
dept7.setTier("x"+id+"x"+id + "-7"+"x");
deptList.add(dept7);
SysOrgDept dept8 = new SysOrgDept();
dept8.setType(2);
dept8.setId(id + "-8");
dept8.setName(name + "八法务部");
dept8.setLabel(id);
dept8.setParent(new SysOrg(id));
dept8.setOrnum(8);
dept8.setAvtag(true);
dept8.setTier("x"+id+"x"+id + "-8"+"x");
deptList.add(dept8);
SysOrgDept dept9 = new SysOrgDept();
dept9.setType(2);
dept9.setId(id + "-9");
dept9.setName(name + "九信息部");
dept9.setLabel(id);
dept9.setParent(new SysOrg(id));
dept9.setOrnum(9);
dept9.setAvtag(true);
dept9.setTier("x"+id+"x"+id + "-9"+"x");
deptList.add(dept9);
for (int i = 1; i <= 50; i++) {
String RSID8= XstrUtil.getRSID8();
SysOrgDept xdept = new SysOrgDept();
xdept.setType(2);
xdept.setId(id + "--"+i);
xdept.setName(RSID8);
xdept.setLabel(id);
xdept.setParent(new SysOrg(id+"-"+(i%10==0?1:i%10)));
xdept.setAvtag(true);
xdept.setTier("x"+id+"x"+id+"-"+(i%10==0?1:i%10)+"x"+id + "--"+i+"x");
deptList.add(xdept);
}
}
//用户初始化
protected void initUser() {
List<SysOrgUser> userList = new ArrayList<>();
initUser(userList,"刘", "liu", "LIU");
initUser(userList,"陈", "c", "CHEN");
initUser(userList,"张", "z", "ZHANG");
initUser(userList,"李", "l", "LI");
initUser(userList,"王", "w", "WANG");
initUser(userList,"赵", "zhao", "ZHAO");
initUser(userList,"孙", "s", "SUN");
initUser(userList,"周", "zhou", "ZHOU");
initUser(userList,"吴", "wu", "WU");
initUser(userList,"郑", "zheng", "ZHENG");
userService.insertAll(userList);
}
//用户初始化具体实现
private void initUser(List<SysOrgUser> userList,String name, String id, String pid) {
SysOrgUser user0 = new SysOrgUser();
user0.setId(id+"lao");
user0.setUsnam(id);
user0.setName(name + "老");
user0.setDept(new SysOrg(pid));
user0.setPacod("1");//1
user0.setAvtag(true);
user0.setTier("x"+pid+"x"+id+"lao");
userList.add(user0);
for (int i = 1; i <= 9; i++) {
SysOrgUser userx = new SysOrgUser();
userx.setId(id + i);
userx.setUsnam(id + i);
userx.setName(name + numChange("" + i));
userx.setDept(new SysOrg(pid + "-" + i));
userx.setOrnum(i);
userx.setPacod("1");//1
userx.setAvtag(true);
userx.setTier("x"+pid+"x"+pid + "-" + i+"x"+id + i+"x");
userList.add(userx);
for (int j = 1; j <= 9; j++) {
SysOrgUser usery = new SysOrgUser();
usery.setId(id + i + j);
usery.setUsnam(id + i + j);
usery.setName(name + numChange("" + i) + numChange("" + j));
usery.setDept(new SysOrg(pid + "-" + i));
usery.setOrnum(j);
usery.setPacod("1");//1
usery.setAvtag(true);
usery.setTier("x"+pid+"x"+pid + "-" + i+"x"+id + i + j+"x");
userList.add(usery);
}
}
}
//多层级部门与用户初始化
protected void initZsf() {
SysOrgDept dept1 = new SysOrgDept();
dept1.setType(2);
dept1.setId("ZHANG-3-1");
dept1.setName("张三销售一室");
dept1.setLabel("ZHANG");
dept1.setParent(new SysOrg("ZHANG-3"));
dept1.setOrnum(1);
dept1.setAvtag(true);
dept1.setTier("xZHANGxZHANG-3xZHANG-3-1x");
deptService.insert(dept1);
SysOrgDept dept2 = new SysOrgDept();
dept2.setType(2);
dept2.setId("ZHANG-3-2");
dept2.setName("张三销售二室");
dept2.setLabel("ZHANG");
dept2.setParent(new SysOrg("ZHANG-3"));
dept2.setOrnum(1);
dept2.setAvtag(true);
dept2.setTier("xZHANGxZHANG-3xZHANG-3-2x");
deptService.insert(dept2);
SysOrgUser user4 = new SysOrgUser();
user4.setId("zsf");
user4.setUsnam("zsf");
user4.setName("张三丰");
user4.setDept(new SysOrg("ZHANG-3-2"));
user4.setOrnum(1);
user4.setPacod("1");
user4.setAvtag(true);
user4.setTier("xZHANGxZHANG-3xZHANG-3-2xzsfx");
userService.insert(user4);
}
//管理员初始化,正式项目一般只初始化这个就够了,上面的都是演示数据
protected void initSa() {
SysOrgUser user = new SysOrgUser();
user.setId("sa");
user.setUsnam("sa");
user.setName("管理员");
user.setPacod("1");
user.setAvtag(true);
user.setTier("xsax");
userService.insert(user);
SysOrgUser user2 = new SysOrgUser();
user2.setId("vben");
user2.setUsnam("vben");
user2.setName("小维");
user2.setPacod("123456");
user2.setAvtag(true);
user2.setTier("xvbenx");
userService.insert(user2);
}
private String numChange(String num) {
switch (num) {
case "1":
return "一";
case "2":
return "二";
case "3":
return "三";
case "4":
return "四";
case "5":
return "五";
case "6":
return "六";
case "7":
return "七";
case "8":
return "八";
case "9":
return "九";
case "10":
return "十";
}
return "零";
}
//
// //岗位初始化
// private void initPost() {
//
// }
//
// //组织架构组初始化
// private void initGroup() {
//
// }
@Autowired
private JdbcDao jdbcDao;
@Autowired
private SysOrgDeptService deptService;
@Autowired
private SysOrgUserService userService;
}
@@ -1,50 +0,0 @@
package vboot.core.framework.ldap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class LdapConfig {
@Value("${ldap.url}")
private String ldapUrl;
@Value("${ldap.base}")
private String ldapBase;
@Value("${ldap.userDn}")
private String ldapUserDn;
@Value("${ldap.userPwd}")
private String ldapUserPwd;
@Value("${ldap.referral}")
private String ldapReferral;
@Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSourceTarget());
}
@Bean
public LdapContextSource contextSourceTarget() {
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setUrl(ldapUrl);
ldapContextSource.setBase(ldapBase);
ldapContextSource.setUserDn(ldapUserDn);
ldapContextSource.setPassword(ldapUserPwd);
ldapContextSource.setReferral(ldapReferral);
Map<String, Object> config = new HashMap();
config.put("java.naming.ldap.attributes.binary", "objectGUID");
// config.put("com.sun.jndi.ldap.read.timeout","3000");
ldapContextSource.setPooled(false);
ldapContextSource.setBaseEnvironmentProperties(config);
return ldapContextSource;
}
}
@@ -1,38 +0,0 @@
package vboot.core.framework.ldap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Component;
import javax.naming.directory.DirContext;
@Component
public class LdapHandler {
@Autowired
private LdapTemplate ldapTemplate;
@Value("${ldap.domainName}")
private String ldapDomainName;
@Value("${ldap.base}")
private String ldapBaseDn;
public boolean authenticate(String userName, String password) {
//String userDomainName = getDnForUser(userName);
String userDomainName = String.format(ldapDomainName, userName);
DirContext ctx = null;
try {
ctx = ldapTemplate.getContextSource().getContext(userDomainName, password);
return true;
} catch (Exception e) {
// e.printStackTrace();
} finally {
LdapUtils.closeContext(ctx);
}
return false;
}
}
@@ -99,9 +99,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
//配置security忽略的请求与资源
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/","/assets/**","/druid/**","/login", "/index.html","/vben.html","/vue.html","/favicon.ico","/resource/**","/_app.config.js");
web.ignoring().antMatchers("/","/auth/**","/ws/**","/assets/**","/druid/**","/login", "/index.html","/vben.html","/vue.html","/favicon.ico","/resource/**","/_app.config.js");
//测试环境swagger放行
web.ignoring().antMatchers("/favicon.ico","/doc.html","/swagger-ui.html","/webjars/**","/swagger-resources/**","/v2/**","/v3/**");
web.ignoring().antMatchers("/doc.html","/swagger-ui.html","/webjars/**","/swagger-resources/**","/v2/**","/v3/**");
// web.ignoring().antMatchers("/","/login","/getMenuList","/getUserInfo","/assets/**","/druid/**", "/index.html","/vben.html","/vue.html","/favicon.ico","/resource/**","/_app.config.js");
// web.ignoring().antMatchers("/assets/**","/**");
}
@@ -32,7 +32,7 @@ public class AuthcService {
passFlag = true;
} else {
//如数据库校验不通过,可尝试其他方式校验,比如下面的AD域密码验证校验
//passFlag = ldapHandler.authenticate(loginVo.getUsername(), loginVo.getPassword());
// passFlag = ldapHandler.authenticate(loginVo.getUsername(), loginVo.getPassword());
}
}
return passFlag;
@@ -53,7 +53,8 @@ public class Zuser implements UserDetails, Serializable {
if("sa".equals(usnam)||"admin".equals(usnam)||"vben".equals(usnam)){
return true;
}
return isAdmin;
// return isAdmin;
return true;
}
public void setAdmin(boolean admin) {
@@ -3,7 +3,10 @@ package vboot.core.framework.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.ContentVersionStrategy;
import org.springframework.web.servlet.resource.VersionResourceResolver;
@Configuration
public class CorsConfig {
@@ -19,6 +22,19 @@ public class CorsConfig {
.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
.maxAge(3600);
}
// @Override//这个在security那里配置了
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
//// VersionResourceResolver versionResourceResolver = new VersionResourceResolver()
//// .addVersionStrategy(new ContentVersionStrategy(), "/**");
//// registry.addResourceHandler("static/**")
////// .addResourceLocations("classpath:/static/")
//// .setCachePeriod(2592000).resourceChain(true)
//// .addResolver(versionResourceResolver);
// registry.addResourceHandler("/gen/file/**")
// .addResourceLocations("file:C:\\vboot\\att\\");
// }
};
}
}
@@ -0,0 +1,23 @@
package vboot.core.framework.webservice;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>description:自动发布接口地址注解</p>
*
* @author newzhong
* @version 1.0
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoPublish {
/**
*<p>description:发布地址</p>
* @return String
* @author newzhong
*/
String publishAddress();
}
@@ -0,0 +1,26 @@
package vboot.core.framework.webservice;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//https://blog.csdn.net/m0_50172764/article/details/126014196
//https://blog.csdn.net/m0_48958478/article/details/125274698
/**
* <b>功能描述:CXF配置类</b><br>
*
* @author newzhong
* @version 1.0.0
* @since JDK 1.8
*/
@Configuration
public class CxfConfig {
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
SpringBus bus = new SpringBus();
// bus.getFeatures().add(new LoggingFeature());
return bus;
}
}
@@ -0,0 +1,14 @@
package vboot.core.framework.webservice;
import javax.jws.WebService;
//@AutoPublish(publishAddress = "/pig")
@WebService(name = "PigService", // 暴露服务名称
targetNamespace = "http://service.sbmpservice.usts.edu.cn"// 命名空间,一般是接口的包名倒序
)
public interface PigService {
int addUser();
}
@@ -0,0 +1,24 @@
package vboot.core.framework.webservice;
import org.springframework.stereotype.Component;
import javax.jws.WebService;
@Component
@AutoPublish(publishAddress = "/pig")
@WebService(serviceName = "PigService", // 与接口中指定的name一致
targetNamespace = "http://service.sbmpservice.usts.edu.cn", // 与接口中的命名空间一致,一般是接口的包名倒
endpointInterface = "vboot.core.framework.webservice.PigService"// 接口地址
)
public class PigServiceImpl implements PigService {
@Override
public int addUser(){
System.out.println("addUser");
return 2;
}
}
@@ -0,0 +1,81 @@
package vboot.core.framework.webservice;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import javax.xml.ws.Endpoint;
@Component
@Slf4j
public class StartClas implements ApplicationRunner {
// @Bean(name = Bus.DEFAULT_BUS_ID)
// public SpringBus springBus() {
// return new SpringBus();
// }
@Autowired
private WebApplicationContext applicationConnect;
@Autowired()
@Qualifier(Bus.DEFAULT_BUS_ID)
private SpringBus bus;
@Bean(name = "wsBean")
public ServletRegistrationBean dispatcherServlet() {
ServletRegistrationBean wbsServlet = new ServletRegistrationBean(new CXFServlet(), "/ws/*");
return wbsServlet;
}
// @Bean
// public PigService pigService() {
// return new PigServiceImpl();
// }
@SuppressWarnings("resource")
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
log.info("开始进行自动发布webService接口");
//
String[] beanNames = applicationConnect.getBeanNamesForAnnotation(AutoPublish.class);
for(String beanName : beanNames) {
String publishAddr = applicationConnect.getType(beanName).getAnnotation(AutoPublish.class).publishAddress();
EndpointImpl endpoint = new EndpointImpl(bus, applicationConnect.getBean(beanName));
endpoint.publish(publishAddr);
log.info(String.format("发布接口地址:[%s]", "http://localhost:5000"+publishAddr));
}
log.info("weBservice接口自动发布结束");
// EndpointImpl endpoint = new EndpointImpl(bus,pigService);
// endpoint.publish("/api");
// System.out.println("服务发布成功!地址为:http://localhost:8081/ws/api?wsdl");
}
@Autowired
private PigService pigService;
//
// @Bean
// public Endpoint endpointPurchase(SpringBus springBus) {
//
//
//
// return endpoint;
//
// }
}
@@ -192,7 +192,6 @@ public class VelocityUtils
*/
public static String getFileName(String template, AssCogeTable genTable)
{
System.out.println(111111111);
// 文件名称
String fileName = "";
// 包路径
@@ -1,41 +0,0 @@
package vboot.core.module.ass.file.att;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
@Entity
@Data
@ApiModel("附件信息")
public class AssFileAtt {
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
@Column(length = 32)
@ApiModelProperty("地址")
private String addre;
@Column(length = 128)
@ApiModelProperty("前缀名称")
private String pname;
@Column(length = 128)
@ApiModelProperty("后缀名称")
private String sname;
@Column(length = 16)
@ApiModelProperty("大小")
private String zsize;
@Transient
@ApiModelProperty("缩略图")
private String zimg;
}
@@ -1,296 +0,0 @@
package vboot.core.module.ass.file.att;
import vboot.core.common.utils.file.XfileUtil;
import vboot.core.common.utils.lang.XdateUtil;
import vboot.core.common.utils.lang.XstrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@Component
public class AssFileAttHandler {
@Value("${app.att.path}")
private String ATT_PATH;
public List<AssFileAtt> saveFiles(MultipartFile[] files) throws IOException
{
List<AssFileAtt> attList = new ArrayList<>();
if (files != null)
{
for (int i = 0; i < files.length; i++)
{
String fileName = files[i].getOriginalFilename();
if (!"".equals(fileName))
{
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
String pName;
String sName = "";
if(fileName.contains(".")){
pName= fileName.substring(0,fileName.lastIndexOf("."));
sName = fileName.substring(fileName.lastIndexOf(".")+1);
}else{
pName=fileName;
}
String uuid = XstrUtil.getUUID();
String newName = uuid +"."+ sName;
int code = newName.hashCode();
String dirY = XdateUtil.getYYYY();
String dirM = XdateUtil.getMM();
String dirD = XdateUtil.getDD();
String dirX = Integer.toHexString(code & 0xf);
String savePath = dirY + "/" + dirM + "/" + dirD + "/" + dirX;
File targetFolder = new File(ATT_PATH + "/" + savePath);
File targetFile = new File(ATT_PATH + "/" + savePath, newName);
if (!targetFolder.exists())
{
targetFolder.mkdirs();
}
files[i].transferTo(targetFile);
AssFileAtt att = new AssFileAtt();
att.setZsize(XfileUtil.getFileSize(files[i].getSize()));
att.setPname(pName);
att.setAddre(savePath);
att.setId(uuid);
att.setSname(sName);
attList.add(att);
}
}
}
return attList;
}
public AssFileAtt saveFile(MultipartFile file) throws IOException
{
AssFileAtt att = new AssFileAtt();
String fileName = file.getOriginalFilename();
if (!"".equals(fileName))
{
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
String pName;
String sName = "";
if(fileName.contains(".")){
pName= fileName.substring(0,fileName.lastIndexOf("."));
sName = fileName.substring(fileName.lastIndexOf(".")+1);
}else{
pName=fileName;
}
String uuid = XstrUtil.getUUID();
String newName = uuid +"."+ sName;
int code = newName.hashCode();
String dirY = XdateUtil.getYYYY();
String dirM = XdateUtil.getMM();
String dirD = XdateUtil.getDD();
String dirX = Integer.toHexString(code & 0xf);
String savePath = dirY + "/" + dirM + "/" + dirD + "/" + dirX;
File targetFolder = new File(ATT_PATH + "/" + savePath);
File targetFile = new File(ATT_PATH + "/" + savePath, newName);
if (!targetFolder.exists())
{
targetFolder.mkdirs();
}
att.setZsize(XfileUtil.getFileSize(file.getSize()));
att.setPname(pName);
att.setAddre(savePath);
att.setId(uuid);
att.setSname(sName);
file.transferTo(targetFile);
// if("jpg".equals(sName)||"JPG".equals(sName)||"png".equals(sName)||"PNG".equals(sName)){
// Thumbnails.of(ATT_PATH + "/" + savePath+"/"+newName).scale(1f).outputQuality(0.25f).toFile(ATT_PATH + "/" + savePath+"/"+uuid +"_2.jpg");
// }
}
return att;
}
public AssFileAtt saveFile2(MultipartFile file) throws IOException
{
AssFileAtt att = new AssFileAtt();
String fileName = file.getOriginalFilename();
if (!"".equals(fileName))
{
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
String pName;
String sName = "";
if(fileName.contains(".")){
pName= fileName.substring(0,fileName.lastIndexOf("."));
sName = fileName.substring(fileName.lastIndexOf(".")+1);
}else{
pName=fileName;
}
String uuid = XstrUtil.getUUID();
String newName = uuid +"."+ sName;
int code = newName.hashCode();
String dirY = XdateUtil.getYYYY();
String dirM = XdateUtil.getMM();
String dirD = XdateUtil.getDD();
String dirX = Integer.toHexString(code & 0xf);
String savePath = dirY + "/" + dirM + "/" + dirD + "/" + dirX;
File targetFolder = new File(ATT_PATH + "/" + savePath);
File targetFile = new File(ATT_PATH + "/" + savePath, newName);
if (!targetFolder.exists())
{
targetFolder.mkdirs();
}
att.setZsize(XfileUtil.getFileSize(file.getSize()));
att.setPname(pName);
att.setAddre(savePath);
att.setId(uuid);
att.setSname(sName);
file.transferTo(targetFile);
}
return att;
}
public AssFileAtt saveImg(String path, String imgData) throws IOException
{
AssFileAtt att = new AssFileAtt();
BASE64Decoder decoder = new BASE64Decoder();
//Base64解码
byte[] b = decoder.decodeBuffer(imgData);
for (int i = 0; i < b.length; ++i)
{
if (b[i] < 0)
{//调整异常数据
b[i] += 256;
}
}
//生成jpeg图片
String dirY = XdateUtil.getYYYY();
String dirM = XdateUtil.getMM();
String dirD = XdateUtil.getDD();
String uid= XstrUtil.getUUID();
String savePath =dirY + "/" + dirM + "/" + dirD + "/" +uid + ".png";
byte2File(b, path + "att/kk/" + "/" + dirY + "/" + dirM + "/" + dirD+"/", uid + ".png");
att.setAddre(savePath);
att.setId(uid);
return att;
}
public void download(HttpServletRequest request,
HttpServletResponse response, AssFileAtt att) throws Exception
{
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String realName = att.getPname()+"."+att.getSname();
String storeName = att.getAddre() + "/" + att.getId() + realName.substring(realName.lastIndexOf("."));
String downLoadPath = ATT_PATH + "/" + storeName;
long fileLength = new File(downLoadPath).length();
response.setContentType("application/octet-stream");
realName = URLEncoder.encode(realName, "UTF-8");
Locale localLanguage = request.getLocale();
if (realName.length() > 150)
{
realName = new String(realName.getBytes("gb2312"), "ISO8859-1");
}
response.addHeader("Access-Control-Expose-Headers", "Content-disposition,download-filename");
response.setHeader("Content-disposition", "attachment; filename=" + realName);
response.setHeader("Content-Length", String.valueOf(fileLength));
response.setHeader("download-filename", realName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downLoadPath));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
public void downloadByPath(HttpServletRequest request,
HttpServletResponse response, String name,String path) throws Exception
{
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String downLoadPath = ATT_PATH + "/" + path;
long fileLength = new File(downLoadPath).length();
response.setContentType("application/octet-stream");
name = URLEncoder.encode(name, "UTF-8");
Locale localLanguage = request.getLocale();
if (name.length() > 150)
{
name = new String(name.getBytes("gb2312"), "ISO8859-1");
}
response.addHeader("Access-Control-Expose-Headers", "Content-disposition,download-filename");
response.setHeader("Content-disposition", "attachment; filename=" + name);
response.setHeader("Content-Length", String.valueOf(fileLength));
response.setHeader("download-filename", name);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downLoadPath));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
private void byte2File(byte[] buf, String filePath, String fileName){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try
{
File dir = new File(filePath);
if (!dir.exists())
{
dir.mkdirs();
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (bos != null)
{
try
{
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (fos != null)
{
try
{
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
@@ -1,7 +0,0 @@
package vboot.core.module.ass.file.att;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AssFileAttRepo extends JpaRepository<AssFileAtt,String> {
}
@@ -0,0 +1,92 @@
package vboot.core.module.ass.oss.config;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* 对象存储配置对象 sys_oss_config
*
* @author Lion Li
*/
@Entity
@Data
@ApiModel("附件配置")
public class AssOssConfig {
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
// /**
// * 主建
// */
// @TableId(value = "oss_config_id")
// private Long ossConfigId;
/**
* 配置key
*/
private String configKey;
/**
* accessKey
*/
private String accessKey;
/**
* 秘钥
*/
private String secretKey;
/**
* 桶名称
*/
private String bucketName;
/**
* 前缀
*/
private String prefix;
/**
* 访问站点
*/
private String endpoint;
/**
* 自定义域名
*/
private String domain;
/**
* 是否https(0否 1是)
*/
private String isHttps;
/**
* 域
*/
private String region;
/**
* 状态(0正常 1停用)
*/
private String status;
/**
* 扩展字段
*/
private String ext1;
/**
* 备注
*/
private String remark;
}
@@ -0,0 +1,31 @@
package vboot.core.module.ass.oss.config;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.mvc.dao.Sqler;
@RestController
@RequestMapping("ass/oss/config")
@Api(tags = {"存储配置"})
public class AssOssConfigApi {
@GetMapping
@ApiOperation("查询存储配置分页")
public R get(String name) {
Sqler sqler = new Sqler("t.id,t.config_key,t.access_key,t.secretKey", "ass_oss_config");
sqler.addLike("t.config_key", name);
sqler.addSelect("t.endpoint,t.bucket_name,t.prefix,t.status");
return R.ok(jdbcDao.findPageData(sqler));
}
@Autowired
private JdbcDao jdbcDao;
}
@@ -0,0 +1,8 @@
package vboot.core.module.ass.oss.config;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AssOssConfigRepo extends JpaRepository<AssOssConfig,String> {
}
@@ -0,0 +1,188 @@
package vboot.core.module.ass.oss.config;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vboot.core.common.utils.ruoyi.JsonUtils;
import vboot.core.common.utils.ruoyi.RedisUtils;
import vboot.core.module.ass.oss.root.OssConstant;
import vboot.core.module.ass.oss.root.OssFactory;
import java.util.List;
/**
* 对象存储配置Service业务层处理
*
* @author Lion Li
* @author 孤舟烟雨
* @date 2021-08-13
*/
@Slf4j
@RequiredArgsConstructor
@Service
public class AssOssConfigService {
// private final SysOssConfigMapper baseMapper;
@Autowired
private AssOssConfigRepo repo;
/**
* 项目启动时,初始化参数到缓存,加载配置类
*/
public void init() {
List<AssOssConfig> list = repo.findAll();
AssOssConfig assOssConfig=new AssOssConfig();
assOssConfig.setConfigKey("");
assOssConfig.setAccessKey("");
assOssConfig.setSecretKey("");
assOssConfig.setBucketName("");
assOssConfig.setEndpoint("oss-cn-hangzhou.aliyuncs.com");
assOssConfig.setIsHttps("N");
assOssConfig.setRegion("oss-cn-hangzhou.aliyuncs.com");
assOssConfig.setStatus("0");
assOssConfig.setId("111");
list.add(assOssConfig);
// 加载OSS初始化配置
for (AssOssConfig config : list) {
String configKey = config.getConfigKey();
if ("0".equals(config.getStatus())) {
RedisUtils.setCacheObject(OssConstant.CACHE_CONFIG_KEY, configKey);
}
setConfigCache(true, config);
}
// 初始化OSS工厂
OssFactory.init();
}
// @Override
// public SysOssConfigVo queryById(Long ossConfigId) {
// return baseMapper.selectVoById(ossConfigId);
// }
//
// @Override
// public TableDataInfo<SysOssConfigVo> queryPageList(SysOssConfigBo bo, PageQuery pageQuery) {
// LambdaQueryWrapper<SysOssConfig> lqw = buildQueryWrapper(bo);
// Page<SysOssConfigVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
// return TableDataInfo.build(result);
// }
//
//
// private LambdaQueryWrapper<SysOssConfig> buildQueryWrapper(SysOssConfigBo bo) {
// LambdaQueryWrapper<SysOssConfig> lqw = Wrappers.lambdaQuery();
// lqw.eq(StringUtils.isNotBlank(bo.getConfigKey()), SysOssConfig::getConfigKey, bo.getConfigKey());
// lqw.like(StringUtils.isNotBlank(bo.getBucketName()), SysOssConfig::getBucketName, bo.getBucketName());
// lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysOssConfig::getStatus, bo.getStatus());
// return lqw;
// }
//
// @Override
// public Boolean insertByBo(SysOssConfigBo bo) {
// SysOssConfig config = BeanUtil.toBean(bo, SysOssConfig.class);
// validEntityBeforeSave(config);
// return setConfigCache(baseMapper.insert(config) > 0, config);
// }
//
// @Override
// public Boolean updateByBo(SysOssConfigBo bo) {
// SysOssConfig config = BeanUtil.toBean(bo, SysOssConfig.class);
// validEntityBeforeSave(config);
// LambdaUpdateWrapper<SysOssConfig> luw = new LambdaUpdateWrapper<>();
// luw.set(ObjectUtil.isNull(config.getPrefix()), SysOssConfig::getPrefix, "");
// luw.set(ObjectUtil.isNull(config.getRegion()), SysOssConfig::getRegion, "");
// luw.set(ObjectUtil.isNull(config.getExt1()), SysOssConfig::getExt1, "");
// luw.set(ObjectUtil.isNull(config.getRemark()), SysOssConfig::getRemark, "");
// luw.eq(SysOssConfig::getOssConfigId, config.getOssConfigId());
// return setConfigCache(baseMapper.update(config, luw) > 0, config);
// }
//
// /**
// * 保存前的数据校验
// */
// private void validEntityBeforeSave(SysOssConfig entity) {
// if (StringUtils.isNotEmpty(entity.getConfigKey())
// && UserConstants.NOT_UNIQUE.equals(checkConfigKeyUnique(entity))) {
// throw new ServiceException("操作配置'" + entity.getConfigKey() + "'失败, 配置key已存在!");
// }
// }
//
// @Override
// public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
// if (isValid) {
// if (CollUtil.containsAny(ids, OssConstant.SYSTEM_DATA_IDS)) {
// throw new ServiceException("系统内置, 不可删除!");
// }
// }
// List<SysOssConfig> list = Lists.newArrayList();
// for (Long configId : ids) {
// SysOssConfig config = baseMapper.selectById(configId);
// list.add(config);
// }
// boolean flag = baseMapper.deleteBatchIds(ids) > 0;
// if (flag) {
// list.stream().forEach(sysOssConfig -> {
// RedisUtils.deleteObject(getCacheKey(sysOssConfig.getConfigKey()));
// });
// }
// return flag;
// }
//
// /**
// * 判断configKey是否唯一
// */
// private String checkConfigKeyUnique(SysOssConfig sysOssConfig) {
// long ossConfigId = ObjectUtil.isNull(sysOssConfig.getOssConfigId()) ? -1L : sysOssConfig.getOssConfigId();
// SysOssConfig info = baseMapper.selectOne(new LambdaQueryWrapper<SysOssConfig>()
// .select(SysOssConfig::getOssConfigId, SysOssConfig::getConfigKey)
// .eq(SysOssConfig::getConfigKey, sysOssConfig.getConfigKey()));
// if (ObjectUtil.isNotNull(info) && info.getOssConfigId() != ossConfigId) {
// return UserConstants.NOT_UNIQUE;
// }
// return UserConstants.UNIQUE;
// }
//
// /**
// * 启用禁用状态
// */
// @Override
// @Transactional(rollbackFor = Exception.class)
// public int updateOssConfigStatus(SysOssConfigBo bo) {
// SysOssConfig sysOssConfig = BeanUtil.toBean(bo, SysOssConfig.class);
// int row = baseMapper.update(null, new LambdaUpdateWrapper<SysOssConfig>()
// .set(SysOssConfig::getStatus, "1"));
// row += baseMapper.updateById(sysOssConfig);
// if (row > 0) {
// RedisUtils.setCacheObject(OssConstant.CACHE_CONFIG_KEY, sysOssConfig.getConfigKey());
// }
// return row;
// }
//
// /**
// * 设置cache key
// *
// * @param configKey 参数键
// * @return 缓存键key
// */
private String getCacheKey(String configKey) {
return OssConstant.SYS_OSS_KEY + configKey;
}
//
// /**
// * 如果操作成功 则更新缓存
// *
// * @param flag 操作状态
// * @param config 配置
// * @return 返回操作状态
// */
private boolean setConfigCache(boolean flag, AssOssConfig config) {
if (flag) {
RedisUtils.setCacheObject(
getCacheKey(config.getConfigKey()),
JsonUtils.toJsonString(config));
RedisUtils.publish(OssConstant.CACHE_CONFIG_KEY, config.getConfigKey(), msg -> {
log.info("发布刷新OSS配置 => " + msg);
});
}
return flag;
}
}
@@ -0,0 +1,39 @@
package vboot.core.module.ass.oss.file;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
@ApiModel("OSS存储文件")
@Table(indexes = {@Index(columnList = "md5")})
public class AssOssFile {
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
@ApiModelProperty("文件md5")
@Column(length = 32)
private String md5;
@ApiModelProperty("文件大小")
private Long size;
@ApiModelProperty("存储地址")
private String path;
@ApiModelProperty("存储服务")
@Column(length = 32)
private String service;
@Column(updatable = false)
@ApiModelProperty("创建时间")
private Date crtim = new Date();
}
@@ -0,0 +1,10 @@
package vboot.core.module.ass.oss.file;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AssOssFileRepo extends JpaRepository<AssOssFile,String> {
AssOssFile findByMd5(String md5);
}
@@ -0,0 +1,49 @@
package vboot.core.module.ass.oss.main;
import com.alibaba.excel.annotation.ExcelIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import vboot.core.module.sys.org.root.SysOrg;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
@ApiModel("OSS存储引用")
public class AssOssMain {
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
@ApiModelProperty("文件名称")
private String name;
@ApiModelProperty("类型(后缀)")
@Column(length = 32)
private String type;
@ApiModelProperty("文件ID")
@Column(length = 32)
private String filid;
@ApiModelProperty("业务ID")
@Column(length = 32)
private String busid;
@Column(updatable = false)
@ApiModelProperty("创建时间")
private Date crtim = new Date();
@ManyToOne
@JoinColumn(name = "crman", updatable = false)
@ExcelIgnore
@ApiModelProperty("创建人")
protected SysOrg crman;
}
@@ -0,0 +1,57 @@
package vboot.core.module.ass.oss.main;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.mvc.dao.Sqler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("ass/oss/main")
@Api(tags = {"文件存储"})
public class AssOssMainApi {
@GetMapping
@ApiOperation("查询存储分页")
public R get(String name) {
Sqler sqler = new Sqler("t.name,t.id,t.type,t.crtim", "ass_oss_main");
sqler.addInnerJoin("f.size,f.service,f.path", "ass_oss_file f", "f.id=t.filid");
sqler.addLeftJoin("u.name crman", "sys_org_user u", "u.id=t.crman");
sqler.addLike("t.name", name);
sqler.addOrder("t.crtim desc");
return R.ok(jdbcDao.findPageData(sqler));
}
@GetMapping("download")
@ApiOperation("附件下载")
public void download(String table, String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
service.downloadFile(request,response,table,id);
}
@PostMapping(value="upload",produces = "text/html;charset=UTF-8")
@ApiOperation("附件上传")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
Zfile zfile = service.uploadFile(file);
return "{\"id\":\"" + zfile.getId() + "\",\"path\":\"" + zfile.getPath() + "\",\"filid\":\"" + zfile.getFilid() + "\",\"name\":\"" + zfile.getName() + "\",\"size\":\"" + zfile.getSize() + "\"}";
}
@DeleteMapping("{ids}")
@ApiOperation("删除文件")
public R delete(@PathVariable String[] ids) {
service.delete(ids);
return R.ok();
}
@Autowired
private JdbcDao jdbcDao;
@Autowired
private AssOssMainService service;
}
@@ -0,0 +1,10 @@
package vboot.core.module.ass.oss.main;
import org.springframework.data.jpa.repository.JpaRepository;
import vboot.core.module.ass.oss.file.AssOssFile;
public interface AssOssMainRepo extends JpaRepository<AssOssMain,String> {
}
@@ -0,0 +1,136 @@
package vboot.core.module.ass.oss.main;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.utils.file.XfileUtil;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.common.utils.web.XuserUtil;
import vboot.core.module.ass.oss.file.AssOssFile;
import vboot.core.module.ass.oss.file.AssOssFileRepo;
import vboot.core.module.ass.oss.root.AssOssLocalHand;
import vboot.core.module.ass.oss.root.AssOssRemoteHand;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Map;
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class AssOssMainService {
public Zfile uploadFile(MultipartFile file) throws IOException, NoSuchAlgorithmException {
String md5 = getMd5(file);
AssOssFile dbFile = fileRepo.findByMd5(md5);
Zfile zfile = new Zfile();
if (dbFile != null) {//相同文件已上传过
AssOssMain main = new AssOssMain();
main.setId(XstrUtil.getUUID());
main.setFilid(dbFile.getId());
main.setName(file.getOriginalFilename());
if (main.getName().contains(".")) {
main.setType(main.getName().substring(main.getName().lastIndexOf(".") + 1));
}
repo.save(main);
zfile.setId(main.getId());
zfile.setName(main.getName());
zfile.setSize(XfileUtil.getFileSize(dbFile.getSize()));
zfile.setPath(dbFile.getPath());
zfile.setFilid(dbFile.getId());
} else {
AssOssFile newFile = localHand.upload(file,md5);
// AssOssFile newFile = remoteHand.upload(file,md5);
fileRepo.save(newFile);
AssOssMain main = new AssOssMain();
main.setId(newFile.getId());
main.setFilid(newFile.getId());
main.setName(file.getOriginalFilename());
if (main.getName().contains(".")) {
main.setType(main.getName().substring(main.getName().lastIndexOf(".") + 1));
}
main.setCrman(XuserUtil.getUser());
repo.save(main);
zfile.setId(main.getId());
zfile.setName(main.getName());
zfile.setSize(XfileUtil.getFileSize(newFile.getSize()));
zfile.setPath(newFile.getPath());
zfile.setFilid(newFile.getId());
}
return zfile;
}
public void downloadFile(HttpServletRequest request, HttpServletResponse response,
String table, String id) throws Exception {
String sql = "select t.path,t.name,f.service from " + table + " t " +
"inner join ass_oss_file f on f.id=t.filid " +
"where t.id=?";
Map<String, Object> map = null;
if (XstrUtil.isNotBlank(table)) {
map = jdbcDao.findMap(sql, id);
}
if (map == null) {
sql = "select f.path,t.name,f.service from ass_oss_main t " +
"inner join ass_oss_file f on f.id=t.filid " +
"where t.id=?";
map = jdbcDao.findMap(sql, id);
}
if("local".equals(map.get("service"))){
localHand.download(request,response,""+map.get("name"),""+map.get("path"));
}else{
remoteHand.download(request, response, "" + map.get("name"), "" + map.get("path"));
}
}
public int delete(String[] ids) {
for (String id : ids) {
repo.deleteById(id);
}
return ids.length;
}
@Autowired
private JdbcDao jdbcDao;
@Autowired
private AssOssLocalHand localHand;
@Autowired
private AssOssRemoteHand remoteHand;
@Autowired
private AssOssMainRepo repo;
@Autowired
private AssOssFileRepo fileRepo;
private String getMd5(MultipartFile file) {
try {
//获取文件的byte信息
byte[] uploadBytes = file.getBytes();
// 拿到一个MD5转换器
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(uploadBytes);
//转换为16进制
return new BigInteger(1, digest).toString(16);
// MessageDigest messageDigest = MessageDigest.getInstance("md5");
// return Base64.getEncoder().encodeToString(messageDigest.digest(file.getBytes()));
} catch (IOException | NoSuchAlgorithmException e) {
log.error("get file md5 error!!!", e);
}
return null;
}
}
@@ -0,0 +1,18 @@
package vboot.core.module.ass.oss.main;
import lombok.Data;
@Data
public class Zfile {
private String id;
private String name;
private String size;
private String path;
private String filid;
}
@@ -0,0 +1,85 @@
package vboot.core.module.ass.oss.root;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.utils.lang.XdateUtil;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.module.ass.oss.file.AssOssFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Locale;
@Component
public class AssOssLocalHand {
@Value("${app.att.path}")
private String ATT_PATH;
public AssOssFile upload(MultipartFile file,String md5) throws IOException, NoSuchAlgorithmException {
AssOssFile ossFile = new AssOssFile();
String fileName = file.getOriginalFilename();
if (!"".equals(fileName)) {
String uuid = XstrUtil.getUUID();
String newName = uuid;
if(fileName.contains(".")){
newName+="."+fileName.substring(fileName.lastIndexOf(".")+1);
}
String dirX = Integer.toHexString(newName.hashCode() & 0xf);
String savePath =XdateUtil.getYYYYMMDDPath() + "/" + dirX;
File targetFolder = new File(ATT_PATH + "/" + savePath);
File targetFile = new File(ATT_PATH + "/" + savePath, newName);
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
file.transferTo(targetFile);
ossFile.setId(uuid);
ossFile.setSize(file.getSize());
ossFile.setMd5(md5);
ossFile.setPath(savePath + "/" + newName);
ossFile.setService("local");
}
return ossFile;
}
public void download(HttpServletRequest request,HttpServletResponse response,
String fileName,String path) throws Exception
{
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String downLoadPath = ATT_PATH + "/" + path;
long fileLength = new File(downLoadPath).length();
response.setContentType("application/octet-stream");
fileName = URLEncoder.encode(fileName, "UTF-8");
Locale localLanguage = request.getLocale();
if (fileName.length() > 150)
{
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
}
response.addHeader("Access-Control-Expose-Headers", "Content-disposition,download-filename");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(fileLength));
response.setHeader("download-filename", fileName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downLoadPath));
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
}
@@ -0,0 +1,64 @@
package vboot.core.module.ass.oss.root;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import org.hibernate.service.spi.ServiceException;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.exception.base.BaseException;
import vboot.core.common.utils.file.FileUtils;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.common.utils.ruoyi.StringUtils;
import vboot.core.module.ass.oss.file.AssOssFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
@Component
public class AssOssRemoteHand {
public AssOssFile upload(MultipartFile file,String md5) {
String originalfileName = file.getOriginalFilename();
String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
OssClient storage = OssFactory.instance();
UploadResult uploadResult;
try {
uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
} catch (IOException e) {
throw new BaseException(e.getMessage());
}
// 保存文件信息
AssOssFile ossFile = new AssOssFile();
ossFile.setId(XstrUtil.getUUID());
ossFile.setSize(file.getSize());
ossFile.setMd5(md5);
ossFile.setPath(uploadResult.getUrl());
ossFile.setService(storage.getConfigKey());
return ossFile;
}
public void download(HttpServletRequest request, HttpServletResponse response,
String fileName, String path) throws IOException {
// response.reset();
FileUtils.setAttachmentResponseHeader(response, fileName);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
long data;
try {
data = HttpUtil.download(path, response.getOutputStream(), false);
} catch (HttpException e) {
if (e.getMessage().contains("403")) {
throw new ServiceException("无读取权限, 请在对应的OSS开启'公有读'权限!");
} else {
throw new ServiceException(e.getMessage());
}
}
response.setContentLength(Convert.toInt(data));
}
}
@@ -0,0 +1,184 @@
package vboot.core.module.ass.oss.root;
import cn.hutool.core.util.IdUtil;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import vboot.core.common.utils.ruoyi.DateUtils;
import vboot.core.common.utils.ruoyi.StringUtils;
import vboot.core.module.ass.oss.root.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* S3 存储协议 所有兼容S3协议的云厂商均支持
* 阿里云 腾讯云 七牛云 minio
*
* @author Lion Li
*/
public class OssClient {
private final String configKey;
private final OssProperties properties;
private final AmazonS3 client;
public OssClient(String configKey, OssProperties ossProperties) {
this.configKey = configKey;
this.properties = ossProperties;
try {
AwsClientBuilder.EndpointConfiguration endpointConfig =
new AwsClientBuilder.EndpointConfiguration(properties.getEndpoint(), properties.getRegion());
AWSCredentials credentials = new BasicAWSCredentials(properties.getAccessKey(), properties.getSecretKey());
AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
ClientConfiguration clientConfig = new ClientConfiguration();
if (OssConstant.IS_HTTPS.equals(properties.getIsHttps())) {
clientConfig.setProtocol(Protocol.HTTPS);
} else {
clientConfig.setProtocol(Protocol.HTTP);
}
this.client = AmazonS3Client.builder()
.withEndpointConfiguration(endpointConfig)
.withClientConfiguration(clientConfig)
.withCredentials(credentialsProvider)
.disableChunkedEncoding()
.build();
createBucket();
} catch (Exception e) {
if (e instanceof OssException) {
throw e;
}
throw new OssException("配置错误! 请检查系统配置:[" + e.getMessage() + "]");
}
}
public void createBucket() {
try {
String bucketName = properties.getBucketName();
if (client.doesBucketExistV2(bucketName)) {
return;
}
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
client.createBucket(createBucketRequest);
client.setBucketPolicy(bucketName, getPolicy(bucketName, PolicyType.READ));
} catch (Exception e) {
throw new OssException("创建Bucket失败, 请核对配置信息:[" + e.getMessage() + "]");
}
}
public UploadResult upload(byte[] data, String path, String contentType) {
return upload(new ByteArrayInputStream(data), path, contentType);
}
public UploadResult upload(InputStream inputStream, String path, String contentType) {
try {
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(contentType);
metadata.setContentLength(inputStream.available());
client.putObject(new PutObjectRequest(properties.getBucketName(), path, inputStream, metadata));
} catch (Exception e) {
throw new OssException("上传文件失败,请检查配置信息:[" + e.getMessage() + "]");
}
return UploadResult.builder().url(getUrl() + "/" + path).filename(path).build();
}
public void delete(String path) {
path = path.replace(getUrl() + "/", "");
try {
client.deleteObject(properties.getBucketName(), path);
} catch (Exception e) {
throw new OssException("上传文件失败,请检查配置信息:[" + e.getMessage() + "]");
}
}
public UploadResult uploadSuffix(byte[] data, String suffix, String contentType) {
return upload(data, getPath(properties.getPrefix(), suffix), contentType);
}
public UploadResult uploadSuffix(InputStream inputStream, String suffix, String contentType) {
return upload(inputStream, getPath(properties.getPrefix(), suffix), contentType);
}
public String getUrl() {
String domain = properties.getDomain();
if (StringUtils.isNotBlank(domain)) {
return domain;
}
String endpoint = properties.getEndpoint();
String header = OssConstant.IS_HTTPS.equals(properties.getIsHttps()) ? "https://" : "http://";
// 云服务商直接返回
if (StringUtils.containsAny(endpoint, OssConstant.CLOUD_SERVICE)){
return header + properties.getBucketName() + "." + endpoint;
}
// minio 单独处理
return header + endpoint + "/" + properties.getBucketName();
}
public String getPath(String prefix, String suffix) {
// 生成uuid
String uuid = IdUtil.fastSimpleUUID();
// 文件路径
String path = DateUtils.datePath() + "/" + uuid;
if (StringUtils.isNotBlank(prefix)) {
path = prefix + "/" + path;
}
return path + suffix;
}
public String getConfigKey() {
return configKey;
}
private static String getPolicy(String bucketName, PolicyType policyType) {
StringBuilder builder = new StringBuilder();
builder.append("{\n\"Statement\": [\n{\n\"Action\": [\n");
if (policyType == PolicyType.WRITE) {
builder.append("\"s3:GetBucketLocation\",\n\"s3:ListBucketMultipartUploads\"\n");
} else if (policyType == PolicyType.READ_WRITE) {
builder.append("\"s3:GetBucketLocation\",\n\"s3:ListBucket\",\n\"s3:ListBucketMultipartUploads\"\n");
} else {
builder.append("\"s3:GetBucketLocation\"\n");
}
builder.append("],\n\"Effect\": \"Allow\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
builder.append(bucketName);
builder.append("\"\n},\n");
if (policyType == PolicyType.READ) {
builder.append("{\n\"Action\": [\n\"s3:ListBucket\"\n],\n\"Effect\": \"Deny\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
builder.append(bucketName);
builder.append("\"\n},\n");
}
builder.append("{\n\"Action\": ");
switch (policyType) {
case WRITE:
builder.append("[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n");
break;
case READ_WRITE:
builder.append("[\n\"s3:AbortMultipartUpload\",\n\"s3:DeleteObject\",\n\"s3:GetObject\",\n\"s3:ListMultipartUploadParts\",\n\"s3:PutObject\"\n],\n");
break;
default:
builder.append("\"s3:GetObject\",\n");
break;
}
builder.append("\"Effect\": \"Allow\",\n\"Principal\": \"*\",\n\"Resource\": \"arn:aws:s3:::");
builder.append(bucketName);
builder.append("/*\"\n}\n],\n\"Version\": \"2012-10-17\"\n}\n");
return builder.toString();
}
}
@@ -0,0 +1,48 @@
package vboot.core.module.ass.oss.root;
import java.util.Arrays;
import java.util.List;
/**
* 对象存储常量
*
* @author Lion Li
*/
public interface OssConstant {
/**
* OSS模块KEY
*/
String SYS_OSS_KEY = "sys_oss:";
/**
* 对象存储配置KEY
*/
String OSS_CONFIG_KEY = "OssConfig";
/**
* 缓存配置KEY
*/
String CACHE_CONFIG_KEY = SYS_OSS_KEY + OSS_CONFIG_KEY;
/**
* 预览列表资源开关Key
*/
String PEREVIEW_LIST_RESOURCE_KEY = "sys.oss.previewListResource";
/**
* 系统数据ids
*/
List<Integer> SYSTEM_DATA_IDS = Arrays.asList(1, 2, 3, 4);
/**
* 云服务商
*/
String[] CLOUD_SERVICE = new String[] {"aliyun", "qcloud", "qiniu"};
/**
* https 状态
*/
String IS_HTTPS = "Y";
}
@@ -0,0 +1,16 @@
package vboot.core.module.ass.oss.root;
/**
* OSS异常类
*
* @author Lion Li
*/
public class OssException extends RuntimeException {
private static final long serialVersionUID = 1L;
public OssException(String msg) {
super(msg);
}
}
@@ -0,0 +1,73 @@
package vboot.core.module.ass.oss.root;
import lombok.extern.slf4j.Slf4j;
import vboot.core.common.utils.ruoyi.JsonUtils;
import vboot.core.common.utils.ruoyi.RedisUtils;
import vboot.core.common.utils.ruoyi.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 文件上传Factory
*
* @author Lion Li
*/
@Slf4j
public class OssFactory {
private static final Map<String, OssClient> CLIENT_CACHE = new ConcurrentHashMap<>();
/**
* 初始化工厂
*/
public static void init() {
log.info("初始化OSS工厂");
RedisUtils.subscribe(OssConstant.CACHE_CONFIG_KEY, String.class, configKey -> {
OssClient client = getClient(configKey);
// 未初始化不处理
if (client != null) {
refresh(configKey);
log.info("订阅刷新OSS配置 => " + configKey);
}
});
}
/**
* 获取默认实例
*/
public static OssClient instance() {
// 获取redis 默认类型
String configKey = RedisUtils.getCacheObject(OssConstant.CACHE_CONFIG_KEY);
if (StringUtils.isEmpty(configKey)) {
throw new OssException("文件存储服务类型无法找到!");
}
return instance(configKey);
}
/**
* 根据类型获取实例
*/
public static OssClient instance(String configKey) {
OssClient client = getClient(configKey);
if (client == null) {
refresh(configKey);
return getClient(configKey);
}
return client;
}
private static void refresh(String configKey) {
Object json = RedisUtils.getCacheObject(OssConstant.SYS_OSS_KEY + configKey);
OssProperties properties = JsonUtils.parseObject(json.toString(), OssProperties.class);
if (properties == null) {
throw new OssException("系统异常, '" + configKey + "'配置信息不存在!");
}
CLIENT_CACHE.put(configKey, new OssClient(configKey, properties));
}
private static OssClient getClient(String configKey) {
return CLIENT_CACHE.get(configKey);
}
}
@@ -0,0 +1,53 @@
package vboot.core.module.ass.oss.root;
import lombok.Data;
/**
* OSS对象存储 配置属性
*
* @author Lion Li
*/
@Data
public class OssProperties {
/**
* 访问站点
*/
private String endpoint;
/**
* 自定义域名
*/
private String domain;
/**
* 前缀
*/
private String prefix;
/**
* ACCESS_KEY
*/
private String accessKey;
/**
* SECRET_KEY
*/
private String secretKey;
/**
* 存储空间名
*/
private String bucketName;
/**
* 存储区域
*/
private String region;
/**
* 是否https(Y=是,N=否)
*/
private String isHttps;
}
@@ -0,0 +1,35 @@
package vboot.core.module.ass.oss.root;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* minio策略配置
*
* @author Lion Li
*/
@Getter
@AllArgsConstructor
public enum PolicyType {
/**
* 只读
*/
READ("read-only"),
/**
* 只写
*/
WRITE("write-only"),
/**
* 读写
*/
READ_WRITE("read-write");
/**
* 类型
*/
private final String type;
}
@@ -0,0 +1,24 @@
package vboot.core.module.ass.oss.root;
import lombok.Builder;
import lombok.Data;
/**
* 上传返回体
*
* @author Lion Li
*/
@Data
@Builder
public class UploadResult {
/**
* 文件路径
*/
private String url;
/**
* 文件名
*/
private String filename;
}
@@ -1,55 +0,0 @@
package vboot.core.module.gen.file;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import vboot.core.module.ass.file.att.AssFileAtt;
import vboot.core.module.ass.file.att.AssFileAttRepo;
import vboot.core.module.ass.file.att.AssFileAttHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("gen/att")
@Api(tags = {"附件管理"})
public class GenAttApi {
@PostMapping(value="up",produces = "text/html;charset=UTF-8")
@ApiOperation("附件上传")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
System.out.println("上传xxxxxx");
AssFileAtt att = handler.saveFile(file);
repo.save(att);
return "{\"id\":\"" + att.getId() + "\",\"addre\":\"" + att.getAddre() + "\",\"pname\":\"" + att.getPname() + "\",\"sname\":\"" + att.getSname() + "\",\"zsize\":\"" + att.getZsize() + "\",\"zimg\":\"" + att.getZimg() + "\"}";
}
@GetMapping(value="one/{id}")
@ApiOperation("通过ID下载附件")
public void getOne(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
AssFileAtt att=repo.findById(id).get();
handler.download(request,response,att);
}
@GetMapping(value="pdf")
@ApiOperation("查看PDF附件")
public void pdf(String f, HttpServletRequest request, HttpServletResponse response) throws Exception {
AssFileAtt att=repo.findById(f).get();
handler.download(request,response,att);
}
@GetMapping(value="path")
@ApiOperation("通过地址下载附件")
public void downloadByPath(String name, String path, HttpServletRequest request, HttpServletResponse response) throws Exception {
handler.downloadByPath(request,response,name,path);
}
@Autowired
private AssFileAttRepo repo;
@Autowired
private AssFileAttHandler handler;
}
@@ -1,69 +0,0 @@
package vboot.core.module.gen.file;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import vboot.core.common.utils.file.XqcodeUtil;
import vboot.core.module.ass.file.att.AssFileAttHandler;
import vboot.core.module.ass.file.att.AssFileAtt;
import vboot.core.module.ass.file.att.AssFileAttRepo;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
@RestController
@RequestMapping("gen/img")
@Api(tags = {"图片管理"})
public class GenImgApi {
//{
// "code": 0 //0表示成功,其它失败
// ,"msg": "" //提示信息 //一般上传失败后返回
// ,"data": {
// "src": "图片路径"
// ,"title": "图片名称" //可选
// }
//}
@PostMapping(value="up",produces = "text/html;charset=UTF-8")
@ApiOperation("图片上传")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
AssFileAtt att = handler.saveFile2(file);
repo.save(att);
return "{\"code\":\"" + 0 + "\",\"msg\":\"" + "\",\"data\":{\"src\":\"" + "co/img/one/"+att.getId() + "\",\"title\":\"" + att.getPname()+"."+att.getSname() + "\"}}";
}
@GetMapping(value="one/{id}")
@ApiOperation("图片下载")
public void getOne(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
AssFileAtt att=repo.findById(id).get();
handler.download(request,response,att);
}
@RequestMapping(value="qr",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
@ApiOperation("生产图片二维码")
public byte[] getImage(String label,Integer size) throws IOException, WriterException {
if(size==null||size==0)
{
size=900;
}
InputStream inputStream= XqcodeUtil.createQrCode(label, size, "JPEG");
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
@Autowired
private AssFileAttRepo repo;
@Autowired
private AssFileAttHandler handler;
}
@@ -0,0 +1,34 @@
package vboot.core.module.gen.img;
import com.google.zxing.WriterException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import vboot.core.common.utils.file.XqcodeUtil;
import java.io.IOException;
import java.io.InputStream;
@RestController
@RequestMapping("gen/img")
@Api(tags = {"图片服务"})
public class GenImgApi {
@RequestMapping(value="qr",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
@ApiOperation("生产图片二维码")
public byte[] getImage(String label,Integer size) throws IOException, WriterException {
if(size==null||size==0)
{
size=900;
}
InputStream inputStream= XqcodeUtil.createQrCode(label, size, "JPEG");
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
}
@@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("gen/num")
@Api(tags = {"编号管理"})
@Api(tags = {"编号服务"})
public class GenNumApi {
@GetMapping("uuid")
@@ -1,4 +1,4 @@
package vboot.core.module.gen.org.root;
package vboot.core.module.gen.org;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
@@ -1,4 +1,4 @@
package vboot.core.module.gen.org.root;
package vboot.core.module.gen.org;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
@@ -1,4 +1,4 @@
package vboot.core.module.gen.org.rece;
package vboot.core.module.gen.org;
import io.swagger.annotations.Api;
import vboot.core.common.mvc.api.R;
@@ -15,7 +15,7 @@ import java.util.Map;
@RestController
@RequestMapping("gen/org/rece")
@Api(tags = {"组织架构"})
@Api(tags = {"组织架构服务"})
public class GenOrgReceApi {
@GetMapping
@@ -1,7 +1,8 @@
package vboot.core.module.gen.org.rece;
package vboot.core.module.gen.org;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.mvc.dao.Sqler;
import vboot.core.common.utils.db.DbType;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.common.utils.web.XuserUtil;
import vboot.core.module.sys.org.rece.SysOrgRece;
@@ -33,9 +34,9 @@ public class GenOrgReceService {
sqler.addDescOrder("t.uptim");
sqler.addEqual("t.userid", userid);
List<SysOrgRece> list;
if ("mysql".equals(jdbcDao.getDbType())) {
if (DbType.MYSQL.equals(jdbcDao.getDbType())) {
list = jdbcDao.getTp().query(sqler.getMysqlPagingSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysOrgRece.class));
} else if("oracle".equals(jdbcDao.getDbType())) {
} else if(DbType.ORACLE.equals(jdbcDao.getDbType())) {
list = jdbcDao.getTp().query(sqler.getOraclePagingLowerCaseSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysOrgRece.class));
}else{
list = jdbcDao.getTp().query(sqler.getSqlserverPagingSql(), sqler.getParams(), new BeanPropertyRowMapper<>(SysOrgRece.class));
@@ -0,0 +1,35 @@
package vboot.core.module.gen.oss;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import vboot.core.module.ass.oss.main.Zfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.module.ass.oss.main.AssOssMainService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("gen/oss")
@Api(tags = {"存储服务"})
public class GenOssApi {
@PostMapping(value="upload",produces = "text/html;charset=UTF-8")
@ApiOperation("文件上传")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
Zfile zfile = assOssMainService.uploadFile(file);
return "{\"id\":\"" + zfile.getId() + "\",\"path\":\"" + zfile.getPath() + "\",\"filid\":\"" + zfile.getFilid() + "\",\"name\":\"" + zfile.getName() + "\",\"size\":\"" + zfile.getSize() + "\"}";
}
@GetMapping("download")
@ApiOperation("文件下载")
public void download(String table,String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
assOssMainService.downloadFile(request,response,table,id);
}
@Autowired
private AssOssMainService assOssMainService;
}
@@ -1,69 +0,0 @@
package vboot.core.module.gen.sys.auth;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.framework.security.pojo.Zuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("gen/auth")
public class GenAuthApi {
@PostMapping(value="btns")
public R getBtns(HttpServletRequest request, @RequestBody Map<String,String> btns) {
Zuser zuser = null;
Map<String, Boolean> backMap = new HashMap<>();
for (String str : btns.keySet()) {
if(zuser.isAdmin()){
backMap.put(str, true);
continue;
}
backMap.put(str, false);
String sql = "select pos,code from sys_api_main p where p.id = ?";
try{
Map<String, Object> map = jdbcDao.findMap(sql, btns.get(str));
if (zuser.hasPerm(Integer.parseInt(""+map.get("pos")) , Long.parseLong(""+map.get("code")))) {
backMap.put(str, true);
}
}catch (Exception e){
}
}
return R.ok(backMap);
}
//获取用户信息,如果没有登录到不了这里
@GetMapping("user")
public R getUser(HttpServletRequest request,String id) {
Map<String, Object> map = new HashMap<>();
Zuser zuser= null;
if("sa".equals(id)){
//主页滚动通知
String noteSql = "select n.notes from sys_por_note n inner join sys_por_note_org o on o.id=n.id where n.label='sa' and n.avtag=1 and o.org in (" + zuser.getConds() + ")";
String note = jdbcDao.findOneString(noteSql);
map.put("note", note);
//主页弹框通知
// String note2Sql = "select n.id,r.org from sys_por_note n inner join sys_por_note_org o on o.id=n.id left join sys_por_note_reader r on r.id=n.id AND r.org = '"+zuser.getId()+"' where n.label='sa2' and n.avtag=1 and o.org in (" + zuser.getConds() + ")";
// List<Map<String, Object>> note2List = jdbcDao.findMapList(note2Sql);
// if(note2List.size()>0){
// if(note2List.get(0).get("org")==null){
// map.put("note2", note2List.get(0).get("id"));
// }
// }
}
map.put("zuser", zuser);
return R.build(200, "已登录",map);
}
@Autowired
private JdbcDao jdbcDao;
}
@@ -1,61 +0,0 @@
package vboot.core.module.gen.sys.org;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.mvc.dao.Sqler;
import vboot.core.common.utils.lang.XstrUtil;
import vboot.core.framework.security.pojo.Zuser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("gen/org")
public class GenOrgApi {
@GetMapping(value="watag")
public R getWatag(HttpServletRequest request) {
Zuser zuser = null;
String sql = "update sys_org_user set watag=0 where id=?";
jdbcDao.update(sql, zuser.getId());
zuser.setWatag(false);
return R.ok();
}
@GetMapping(value="choose")
public R getChoose(String name, String type) {
Sqler sqlHelper = new Sqler("id,pid,name","sys_org_main");
sqlHelper.addWhere("t.avtag = 1");
sqlHelper.addWhere(XstrUtil.isNotBlank(type),"type in ("+type+")");
sqlHelper.addLike("name",name);
sqlHelper.addEqual("t.label", "ekp");
return R.ok(jdbcDao.findInpList(sqlHelper));
}
@GetMapping("search")
public R getSearch(String name, String type) {
Sqler sqlHelper = new Sqler("t.id,t.name","sys_org_main");
sqlHelper.addLeftJoin("t2.name as pid", "sys_org t2", "t2.id=t.pid");
sqlHelper.addWhere("t.avtag = 1");
sqlHelper.addLike("t.name",name);
sqlHelper.addWhere(XstrUtil.isNotBlank(type),"t.type in ("+type+")");
return R.ok(jdbcDao.findInpList(sqlHelper));
}
@GetMapping("dept/{id}")
public R getDept(@PathVariable String id, String type) {
Sqler sqlHelper = new Sqler("t.id,t.name","sys_org_main");
sqlHelper.addLeftJoin("t2.name as pid", "sys_org t2", "t2.id=t.pid");
sqlHelper.addWhere("t.avtag = 1");
sqlHelper.addWhere(XstrUtil.isNotBlank(type),"t.type in ("+type+")");
sqlHelper.addWhere("t.pid = ?",id);
return R.ok(jdbcDao.findInpList(sqlHelper));
}
@Autowired
private JdbcDao jdbcDao;
}
@@ -12,7 +12,7 @@ import java.util.List;
@Entity
@Data
@Table(indexes = {@Index(columnList = "tier",unique = true), @Index(columnList = "avtag")})
@Table(indexes = {@Index(columnList = "tier"), @Index(columnList = "avtag")})
@ApiModel("组织架构部门")
public class SysOrgDept {
@@ -33,12 +33,12 @@ public class SysOrgDeptService {
if (main.getId() == null || "".equals(main.getId())) {
main.setId(XstrUtil.getUUID());
}
if (main.getParent() == null || StrUtil.isBlank(main.getParent().getId())) {
main.setTier("x" + main.getId() + "x");
} else {
String tier = jdbcDao.findOneString("select tier from sys_org_dept where id=?", main.getParent().getId());
main.setTier(tier + main.getId() + "x");
}
// if (main.getParent() == null || StrUtil.isBlank(main.getParent().getId())) {
// main.setTier("x" + main.getId() + "x");
// } else {
// String tier = jdbcDao.findOneString("select tier from sys_org_dept where id=?", main.getParent().getId());
// main.setTier(tier + main.getId() + "x");
// }
SysOrg sysOrg = new SysOrg(main.getId(), main.getName());
orgList.add(sysOrg);
}
@@ -45,6 +45,8 @@ public class SysOrgGroup {
@ApiModelProperty("成员信息")
private List<SysOrg> members;
@Column(length = 32)
@ApiModelProperty("标签")
private String label;//主要用于区分组织架构分类,ABC为系统内置组织架构
}
@@ -11,7 +11,8 @@ import java.util.List;
@Entity
@Data
@Table(indexes = {@Index(columnList = "tier",unique = true), @Index(columnList = "avtag")})
//@Table(indexes = {@Index(columnList = "tier",unique = true), @Index(columnList = "avtag")})
@Table(indexes = {@Index(columnList = "tier"), @Index(columnList = "avtag")})
@ApiModel("组织架构岗位")
public class SysOrgPost{
@Id
@@ -62,5 +63,8 @@ public class SysOrgPost{
@ApiModelProperty("员工列表")
private List<SysOrg> users;
@Column(length = 32)
@ApiModelProperty("标签")
private String label;//主要用于区分组织架构分类,ABC为系统内置组织架构
}
@@ -11,7 +11,7 @@ import java.util.Date;
@Entity
@Data
@Table(indexes = {@Index(columnList = "usnam",unique = true),@Index(columnList = "tier",unique = true), @Index(columnList = "avtag")})
@Table(indexes = {@Index(columnList = "usnam"),@Index(columnList = "tier"), @Index(columnList = "avtag")})
@ApiModel("组织架构用户")
public class SysOrgUser {
@Id
@@ -49,7 +49,6 @@ public class SysOrgUser {
private String usnam;
@Column(length = 64,updatable = false)
@JsonIgnore
@ApiModelProperty("密码")
private String pacod;
@@ -90,4 +89,9 @@ public class SysOrgUser {
@ApiModelProperty("更新时间")
private Date uptim;
@Column(length = 32)
@ApiModelProperty("标签")
private String label;//主要用于区分组织架构分类,ABC为系统内置组织架构
}
@@ -30,6 +30,7 @@ public class SysOrgUserApi {
sqler.addEqual("t.deptid", deptid);
}
sqler.addSelect("t.crtim,t.uptim,t.deptid,t.notes");
sqler.addOrder("t.ornum");
return R.ok(service.findPageData(sqler));
}
@@ -32,11 +32,13 @@ public class SysOrgUserService {
if (main.getId() == null || "".equals(main.getId())) {
main.setId(XstrUtil.getUUID());
}
if (main.getDept() == null || StrUtil.isBlank(main.getDept().getId())) {
main.setTier("x" + main.getId() + "x");
} else {
String tier = jdbcDao.findOneString("select tier from sys_org_dept where id=?", main.getDept().getId());
main.setTier(tier + main.getId() + "x");
if(XstrUtil.isBlank(main.getTier())){
if (main.getDept() == null || StrUtil.isBlank(main.getDept().getId())) {
main.setTier("x" + main.getId() + "x");
} else {
String tier = jdbcDao.findOneString("select tier from sys_org_dept where id=?", main.getDept().getId());
main.setTier(tier + main.getId() + "x");
}
}
main.setPacod(DigestUtils.md5DigestAsHex(("abc" + main.getPacod() + "xyz").getBytes()));
SysOrg sysOrg = new SysOrg(main.getId(), main.getName());
@@ -51,11 +53,13 @@ public class SysOrgUserService {
if (main.getId() == null || "".equals(main.getId())) {
main.setId(XstrUtil.getUUID());
}
if (main.getDept() == null || StrUtil.isBlank(main.getDept().getId())) {
main.setTier("x" + main.getId() + "x");
} else {
String tier = jdbcDao.findOneString("select tier from sys_org_dept where id=?", main.getDept().getId());
main.setTier(tier + main.getId() + "x");
if(XstrUtil.isBlank(main.getTier())) {
if (main.getDept() == null || StrUtil.isBlank(main.getDept().getId())) {
main.setTier("x" + main.getId() + "x");
} else {
String tier = jdbcDao.findOneString("select tier from sys_org_dept where id=?", main.getDept().getId());
main.setTier(tier + main.getId() + "x");
}
}
main.setPacod(DigestUtils.md5DigestAsHex(("abc" + main.getPacod() + "xyz").getBytes()));
SysOrg sysOrg = new SysOrg(main.getId(), main.getName());
+13
View File
@@ -132,6 +132,19 @@
<version>2.7</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dingtalk</artifactId>
<version>1.3.99</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibaba-dingtalk-service-sdk</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
<!-- <build>-->
@@ -14,7 +14,6 @@ public class OaFlowTemp extends BaseMainEntity {
private Integer ornum;
private String protd;//全局流程模板ID
@Lob
@@ -0,0 +1,43 @@
package vboot.extend.oa.proj.main;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
//主记录OneToMany
@Entity
@Data
@ApiModel("项目附件")
public class OaProjAtt
{
@Id
@Column(length = 32)
@ApiModelProperty("主键ID")
private String id;
@ApiModelProperty("附件名称")
private String name;
@ApiModelProperty("附件大小")
private String size;
@ApiModelProperty("存储地址")
private String path;
@ApiModelProperty("文件ID")
@Column(length = 32)
private String filid;
@ApiModelProperty("业务ID")
@Column(length = 32)
private String busid;
@ApiModelProperty("排序号")
private Integer ornum;
}
@@ -0,0 +1,57 @@
package vboot.extend.oa.proj.main;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import vboot.core.common.mvc.entity.BaseMainEntity;
import vboot.core.module.sys.org.root.SysOrg;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Getter
@Setter
@ApiModel("项目")
public class OaProjMain extends BaseMainEntity {
//流水号示例
@Column(length = 32)
@ApiModelProperty("流水号")
private String senum;
//ManyToOne示例
@ManyToOne
@JoinColumn(name = "prman")
@ApiModelProperty("负责人")
private SysOrg prman;
//ManyToMany示例
@ManyToMany
@JoinTable(name = "oa_proj_viewer", joinColumns = {@JoinColumn(name = "mid")},
inverseJoinColumns = {@JoinColumn(name = "oid")})
@ApiModelProperty("可查看者")
private List<SysOrg> viewers;
//ManyToMany示例
@ManyToMany
@JoinTable(name = "oa_proj_editor", joinColumns = {@JoinColumn(name = "mid")},
inverseJoinColumns = {@JoinColumn(name = "oid")})
@ApiModelProperty("可编辑者")
private List<SysOrg> editors;
//OneToMany示例
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "maiid")
@OrderBy("ornum ASC")
@ApiModelProperty("项目成员")
private List<OaProjMember> members = new ArrayList<>();
//附件示例
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "maiid")
@ApiModelProperty("附件清单")
private List<OaProjAtt> atts = new ArrayList<>();
}
@@ -0,0 +1,79 @@
package vboot.extend.oa.proj.main;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vboot.core.common.mvc.api.R;
import vboot.core.common.mvc.dao.JdbcDao;
import vboot.core.common.mvc.dao.Sqler;
import vboot.core.module.ass.num.main.AssNumMainService;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("oa/proj/main")
@Api(tags = {"项目管理"})
public class OaProjMainApi {
@GetMapping
@ApiOperation("查询项目分页")
public R get(String name) {
Sqler sqler = new Sqler("oa_proj_main");
sqler.addLike("t.name", name);
sqler.addSelect("t.senum,t.notes");
return R.ok(service.findPageData(sqler));
}
@GetMapping("list")
public R getList() {
Sqler sqler = new Sqler("oa_proj_main");
return R.ok(jdbcDao.findIdNameList(sqler));
}
@GetMapping("one/{id}")
@ApiOperation("查询项目详情")
public R getOne(@PathVariable String id) {
OaProjMain main = service.findOne(id);
return R.ok(main);
}
@PostMapping("impdd")
@ApiOperation("钉钉旧项目导入")
public R impdd(@RequestParam(value = "file", required = false) MultipartFile file) {
service.impDd(file);
return R.ok();
}
@PostMapping
@ApiOperation("新增项目")
public R post(@RequestBody OaProjMain main) {
main.setSenum(numService.getNum("PROJ"));//设置供应商流水号
return R.ok(service.insert(main));
}
@PutMapping
@ApiOperation("更新项目")
public R put(@RequestBody OaProjMain main) {
return R.ok(service.update(main));
}
@DeleteMapping("{ids}")
@ApiOperation("删除项目")
public R delete(@PathVariable String[] ids) {
return R.ok(service.delete(ids));
}
@Autowired
private OaProjMainService service;
@Autowired
private JdbcDao jdbcDao;
@Autowired
private AssNumMainService numService;
}

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