Commit b4e410d5 by zhoujinghao

Merge branch 'test'

2 parents 788e8060 1217a54a
Showing 214 changed files with 10135 additions and 2831 deletions
...@@ -13,125 +13,124 @@ ...@@ -13,125 +13,124 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>nafmii-admin</name> <name>nafmii-admin</name>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<description>Demo project for Spring Boot</description> <description>中心端(后台管理系统)</description>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
<!--区分环境打包-->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!--指定默认激活-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<dependencies> <dependencies>
<!--集成SpringBoot Admin监控-->
<!-- https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-starter-server -->
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>de.codecentric</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <artifactId>spring-boot-admin-starter-server</artifactId>
</dependency> <version>2.4.1</version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!--MyBatis分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<!--feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<exclusions><!-- 去掉springboot默认配置 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<!--SpringData工具包-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc14 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
</dependency> </dependency>
<!--集成logstash-->
<dependency> <dependency>
<groupId>net.logstash.logback</groupId> <groupId>org.nafmii</groupId>
<artifactId>logstash-logback-encoder</artifactId> <artifactId>nafmii-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<!--集成SpringBoot Admin监控--> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-sleuth -->
<dependency> <dependency>
<groupId>de.codecentric</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId> <artifactId>spring-cloud-starter-sleuth</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> </dependency>
<!--Knife4j API文档生产工具--> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-sleuth-zipkin -->
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId> <artifactId>spring-cloud-sleuth-zipkin</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-zipkin</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> </dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency> <dependency>
<groupId>org.nafmii</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>nafmii-common</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
<finalName>${project.artifactId}-${project.version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>application-dev.yml</exclude>
<exclude>application-test.yml</exclude>
<exclude>application-prod.yml</exclude>
</excludes>
</resource>
<!--需要动态添加的资源-->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<!--读取打包命令中指定的环境-->
<include>application-${env}.yml</include>
<include>application.yml</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>
package org.nafmii.nafmiiadmin; package org.nafmii.admin;
import org.mybatis.spring.annotation.MapperScan; import org.mybatis.spring.annotation.MapperScan;
import org.nafmii.common.ftp.EnableFtpServer;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @SpringBootApplication
@EnableEurekaClient @EnableEurekaClient
@EnableSwagger2
@EnableFeignClients @EnableFeignClients
@ComponentScan(value = {"org.nafmii.nafmiiadmin"}) @MapperScan(basePackages ={"org.nafmii.admin/**/dao"})
@MapperScan(basePackages ={"org.nafmii.nafmiiadmin.mapper"}) @EnableFtpServer
public class NafmiiAdminApplication { public class NafmiiAdminApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
package org.nafmii.admin.att.controller;
import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.admin.att.service.AttService;
import org.nafmii.common.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.InputStream;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/7 14:30
* @ClassName:文件服务公共接口
* @version:
* @remark:
*/
@RestController
@RequestMapping("/nafmii/admin/att")
@Api(tags = "2.0.2", description = "上传文件到文件服务器【zjh】")
@Slf4j
public class AttController {
@Autowired
private AttService attService;
/**上传文件到ftp
*
* @param description 描述
* @param userId 用户id
* @param files 文件
* @return
*/
@ApiOperation( value = "上传文件到ftp",notes = "上传文件到ftp")
@PostMapping(value = "/uploadToFtp",headers = "content-type=multipart/form-data")
@ResponseBody
public ApiResponse uploadToFtp(@RequestParam("description") String description,
@RequestParam("userId") String userId,
@RequestParam("files") MultipartFile[] files) {
log.info("外部网关通过ftp批量上传文件名称参数================》{}", files);
ApiResponse apiResponse = attService.uploadToFtp(files,description,Long.valueOf(userId));
return apiResponse;
}
/**
* 下载ftp上文件到本地
*@param newFileName 新文件名
*@param fileName 原文件(路径+文件名)
*@param downUrl 下载路径
*@return
*/
@ApiOperation( value = "下载ftp上文件到本地",notes = "下载ftp上文件到本地")
@PostMapping(value = "/downloadFile",headers = "content-type=multipart/form-data")
@ResponseBody
public ApiResponse downloadFile(@RequestParam("newFileName") String newFileName,
@RequestParam("fileName") String fileName,
@RequestParam("downUrl") String downUrl) {
ApiResponse apiResponse = attService.downloadFile(newFileName,fileName,downUrl);
return apiResponse;
}
}
package org.nafmii.admin.att.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.admin.att.service.ImportExcelService;
import org.nafmii.common.response.ApiResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
@RestController
@RequestMapping("/nafmii/admin/excel")
@Api(tags = "2.0.3", description = "中心端批量导入Excel接口【zjh】")
public class ImportExcelController {
@Resource
private ImportExcelService iImportExcelService;
@ApiOperation( value = "中心端导入Excel",notes = "中心端导入Excel")
@PostMapping("/import")
@ResponseBody
public ApiResponse ImportExcel(MultipartFile file) throws IOException {
ApiResponse result = iImportExcelService.importExcel(file);
return result;
}
@ApiOperation( value = "中心端导出Excel",notes = "中心端导出Excel")
@PostMapping("/export")
@ResponseBody
public ApiResponse exportExcel() throws IOException {
ApiResponse result = iImportExcelService.exportExcel();
return result;
}
}
package org.nafmii.admin.att.dao;
import org.nafmii.admin.att.entity.AttachmentInfoPO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 公用附件表 Mapper 接口
* </p>
*
* @author zjh
* @since 2021-05-07
*/
public interface AttachmentInfoMapper extends BaseMapper<AttachmentInfoPO> {
}
package org.nafmii.admin.att.dao;
import org.nafmii.admin.att.entity.BusinessAttachmentInfoPO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zjh
* @since 2021-05-07
*/
public interface BusinessAttachmentInfoMapper extends BaseMapper<BusinessAttachmentInfoPO> {
}
package org.nafmii.admin.att.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.nafmii.admin.att.dto.ImportExcelDto;
/**
* <p>
* 中心端-用户表 Mapper 接口
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Mapper
public interface ImportExcelMapper extends BaseMapper<ImportExcelDto> {
/**
* @author:suncq
* @Function:批量导入EXCEL数据
* @date 2021/5/6
* @ClassName:
* @version:
* @remark:
*/
int insertExcelData(@Param("data") ImportExcelDto data);
}
package org.nafmii.admin.att.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* AttachmentInfoDto对象.对应实体描述:公用附件表
*/
@Data
@ApiModel("AttachmentInfoDto对象")
public class AttachmentInfoDto {
@ApiModelProperty("附件id")
private String id;
@ApiModelProperty("源文件名称包括后缀")
private String fileName;
@ApiModelProperty("相对url")
private String fileUrl;
@ApiModelProperty("文件存储相对目录")
private String filePath;
@ApiModelProperty("描述")
private String description;
@ApiModelProperty("软删除字段0未删除1已删除")
private String delFlag;
@ApiModelProperty("创建人")
private Long createUser;
@ApiModelProperty("创建时间")
private Date createDate;
@ApiModelProperty("修改人")
private Long updateUser;
@ApiModelProperty("修改时间")
private Date updateDate;
}
package org.nafmii.admin.att.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
/**
* AttachmentInfoDto对象.对应实体描述:公用附件表
*/
@Data
@ApiModel("AttachmentInfoListDto对象")
public class AttachmentInfoListDto {
@ApiModelProperty("附件集合信息")
List<AttachmentInfoDto> attachmentInfoDtoList;
}
package org.nafmii.admin.att.dto;
import io.swagger.annotations.ApiModel;
import lombok.Data;
@Data
@ApiModel("导入Excel参数对象")
public class ImportExcelDto {
private String column1;
private String column2;
private String column3;
}
package org.nafmii.admin.att.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 公用附件表
* </p>
*
* @author zjh
* @since 2021-05-07
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("ATTACHMENT_INFO")
@ApiModel(value="AttachmentInfoPO对象", description="公用附件表")
public class AttachmentInfoPO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "附件id")
@TableId("ID")
private Long id;
@ApiModelProperty(value = "源文件名称")
@TableField("FILE_NAME")
private String fileName;
@ApiModelProperty(value = "相对url")
@TableField("FILE_URL")
private String fileUrl;
@ApiModelProperty(value = "文件存储相对目录")
@TableField("FILE_PATH")
private String filePath;
@ApiModelProperty(value = "描述")
@TableField("DESCRIPTION")
private String description;
@ApiModelProperty(value = "是否有效 0 有效 1无效")
@TableField("IS_ENABLE")
private String isEnable;
@ApiModelProperty(value = "创建人")
@TableField("CREATE_USER_ID")
private Long createUserId;
@ApiModelProperty(value = "修改人")
@TableField("UPDATE_USER_ID")
private Long updateUserId;
@ApiModelProperty(value = "创建时间")
@TableField("CREATE_TIME")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
}
package org.nafmii.admin.att.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author zjh
* @since 2021-05-07
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("BUSINESS_ATTACHMENT_INFO")
@ApiModel(value="BusinessAttachmentInfoPO对象", description="")
public class BusinessAttachmentInfoPO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键id")
@TableId("ID")
private Long id;
@ApiModelProperty(value = "业务类型")
@TableField("BUSINESS")
private String business;
@ApiModelProperty(value = "业务id")
@TableField("BUSINESS_ID")
private Long businessId;
@ApiModelProperty(value = "附件id")
@TableField("ATTACHMENT_ID")
private Long attachmentId;
@ApiModelProperty(value = "创建人")
@TableField("CREATE_USER_ID")
private Long createUserId;
@ApiModelProperty(value = "修改人")
@TableField("UPDATE_USER_ID")
private Long updateUserId;
@ApiModelProperty(value = "创建时间")
@TableField("CREATE_TIME")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
@ApiModelProperty(value = "排序")
@TableField("SORT")
private Integer sort;
@ApiModelProperty(value = "描述")
@TableField("DESCRIPTION")
private String description;
@ApiModelProperty(value = "是否有效 0 有效 1无效")
@TableField("IS_ENABLE")
private String isEnable;
}
package org.nafmii.admin.att.service;
import org.nafmii.admin.att.dto.AttachmentInfoListDto;
import org.nafmii.common.response.ApiResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/7 14:42
* @ClassName:
* @version:
* @remark:
*/
public interface AttService {
//下载ftp上文件到本地
ApiResponse downloadFile(String newFileName, String fileName, String downUrl);
//上传文件到ftp
ApiResponse uploadToFtp(MultipartFile[] files, String description, Long userId);
//ftp上传存库操作
ApiResponse uploadByFtp(AttachmentInfoListDto attachmentInfoListDto);
}
package org.nafmii.admin.att.service;
import org.nafmii.common.response.ApiResponse;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
* <p>
* 中心端批量导入Excel
* </p>
*
* @author zjh
* @since 2021-04-27
*/
public interface ImportExcelService {
//中心端导出Excle
ApiResponse exportExcel();
//中心端批量导入Excel
ApiResponse importExcel(MultipartFile file) throws IOException;
}
package org.nafmii.admin.att.service.impl;
import cn.hutool.core.bean.copier.BeanCopier;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.admin.att.dao.AttachmentInfoMapper;
import org.nafmii.admin.att.dto.AttachmentInfoDto;
import org.nafmii.admin.att.dto.AttachmentInfoListDto;
import org.nafmii.admin.att.entity.AttachmentInfoPO;
import org.nafmii.admin.att.service.AttService;
import org.nafmii.admin.att.vo.EshopAttachmentInfoVo;
import org.nafmii.common.constant.CommonEnum;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.FtpUtil;
import org.nafmii.common.utils.SnowFlakeUtil;
import org.nafmii.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.util.*;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/7 14:42
* @ClassName:
* @version:
* @remark:
*/
@Service
@Slf4j
public class AttServiceImpl implements AttService {
// @Value("${att.upload.docBase}")
// private String ftpPath;
// @Value("${att.upload.path}")
// private String downLoad;
//
// @Value("${web.upload.path}")
// private String fileRootPath;
@Resource
private AttachmentInfoMapper infoMapper;
/**
* 下载ftp上文件到本地
*@param newFileName 新文件名
*@param fileName 原文件(路径+文件名)
*@param downUrl 下载路径
*@return
*/
@Override
public ApiResponse downloadFile(String newFileName, String fileName, String downUrl) {
log.info("下载文件参数newFileName:{}fileName:{}downUrl:",newFileName,fileName,downUrl);
OutputStream os=null;
String lastPath="";
File localFile = new File(downUrl + "/" + newFileName);
if (!localFile.getParentFile().exists()){//文件夹目录不存在创建目录
localFile.getParentFile().mkdirs();
//存放图片的路径地址
StringBuilder sb = new StringBuilder("").append("/");
String path = sb.toString();
lastPath=path;
try {
localFile.createNewFile();
os = new FileOutputStream(localFile);
FtpUtil fileFtp = new FtpUtil();
log.info("通过ftp下载文件参数lastPath:{}ileName:{}downUrl:",lastPath,fileName,downUrl);
fileFtp.downloadFile(lastPath,fileName,downUrl);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT);
}
/**
* 上传文件到ftp
* @param files
* @return
*/
@Override
public ApiResponse uploadToFtp(MultipartFile[] files, String description, Long userId) {
log.info("-----uploadByFtp-----MultipartFile files长度--------"+files.length);
if(files==null){
return new ApiResponse(ApiResponse.FAIL,MessageEnum.FAIL_PARAM.getRemarks());
}else{
List<AttachmentInfoDto> attachList=new ArrayList<>();
String lastPath="";
LinkedList<String> newNameList = new LinkedList<String>();
LinkedList<InputStream> fileList = new LinkedList<InputStream>();
for (MultipartFile file : files) {
AttachmentInfoDto attachVo=new AttachmentInfoDto();
//获取上传的附件原名包括后缀
String realFileName=file.getOriginalFilename();
attachVo.setFileName(realFileName);
//获取后缀名,如.jpg.png
log.info("--------源文件名开始 realFileName--------"+realFileName);
String suffixes = realFileName.substring(realFileName.lastIndexOf("."));
List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
if (!extList.contains(suffixes)) {
return new ApiResponse(ApiResponse.FAIL, MessageEnum.FILE_PICTURE.getRemarks());
}
//重新命名包括后缀名
String newName = StringUtil.getRandomOrderNumber() + "_" + StringUtil.getRandomOrderNumberString() + suffixes;
// String newName= UUID.randomUUID().toString().replaceAll("\\-", "")+suffixes;
newNameList.add(newName);
try {
fileList.add(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
//存放图片的路径地址
StringBuilder sb = new StringBuilder("").append("/");
String path = sb.toString();
lastPath=path;
// fileFtp.uploadFile(path,newName,file.getInputStream());
//文件服务器地址**********************************************
String filePath=path+newName;
//赋值附件数据存储的信息**********************************************
attachVo.setCreateDate(new Date());
attachVo.setCreateUser(userId);
attachVo.setUpdateDate(new Date());
attachVo.setUpdateUser(userId);
attachVo.setDelFlag(CommonEnum.USED.getCode());
attachVo.setDescription(description);
attachVo.setFilePath(filePath);
attachVo.setFileUrl(""+"/"+newName);
attachList.add(attachVo);
}
//ftp上传
try {
FtpUtil fileFtp = new FtpUtil();
fileFtp.uploadArrFile(lastPath,newNameList,fileList);
} catch (Exception e) {
log.error("服务器上传附件异常----------",e);
e.printStackTrace();
}
//相关数据存储到数据库里
AttachmentInfoListDto infoListDto=new AttachmentInfoListDto();
infoListDto.setAttachmentInfoDtoList(attachList);
ApiResponse apiResponse = uploadByFtp(infoListDto);
return apiResponse;
}
}
@Override
public ApiResponse uploadByFtp(AttachmentInfoListDto attachmentInfoListDto) {
if (attachmentInfoListDto == null || attachmentInfoListDto.getAttachmentInfoDtoList()==null
||attachmentInfoListDto.getAttachmentInfoDtoList().size()<=0) {
return new ApiResponse(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks(), null);
}
List<EshopAttachmentInfoVo> infoVoList = new ArrayList<EshopAttachmentInfoVo>();
List<AttachmentInfoDto> attList=attachmentInfoListDto.getAttachmentInfoDtoList();
for (AttachmentInfoDto infoDto : attList) {
AttachmentInfoPO attachmentInfoPO = BeanTransferUtils.transfer(infoDto, AttachmentInfoPO.class);
attachmentInfoPO.setId(SnowFlakeUtil.nextId());
int add = infoMapper.insert(attachmentInfoPO);
if (add > 0) {
EshopAttachmentInfoVo addVo = new EshopAttachmentInfoVo();
addVo.setId(attachmentInfoPO.getId()+"");
addVo.setFileName(attachmentInfoPO.getFileName());
addVo.setFileUrl(attachmentInfoPO.getFileUrl());
infoVoList.add(addVo);
}
}
log.info("文件业务数据存储完毕 {}", System.currentTimeMillis());
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT, infoVoList);
}
}
package org.nafmii.admin.att.service.impl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.admin.att.dto.ImportExcelDto;
import org.nafmii.admin.att.service.ImportExcelService;
import org.nafmii.admin.att.dao.ImportExcelMapper;
import org.nafmii.admin.att.utils.NoModelDataListener;
import org.nafmii.admin.att.vo.ExcelVo;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* <p>
* 中心端批量导入Excel
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Slf4j
@Service
public class ImportExcelServiceImpl implements ImportExcelService {
@Resource
private ImportExcelMapper importExcelMapper;
@Autowired
HttpServletResponse response;
/**
* 导出
* @param
* @return
*/
@Override
public ApiResponse exportExcel() {
ArrayList<ExcelVo> objects = new ArrayList<>();
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileProductName = URLEncoder.encode("店铺运营售后处理导出数据", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileProductName + ".xlsx");
EasyExcel.write(response.getOutputStream(), ExcelVo.class).sheet("导出").doWrite(objects);
} catch (IOException e) {
e.printStackTrace();
}
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT,objects);
}
/**
* 导入
* @param file
* @return
* @throws IOException
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ApiResponse importExcel(MultipartFile file) throws IOException {
List<Map<Integer,String>>list =EasyExcel.read(file.getInputStream(),new NoModelDataListener())
.extraRead(CellExtraTypeEnum.MERGE)
.ignoreEmptyRow(true)
.autoTrim(true)
.headRowNumber(1)
.sheet(0)
.doReadSync();
log.info("导入后生成的数据源=============>"+list);
if (!list.isEmpty()) {
for (Map<Integer,String> data : list) {
ImportExcelDto excelDto = new ImportExcelDto();
if (data.size()!=3){
return new ApiResponse(ApiResponse.FAIL, MessageEnum.EXCEL_ERROR.getRemarks());
}
excelDto.setColumn1(data.get(0));
excelDto.setColumn2(data.get(1));
excelDto.setColumn3(data.get(2));
log.info("导入处理后生成的数据源=============>"+excelDto);
importExcelMapper.insertExcelData(excelDto);
}
}
return new ApiResponse(ApiResponse.SUCCESS, ApiResponse.SUCCESS_TEXT);
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.admin.att.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellExtra;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/8 11:23
* @ClassName:
* @version:
* @remark:
*/
@Slf4j
public class NoModelDataListener extends AnalysisEventListener<Map<Integer, String>> {
/**
* 所有列到字段名的映射
* */
private Map<Integer,String> index2FieldMap ;
/**
* 解析出的数据
*/
private LinkedHashMap<Integer,Map<Integer, String>> row2DataMap = new LinkedHashMap<>();
/**
* 合并单元格
*/
private List<CellExtra> extraMergeInfoList = new ArrayList<>();
public NoModelDataListener(){}
public NoModelDataListener(Map<Integer,String> index2FieldMap){
this.index2FieldMap = index2FieldMap ;
}
@Override
public void invoke(Map<Integer, String> rowData, AnalysisContext analysisContext) {
//读取到的每行数据,其key是以0开始的索引
row2DataMap.put(analysisContext.readRowHolder().getRowIndex(),rowData) ;
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//所有行都解析完成
this.explainMergeData(row2DataMap, extraMergeInfoList) ;
}
/**
* 某行的数据解析失败
* */
@Override
public void onException(Exception exception, AnalysisContext context) {
log.info("解析失败,但是继续解析下一行: " + exception.getMessage());
// 如果是某一个单元格的转换异常 能获取到具体行号
if (exception instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException)exception;
log.info("第{}行,第{}列解析异常" + excelDataConvertException.getRowIndex() +
excelDataConvertException.getColumnIndex());
}
}
@Override
public void extra(CellExtra extra, AnalysisContext context) {
switch (extra.getType()){
case MERGE:{
extraMergeInfoList.add(extra);
break;
}
case HYPERLINK:{
break;
}
case COMMENT:{
}
default: {
}
}
}
/**
* 处理合并单元格
* @param data 解析数据
* @param extraMergeInfoList 合并单元格信息
* @return 填充好的解析数据
*/
private void explainMergeData(Map<Integer,Map<Integer, String>> data, List<CellExtra> extraMergeInfoList) {
//循环所有合并单元格信息
extraMergeInfoList.forEach(cellExtra -> {
int firstRowIndex = cellExtra.getFirstRowIndex();
int lastRowIndex = cellExtra.getLastRowIndex();
int firstColumnIndex = cellExtra.getFirstColumnIndex();
int lastColumnIndex = cellExtra.getLastColumnIndex();
Map<Integer,String> rdata = data.get(cellExtra.getRowIndex()) ;
String val = null ;
if(rdata != null){
val = rdata.get(cellExtra.getColumnIndex()) ;
}
//遍历每行
Map<Integer, String> rowData = null ;
for(int i=firstRowIndex;i<=lastRowIndex;i++){
rowData = data.get(i) ;
if(rowData == null){
continue;
}
for(int c = firstColumnIndex;c<=lastColumnIndex;c++){
rowData.put(c,val) ;
}
}
});
}
}
package org.nafmii.admin.att.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
* EshopAttachmentInfoVo对象.对应实体描述:公用附件表
*
*
*/
@Data
@ApiModel("EshopAttachmentInfoVo对象")
public class EshopAttachmentInfoVo implements Serializable {
private static final long serialVersionUID = 1L;
/** 对应字段:id,备注:附件id */
@ApiModelProperty("附件id")
private String id;
/** 对应字段:file_name,备注:源文件名称 */
@ApiModelProperty("源文件名称")
private String fileName;
/** 对应字段:file_url,备注:相对url */
@ApiModelProperty("相对url")
private String fileUrl;
/** 对应字段:file_path,备注:文件存储相对目录 */
@ApiModelProperty("文件存储相对目录")
private String filePath;
/** 对应字段:description,备注:描述 */
@ApiModelProperty("描述")
private String description;
/** 对应字段:del_flag,备注:软删除字段0未删除1已删除 */
@ApiModelProperty("软删除字段0未删除1已删除")
private Integer delFlag;
/** 对应字段:create_id,备注:创建人 */
@ApiModelProperty("创建人")
private Long createUser;
/** 对应字段:create_date,备注:创建时间 */
@ApiModelProperty("创建时间")
private Date createDate;
/** 对应字段:update_id,备注:修改时间 */
@ApiModelProperty("修改人")
private Long updateUser;
/** 对应字段:update_date,备注:修改时间 */
@ApiModelProperty("修改时间")
private Date updateDate;
/**
* 对应字段:page,备注:页码
*/
@ApiModelProperty("页码")
private int page;
/**
* 对应字段:limit,备注:每页数量
*/
@ApiModelProperty("每页数量")
private int limit;
}
package org.nafmii.admin.att.vo;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/10 13:44
* @ClassName:
* @version:
* @remark:
*/
@ApiModel("ExcelVo")
@ColumnWidth(18)
@Data
public class ExcelVo {
@ExcelProperty(value = "id",index = 0)
@ApiModelProperty("id")
private Long id;
@ExcelProperty(value = "退款交易流水号",index = 1)
@ApiModelProperty("名称")
private String name;
@ExcelProperty(value = "性别",index = 2)
@ApiModelProperty("性别")
private String sex;
@ExcelProperty(value = "电话号",index = 3)
@ApiModelProperty("电话号")
private String phone;
}
package org.nafmii.swagger; package org.nafmii.admin.swagger;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/** /**
* 用于在swagger-ui.html上展示所有Api接口 * 用于在swagger-ui.html上展示所有Api接口
...@@ -22,20 +29,27 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; ...@@ -22,20 +29,27 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
public class SwaggerConfig { public class SwaggerConfig {
@Bean @Bean
public Docket adminApi() { public Docket adminApi() {
// String basePackage = ADMIN_SWAGGER;// 要暴露的API接口的基础包名 ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
ticketPar.name("Authorization").description("Authorization")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build(); //header中的ticket参数非必填,传空也可以
pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置什么参数
return new Docket (DocumentationType.SWAGGER_2) return new Docket (DocumentationType.SWAGGER_2)
.select () .apiInfo(apiInfo())
.apis (RequestHandlerSelectors.basePackage ("org.nafmii")) .select()
.paths (PathSelectors.any ()) .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build () .paths(PathSelectors.any())
.apiInfo (apiInfo ()) .build().globalOperationParameters(pars)
.useDefaultResponseMessages (false); .useDefaultResponseMessages(false)
.enableUrlTemplating(false);
} }
private static ApiInfo apiInfo() { private static ApiInfo apiInfo() {
return new ApiInfoBuilder () return new ApiInfoBuilder ()
.title ("NAFMIIapp应用层接口说明") .title ("NAFMIIweb应用层接口说明")
.description ("NAFMIIapp应用层接口说明") .description ("NAFMIIweb应用层接口说明")
.version ("1.0") .version ("1.0")
.build (); .build ();
} }
......
package org.nafmii.admin.user.controller;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.admin.user.param.EditMenuParam;
import org.nafmii.admin.user.param.QueryMenusParam;
import org.nafmii.admin.user.service.ICenterMenuService;
import org.nafmii.admin.user.vo.CenterMenuVO;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.param.PageResult;
import org.nafmii.common.response.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 中心端菜单表 前端控制器
* </p>
*
* @author suncq
* @since 2021-04-28
*/
@RestController
@RequestMapping("/nafmii/admin/menu")
@Api(tags = "3.0.0", description = "中心端菜单接口")
public class CenterMenuController {
@Resource
private ICenterMenuService centerMenuService;
@ApiOperation( value = "中心端新增修改菜单",notes = "中心端新增修改菜单")
@PostMapping("/edit")
@ResponseBody
public ApiResponse editMenus (@RequestBody @Validated EditMenuParam param){
ApiResponse result = centerMenuService.editMenu(param);
return result;
}
@ApiOperation( value = "中心端菜单列表查询",notes = "中心端菜单列表查询")
@PostMapping("/queryMenuList")
@ResponseBody
public ApiResponse<List<CenterMenuVO>> queryMenuList (@RequestBody @Validated QueryMenusParam param){
PageHelper.startPage(param.getPageNum(),param.getPageSize());
PageResult<CenterMenuVO> result =
BeanTransferUtils.toPagedResult(centerMenuService.queryMenuList(param), CenterMenuVO.class);
return new ApiResponse(result);
}
@ApiOperation( value = "中心端菜单删除",notes = "中心端菜单删除")
@PostMapping("/delete")
@ResponseBody
public ApiResponse deleteMenus(@RequestParam Long[] ids){
ApiResponse result = centerMenuService.deleteMenus(ids);
return result;
}
@ApiOperation( value = "中心端用户对应菜单查询",notes = "中心端用户对应菜单查询")
@PostMapping("/queryUserMenus")
@ResponseBody
public ApiResponse queryUserMenus (){
ApiResponse result = centerMenuService.queryUserMenus();
return result;
}
}
package org.nafmii.admin.user.controller;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.admin.user.dto.CenterRoleDto;
import org.nafmii.admin.user.param.QueryRolesParam;
import org.nafmii.admin.user.service.ICenterRoleService;
import org.nafmii.admin.user.vo.CenterRoleVO;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.param.PageResult;
import org.nafmii.common.response.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 中心端角色表 前端控制器
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@RestController
@RequestMapping("/nafmii/admin/role")
@Api(tags = "3.0.0", description = "中心端角色接口")
public class CenterRoleController {
@Resource
private ICenterRoleService centerRoleService;
@ApiOperation( value = "中心端角色新增修改",notes = "中心端角色新增修改")
@PostMapping("/edit")
@ResponseBody
public ApiResponse editRoles (@Validated @RequestBody CenterRoleDto centerRoleDto){
ApiResponse result = centerRoleService.editRoles(centerRoleDto);
return result;
}
@ApiOperation( value = "中心端角色列表查询",notes = "中心端角色列表查询")
@PostMapping("/queryRolesList")
@ResponseBody
public ApiResponse<List<CenterRoleVO>> queryRolesList (@RequestBody @Validated QueryRolesParam param){
PageHelper.startPage(param.getPageNum(),param.getPageSize());
PageResult<CenterRoleVO> result =
BeanTransferUtils.toPagedResult(centerRoleService.queryRolesList(param),CenterRoleVO.class);
return new ApiResponse(result);
}
@ApiOperation( value = "中心端角色删除",notes = "中心端角色删除")
@PostMapping("/delete")
@ResponseBody
public ApiResponse deleteRoles(@RequestParam Long[] ids){
ApiResponse result = centerRoleService.deleteRoles(ids);
return result;
}
@ApiOperation( value = "中心端用户对应角色查询",notes = "中心端用户对应角色查询")
@PostMapping("/queryUserRole")
@ResponseBody
public ApiResponse queryRolesByUser (){
ApiResponse result = centerRoleService.queryRolesByUser();
return result;
}
}
package org.nafmii.admin.user.controller;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.admin.user.param.LoginParam;
import org.nafmii.admin.user.param.QueryUsersParam;
import org.nafmii.admin.user.service.ICenterUserService;
import org.nafmii.admin.user.vo.CenterUserVO;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.param.PageResult;
import org.nafmii.common.response.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 中心端-用户表 前端控制器
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@RestController
@RequestMapping("/nafmii/admin/user")
@Api(tags = "3.0.0", description = "中心端用户接口")
public class CenterUserController {
@Resource
private ICenterUserService centerUserService;
@ApiOperation( value = "中心端用户登陆",notes = "中心端用户登陆")
@PostMapping("/login")
@ResponseBody
public ApiResponse<CenterUserVO> login (@Validated @RequestBody LoginParam param){
ApiResponse<CenterUserVO> login = centerUserService.userLogin(param);
return login;
}
@ApiOperation( value = "中心端用户列表",notes = "中心端用户列表")
@PostMapping("/queryUserList")
@ResponseBody
public ApiResponse<List<CenterUserVO>> queryUserList (@RequestBody @Validated QueryUsersParam param){
PageHelper.startPage(param.getPageNum(),param.getPageSize());
PageResult<CenterUserVO> result =
BeanTransferUtils.toPagedResult(centerUserService.queryUserList(param),CenterUserVO.class);
return new ApiResponse(result);
}
}
package org.nafmii.admin.user.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.nafmii.admin.user.dto.QueryMenusDto;
import org.nafmii.admin.user.entity.CenterMenuPO;
import org.nafmii.admin.user.vo.CenterMenuVO;
import java.util.List;
/**
* <p>
* 中心端菜单表 Mapper 接口
* </p>
*
* @author suncq
* @since 2021-04-28
*/
public interface CenterMenuMapper extends BaseMapper<CenterMenuPO> {
/**
* @author:suncq
* @Function:中心端菜单新增修改
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
int updateMenuById(CenterMenuPO centerMenuPO);
/**
* @author:suncq
* @Function:中心端菜单列表查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
List<CenterMenuVO> queryMenuList(QueryMenusDto dto);
/**
* @author:suncq
* @Function:中心端菜单删除
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
int deleteMenus(Long[] ids);
/**
* @author:suncq
* @Function:中心端用户对应菜单查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
List<CenterMenuVO> queryUserMenus(Long userid);
}
package org.nafmii.admin.user.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.nafmii.admin.user.dto.QueryRolesDto;
import org.nafmii.admin.user.entity.CenterRolePO;
import org.nafmii.admin.user.vo.CenterRoleVO;
import java.util.List;
/**
* <p>
* 中心端角色表 Mapper 接口
* </p>
*
* @author suncq
* @since 2021-04-27
*/
public interface CenterRoleMapper extends BaseMapper<CenterRolePO> {
/**
* @author:suncq
* @Function:中心端角色新增修改
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
int updateRoleById(CenterRolePO crp);
/**
* @author:suncq
* @Function:中心端角色列表查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
* @param dto
*/
List<CenterRoleVO> queryRolesList(QueryRolesDto dto);
/**
* @author:suncq
* @Function:中心端角色删除
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
int deleteRoles(Long[] ids);
/**
* @author:suncq
* @Function:中心端用户对应角色查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
List<CenterRoleVO> queryRolesByUser(Long userId);
}
package org.nafmii.admin.user.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.nafmii.admin.user.dto.QueryUsersDto;
import org.nafmii.admin.user.entity.CenterUserPO;
import org.nafmii.admin.user.vo.CenterUserVO;
import java.util.List;
/**
* <p>
* 中心端-用户表 Mapper 接口
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Mapper
public interface CenterUserMapper extends BaseMapper<CenterUserPO> {
/**
* @author:suncq
* @Function:中心端用户登陆
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
CenterUserVO selectUserByPhone(@Param("phone") String phone);
/**
* @author:suncq
* @Function:用户列表查询
* @date 2021/4/28
* @ClassName:
* @version:
* @remark:
*/
List<CenterUserVO> queryUserList(QueryUsersDto dto);
}
package org.nafmii.admin.user.dto;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
* 中心端菜单表
* </p>
*
* @author suncq
* @since 2021-04-28
*/
@Data
@ApiModel("中心端菜单参数对象")
public class CenterMenuDTO extends Model {
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "菜单名称")
private String menuName;
@ApiModelProperty(value = "菜单级别")
private Integer menuLevle;
@ApiModelProperty(value = "父级主键")
private Long parentId;
@ApiModelProperty(value = "排序字段")
private Integer orderSeq;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1 禁用")
private String isEnable;
@ApiModelProperty(value = "创建人")
private Long createUserId;
@ApiModelProperty(value = "修改人")
private Long updateUserId;
}
package org.nafmii.admin.user.dto;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* <p>
* 中心端角色表
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Data
@ApiModel("中心端新增修改角色参数对象")
public class CenterRoleDto extends Model {
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "角色名称")
@NotNull(message = "角色名称不能为空")
private String rName;
@ApiModelProperty(value = "启用禁用 0 启用 1禁用")
private String isEnable;
@ApiModelProperty(value = "创建人")
private Long createUserId;
@ApiModelProperty(value = "修改人")
private Long updateUserId;
}
package org.nafmii.admin.user.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:suncq
* @Function:TODO
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("app用户登陆参数对象")
public class LoginDto {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@NotNull(message = "登陆密码不能为空")
@ApiModelProperty("登陆密码")
private String loginPwd;
}
package org.nafmii.admin.user.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.common.param.PageQuery;
import java.time.LocalDate;
/**
* @author lvyp
* @date 2021/4/28
*/
@Data
@ApiModel(value = "菜单列表查询数据交互类型")
public class QueryMenusDto extends PageQuery {
@ApiModelProperty(value = "创建开始时间")
private LocalDate startCreateTime;
@ApiModelProperty(value = "创建结束时间")
private LocalDate endCreateTime;
}
package org.nafmii.admin.user.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.common.param.PageQuery;
import java.time.LocalDate;
/**
* @author suncq
* @date 2021/4/28
*/
@Data
@ApiModel(value = "角色列表查询数据交互类型")
public class QueryRolesDto extends PageQuery {
@ApiModelProperty(value = "创建开始时间")
private LocalDate StartCreateTime;
@ApiModelProperty(value = "创建结束时间")
private LocalDate endCreateTime;
}
package org.nafmii.admin.user.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.common.param.PageQuery;
import java.time.LocalDate;
/**
* @author lvyp
* @date 2021/4/28
*/
@Data
@ApiModel(value = "用户列表查询数据交互类型")
public class QueryUsersDto extends PageQuery {
@ApiModelProperty(value = "创建开始时间")
private LocalDate StartCreateTime;
@ApiModelProperty(value = "创建结束时间")
private LocalDate endCreateTime;
}
package org.nafmii.admin.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 中心端菜单表
* </p>
*
* @author suncq
* @since 2021-04-28
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("CENTER_MENU")
@ApiModel(value="CenterMenuPO对象", description="中心端菜单表")
public class CenterMenuPO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
@TableId("ID")
private Long id;
@ApiModelProperty(value = "菜单名称")
@TableField("MENU_NAME")
private String menuName;
@ApiModelProperty(value = "菜单级别")
@TableField("MENU_LEVLE")
private Integer menuLevle;
@ApiModelProperty(value = "父级主键")
@TableField("PARENT_ID")
private Long parentId;
@ApiModelProperty(value = "排序字段")
@TableField("ORDER_SEQ")
private Integer orderSeq;
@ApiModelProperty(value = "创建时间")
@TableField("CREATE_TIME")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1 禁用")
@TableField("IS_ENABLE")
private String isEnable;
@ApiModelProperty(value = "创建人")
@TableField("CREATE_USER_ID")
private Long createUserId;
@ApiModelProperty(value = "修改人")
@TableField("UPDATE_USER_ID")
private Long updateUserId;
}
package org.nafmii.admin.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 中心端角色表
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("CENTER_ROLE")
@ApiModel(value="CenterRolePO对象", description="中心端角色表")
public class CenterRolePO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
@TableId("ID")
private Long id;
@ApiModelProperty(value = "角色名称")
@TableField("R_NAME")
private String rName;
@ApiModelProperty(value = "创建时间")
@TableField("CREAT_TIME")
private LocalDateTime creatTime;
@ApiModelProperty(value = "更新时间")
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1禁用")
@TableField("IS_ENABLE")
private String isEnable;
@ApiModelProperty(value = "创建人")
@TableField("CREATE_USER_ID")
private Long createUserId;
@ApiModelProperty(value = "修改人")
@TableField("UPDATE_USER_ID")
private Long updateUserId;
}
package org.nafmii.admin.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 中心端-用户表
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("CENTER_USER")
@ApiModel(value="CenterUserPO对象", description="中心端-用户表")
public class CenterUserPO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
@TableId("ID")
private Long id;
@ApiModelProperty(value = "登录用户名")
@TableField("LOGIN_NAME")
private String loginName;
@ApiModelProperty(value = "登录密码")
@TableField("LOGIN_PWD")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
@TableField("CN_NAME")
private String cnName;
@ApiModelProperty(value = "英文姓名")
@TableField("EN_NAME")
private String enName;
@ApiModelProperty(value = "移动电话")
@TableField("PHONE")
private String phone;
@ApiModelProperty(value = "固定电话")
@TableField("TELPHONE")
private String telphone;
@ApiModelProperty(value = "0 男 1 女")
@TableField("SEX")
private String sex;
@ApiModelProperty(value = "邮箱地址")
@TableField("EMAIL")
private String email;
@ApiModelProperty(value = "创建人")
@TableField("CREATE_USER_ID")
private Long createUserId;
@ApiModelProperty(value = "修改人")
@TableField("UPDATE_USER_ID")
private Long updateUserId;
@ApiModelProperty(value = "创建时间")
@TableField("CREATE_TIME")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
@ApiModelProperty(value = "0 有效 1 无效")
@TableField("IS_ENABLE")
private String isEnable;
}
package org.nafmii.admin.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("IMPORT_EXCEL_TEST")
@ApiModel(value="导入ExcelPO对象", description="导入excel测试表")
public class ImportExcelPO extends Model {
private String column1;
private String column2;
private String column3;
}
package org.nafmii.admin.user.param;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
/**
* <p>
* 中心端菜单表
* </p>
*
* @author suncq
* @since 2021-04-28
*/
@Data
@ApiModel(value="菜单列表新增修改入参对象")
public class EditMenuParam extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "菜单名称")
@NotNull(message = "菜单名称不能为空")
private String menuName;
@ApiModelProperty(value = "菜单级别")
@NotNull(message = "菜单级别不能为空")
private Integer menuLevle;
@ApiModelProperty(value = "父级主键")
@NotNull(message = "父级主键不能为空")
private Long parentId;
@ApiModelProperty(value = "排序字段")
@NotNull(message = "排序字段不能为空")
private Integer orderSeq;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1 禁用")
@NotNull(message = "启用禁用不能为空")
private String isEnable;
@ApiModelProperty(value = "创建人")
private Long createUserId;
@ApiModelProperty(value = "修改人")
private Long updateUserId;
}
package org.nafmii.admin.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:suncq
* @Function:TODO
* @date 2021/4/28
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("中心端用户登陆参数对象")
public class LoginParam {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@ApiModelProperty("登陆密码")
@NotNull(message = "登陆密码不能为空")
private String loginPwd;
@NotNull(message = "登陆方式不能为空")
@ApiModelProperty("登陆方式0密码1验证码")
private String type;
}
package org.nafmii.admin.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.common.param.PageQuery;
import java.time.LocalDate;
/**
* @author suncq
* @date 2021/4/28
*/
@Data
@ApiModel(value="菜单列表查询入参对象")
public class QueryMenusParam extends PageQuery {
@ApiModelProperty(value = "创建开始时间 yyyy-MM-dd")
private LocalDate startCreateTime;
@ApiModelProperty(value = "创建结束时间 yyyy-MM-dd")
private LocalDate endCreateTime;
}
package org.nafmii.admin.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.common.param.PageQuery;
import java.time.LocalDate;
/**
* @author suncq
* @date 2021/4/28
*/
@Data
@ApiModel(value="角色列表查询入参对象")
public class QueryRolesParam extends PageQuery {
@ApiModelProperty(value = "创建开始时间 yyyy-MM-dd")
private LocalDate startCreateTime;
@ApiModelProperty(value = "创建结束时间 yyyy-MM-dd")
private LocalDate endCreateTime;
}
package org.nafmii.admin.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.nafmii.common.param.PageQuery;
import java.time.LocalDate;
/**
* @author lvyp
* @date 2021/4/28
*/
@Data
@ApiModel(value="用户列表查询入参对象")
public class QueryUsersParam extends PageQuery {
@ApiModelProperty(value = "创建开始时间 yyyy-MM-dd")
private LocalDate startCreateTime;
@ApiModelProperty(value = "创建结束时间 yyyy-MM-dd")
private LocalDate endCreateTime;
}
package org.nafmii.admin.user.service;
import org.nafmii.admin.user.param.EditMenuParam;
import org.nafmii.admin.user.param.QueryMenusParam;
import org.nafmii.admin.user.vo.CenterMenuVO;
import org.nafmii.common.response.ApiResponse;
import java.util.List;
/**
* <p>
* 中心端菜单表 服务类
* </p>
*
* @author suncq
* @since 2021-04-28
*/
public interface ICenterMenuService{
/**
* @author:suncq
* @Function:中心端菜单新增修改
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse editMenu(EditMenuParam param);
/**
* @author:suncq
* @Function:中心端菜单查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
List<CenterMenuVO> queryMenuList(QueryMenusParam param);
/**
* @author:suncq
* @Function:中心端菜单删除
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse deleteMenus(Long[] ids);
/**
* @author:suncq
* @Function:中心端用户对应菜单查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse queryUserMenus();
}
package org.nafmii.admin.user.service;
import org.nafmii.admin.user.dto.CenterRoleDto;
import org.nafmii.admin.user.param.QueryRolesParam;
import org.nafmii.admin.user.vo.CenterRoleVO;
import org.nafmii.common.response.ApiResponse;
import java.util.List;
/**
* <p>
* 中心端角色表 服务类
* </p>
*
* @author suncq
* @since 2021-04-27
*/
public interface ICenterRoleService{
/**
* @author:suncq
* @Function:中心端角色新增修改
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse editRoles(CenterRoleDto centerRoleDto);
/**
* @author:suncq
* @Function:中心端角色列表查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
List<CenterRoleVO> queryRolesList(QueryRolesParam param);
/**
* @author:suncq
* @Function:中心端角色删除
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse deleteRoles(Long[] ids);
/**
* @author:suncq
* @Function:中心端用户对应角色查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse queryRolesByUser();
}
package org.nafmii.admin.user.service;
import org.nafmii.admin.user.param.LoginParam;
import org.nafmii.admin.user.param.QueryUsersParam;
import org.nafmii.admin.user.vo.CenterUserVO;
import org.nafmii.common.response.ApiResponse;
import java.util.List;
/**
* <p>
* 中心端-用户表 服务类
* </p>
*
* @author suncq
* @since 2021-04-27
*/
public interface ICenterUserService {
/**
* @author:suncq
* @Function:中心端用户登陆
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
ApiResponse<CenterUserVO> userLogin(LoginParam param);
/**
* @author:suncq
* @Function:中心端用户列表查询
* @date 2021/4/27
* @ClassName:
* @version:
* @remark:
*/
List<CenterUserVO> queryUserList(QueryUsersParam param);
}
package org.nafmii.admin.user.service.impl;
import org.nafmii.admin.user.dao.CenterMenuMapper;
import org.nafmii.admin.user.dto.QueryMenusDto;
import org.nafmii.admin.user.entity.CenterMenuPO;
import org.nafmii.admin.user.param.EditMenuParam;
import org.nafmii.admin.user.param.QueryMenusParam;
import org.nafmii.admin.user.service.ICenterMenuService;
import org.nafmii.admin.user.vo.CenterMenuVO;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.RequestUtils;
import org.nafmii.common.utils.SnowFlakeUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* <p>
* 中心端菜单表 服务实现类
* </p>
*
* @author suncq
* @since 2021-04-28
*/
@Service
public class CenterMenuServiceImpl implements ICenterMenuService {
@Resource
private CenterMenuMapper centerMenuMapper;
/**
* 中心端菜单新增修改
* @param param
* @return
*/
@Override
public ApiResponse editMenu(EditMenuParam param) {
Long menuId = param.getId();
if(null == menuId){//新增
CenterMenuPO cmp = new CenterMenuPO();
cmp.setId(SnowFlakeUtil.nextId());
cmp.setMenuName(param.getMenuName());
cmp.setMenuLevle(param.getMenuLevle());
cmp.setOrderSeq(param.getOrderSeq());
cmp.setParentId(param.getParentId());
cmp.setIsEnable(param.getIsEnable());
cmp.setCreateUserId(RequestUtils.getUserId());
cmp.setUpdateUserId(RequestUtils.getUserId());
cmp.setCreateTime(LocalDateTime.now());
cmp.setUpdateTime(LocalDateTime.now());
int i = centerMenuMapper.insert(cmp);
if (i < 0){
return new ApiResponse(ApiResponse.FAIL,ApiResponse.FAIL_TEXT);
}else{
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT);
}
}else{//修改
CenterMenuPO cmp = new CenterMenuPO();
cmp.setId(param.getId());
cmp.setMenuName(param.getMenuName());
cmp.setMenuLevle(param.getMenuLevle());
cmp.setOrderSeq(param.getOrderSeq());
cmp.setParentId(param.getParentId());
cmp.setIsEnable(param.getIsEnable());
cmp.setUpdateUserId(param.getCreateUserId());
cmp.setUpdateTime(LocalDateTime.now());
int i = centerMenuMapper.updateMenuById(cmp);
if (i < 0){
return new ApiResponse(ApiResponse.FAIL,ApiResponse.FAIL_TEXT);
}else{
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT);
}
}
}
/**
* 中心端菜单查询
* @param
* @return
*/
@Override
public List<CenterMenuVO> queryMenuList(QueryMenusParam param) {
QueryMenusDto dto = BeanTransferUtils.transfer(param, QueryMenusDto.class);
return centerMenuMapper.queryMenuList(dto);
}
/**
* 中心端菜单删除
* @param
* @return
*/
@Override
public ApiResponse deleteMenus(Long[] ids) {
int result = centerMenuMapper.deleteMenus(ids);
if (result < 0){
return new ApiResponse(ApiResponse.FAIL,ApiResponse.FAIL_TEXT);
}else{
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT);
}
}
/**
* 中心端用户对应菜单查询
* @param
* @return
*/
@Override
public ApiResponse queryUserMenus() {
Long userid = RequestUtils.getUserId();
List<CenterMenuVO> result = centerMenuMapper.queryUserMenus(userid);
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT,result);
}
}
package org.nafmii.admin.user.service.impl;
import org.nafmii.admin.user.dao.CenterRoleMapper;
import org.nafmii.admin.user.dto.CenterRoleDto;
import org.nafmii.admin.user.dto.QueryRolesDto;
import org.nafmii.admin.user.entity.CenterRolePO;
import org.nafmii.admin.user.param.QueryRolesParam;
import org.nafmii.admin.user.service.ICenterRoleService;
import org.nafmii.admin.user.vo.CenterRoleVO;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.RequestUtils;
import org.nafmii.common.utils.SnowFlakeUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
/**
* <p>
* 中心端角色表 服务实现类
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Service
public class CenterRoleServiceImpl implements ICenterRoleService {
@Resource
private CenterRoleMapper centerRoleMapper;
/**
* 中心端角色新增修改
* @param centerRoleDto
* @return
*/
@Override
public ApiResponse editRoles(CenterRoleDto centerRoleDto) {
Long roleId = centerRoleDto.getId();
if(null == roleId){//新增
CenterRolePO crp = new CenterRolePO();
crp.setId(SnowFlakeUtil.nextId());
crp.setRName(centerRoleDto.getRName());
crp.setCreateUserId(RequestUtils.getUserId());
crp.setCreatTime(LocalDateTime.now());
crp.setUpdateUserId(RequestUtils.getUserId());
crp.setUpdateTime(LocalDateTime.now());
crp.setIsEnable(centerRoleDto.getIsEnable());
int i = centerRoleMapper.insert(crp);
if (i<0){
return new ApiResponse(ApiResponse.FAIL,ApiResponse.FAIL_TEXT);
}else{
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT);
}
}else{//修改
CenterRolePO crp = new CenterRolePO();
crp.setId(centerRoleDto.getId());
crp.setRName(centerRoleDto.getRName());
crp.setUpdateUserId(RequestUtils.getUserId());
crp.setUpdateTime(LocalDateTime.now());
crp.setIsEnable(centerRoleDto.getIsEnable());
int i = centerRoleMapper.updateRoleById(crp);
if (i<0){
return new ApiResponse(ApiResponse.FAIL,ApiResponse.FAIL_TEXT);
}else{
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT);
}
}
}
/**
* 中心端角色列表查询
* @param
* @return
*/
@Override
public List<CenterRoleVO> queryRolesList(QueryRolesParam param) {
QueryRolesDto dto = BeanTransferUtils.transfer(param, QueryRolesDto.class);
List<CenterRoleVO> result = centerRoleMapper.queryRolesList(dto);
return result;
}
/**
* 中心端角色删除
* @param
* @return
*/
@Override
public ApiResponse deleteRoles(Long[] ids) {
int result = centerRoleMapper.deleteRoles(ids);
if (result<0) {
return new ApiResponse(ApiResponse.FAIL,ApiResponse.FAIL_TEXT);
}else{
return new ApiResponse(ApiResponse.SUCCESS, ApiResponse.SUCCESS_TEXT);
}
}
/**
* 中心端用户对应角色查询
* @param
* @return
*/
@Override
public ApiResponse queryRolesByUser() {
Long userId = RequestUtils.getUserId();
List<CenterRoleVO> result = centerRoleMapper.queryRolesByUser(userId);
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT,result);
}
}
package org.nafmii.admin.user.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.admin.user.dao.CenterUserMapper;
import org.nafmii.admin.user.dto.QueryUsersDto;
import org.nafmii.admin.user.param.LoginParam;
import org.nafmii.admin.user.param.QueryUsersParam;
import org.nafmii.admin.user.service.ICenterUserService;
import org.nafmii.admin.user.vo.CenterUserVO;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.response.ApiResponse;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 中心端-用户表 服务实现类
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Slf4j
@Service
public class CenterUserServiceImpl implements ICenterUserService {
@Resource
private CenterUserMapper centerUserMapper;
/**
* 中心端用户登陆
* @param param
* @return
*/
@Override
public ApiResponse<CenterUserVO> userLogin(LoginParam param) {
log.info("===============中心端用户登录请求参数======》{}",param);
CenterUserVO userVo = new CenterUserVO();
//账号密码登陆
String phone = param.getPhone();
userVo = centerUserMapper.selectUserByPhone(phone);
if (null == userVo){
return new ApiResponse(ApiResponse.FAIL,"该用户未注册,请先注册!");
}
if(!param.getLoginPwd().equals(userVo.getLoginPwd())){
return new ApiResponse(ApiResponse.FAIL,"用户名或密码错误!");
}
return new ApiResponse(ApiResponse.SUCCESS,ApiResponse.SUCCESS_TEXT,userVo);
}
@Override
public List<CenterUserVO> queryUserList(QueryUsersParam param) {
QueryUsersDto dto = BeanTransferUtils.transfer(param,QueryUsersDto.class);
return centerUserMapper.queryUserList(dto);
}
}
package org.nafmii.admin.user.vo;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
* 中心端菜单表
* </p>
*
* @author suncq
* @since 2021-04-28
*/
@Data
@ApiModel("菜单返回报文")
public class CenterMenuVO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "菜单名称")
private String menuName;
@ApiModelProperty(value = "菜单级别")
private Integer menuLevle;
@ApiModelProperty(value = "父级主键")
private Long parentId;
@ApiModelProperty(value = "排序字段")
private Integer orderSeq;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1 禁用")
private String isEnable;
@ApiModelProperty(value = "创建人")
private Long createUserId;
@ApiModelProperty(value = "修改人")
private Long updateUserId;
}
package org.nafmii.admin.user.vo;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
* 中心端角色表
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Data
@ApiModel("角色返回报文")
public class CenterRoleVO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "角色名称")
private String rName;
@ApiModelProperty(value = "创建时间")
private LocalDateTime creatTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "启用禁用 0 启用 1禁用")
private String isEnable;
@ApiModelProperty(value = "创建人")
private Long createUserId;
@ApiModelProperty(value = "修改人")
private Long updateUserId;
}
package org.nafmii.admin.user.vo;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
* 中心端-用户表
* </p>
*
* @author suncq
* @since 2021-04-27
*/
@Data
@ApiModel("用户返回报文")
public class CenterUserVO extends Model {
private static final long serialVersionUID=1L;
@ApiModelProperty(value = "主键")
private Long id;
@ApiModelProperty(value = "登录用户名")
private String loginName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String cnName;
@ApiModelProperty(value = "英文姓名")
private String enName;
@ApiModelProperty(value = "移动电话")
private String phone;
@ApiModelProperty(value = "固定电话")
private String telphone;
@ApiModelProperty(value = "0 男 1 女")
private String sex;
@ApiModelProperty(value = "邮箱地址")
private String email;
@ApiModelProperty(value = "创建人")
private Long createUserId;
@ApiModelProperty(value = "修改人")
private Long updateUserId;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "0 有效 1 无效")
private String isEnable;
}
package org.nafmii.nafmiiadmin.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.nafmiiadmin.po.TStudent;
import org.nafmii.nafmiiadmin.service.TestService;
import org.nafmii.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/20 15:46
* @ClassName:
* @version:
* @remark:
*/
@RestController
@RequestMapping("web/nafmii/test/")
@Api(tags = "1.0.0", description = "测试")
public class TestController {
@Autowired
private TestService service;
@ApiOperation( value = "测试",notes = "测试")
@GetMapping("search")
public Result<List<TStudent>> search(){
Result<List<TStudent>> test = service.searchAll();
return test;
}
}
package org.nafmii.nafmiiadmin.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.nafmii.nafmiiadmin.po.TStudent;
import org.nafmii.nafmiiadmin.po.TStudentExample;
import java.util.List;
@Mapper
public interface TStudentMapper {
long countByExample(TStudentExample example);
int deleteByExample(TStudentExample example);
int deleteByPrimaryKey(Integer id);
int insert(TStudent record);
int insertSelective(TStudent record);
List<TStudent> selectByExample(TStudentExample example);
TStudent selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") TStudent record, @Param("example") TStudentExample example);
int updateByExample(@Param("record") TStudent record, @Param("example") TStudentExample example);
int updateByPrimaryKeySelective(TStudent record);
int updateByPrimaryKey(TStudent record);
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiiadmin.po;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class TStudent implements Serializable {
@ApiModelProperty(value = "id")
private Integer id;
private String name;
private Short sex;
private Date createTime;
private Date updateTime;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Short getSex() {
return sex;
}
public void setSex(Short sex) {
this.sex = sex;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", sex=").append(sex);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiiadmin.po;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TStudentExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public TStudentExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andSexIsNull() {
addCriterion("sex is null");
return (Criteria) this;
}
public Criteria andSexIsNotNull() {
addCriterion("sex is not null");
return (Criteria) this;
}
public Criteria andSexEqualTo(Short value) {
addCriterion("sex =", value, "sex");
return (Criteria) this;
}
public Criteria andSexNotEqualTo(Short value) {
addCriterion("sex <>", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThan(Short value) {
addCriterion("sex >", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThanOrEqualTo(Short value) {
addCriterion("sex >=", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThan(Short value) {
addCriterion("sex <", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThanOrEqualTo(Short value) {
addCriterion("sex <=", value, "sex");
return (Criteria) this;
}
public Criteria andSexIn(List<Short> values) {
addCriterion("sex in", values, "sex");
return (Criteria) this;
}
public Criteria andSexNotIn(List<Short> values) {
addCriterion("sex not in", values, "sex");
return (Criteria) this;
}
public Criteria andSexBetween(Short value1, Short value2) {
addCriterion("sex between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andSexNotBetween(Short value1, Short value2) {
addCriterion("sex not between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiiadmin.service.impl;
import org.nafmii.nafmiiadmin.mapper.TStudentMapper;
import org.nafmii.nafmiiadmin.po.TStudent;
import org.nafmii.nafmiiadmin.po.TStudentExample;
import org.nafmii.nafmiiadmin.service.TestService;
import org.nafmii.result.Result;
import org.nafmii.result.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/22 8:58
* @ClassName:
* @version:
* @remark:
*/
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TStudentMapper studentMapper;
@Override
public Result<List<TStudent>> searchAll() {
Result result = new Result();
TStudentExample studentExample = new TStudentExample();
List<TStudent> tStudents = studentMapper.selectByExample(studentExample);
result.setData(tStudents);
result.setCode(ResultCode.SUCCESS.getCode());
result.setMessage(ResultCode.SUCCESS.getMessage());
return result;
}
}
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:20000/eureka
instance:
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true
statusPageUrl: http://127.0.0.1:21000/swagger-ui.html
logging:
config: classpath:logback-spring.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
zipkin:
base-url: http://localhost:9411
enabled: true
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.admin
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:20000/eureka
instance:
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true
statusPageUrl: http://127.0.0.1:21000/swagger-ui.html
logging:
config: classpath:logback-spring.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.admin
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:20000/eureka
instance:
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true
statusPageUrl: http://127.0.0.1:21000/swagger-ui.html
logging:
config: classpath:logback-spring.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.admin
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
server.port=8001
spring.application.name=nafmii-admin
logging.level.root=info
logging.file.path=d:/data/logs/nafmii-admin/
logging.file.max-history=15
logging.file.max-size=300MB
logging.pattern.dateformat=yyyy-MM-dd hh:MM:ss
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.instance.statusPageUrl = http://127.0.0.1:8001/swagger-ui.html
eureka.instance.prefer-ip-address = true
eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port}
spring.datasource.url=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.password=123456
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
\ No newline at end of file \ No newline at end of file
server:
port: 21000
tomcat:
uri-encoding: UTF-8
spring:
profiles:
active: @env@
application:
name: nafmii-admin
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration monitorInterval="5">
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!-- <springProperty scope="context" name="logPath" source="logging.file.path"/>-->
<springProperty scope="context" name="logPath" source="logging.file.path"/>
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<!--变量配置-->
<Properties>
<!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
<!-- %logger{36} 表示 Logger 名字最长36个字符 -->
<property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
<!-- 定义日志存储的路径 -->
<property name="FILE_PATH" value="${logPath:-logs}/${springAppName}" />
<property name="FILE_NAME" value="${springAppName}" />
</Properties>
<appenders>
<console name="Console" target="SYSTEM_OUT">
<!--输出日志的格式-->
<PatternLayout pattern="${LOG_PATTERN}"/>
<!--控制台只输出level及其以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,适合临时测试用-->
<File name="Filelog" fileName="${FILE_PATH}/test.log" append="false">
<PatternLayout pattern="${LOG_PATTERN}"/>
</File>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
<!-- 这个会打印出所有的warn及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
<!-- 这个会打印出所有的error及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
</appenders>
<!--Logger节点用来单独指定日志的形式,比如要为指定包下的class指定不同的日志级别等。-->
<!--然后定义loggers,只有定义了logger并引入的appender,appender才会生效-->
<loggers>
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<logger name="org.mybatis" level="info" additivity="false">
<AppenderRef ref="Console"/>
</logger>
<!--监控系统信息-->
<!--若是additivity设为false,则 子Logger 只会在自己的appender里输出,而不会在 父Logger 的appender里输出。-->
<Logger name="org.springframework" level="info" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<root level="info">
<appender-ref ref="Console"/>
<appender-ref ref="Filelog"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileWarn"/>
<appender-ref ref="RollingFileError"/>
</root>
</loggers>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.admin.dao.AttachmentInfoMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.admin.att.entity.AttachmentInfoPO">
<id column="ID" property="id" />
<result column="FILE_NAME" property="fileName" />
<result column="FILE_URL" property="fileUrl" />
<result column="FILE_PATH" property="filePath" />
<result column="DESCRIPTION" property="description" />
<result column="IS_ENABLE" property="isEnable" />
<result column="CREATE_USER_ID" property="createUserId" />
<result column="UPDATE_USER_ID" property="updateUserId" />
<result column="CREATE_TIME" property="createTime" />
<result column="UPDATE_TIME" property="updateTime" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ID, FILE_NAME, FILE_URL, FILE_PATH, DESCRIPTION, IS_ENABLE, CREATE_USER_ID, UPDATE_USER_ID, CREATE_TIME, UPDATE_TIME
</sql>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.admin.att.dao.BusinessAttachmentInfoMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.admin.att.entity.BusinessAttachmentInfoPO">
<id column="ID" property="id" />
<result column="BUSINESS" property="business" />
<result column="BUSINESS_ID" property="businessId" />
<result column="ATTACHMENT_ID" property="attachmentId" />
<result column="CREATE_USER_ID" property="createUserId" />
<result column="UPDATE_USER_ID" property="updateUserId" />
<result column="CREATE_TIME" property="createTime" />
<result column="UPDATE_TIME" property="updateTime" />
<result column="SORT" property="sort" />
<result column="DESCRIPTION" property="description" />
<result column="IS_ENABLE" property="isEnable" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ID, BUSINESS, BUSINESS_ID, ATTACHMENT_ID, CREATE_USER_ID, UPDATE_USER_ID, CREATE_TIME, UPDATE_TIME, SORT, DESCRIPTION, IS_ENABLE
</sql>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.admin.user.dao.CenterMenuMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.admin.user.entity.CenterMenuPO">
<id column="ID" property="id" />
<result column="MENU_NAME" property="menuName" />
<result column="MENU_LEVLE" property="menuLevle" />
<result column="PARENT_ID" property="parentId" />
<result column="ORDER_SEQ" property="orderSeq" />
<result column="CREATE_TIME" property="createTime" />
<result column="UPDATE_TIME" property="updateTime" />
<result column="IS_ENABLE" property="isEnable" />
<result column="CREATE_USER_ID" property="createUserId" />
<result column="UPDATE_USER_ID" property="updateUserId" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ID, MENU_NAME, MENU_LEVLE, PARENT_ID, ORDER_SEQ, CREATE_TIME, UPDATE_TIME, IS_ENABLE, CREATE_USER_ID, UPDATE_USER_ID
</sql>
<!-- 新增修改中心端角色 -->
<update id="updateMenuById" parameterType="map" >
update CENTER_MENU
<set >
<if test="menuName != null" >
MENU_NAME = #{menuName,jdbcType=VARCHAR},
</if>
<if test="menuLevle != null" >
MENU_LEVLE = #{menuLevle,jdbcType=INTEGER},
</if>
<if test="parentId != null" >
PARENT_ID = #{parentId,jdbcType=BIGINT},
</if>
<if test="orderSeq != null" >
ORDER_SEQ = #{orderSeq,jdbcType=INTEGER},
</if>
<if test="createTime != null" >
CREATE_TIME = #{createTime,jdbcType=BIGINT},
</if>
<if test="updateTime != null" >
UPDATE_TIME = #{updateTime,jdbcType=BIGINT},
</if>
<if test="isEnable != null" >
IS_ENABLE = #{isEnable,jdbcType=VARCHAR},
</if>
<if test="createUserId != null" >
CREATE_USER_ID = #{createUserId,jdbcType=BIGINT},
</if>
<if test="updateUserId != null" >
UPDATE_USER_ID = #{updateUserId,jdbcType=BIGINT},
</if>
</set>
where ID = #{id,jdbcType=BIGINT}
</update>
<!-- 查询中心端菜单 -->
<select id="queryMenuList" parameterType="org.nafmii.admin.user.dto.CenterMenuDTO"
resultType="org.nafmii.admin.user.vo.CenterMenuVO">
select
ID as id, MENU_NAME as menuName, MENU_LEVLE as menuLevle, PARENT_ID as parentId, ORDER_SEQ as orderSeq,
CREATE_TIME as createTime, UPDATE_TIME as updateTime, IS_ENABLE as isEnable, CREATE_USER_ID as createUserId,
UPDATE_USER_ID as updateUserId
from CENTER_MENU
<where>
<if test="startCreateTime != null and endCreateTime != null">
DATE_FORMAT(CREATE_TIME,'%Y-%m-%d') BETWEEN #{startCreateTime} and #{endCreateTime}
</if>
</where>
</select>
<!-- 删除中心端菜单 -->
<update id="deleteMenus">
update
CENTER_MENU
set IS_ENABLE = "1"
where
ID IN
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
<!-- 中心端用户对应菜单查询 -->
<select id="queryUserMenus" parameterType="map" resultType="org.nafmii.admin.user.vo.CenterMenuVO">
SELECT
cm.ID as id, cm.MENU_NAME as menuName, cm.MENU_LEVLE as menuLevle, cm.PARENT_ID as parentId, cm.ORDER_SEQ as orderSeq,
cm.CREATE_TIME as createTime,cm.UPDATE_TIME as updateTime, cm.IS_ENABLE as isEnable, cm.CREATE_USER_ID as createUserId,
cm.UPDATE_USER_ID as updateUserId
FROM
CENTER_MENU cm
INNER JOIN CENTER_ROLE_MENU crm ON cm.id = crm.menu_id
INNER JOIN CENTER_USER_ROLE cur ON cur.role_id = crm.role_id
INNER JOIN CENTER_USER cu ON cur.user_id = cu.id
WHERE
cu.id = #{userid,jdbcType=BIGINT}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.admin.user.dao.CenterRoleMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.admin.user.entity.CenterRolePO">
<id column="ID" property="id" />
<result column="R_NAME" property="rName" />
<result column="CREAT_TIME" property="creatTime" />
<result column="UPDATE_TIME" property="updateTime" />
<result column="IS_ENABLE" property="isEnable" />
<result column="CREATE_USER_ID" property="createUserId" />
<result column="UPDATE_USER_ID" property="updateUserId" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ID, R_NAME, CREAT_TIME, UPDATE_TIME, IS_ENABLE, CREATE_USER_ID, UPDATE_USER_ID
</sql>
<!-- 修改中心端角色 -->
<update id="updateRoleById" parameterType="map" >
update CENTER_ROLE
<set >
<if test="rName != null" >
R_NAME = #{rName,jdbcType=VARCHAR},
</if>
<if test="updateTime != null" >
UPDATE_TIME = #{updateTime,jdbcType=DATE},
</if>
<if test="isEnable != null" >
IS_ENABLE = #{isEnable,jdbcType=VARCHAR},
</if>
<if test="updateUserId != null" >
UPDATE_USER_ID = #{updateUserId,jdbcType=BIGINT},
</if>
</set>
where ID = #{id,jdbcType=VARCHAR}
</update>
<!-- 查询中心端角色列表 -->
<select id="queryRolesList" parameterType="org.nafmii.admin.user.dto.QueryRolesDto"
resultType="org.nafmii.admin.user.vo.CenterRoleVO">
SELECT
ID as id, R_NAME as rName, CREAT_TIME as creatTime, UPDATE_TIME as updateTime, IS_ENABLE as isEnable,
CREATE_USER_ID as createUserId, UPDATE_USER_ID as updateUserId
FROM
CENTER_ROLE
<where>
<if test="startCreateTime != null and endCreateTime != null">
DATE_FORMAT(CREAT_TIME,'%Y-%m-%d') BETWEEN #{startCreateTime} and #{endCreateTime}
</if>
</where>
</select>
<!-- 删除中心端角色 -->
<update id="deleteRoles">
update
CENTER_ROLE
set IS_ENABLE = "1"
where ID IN
<foreach collection="array" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</update>
<!-- 中心端用户对应角色查询 -->
<select id="queryRolesByUser" parameterType="map" resultType="org.nafmii.admin.user.vo.CenterRoleVO">
SELECT
cr.ID as id,
cr.R_NAME as rName,
cr.CREAT_TIME as creatTime,
cr.UPDATE_TIME as updateTime,
cr.IS_ENABLE as isEnable,
cr.CREATE_USER_ID as createUserId,
cr.UPDATE_USER_ID as updateUserId
FROM
CENTER_ROLE cr
INNER JOIN CENTER_USER_ROLE cur ON cur.role_id = cr.id
INNER JOIN CENTER_USER cu ON cur.user_id = cu.id
WHERE
cu.id = #{userid,jdbcType=BIGINT}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.admin.user.dao.CenterUserMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.admin.user.entity.CenterUserPO">
<id column="ID" property="id" />
<result column="LOGIN_NAME" property="loginName" />
<result column="LOGIN_PWD" property="loginPwd" />
<result column="CN_NAME" property="cnName" />
<result column="EN_NAME" property="enName" />
<result column="PHONE" property="phone" />
<result column="TELPHONE" property="telphone" />
<result column="SEX" property="sex" />
<result column="EMAIL" property="email" />
<result column="CREATE_USER_ID" property="createUserId" />
<result column="UPDATE_USER_ID" property="updateUserId" />
<result column="CREATE_TIME" property="createTime" />
<result column="UPDATE_TIME" property="updateTime" />
<result column="IS_ENABLE" property="isEnable" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ID, LOGIN_NAME, LOGIN_PWD, CN_NAME, EN_NAME, PHONE, TELPHONE, SEX, EMAIL, CREATE_USER_ID, UPDATE_USER_ID, CREATE_TIME, UPDATE_TIME, IS_ENABLE
</sql>
<!-- 根据登录人账号(手机号)查询用户信息 -->
<select id="selectUserByPhone" parameterType="map" resultType="org.nafmii.admin.user.vo.CenterUserVO">
select
ID as id, LOGIN_NAME as loginName, LOGIN_PWD as loginPwd, CN_NAME as cnName, EN_NAME as enName, PHONE as phone,
TELPHONE as telphone, SEX as sex, EMAIL as email, CREATE_USER_ID as createUserId, UPDATE_USER_ID as updateUserId,
CREATE_TIME as createTime, UPDATE_TIME as updateTime, IS_ENABLE as isEnable
from CENTER_USER
where IS_ENABLE = 0
<if test="phone !=null">
and PHONE =#{phone}
</if>
</select>
<select id="queryUserList" parameterType="org.nafmii.admin.user.dto.QueryUsersDto"
resultType="org.nafmii.admin.user.vo.CenterUserVO">
SELECT
<include refid="Base_Column_List" />
FROM CENTER_USER CU
<where>
<if test="StartCreateTime != null and endCreateTime != null">
DATE_FORMAT(CU.CREATE_TIME,'%Y-%m-%d') BETWEEN #{StartCreateTime} and #{endCreateTime}
</if>
</where>
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.admin.att.dao.ImportExcelMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.admin.att.dto.ImportExcelDto">
<result column="COLUMN1" property="column1" />
<result column="COLUMN2" property="column2" />
<result column="COLUMN3" property="column3" />
</resultMap>
<insert id ="insertExcelData" parameterType="org.nafmii.admin.att.dto.ImportExcelDto" >
insert into IMPORT_EXCEL_TEST
(COLUMN1,COLUMN2,COLUMN3)
values(#{data.column1},
#{data.column2},
#{data.column3})
</insert >
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.nafmiimbg.mapper.TStudentMapper">
<resultMap id="BaseResultMap" type="org.nafmii.nafmiiadmin.po.TStudent">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="SMALLINT" property="sex" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, name, sex, create_time, update_time
</sql>
<select id="selectByExample" parameterType="org.nafmii.nafmiiadmin.po.TStudentExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from t_student
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_student
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from t_student
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="org.nafmii.nafmiiadmin.po.TStudentExample">
delete from t_student
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="org.nafmii.nafmiiadmin.po.TStudent">
insert into t_student (id, name, sex,
create_time, update_time)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=SMALLINT},
#{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="org.nafmii.nafmiiadmin.po.TStudent">
insert into t_student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=SMALLINT},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="org.nafmii.nafmiiadmin.po.TStudentExample" resultType="java.lang.Long">
select count(*) from t_student
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update t_student
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.name != null">
name = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.sex != null">
sex = #{record.sex,jdbcType=SMALLINT},
</if>
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=TIMESTAMP},
</if>
<if test="record.updateTime != null">
update_time = #{record.updateTime,jdbcType=TIMESTAMP},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update t_student
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
sex = #{record.sex,jdbcType=SMALLINT},
create_time = #{record.createTime,jdbcType=TIMESTAMP},
update_time = #{record.updateTime,jdbcType=TIMESTAMP}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="org.nafmii.nafmiiadmin.po.TStudent">
update t_student
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=SMALLINT},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="org.nafmii.nafmiiadmin.po.TStudent">
update t_student
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=SMALLINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiiadmin;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NafmiiAdminApplicationTests {
@Test
void contextLoads() {
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.nafmii</groupId>
<artifactId>nafmii-app</artifactId>
<version>0.0.1-SNAPSHOT</version><!-- lookup parent from repository -->
</parent>
<groupId>org.nafmii</groupId>
<artifactId>app-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app-client</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<httpClient.version>4.5.3</httpClient.version>
<fastjson.version>1.2.58</fastjson.version>
<ojdbc.version>10.2.0.4</ojdbc.version>
<jjwt.version>0.9.1</jjwt.version>
</properties>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>
package org.nafmii.app.client.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/26 16:41
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("app用户登陆参数对象")
public class LoginClientParam {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@ApiModelProperty("登陆密码")
private String loginPwd;
@ApiModelProperty("验证码")
private String code;
}
package org.nafmii.app.client.user.service;
import org.nafmii.app.client.user.param.LoginClientParam;
import org.nafmii.app.client.user.vo.UserClientVO;
import org.nafmii.common.response.ApiResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/11 13:42
* @ClassName:对外提供用户接口
* @version:1.0
* @remark:
*/
@FeignClient("nafmii-app")
@RequestMapping("/app/nafmii/user")
public interface UserClient {
@PostMapping("/userLogin")
@ResponseBody
ApiResponse<UserClientVO> userLogin (@RequestBody @Validated LoginClientParam loginClientParam);
@PostMapping("/phoneLogin")
@ResponseBody
ApiResponse<UserClientVO> phoneLogin (@RequestBody @Validated LoginClientParam loginClientParam);
}
package org.nafmii.app.client.user.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:22
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("用户返回报文")
public class UserClientVO {
private Long id;
@ApiModelProperty(value = "昵称")
private String userName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
private String phone;
@ApiModelProperty(value = "出生日期")
private String birthday;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "头像图片地址")
private String headPicture;
@ApiModelProperty(value = "国籍")
private String nationality;
@ApiModelProperty(value = "单位全称")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
private String isEnable;
@ApiModelProperty(value = "token")
private String authorization;
@ApiModelProperty(value = "验证码登陆判断是否第一次登陆 0是 1否")
private String loginType;
}
...@@ -13,132 +13,121 @@ ...@@ -13,132 +13,121 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>nafmii-app</name> <name>nafmii-app</name>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<description>Demo project for Spring Boot</description> <description>移动端应用服务</description>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
<!--区分环境打包-->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!--指定默认激活-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.nafmii</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <artifactId>nafmii-common</artifactId>
</dependency> <version>0.0.1-SNAPSHOT</version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!--MyBatis分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<!--feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mybatis.generator</groupId> <groupId>org.nafmii</groupId>
<artifactId>mybatis-generator-core</artifactId> <artifactId>app-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<exclusions><!-- 去掉springboot默认配置 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<!--SpringData工具包-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc14 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-sleuth -->
<!--集成logstash-->
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
</dependency>
<!--集成SpringBoot Admin监控-->
<dependency> <dependency>
<groupId>de.codecentric</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId> <artifactId>spring-cloud-starter-sleuth</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> </dependency>
<!--Knife4j API文档生产工具--> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-sleuth-zipkin -->
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId> <artifactId>spring-cloud-sleuth-zipkin</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId> <artifactId>spring-cloud-starter-zipkin</artifactId>
<version>2.2.4.RELEASE</version>
</dependency> </dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency> <dependency>
<groupId>org.nafmii</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>nafmii-common</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <configuration>
<excludes> <includeSystemScope>true</includeSystemScope>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration> </configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
<finalName>${project.artifactId}-${project.version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>application-dev.yml</exclude>
<exclude>application-test.yml</exclude>
<exclude>application-prod.yml</exclude>
</excludes>
</resource>
<!--需要动态添加的资源-->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<!--读取打包命令中指定的环境-->
<include>application-${env}.yml</include>
<include>application.yml</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>
package org.nafmii; package org.nafmii.app;
import org.mybatis.spring.annotation.MapperScan;
import org.nafmii.common.ftp.EnableFtpServer;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.EnableFeignClients;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @SpringBootApplication(scanBasePackages={"org.nafmii"})
@EnableEurekaClient @EnableEurekaClient
@EnableSwagger2
@EnableFeignClients @EnableFeignClients
@MapperScan("org.nafmii.app/**/dao")
@EnableFtpServer
public class NafmiiAppApplication { public class NafmiiAppApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
package org.nafmii.adminService; package org.nafmii.app.feign;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
......
package org.nafmii.app.feign.controller;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.app.client.user.service.UserClient;
import org.nafmii.app.feign.service.UserFeignService;
import org.nafmii.app.user.param.LoginParam;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.BeanTransferUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/11 14:12
* @ClassName:
* @version:
* @remark:
*/
@RestController
@RequestMapping("/app/nafmii/user/client")
@Api(tags = "2.0.4", description = "用户登陆对外提供【zjh】")
public class UserFeignController {
@Resource
private UserFeignService feignService;
@ApiOperation( value = "app用户登陆接口",notes = "app用户登陆接口")
@PostMapping("/userLogin")
@ResponseBody
public ApiResponse userLogin (@RequestBody JSONObject object){
ApiResponse userLogin = feignService.userLogin(object);
return userLogin;
}
@ApiOperation( value = "app手机号登陆接口",notes = "app手机号登陆接口")
@PostMapping("/phoneLogin")
@ResponseBody
public ApiResponse phoneLogin (@RequestBody JSONObject object){
ApiResponse phoneLogin = feignService.phoneLogin(object);
return phoneLogin;
}
}
package org.nafmii.nafmiiadmin.service; package org.nafmii.app.feign.service;
import org.nafmii.nafmiiadmin.po.TStudent; import com.alibaba.fastjson.JSONObject;
import org.nafmii.result.Result; import org.nafmii.common.response.ApiResponse;
import java.util.List;
/** /**
* @author:zhoujh * @author:zhoujh
* @Function:TODO * @Function:TODO
* @date 2021/4/22 8:57 * @date 2021/5/11 14:21
* @ClassName: * @ClassName:
* @version: * @version:
* @remark: * @remark:
*/ */
public interface TestService { public interface UserFeignService {
Result<List<TStudent>> searchAll(); //对外提供手机号登陆接口
ApiResponse phoneLogin(JSONObject object);
//对外提供用户登陆接口
ApiResponse userLogin(JSONObject object);
} }
package org.nafmii.app.feign.service.impl;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.app.client.user.param.LoginClientParam;
import org.nafmii.app.client.user.service.UserClient;
import org.nafmii.app.feign.service.UserFeignService;
import org.nafmii.app.feign.vo.UserFeignVO;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.BeanTransferUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/5/11 14:21
* @ClassName:
* @version:
* @remark:
*/
@Service
@Slf4j
public class UserFeignServiceImpl implements UserFeignService {
@Resource
private UserClient userClient;
/**
* 对外提供手机号登陆接口
* @param object
* @return
*/
@Override
public ApiResponse phoneLogin(JSONObject object) {
ApiResponse<UserFeignVO> apiResponse = new ApiResponse<>();
log.info("对外提供手机号登陆接口相关json参数========》{}",object.toJSONString());
LoginClientParam loginClientParam = BeanTransferUtils.transfer(object, LoginClientParam.class);
log.info("对外提供手机号登陆接口相关对象参数========》{}",loginClientParam);
if("002".equals(object.get("apiCode"))){
apiResponse = userClient.phoneLogin(loginClientParam);
}
return apiResponse;
}
/**
* 对外提供用户登陆接口
* @param object
* @return
*/
@Override
public ApiResponse userLogin(JSONObject object) {
ApiResponse<UserFeignVO> apiResponse = new ApiResponse<>();
log.info("对外提供登陆接口相关json参数========》{}",object.toJSONString());
LoginClientParam loginClientParam = BeanTransferUtils.transfer(object, LoginClientParam.class);
log.info("对外提供登陆接口相关对象参数========》{}",loginClientParam);
if("001".equals(object.get("apiCode"))){
apiResponse = userClient.userLogin(loginClientParam);
}
return apiResponse;
}
}
package org.nafmii.app.feign.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:22
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("用户返回报文")
public class UserFeignVO {
private Long id;
@ApiModelProperty(value = "昵称")
private String userName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
private String phone;
@ApiModelProperty(value = "出生日期")
private String birthday;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "头像图片地址")
private String headPicture;
@ApiModelProperty(value = "国籍")
private String nationality;
@ApiModelProperty(value = "单位全称")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
private String isEnable;
@ApiModelProperty(value = "token")
private String authorization;
@ApiModelProperty(value = "验证码登陆判断是否第一次登陆 0是 1否")
private String loginType;
}
package org.nafmii.nafmiiadmin.swagger; package org.nafmii.app.swagger;
import org.springframework.beans.factory.annotation.Value; import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/** /**
...@@ -24,20 +29,28 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; ...@@ -24,20 +29,28 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
public class SwaggerConfig { public class SwaggerConfig {
@Bean @Bean
public Docket adminApi() { public Docket adminApi() {
// String basePackage = ADMIN_SWAGGER;// 要暴露的API接口的基础包名 ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
ticketPar.name("Authorization").description("Authorization")
.modelRef(new ModelRef("string")).parameterType("header")
.required(false).build(); //header中的ticket参数非必填,传空也可以
pars.add(ticketPar.build()); //根据每个方法名也知道当前方法在设置什么参数
return new Docket (DocumentationType.SWAGGER_2) return new Docket (DocumentationType.SWAGGER_2)
.select () .apiInfo(apiInfo())
.apis (RequestHandlerSelectors.basePackage ("org.nafmii.nafmiiadmin")) .select()
.paths (PathSelectors.any ()) .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build () .paths(PathSelectors.any())
.apiInfo (apiInfo ()) .build().globalOperationParameters(pars)
.useDefaultResponseMessages (false); .useDefaultResponseMessages(false)
.enableUrlTemplating(false);
} }
private static ApiInfo apiInfo() { private static ApiInfo apiInfo() {
return new ApiInfoBuilder () return new ApiInfoBuilder ()
.title ("NAFMIIweb管理平台应用层接口说明") .title ("NAFMII-APP应用层接口说明")
.description ("NAFMIIweb管理平台应用层接口说明") .description ("NAFMII-APP应用层接口说明")
.version ("1.0") .version ("1.0")
.build (); .build ();
} }
......
package org.nafmii.controller; package org.nafmii.app.user.controller;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.nafmii.adminService.AdminService; import org.nafmii.app.user.service.AppService;
import org.nafmii.service.AppService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
......
package org.nafmii.app.user.controller;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.nafmii.app.user.dto.LoginDto;
import org.nafmii.app.user.dto.RegisterDto;
import org.nafmii.app.user.param.LoginParam;
import org.nafmii.app.user.param.RegisterParam;
import org.nafmii.app.user.service.UserService;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.ftp.FTPClientHelper;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.BeanTransferUtils;
import org.nafmii.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.File;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:10
* @ClassName:
* @version:
* @remark:
*/
@RestController
@RequestMapping("/app/nafmii/user")
@Api(tags = "2.0.1", description = "用户登陆注册操作操作【zjh】")
public class UserController {
@Resource
private UserService userService;
@ApiOperation( value = "app用户注册接口",notes = "app用户注册接口")
@PostMapping("/register")
@ResponseBody
public ApiResponse register (@RequestBody RegisterParam registerParam){
ApiResponse register = userService.register(registerParam);
return register;
}
@ApiOperation( value = "app用户登陆接口",notes = "app用户登陆接口")
@PostMapping("/userLogin")
@ResponseBody
public ApiResponse<UserVO> login (@RequestBody @Validated LoginParam loginParam){
ApiResponse<UserVO> login = userService.userLogin(loginParam);
return login;
}
@ApiOperation( value = "app手机号登陆接口",notes = "app手机号登陆接口")
@PostMapping("/phoneLogin")
@ResponseBody
public ApiResponse<UserVO> phoneLogin (@RequestBody @Validated LoginParam loginParam){
ApiResponse<UserVO> phoneLogin = userService.phoneLogin(loginParam);
return phoneLogin;
}
@ApiOperation( value = "测试ftp",notes = "测试ftp")
@PostMapping("/testFtp")
@ResponseBody
public ApiResponse testFtp (){
String ftpClient = FTPClientHelper.uploadFile("1",new File("e:/new1.txt"),"aa");
System.out.println(ftpClient);
return new ApiResponse();
}
}
package org.nafmii.app.user.dao;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.nafmii.app.user.dto.LoginDto;
import org.nafmii.app.user.entity.AppUserPO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.nafmii.app.user.vo.UserVO;
import java.util.List;
/**
* <p>
* APP用户表 Mapper 接口
* </p>
*
* @author zjh
* @since 2021-04-27
*/
@Mapper
public interface AppUserMapper extends BaseMapper<AppUserPO> {
UserVO selectByPassword(LoginDto loginDto);
UserVO selectByPhone(@Param("phone") String phone);
}
package org.nafmii.app.user.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/26 16:41
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("app用户登陆参数对象")
public class LoginDto {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@ApiModelProperty("登陆密码")
private String loginPwd;
@ApiModelProperty("验证码")
private String code;
}
package org.nafmii.app.user.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/26 13:39
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("app用户注册参数对象")
public class RegisterDto {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@ApiModelProperty("头像图片地址")
private String headPicture;
@NotNull(message = "验证码不能为空")
@ApiModelProperty("验证码")
private String code;
@NotNull(message = "注册密码不能为空")
@ApiModelProperty("登陆密码")
private String loginPwd;
@NotNull(message = "确认密码不能为空")
@ApiModelProperty("确认密码")
private String confirmPwd;
}
package org.nafmii.app.user.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* APP用户表
* </p>
*
* @author zjh
* @since 2021-04-27
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("APP_USER")
@ApiModel(value="AppUserPO对象", description="APP用户表")
public class AppUserPO extends Model {
private static final long serialVersionUID=1L;
@TableId("ID")
private Long id;
@ApiModelProperty(value = "昵称")
@TableField("USER_NAME")
private String userName;
@ApiModelProperty(value = "登录密码")
@TableField("LOGIN_PWD")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
@TableField("REAL_NAME")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
@TableField("PHONE")
private String phone;
@ApiModelProperty(value = "出生日期 示例:2020-10-10")
@TableField("BIRTHDAY")
private String birthday;
@ApiModelProperty(value = "邮箱")
@TableField("EMAIL")
private String email;
@ApiModelProperty(value = "头像图片地址")
@TableField("HEAD_PICTURE")
private String headPicture;
@ApiModelProperty(value = "国籍")
@TableField("NATIONALITY")
private String nationality;
@ApiModelProperty(value = "单位全称")
@TableField("UNIT_NAME")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
@TableField("OPEN_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
@TableField("FIGERPRINT_FALG")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
@TableField("FACEID_FALG")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
@TableField("CREATE_TIME")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
@TableField("UPDATE_TIME")
private LocalDateTime updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
@TableField("IS_ENABLE")
private String isEnable;
}
package org.nafmii.app.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/26 16:41
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("app用户登陆参数对象")
public class LoginParam {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@ApiModelProperty("登陆密码")
private String loginPwd;
@ApiModelProperty("验证码")
private String code;
}
package org.nafmii.app.user.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/26 13:39
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("app用户注册参数对象")
public class RegisterParam {
@NotNull(message = "手机号或登录账号不能为空")
@ApiModelProperty("手机号/登录账号")
private String phone;
@ApiModelProperty("头像图片地址")
private String headPicture;
@NotNull(message = "验证码不能为空")
@ApiModelProperty("验证码")
private String code;
@NotNull(message = "注册密码不能为空")
@ApiModelProperty("登陆密码")
private String loginPwd;
@NotNull(message = "确认密码不能为空")
@ApiModelProperty("确认密码")
private String confirmPwd;
}
package org.nafmii.service; package org.nafmii.app.user.service;
/** /**
* @author:zhoujh * @author:zhoujh
......
package org.nafmii.app.user.service;
import org.nafmii.app.user.dto.LoginDto;
import org.nafmii.app.user.dto.RegisterDto;
import org.nafmii.app.user.param.LoginParam;
import org.nafmii.app.user.param.RegisterParam;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.response.ApiResponse;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:20
* @ClassName:
* @version:
* @remark:
*/
public interface UserService {
//手机号登陆接口
ApiResponse<UserVO> phoneLogin(LoginParam loginParam);
//app注册接口
ApiResponse register(RegisterParam registerParam);
//用户登陆接口
ApiResponse<UserVO> userLogin(LoginParam loginParam);
}
package org.nafmii.service.impl; package org.nafmii.app.user.service.impl;
import org.nafmii.adminService.AdminService;
import org.nafmii.service.AppService; import org.nafmii.app.feign.AdminService;
import org.nafmii.app.user.service.AppService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
......
package org.nafmii.app.user.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.app.user.dao.AppUserMapper;
import org.nafmii.app.user.dto.LoginDto;
import org.nafmii.app.user.dto.RegisterDto;
import org.nafmii.app.user.entity.AppUserPO;
import org.nafmii.app.user.param.LoginParam;
import org.nafmii.app.user.param.RegisterParam;
import org.nafmii.app.user.service.UserService;
import org.nafmii.app.user.vo.UserAndRoleVo;
import org.nafmii.app.user.vo.UserVO;
import org.nafmii.common.constant.HttpClientHeaderEnum;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.param.BeanTransferUtils;
import org.nafmii.common.response.ApiResponse;
import org.nafmii.common.utils.JwtUtils;
import org.nafmii.common.utils.SnowFlakeUtil;
import org.nafmii.common.constant.UserEnum;
import org.nafmii.common.constant.RedisEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:20
* @ClassName:app用户实现类
* @version:
* @remark:
*/
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Resource
private AppUserMapper appUserMapper;
//redis缓存快递集合-key
public static final String USER_CODE_KEY="user:code";
@Autowired
StringRedisTemplate stringRedisTemplate;
/**
* 手机号登陆接口
* @param loginParam
* @return
*/
@Override
public ApiResponse<UserVO> phoneLogin(LoginParam loginParam) {
LoginDto loginDto = BeanTransferUtils.transfer(loginParam, LoginDto.class);
log.info("========登陆接口相关参数======>"+loginDto);
long EXPIRITION = 1000 * 60 * 60 * 24 * 7;
//验证码登陆
String code = stringRedisTemplate.opsForValue().get(USER_CODE_KEY+loginDto.getPhone());
log.info("重redis中获取的验证码===============》{}",code);
if (null == code){
return new ApiResponse(ApiResponse.FAIL, MessageEnum.CODE_ERROR.getRemarks());
}
if (!loginDto.getCode().equals(code)){
return new ApiResponse(ApiResponse.FAIL, MessageEnum.CODE_ERROR.getRemarks());
}
UserVO userVo = appUserMapper.selectByPhone(loginDto.getPhone());
log.info("验证码登录返回用户实体=======》{}",userVo);
userVo.setLoginType(userVo!=null ? UserEnum.NOTFIRSTLOGIN.getCode() :UserEnum.FIRSTLOGIN.getCode());
Map<String,Object> map = new HashMap<>();
map.put(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode(),userVo.getId());
String token = JwtUtils.generateJsonWebToken(map,EXPIRITION);
userVo.setAuthorization(token);
ApiResponse apiResponse =new ApiResponse();
apiResponse.setData(userVo);
return apiResponse;
}
/**
* app用户注册接口
* @param registerParam
* @return ApiResponse
*/
@Override
public ApiResponse register(RegisterParam registerParam) {
RegisterDto registerDto = BeanTransferUtils.transfer(registerParam, RegisterDto.class);
//查询用户信息通过手机号
UserVO userVO = appUserMapper.selectByPhone(registerDto.getPhone());
if (null != userVO){
return new ApiResponse(ApiResponse.FAIL,"该用户已注册");
}
//用户实体类
AppUserPO appUser = new AppUserPO();
appUser.setId(SnowFlakeUtil.nextId());
appUser.setFaceidFalg(UserEnum.NOTFACE.getCode());
appUser.setFigerprintFalg(UserEnum.NOTFINGERPRINT.getCode());
appUser.setHeadPicture(registerDto.getHeadPicture());
appUser.setIsEnable(UserEnum.ENABLE.getCode());
appUser.setPhone(registerDto.getPhone());
//判断注册密码和再次输入密码
if (!registerDto.getLoginPwd().equals(registerDto.getConfirmPwd())){
return new ApiResponse(ApiResponse.FAIL,"两次密码输入不相同,请再次输入");
}
appUser.setLoginPwd(registerDto.getLoginPwd());
appUser.setCreateTime(LocalDateTime.now());
appUser.setUpdateTime(LocalDateTime.now());
log.info("用户注册参数==============>"+registerDto);
//将验证码放入到缓存当中(过期时间60s)test
// GuavaUtil.putTrackGuava(registerDto.getPhone(),registerDto.getCode());
stringRedisTemplate.opsForValue().set(new StringBuilder().append(USER_CODE_KEY).append(registerDto.getPhone()).toString(), registerDto.getCode(), RedisEnum.PHONECODE.getCode(), TimeUnit.SECONDS);
//重缓存中获取(通过手机号获取)
String code = stringRedisTemplate.opsForValue().get(USER_CODE_KEY+registerDto.getPhone());
log.info("冲缓存中获取的验证码===============》{}",code);
if (null == code){
return new ApiResponse(ApiResponse.FAIL,"验证码已过期");
}
if (!code.equals(registerDto.getCode())){
return new ApiResponse(ApiResponse.FAIL,"验证码错误请重新输入");
}
int i = appUserMapper.insert(appUser);
if (i<0){
return new ApiResponse(ApiResponse.FAIL,"新增失败");
}
return new ApiResponse(ApiResponse.SUCCESS,"新增成功");
}
/**
* 用户登陆接口
* @param loginParam
* @return
*/
@Override
public ApiResponse<UserVO> userLogin(LoginParam loginParam) {
LoginDto loginDto = BeanTransferUtils.transfer(loginParam, LoginDto.class);
log.info("========登陆接口相关参数======>"+loginDto);
long EXPIRITION = 1000 * 60 * 60 * 24 * 7;
//密码登陆
UserVO userVo = appUserMapper.selectByPassword(loginDto);
log.info("账号密码登录返回用户实体=======》{}",userVo);
if (null == userVo){
return new ApiResponse(ApiResponse.FAIL, MessageEnum.FAIR_PASSWORD.getRemarks());
}
userVo.setLoginType(UserEnum.NOTFIRSTLOGIN.getCode());
Map<String,Object> map = new HashMap<>();
map.put(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode(),userVo.getId());
String token = JwtUtils.generateJsonWebToken(map,EXPIRITION);
userVo.setAuthorization(token);
ApiResponse apiResponse =new ApiResponse();
apiResponse.setData(userVo);
return apiResponse;
}
}
package org.nafmii; package org.nafmii.app.user;
/** /**
* @author:zhoujh * @author:zhoujh
* @Function:TODO * @Function:TODO
* @date 2021/4/23 8:58 * @date 2021/4/27 10:54
* @ClassName: * @ClassName:
* @version: * @version:
* @remark: * @remark:
......
package org.nafmii.app.user.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 9:06
* @ClassName:
* @version:
* @remark:
*/
@Data
public class UserAndRoleVo {
private Long id;
private String userName;
private String password;
@ApiModelProperty("角色名称")
private String Role;
}
package org.nafmii.app.user.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:22
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("用户返回报文")
public class UserVO {
private Long id;
@ApiModelProperty(value = "昵称")
private String userName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
private String phone;
@ApiModelProperty(value = "出生日期")
private String birthday;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "头像图片地址")
private String headPicture;
@ApiModelProperty(value = "国籍")
private String nationality;
@ApiModelProperty(value = "单位全称")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
private String isEnable;
@ApiModelProperty(value = "token")
private String authorization;
@ApiModelProperty(value = "验证码登陆判断是否第一次登陆 0是 1否")
private String loginType;
}
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:20000/eureka
instance:
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true
statusPageUrl: http://127.0.0.1:22000/swagger-ui.html
logging:
config: classpath:logback-spring.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
port: 6379
# Redis服务器连接密码(默认为空)
password:
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 20
max-wait: -1ms
max-idle: 10
min-idle: 0
timeout: 1000ms
zipkin:
base-url: http://localhost:9411
enabled: true
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.app
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
\ No newline at end of file \ No newline at end of file
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:20000/eureka
instance:
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true
statusPageUrl: http://127.0.0.1:22000/swagger-ui.html
logging:
config: classpath:logback-spring.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
port: 6379
# Redis服务器连接密码(默认为空)
password:
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 20
max-wait: -1ms
max-idle: 10
min-idle: 0
timeout: 1000ms
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.app
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
\ No newline at end of file \ No newline at end of file
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:20000/eureka
instance:
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true
statusPageUrl: http://127.0.0.1:22000/swagger-ui.html
logging:
config: classpath:logback-spring.xml
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
port: 6379
# Redis服务器连接密码(默认为空)
password:
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 20
max-wait: -1ms
max-idle: 10
min-idle: 0
timeout: 1000ms
nafmii:
log-path: E:/NAFMII
dao-uri: org.nafmii.app
ftp:
host: 127.0.0.1
password: peng1003
prot: 21
username: ypenglv
\ No newline at end of file \ No newline at end of file
server.port=8002
spring.application.name=nafmii-app
logging.level.root=info
logging.file.path=d:/data/logs/nafmii-app/
logging.file.max-history=15
logging.file.max-size=300MB
logging.pattern.dateformat=yyyy-MM-dd hh:MM:ss
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.instance.statusPageUrl = http://127.0.0.1:8002/swagger-ui.html
eureka.instance.prefer-ip-address = true
eureka.instance.instance-id = ${spring.cloud.client.ip-address}:${server.port}
\ No newline at end of file \ No newline at end of file
server:
port: 22000
tomcat:
uri-encoding: UTF-8
spring:
profiles:
active: @env@
application:
name: nafmii-app
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.app.user.dao.AppUserMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="org.nafmii.app.user.entity.AppUserPO">
<id column="ID" property="id" />
<result column="USER_NAME" property="userName" />
<result column="LOGIN_PWD" property="loginPwd" />
<result column="REAL_NAME" property="realName" />
<result column="PHONE" property="phone" />
<result column="BIRTHDAY" property="birthday" />
<result column="EMAIL" property="email" />
<result column="HEAD_PICTURE" property="headPicture" />
<result column="NATIONALITY" property="nationality" />
<result column="UNIT_NAME" property="unitName" />
<result column="OPEN_ID" property="openId" />
<result column="FIGERPRINT_FALG" property="figerprintFalg" />
<result column="FACEID_FALG" property="faceidFalg" />
<result column="CREATE_TIME" property="createTime" />
<result column="UPDATE_TIME" property="updateTime" />
<result column="IS_ENABLE" property="isEnable" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
ID, USER_NAME, LOGIN_PWD, REAL_NAME, PHONE, BIRTHDAY, EMAIL, HEAD_PICTURE, NATIONALITY, UNIT_NAME, OPEN_ID, FIGERPRINT_FALG, FACEID_FALG, CREATE_TIME, UPDATE_TIME, IS_ENABLE
</sql>
<select id="selectByPassword" parameterType="org.nafmii.app.user.dto.LoginDto" resultType="org.nafmii.app.user.vo.UserVO">
select ID as id,
USER_NAME as userName, LOGIN_PWD as loginPwd, REAL_NAME as realName, PHONE as phone, BIRTHDAY as birthday, EMAIL as email, HEAD_PICTURE as headPicture, NATIONALITY as nationality,
UNIT_NAME as unitName, OPEN_ID as openId, FIGERPRINT_FALG as figerprintFalg, FACEID_FALG as faceidFalg, CREATE_TIME as createTime, UPDATE_TIME as updateTime, IS_ENABLE as isEnable
from APP_USER where IS_ENABLE = 0
<if test="phone !=null">
and PHONE =#{phone}
</if>
<if test="loginPwd !=null">
and LOGIN_PWD =#{loginPwd}
</if>
</select>
<select id="selectByPhone" parameterType="map" resultType="org.nafmii.app.user.vo.UserVO">
select ID as id,
USER_NAME as userName, LOGIN_PWD as loginPwd, REAL_NAME as realName, PHONE as phone, BIRTHDAY as birthday, EMAIL as email, HEAD_PICTURE as headPicture, NATIONALITY as nationality,
UNIT_NAME as unitName, OPEN_ID as openId, FIGERPRINT_FALG as figerprintFalg, FACEID_FALG as faceidFalg, CREATE_TIME as createTime, UPDATE_TIME as updateTime, IS_ENABLE as isEnable
from APP_USER where IS_ENABLE = 0
<if test="phone !=null">
and PHONE =#{phone}
</if>
</select>
</mapper>
package org.nafmii;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NafmiiAppApplicationTests {
@Test
void contextLoads() {
}
}
...@@ -17,63 +17,85 @@ ...@@ -17,63 +17,85 @@
<httpClient.version>4.5.3</httpClient.version> <httpClient.version>4.5.3</httpClient.version>
<fastjson.version>1.2.58</fastjson.version> <fastjson.version>1.2.58</fastjson.version>
<ojdbc.version>10.2.0.4</ojdbc.version> <ojdbc.version>10.2.0.4</ojdbc.version>
<jjwt.version>0.9.1</jjwt.version>
<jasypt.version>3.0.2</jasypt.version>
</properties> </properties>
<dependencies> <dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!--swagger 相关依赖--> <!--swagger 相关依赖-->
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId> <artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version> <version>2.8.0</version>
</dependency> </dependency>
<!--- ftp-->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<!--- swagger-->
<dependency> <dependency>
<groupId>io.springfox</groupId> <groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId> <artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version> <version>2.8.0</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/net.logstash.logback/logstash-logback-encoder -->
<dependency> <dependency>
<groupId>net.logstash.logback</groupId> <groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId> <artifactId>logstash-logback-encoder</artifactId>
<version>6.3</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.data</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-data-commons</artifactId> <artifactId>spring-boot-starter-test</artifactId>
</dependency> <scope>test</scope>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency> </dependency>
<!--MyBatis分页插件-->
<dependency> <dependency>
<groupId>com.github.pagehelper</groupId> <groupId>org.springframework.data</groupId>
<artifactId>pagehelper</artifactId> <artifactId>spring-data-commons</artifactId>
</dependency> </dependency>
<!--Knife4j API文档生产工具-->
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId> <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>io.jsonwebtoken</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId> <artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>com.auth0</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>java-jwt</artifactId>
<exclusions><!-- 去掉springboot默认配置 --> <version>3.2.0</version>
<exclusions>
<exclusion> <exclusion>
<groupId>org.springframework.boot</groupId> <artifactId>bcprov-jdk15on</artifactId>
<artifactId>spring-boot-starter-logging</artifactId> <groupId>org.bouncycastle</groupId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>com.github.pagehelper</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>3.0.2</version>
</dependency> </dependency>
<!--redis--> <!--redis-->
<dependency> <dependency>
...@@ -101,6 +123,7 @@ ...@@ -101,6 +123,7 @@
<artifactId>mybatis-plus-extension</artifactId> <artifactId>mybatis-plus-extension</artifactId>
<version>3.3.0</version> <version>3.3.0</version>
</dependency> </dependency>
<!-- 代码生成器模板 --> <!-- 代码生成器模板 -->
<dependency> <dependency>
<groupId>org.apache.velocity</groupId> <groupId>org.apache.velocity</groupId>
...@@ -138,28 +161,83 @@ ...@@ -138,28 +161,83 @@
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId> <artifactId>poi</artifactId>
<version>3.9</version> <version>3.17</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId> <artifactId>poi-ooxml</artifactId>
<version>3.9</version> <version>3.17</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.0-android</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId> <artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version> <version>3.17</version>
</dependency> </dependency>
<!-- 反射 --> <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency> <dependency>
<groupId>cn.hutool</groupId> <groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId> <artifactId>hutool-all</artifactId>
<version>5.6.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.4</version> <version>2.4</version>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.0</version>
</dependency>
<!-- ftp -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<!-- jasypt -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.version}</version>
</dependency>
<!-- 线程池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package org.nafmii.common.config;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author by zhangbr
* @date 2020/7/25
*/
@Configuration
public class EncryptConfig {
private final static String ENCRYPT_PASSWORD = "P0O9I8U7Y6T5R4E3W2Q1";
private static StringEncryptor encrypt = initStringEncrypt();
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
return encrypt;
}
private static StringEncryptor initStringEncrypt(){
PooledPBEStringEncryptor encrypt = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(ENCRYPT_PASSWORD);
config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
encrypt.setConfig(config);
return encrypt;
}
/**
* 加密
* @param code 编码
* @return String
*/
public static String encrypt(String code){
return encrypt.encrypt(code);
}
/**
* 解密
* @param code 编码
* @return String
*/
public static String decrypt(String code) throws EncryptionOperationNotPossibleException {
return encrypt.decrypt(code);
}
}
package org.nafmii.config; package org.nafmii.common.config;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
......
package org.nafmii.config; package org.nafmii.common.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
......
package org.nafmii.common.constant;
/**
* @author lvyp
* @date 2021/4/25
*/
public enum BusinessEnum {
APP_CONF_CAROUSE_PIC("1","轮播图"),
APP_CONF_OPENSCREEN_PIC("2","开屏图"),
APP_CONF_ICON("3","首页ICON");
private String businessType;
private String businessName;
BusinessEnum(String businessType, String businessName) {
this.businessType = businessType;
this.businessName = businessName;
}
BusinessEnum() {
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
}
package org.nafmii.common.constant;
public enum CommonEnum {
/**
* 通用枚举
*/
DELETE("1", "删除"),
USED("0", "在用"),
DISABLE("1", "停用"),
ENABLE("0", "启用"),
/**
* 排序
*/
ORDER_BY_ASC("ASC", "正序"),
ORDER_BY_DESC("DESC", "倒序"),
;
CommonEnum(String code, String name){
this.code = code;
this.name = name;
}
private String name;
private String code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package org.nafmii.constant; package org.nafmii.common.constant;
/**
* @author by zhangbr
* @date 2020/4/8.
*/
public enum HttpClientHeaderEnum { public enum HttpClientHeaderEnum {
/** /**
* 系统自定义请求header参数 * 系统自定义请求header参数
*/ */
USER_HEADER_USER_ID("userId", "用户ID"), USER_HEADER_USER_ID("userId", "用户ID"),
USER_HEADER_OLD_USER_ID("oldUserId", "老用户ID"), USER_HEADER_USER_TOKEN("Authorization", "用户token"),
USER_HEADER_USER_TOKEN("token", "用户token"),
USER_HEADER_MODE("mode", "设备:PC,APP,PAD"), USER_HEADER_MODE("mode", "设备:PC,APP,PAD"),
; USER_VO("USERVO","用户信息");
HttpClientHeaderEnum(String code, String name){ HttpClientHeaderEnum(String code, String name){
this.code = code; this.code = code;
......
package org.nafmii.constant; package org.nafmii.common.constant;
public enum MessageEnum { public enum MessageEnum {
/** /**
...@@ -19,6 +19,10 @@ public enum MessageEnum { ...@@ -19,6 +19,10 @@ public enum MessageEnum {
FILE_TYPE_ERROR(-110L, "文件类型不允许上传!"), FILE_TYPE_ERROR(-110L, "文件类型不允许上传!"),
FILE_UPLOAD_FAIL(-111L, "文件上传失败!"), FILE_UPLOAD_FAIL(-111L, "文件上传失败!"),
FILE_DOWN_FAIL(-112L, "文件不存在或已被删除!"), FILE_DOWN_FAIL(-112L, "文件不存在或已被删除!"),
FILE_PICTURE(-113L, "图片格式非法!"),
CODE_ERROR(-114L, "验证码错误或失效!"),
EXCEL_ERROR(-115L, "导入模板列数不匹配!"),
FAIR_PASSWORD(-116L, "密码有误!"),
; ;
private Long code; private Long code;
......
package org.nafmii.common.constant;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/27 13:48
* @ClassName:
* @version:
* @remark:
*/
public enum RedisEnum {
/**
* 验证码失效时间60s
*/
PHONECODE(60, "60秒后失效")
;
RedisEnum(Integer code, String name){
this.code = code;
this.name = name;
}
private String name;
private Integer code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
package org.nafmii.common.constant;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/27 9:57
* @ClassName:
* @version:
* @remark:
*/
public enum UserEnum{
/**
* 是否开启人脸识别登录 0 未开启 1 已开启
*/
FACE("1", "已开启"),
NOTFACE("0", "未开启"),
/**
* 是否开启指纹登录 0 未开启 1 已开启
*/
FINGERPRINT("1","已开启"),
NOTFINGERPRINT("0","未开启"),
/**
* 是否有效标识 0 有效用户 1无效用户
*/
ENABLE("0","有效用户"),
NOTENABLE("1","无效用户"),
/**
* 登陆方式
*/
LOGINPHONE("1","验证码"),
LOGINPWD("0","密码"),
/**
*用户是否第一次登陆
*/
FIRSTLOGIN("0","是第一次登陆"),
NOTFIRSTLOGIN("1","不是第一次登陆"),
;
UserEnum(String code, String name){
this.code = code;
this.name = name;
}
private String name;
private String code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package org.nafmii.exception; package org.nafmii.common.exception;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
public class BusinessException extends RuntimeException { public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private Integer statusCode; private Integer status;
public BusinessException() { public BusinessException() {
super (); super ();
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; this.status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
} }
public BusinessException(String message) { public BusinessException(String message) {
super (message); super (message);
this.statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; this.status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
} }
public BusinessException(Integer statusCode, String message) { public BusinessException(Integer statusCode, String message) {
super (message); super (message);
this.statusCode = statusCode; this.status = statusCode;
} }
public BusinessException(Long statusCode, String message) { public BusinessException(Long statusCode, String message) {
super (message); super (message);
this.statusCode = Integer.parseInt(statusCode.toString()); this.status = Integer.parseInt(statusCode.toString());
} }
public Integer getStatusCode() { public Integer getStatusCode() {
return statusCode; return status;
} }
public void setStatusCode(Integer statusCode) { public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode; this.status = statusCode;
} }
} }
package org.nafmii.exception; package org.nafmii.common.exception;
import feign.codec.DecodeException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.nafmii.constant.MessageEnum; import org.nafmii.common.constant.MessageEnum;
import org.nafmii.result.Result; import org.nafmii.common.response.ApiResponse;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
...@@ -12,8 +13,6 @@ import org.springframework.web.bind.annotation.ExceptionHandler; ...@@ -12,8 +13,6 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MaxUploadSizeExceededException;
import javax.websocket.DecodeException;
@Order(Integer.MIN_VALUE) @Order(Integer.MIN_VALUE)
@ControllerAdvice @ControllerAdvice
@Slf4j @Slf4j
...@@ -24,9 +23,9 @@ public class BusinessExceptionHandler { ...@@ -24,9 +23,9 @@ public class BusinessExceptionHandler {
*/ */
@ExceptionHandler(value = Exception.class) @ExceptionHandler(value = Exception.class)
@ResponseBody @ResponseBody
public Result defaultErrorHandler(Exception e) { public ApiResponse defaultErrorHandler(Exception e) {
log.error (e.getMessage (), e); log.error (e.getMessage (), e);
return new Result(MessageEnum.FAIL.getCode(), e.getMessage()); return new ApiResponse(MessageEnum.FAIL.getCode(), e.getMessage());
} }
/** /**
...@@ -36,9 +35,9 @@ public class BusinessExceptionHandler { ...@@ -36,9 +35,9 @@ public class BusinessExceptionHandler {
*/ */
@ExceptionHandler(value = BusinessException.class) @ExceptionHandler(value = BusinessException.class)
@ResponseBody @ResponseBody
public Result businessErrorHandler(BusinessException e) { public ApiResponse businessErrorHandler(BusinessException e) {
log.error (e.getMessage (), e); log.error (e.getMessage (), e);
return new Result(e.getStatusCode(), e.getMessage()); return new ApiResponse(new Long((long)e.getStatusCode()), e.getMessage());
} }
/** /**
...@@ -46,13 +45,13 @@ public class BusinessExceptionHandler { ...@@ -46,13 +45,13 @@ public class BusinessExceptionHandler {
*/ */
@ExceptionHandler(value = MethodArgumentNotValidException.class) @ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseBody @ResponseBody
public Result argumentErrorHandler(MethodArgumentNotValidException e) { public ApiResponse argumentErrorHandler(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult(); BindingResult bindingResult = e.getBindingResult();
String errorMessage = "参数不能为空!"; String errorMessage = "参数不能为空!";
if (bindingResult.getFieldError() != null){ if (bindingResult.getFieldError() != null){
errorMessage = bindingResult.getFieldError().getDefaultMessage(); errorMessage = bindingResult.getFieldError().getDefaultMessage();
} }
return new Result(MessageEnum.FAIL_PARAM.getCode(), errorMessage); return new ApiResponse(MessageEnum.FAIL_PARAM.getCode(), errorMessage);
} }
/** /**
...@@ -60,9 +59,9 @@ public class BusinessExceptionHandler { ...@@ -60,9 +59,9 @@ public class BusinessExceptionHandler {
*/ */
@ExceptionHandler(value = HttpMessageNotReadableException.class) @ExceptionHandler(value = HttpMessageNotReadableException.class)
@ResponseBody @ResponseBody
public Result argumentErrorHandler(HttpMessageNotReadableException e) { public ApiResponse argumentErrorHandler(HttpMessageNotReadableException e) {
log.error (e.getMessage(), e); log.error (e.getMessage(), e);
return new Result(MessageEnum.FAIL_PARAM_TYPE.getCode(), MessageEnum.FAIL_PARAM_TYPE.getRemarks()); return new ApiResponse(MessageEnum.FAIL_PARAM_TYPE.getCode(), MessageEnum.FAIL_PARAM_TYPE.getRemarks());
} }
/** /**
...@@ -70,9 +69,9 @@ public class BusinessExceptionHandler { ...@@ -70,9 +69,9 @@ public class BusinessExceptionHandler {
*/ */
@ExceptionHandler(value = DecodeException.class) @ExceptionHandler(value = DecodeException.class)
@ResponseBody @ResponseBody
public Result argumentErrorHandler(DecodeException e) { public ApiResponse argumentErrorHandler(DecodeException e) {
log.error (e.getMessage(), e); log.error (e.getMessage(), e);
return new Result(MessageEnum.FEIGN_CLIENT_DECODE.getCode(), MessageEnum.FEIGN_CLIENT_DECODE.getRemarks()); return new ApiResponse(MessageEnum.FEIGN_CLIENT_DECODE.getCode(), MessageEnum.FEIGN_CLIENT_DECODE.getRemarks());
} }
/** /**
...@@ -80,8 +79,8 @@ public class BusinessExceptionHandler { ...@@ -80,8 +79,8 @@ public class BusinessExceptionHandler {
*/ */
@ExceptionHandler(value = MaxUploadSizeExceededException.class) @ExceptionHandler(value = MaxUploadSizeExceededException.class)
@ResponseBody @ResponseBody
public Result argumentErrorHandler(MaxUploadSizeExceededException e) { public ApiResponse argumentErrorHandler(MaxUploadSizeExceededException e) {
log.error (e.getMessage(), e); log.error (e.getMessage(), e);
return new Result(MessageEnum.MAX_FILE_SIZE.getCode(), MessageEnum.MAX_FILE_SIZE.getRemarks()); return new ApiResponse(MessageEnum.MAX_FILE_SIZE.getCode(), MessageEnum.MAX_FILE_SIZE.getRemarks());
} }
} }
package org.nafmii.common.ftp;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author by zhangbr
* @date 2020/7/24.
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({FTPClientConfigure.class, FTPClientHelper.class})
public @interface EnableFtpServer {
}
package org.nafmii.common.ftp;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author by zhangbr
* @date 2020/7/24.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@ConfigurationProperties("nafmii.ftp")
class FTPClientConfigure extends GenericObjectPoolConfig<FTPClient> {
/**
* ftp服务器地址
*/
private String host;
/**
* ftp登录账号
*/
private String username;
/**
* ftp登录密码
*/
private String password;
/**
* ftp服务器端口号,默认为21
*/
private Integer port = 21;
/**
* 上传附件前缀
*/
private String prefix;
/**
* ftp连接超时时间,毫秒,0 = 无限超时
*/
private int connectTimeOut = 0;
/**
* 缓冲区大小
*/
private int bufferSize = 1024;
/**
* 传输文件类型
*/
private int transferFileType = FTPClient.BINARY_FILE_TYPE;
/**
* 编码格式
*/
private String controlEncoding = "utf-8";
/**
* 默认120S
*/
private int dataTimeout = 120 * 1000;
/**
* 是否启用被动模式
*/
private boolean passiveMode = true;
/**
* 开启线程数
*/
private int threadNum = 8;
/**
* 是否上传文件重命名;
*/
private boolean renameUploaded = false;
/**
* 重试次数
*/
private int retryTimes = 3;
private boolean ipv4 = false;
}
package org.nafmii.common.ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.nafmii.common.exception.BusinessException;
import javax.annotation.Resource;
import java.io.IOException;
/**
* FTPClient工厂类,通过FTPClient工厂提供FTPClient实例的创建和销毁
* @author by zhangbr
* @date 2020/7/24.
*/
@Slf4j
public class FTPClientFactory{
private FTPClientConfigure config;
public FTPClientFactory(FTPClientConfigure config){
this.config = config;
}
/**
* 新建对象
*/
public FTPClient create() {
FTPClient ftpClient = new FTPClient();
ftpClient.setConnectTimeout(config.getConnectTimeOut());
try {
log.info("======连接ftp服务器:" + config.getHost() + ":" + config.getPort() + "======");
ftpClient.connect(config.getHost(), config.getPort());
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
log.info("======FTPServer连接被拒绝======");
return null;
}
boolean result = ftpClient.login(config.getUsername(), config.getPassword());
if (!result) {
throw new BusinessException(-100, "ftpClient登陆失败");
}
ftpClient.setControlEncoding(config.getControlEncoding());
ftpClient.setBufferSize(config.getBufferSize());
ftpClient.setFileType(config.getTransferFileType());
ftpClient.setDataTimeout(config.getDataTimeout());
ftpClient.setUseEPSVwithIPv4(config.isIpv4());
if (config.isPassiveMode()) {
ftpClient.enterLocalPassiveMode();
}
} catch (IOException e) {
log.info("FTP连接失败:", e.getMessage());
throw new BusinessException(-100, "FTP服务器连接失败");
}
return ftpClient;
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.common.ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.exception.BusinessException;
import org.nafmii.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author by zhangbr
* @date 2020/7/24.
*/
@Slf4j
public class FTPClientHelper implements AutoCloseable {
@Resource
private FTPClientConfigure configure;
private static FTPClientHelper ftpClientHelper;
private static FTPClientFactory factory;
private static final String SUB_SPOT = ".";
/**
* 初始化设置
*/
@PostConstruct
public boolean init() {
factory = new FTPClientFactory(configure);
ftpClientHelper = this;
return true;
}
/**
* 获取一个连接对象
* @return FTPClient
*/
private static FTPClient getClient() {
return factory.create();
}
/**
* 列出目录下的所有文件
* @param pathName 路径
* @return FTPFile[]
*/
public static FTPFile[] listFiles(String pathName) {
FTPClient client = getClient();
try {
return client.listFiles(pathName);
} catch (IOException e) {
log.info(e.getMessage());
}finally {
releaseClient(client);
}
return null;
}
/**
* 下载 remote文件流
* @param form ftp资源下载
* @return boolean
*/
public static boolean retrieveFile(FileDownLoadForm form) {
String remote = form.encodeFileId();
if (StringUtils.isEmpty(remote)){
log.info("==============下载FTP文件失败:remote:{}=============", remote, remote);
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
log.info("==============开始下载FTP文件:{}=============", remote);
long startTime = System.currentTimeMillis();
FTPClient client = getClient();
OutputStream outputStream = null;
try {
if (!existFile(client, remote)){
log.info("==============下载FTP文件失败:未找到文件:{}=============", remote);
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
outputStream = RequestUtils.getResponse().getOutputStream();
boolean result = client.retrieveFile(remote, outputStream);
long endTime = System.currentTimeMillis();
log.info("==============下载FTP文件:{}完成,result:{},用时:{}=============", remote, result, (endTime - startTime) + "ms");
return result;
} catch (IOException e) {
log.info(e.getMessage());
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
} finally {
if (outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
log.info(e.getMessage());
}
}
releaseClient(client);
}
}
/**
* 下载 remote文件流
* @param remote ftp资源文件路径
* @return byte[]
*/
public static InputStream retrieveFileStream(String remote) {
log.info("==============开始下载FTP文件:{}=============", remote);
long startTime = System.currentTimeMillis();
FTPClient client = getClient();
InputStream in = null;
try {
if (!existFile(client, remote)){
log.info("==============下载FTP文件失败:未找到文件:{}=============", remote);
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
in = client.retrieveFileStream(remote);
long endTime = System.currentTimeMillis();
log.info("==============下载FTP文件:{}完成,用时:{}=============", remote, (endTime - startTime) + "ms");
} catch (IOException e) {
log.info(e.getMessage());
} finally {
releaseClient(client);
}
return in;
}
/**
* 根据业务分类上传文件(同步上传)
* @param business 业务模块
* @param inputStream 文件流
* @return String
*/
public static String uploadFile(String business, InputStream inputStream, String fileName) {
String remotePath;
FTPClient client = getClient();
try {
remotePath = makeDirectory(client, business);
remotePath += fileName;
upload(client, remotePath, inputStream);
} catch (IOException e) {
throw new BusinessException(-102, "附件上传失败!");
} finally {
releaseClient(client);
}
return remotePath;
}
/**
* 根据业务分类上传文件(同步上传)
* @param business 业务模块
* @param file 文件资源
* @return String
*/
public static String uploadFile(String business, File file, String fileName) {
if (file == null || StringUtils.isEmpty(business) || StringUtils.isEmpty(fileName)){
log.info("======上传附件异常======business:{},fileName:{}", business, fileName);
throw new BusinessException(-101, "附件上传失败!");
}
String remotePath;
FTPClient client = getClient();
InputStream inputStream;
try {
remotePath = makeDirectory(client, business);
remotePath += fileName;
inputStream = new FileInputStream(file);
upload(client, remotePath, inputStream);
} catch (IOException e) {
throw new BusinessException(-102, "附件上传失败!");
} finally {
releaseClient(client);
}
return remotePath;
}
/**
* 根据路径上传文件(异步上传)
* @param filePathName ftp附件上传路径
* @param file 文件资源
* @return boolean
*/
public static boolean uploadFile(String filePathName, File file) {
if (file == null || StringUtils.isEmpty(filePathName)){
log.info("======上传附件异常======filePathName:{}", filePathName);
throw new BusinessException(-103, "附件上传失败!");
}
FTPClient client = getClient();
InputStream inputStream;
boolean flag;
try {
inputStream = new FileInputStream(file);
flag = upload(client, filePathName, inputStream);
} catch (IOException e) {
log.info(e.getMessage());
throw new BusinessException(-104, "附件上传失败!");
} finally {
releaseClient(client);
}
return flag;
}
/**
* 多文件上传
* @param business 业务模块
* @param files 文件集合
* @return List<FileVO>
*/
public static List<FileVO> uploadFiles(String business, MultipartFile[] files){
List<FileVO> fileList = new ArrayList<>();
FTPClient client = getClient();
try {
String remotePath = makeDirectory(client, business);
for (MultipartFile file : files) {
try {
//上传文件
String fileName = file.getOriginalFilename();
if (StringUtils.isEmpty(fileName)){
continue;
}
String suffix = fileName.substring(fileName.lastIndexOf(SUB_SPOT));
if (StringUtils.isEmpty(suffix)){
continue;
}
String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;
String remoteFilePath = remotePath + newFileName;
InputStream inputStream = file.getInputStream();
upload(client, remoteFilePath, inputStream);
inputStream.close();
fileList.add(new FileVO(remoteFilePath, newFileName));
} catch (IOException e) {
throw new BusinessException(MessageEnum.FILE_UPLOAD_FAIL.getCode(), MessageEnum.FILE_UPLOAD_FAIL.getRemarks());
}
}
} catch (IOException e) {
throw new BusinessException(-100, "FTP目录生成失败!");
} finally {
releaseClient(client);
}
return fileList;
}
private static boolean upload(FTPClient client, String filePathName, InputStream inputStream){
try {
log.info("==============FTP文件:{},开始上传=============", filePathName);
long start = System.currentTimeMillis();
boolean result = client.storeFile(filePathName, inputStream);
long end = System.currentTimeMillis();
log.info("==============FTP文件:{},上传完成时间:{}=============", filePathName, (end - start) + "ms");
return result;
} catch (IOException e) {
throw new BusinessException(MessageEnum.FILE_UPLOAD_FAIL.getCode(), MessageEnum.FILE_UPLOAD_FAIL.getRemarks());
}finally {
if (inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
log.info(e.getMessage());
}
}
}
}
/**
* 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
* @param business 业务模块
* @return String
*/
public static String makeDirectory(String business){
String remotePath;
FTPClient client = getClient();
try {
remotePath = makeDirectory(client, business);
} catch (IOException e) {
throw new BusinessException(-100, "文件目录生成失败!");
} finally {
releaseClient(client);
}
return remotePath;
}
/**
* 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
* @param client client
* @param business 业务模块
* @return String
* @throws IOException e
*/
private static String makeDirectory(FTPClient client, String business) throws IOException {
log.info("==============开始生成FTP目录:{}=============", business);
long startTime = System.currentTimeMillis();
String directory = getRemoteBusinessPath(business);
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase(File.separator) && !changeWorkingDirectory(client, directory)) {
int start;
int end;
if (directory.startsWith(File.separator)) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf(File.separator, start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(directory.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
path = path + File.separator + subDirectory;
if (!existFile(client, path)) {
if (createDirectory(client, subDirectory)) {
changeWorkingDirectory(client, subDirectory);
} else {
log.info("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(client, subDirectory);
}
} else {
changeWorkingDirectory(client, subDirectory);
}
paths = paths + File.separator + subDirectory;
start = end + 1;
end = directory.indexOf(File.separator, start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
long endTime = System.currentTimeMillis();
log.info("==============生成FTP目录:{}完成,用时:{}=============", business, (endTime - startTime) + "ms");
return directory;
}
/**
* 根据业务模块创建远程文件路径
* @param business 业务模块
* @return String
*/
public static String getRemoteBusinessPath(String business){
if (StringUtils.isEmpty(business)){
throw new BusinessException(-100, "业务模块不能为空!");
}
String filePath = StringUtils.isEmpty(ftpClientHelper.configure.getPrefix()) ? "" : ftpClientHelper.configure.getPrefix();
if (!filePath.startsWith(File.separator)){
filePath = File.separator + filePath;
}
if (!filePath.endsWith(File.separator)){
filePath += File.separator;
}
filePath += business + File.separator;
filePath += new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + File.separator;
return filePath;
}
/**
* 判断ftp服务器文件是否存在
* @param path path
* @return boolean
*/
public static boolean existFile(String path){
log.info("==============校验FTP文件是否存在:{}=============", path);
long startTime = System.currentTimeMillis();
boolean flag;
FTPClient client = getClient();
try {
flag = existFile(client, path);
} finally {
releaseClient(client);
}
long endTime = System.currentTimeMillis();
log.info("==============校验FTP文件:{}完成,结果:{},用时:{}=============", path, flag, (endTime - startTime) + "ms");
return flag;
}
/**
* 判断ftp服务器文件是否存在
* @param client client
* @param path path
* @return boolean
*/
private static boolean existFile(FTPClient client, String path){
boolean flag = false;
FTPFile[] ftpFileArr = new FTPFile[0];
try {
ftpFileArr = client.listFiles(path);
} catch (IOException e) {
log.info(e.getMessage());
}
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
/**
* 改变目录路径
* @param client client
* @param directory directory
* @return boolean
*/
private static boolean changeWorkingDirectory(FTPClient client, String directory) {
try {
return client.changeWorkingDirectory(directory);
} catch (IOException ioe) {
log.info(ioe.getMessage());
throw new BusinessException(-100, "改变目录路径异常!");
}
}
/**
* 创建目录 单个不可递归
* @param client client
* @param pathName ftp路径
* @return boolean
* @throws IOException e
*/
private static boolean createDirectory(FTPClient client, String pathName) throws IOException {
return client.makeDirectory(pathName);
}
/**
* 删除目录,单个不可递归
* @param pathName ftp路径
* @return boolean
* @throws Exception e
*/
public static boolean removeDirectory(String pathName) throws Exception {
FTPClient client = getClient();
try {
return client.removeDirectory(pathName);
} finally {
releaseClient(client);
}
}
/**
* 删除文件 单个 ,不可递归
* @param pathName ftp资源文件路径
* @return boolean
* @throws Exception e
*/
public static boolean deleteFile(String pathName) throws Exception {
FTPClient client = getClient();
try {
return client.deleteFile(pathName);
} finally {
releaseClient(client);
}
}
/**
* 释放连接
* @param client client
*/
private static void releaseClient(FTPClient client) {
if (client == null) {
return;
}
try {
client.logout();
client.disconnect();
} catch (Exception io) {
log.info(io.getMessage());
}
}
@Override
public void close() throws Exception {
// TODO Auto-generated method stub
log.info("---Resources Closed---.");
}
}
package org.nafmii.common.ftp;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.nafmii.common.config.EncryptConfig;
import org.nafmii.common.constant.MessageEnum;
import org.nafmii.common.exception.BusinessException;
import org.springframework.util.StringUtils;
import javax.validation.constraints.NotEmpty;
import java.io.File;
/**
* @author by zhangbr
* @date 2020/7/25
*/
@Slf4j
@Data
public class FileDownLoadForm {
@ApiModelProperty("附件ID")
@NotEmpty(message = "附件ID不能为空")
private String fileId;
public String encodeFileId() {
if (!StringUtils.isEmpty(fileId)){
try {
return EncryptConfig.decrypt(fileId);
} catch (EncryptionOperationNotPossibleException e) {
log.info("======文件ID解码失败======");
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
}
return null;
}
public String encodeFileName(){
if (!StringUtils.isEmpty(fileId)){
try {
String filePath = EncryptConfig.decrypt(fileId);
if (!StringUtils.isEmpty(filePath)){
String fileName = filePath;
if (filePath.lastIndexOf(File.separator) >= 0){
fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
}
return fileName;
}
} catch (EncryptionOperationNotPossibleException e) {
log.info("======文件名称解码失败======");
throw new BusinessException(MessageEnum.FILE_DOWN_FAIL.getCode(), MessageEnum.FILE_DOWN_FAIL.getRemarks());
}
}
return null;
}
}
package org.nafmii.common.ftp;
import io.swagger.annotations.ApiModelProperty;
import org.nafmii.common.config.EncryptConfig;
import org.springframework.util.StringUtils;
/**
* @author by zhangbr
* @date 2020/7/25
*/
public class FileVO {
public FileVO(String fileId, String fileName) {
if (!StringUtils.isEmpty(fileId)){
this.fileId = EncryptConfig.encrypt(fileId);
}
this.fileName = fileName;
}
@ApiModelProperty("附件ID")
private String fileId;
@ApiModelProperty("附件名称")
private String fileName;
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
if (!StringUtils.isEmpty(fileId)){
this.fileId = EncryptConfig.encrypt(fileId);
}
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
@Override
public String toString() {
return "FileVO{" +
"fileId='" + fileId + '\'' +
'}';
}
}
package org.nafmii.utils; package org.nafmii.common.param;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.github.pagehelper.Page;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -12,11 +12,14 @@ import java.util.List; ...@@ -12,11 +12,14 @@ import java.util.List;
* @date 2020/3/26. * @date 2020/3/26.
*/ */
public class BeanTransferUtils { public class BeanTransferUtils {
public static <T> T transfer(Object text, Class<T> clazz) { public static <T> T transfer(Object text, Class<T> clazz) {
T t; T t;
try { try {
t = clazz.newInstance(); t = clazz.newInstance();
if (text != null){
org.springframework.beans.BeanUtils.copyProperties(text, t); org.springframework.beans.BeanUtils.copyProperties(text, t);
}
return t; return t;
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
...@@ -33,32 +36,19 @@ public class BeanTransferUtils { ...@@ -33,32 +36,19 @@ public class BeanTransferUtils {
} }
return result; return result;
} }
public static <T> PageResult<T> toPagedResult(List<?> list, Class<T> clazz) {
public static <T> PagedResult<T> toPagedResult(List<T> list, Page page) { PageResult<T> result = new PageResult();
PagedResult<T> result = new PagedResult<>(); if (list instanceof Page) {
if (list != null && !list.isEmpty()){ Page page = (Page)list;
result.setList(list);
if (page != null){
result.setTotal(page.getTotal()); result.setTotal(page.getTotal());
}else { } else if (list != null) {
result.setTotal(list.size()); result.setTotal((long)list.size());
}
}
return result;
} }
public static <T> PagedResult<T> toPagedResult(List<?> list, Class<T> clazz, Page page) { if (list != null && !list.isEmpty()) {
PagedResult<T> result = new PagedResult<>(); result.setList(transferList(list, clazz));
if (page != null){
result.setTotal(page.getTotal());
}else {
if (list != null){
result.setTotal(list.size());
}
}
if (list != null && !list.isEmpty()){
result.setList(BeanTransferUtils.transferList(list, clazz));
} }
return result; return result;
} }
} }
package org.nafmii.common.param;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
/**
* @author by zhangbr
* @date 2020/6/24.
*/
public class PageQuery {
@ApiModelProperty("当前页码")
@NotNull(message = "页码不能为空")
private Integer pageNum = 1;
@ApiModelProperty("每页显示条数,默认30")
@NotNull(message = "每页条数不能为空")
private Integer pageSize = 30;
@ApiModelProperty(value = "是否分页,默认:true")
private Boolean isPage = true;
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Boolean getPage() {
return isPage;
}
public void setPage(Boolean page) {
isPage = page;
}
}
package org.nafmii.common.param;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* @author by zhangbr
* @date 2020/4/3.
*/
public class PageResult<T> {
@ApiModelProperty("数据")
private List<T> list;
@ApiModelProperty("总条数")
private long total;
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
}
package org.nafmii.common.response;
import java.io.Serializable;
/**
* @author lvyp
* @date 2021/4/26
*/
public class ApiResponse <T> implements Serializable {
private static final long serialVersionUID = 1L;
public static final int SUCCESS = 0;
public static final int FAIL = -1;
public static final int BUSY = -100;
public static final String SUCCESS_TEXT = "Success";
public static final String FAIL_TEXT = "Fail";
public static final String BUSY_TEXT = "Busy";
private long status;
private String statusText;
private T data;
public ApiResponse() {
this.status = 0L;
this.statusText = "Success";
}
public ApiResponse(long status, String statusText, T data) {
this.status = status;
this.statusText = statusText;
this.data = data;
}
public ApiResponse(long status, String statusText) {
this.status = status;
this.statusText = statusText;
}
public ApiResponse(T data) {
this.status = 0L;
this.statusText = "Success";
this.data = data;
}
public ApiResponse<T> fail(String msg){
return new ApiResponse<>(-1,msg);
}
public long getStatus() {
return this.status;
}
public void setStatus(long status) {
this.status = status;
if (status == 0L) {
this.statusText = "Success";
} else if (status == -100L) {
this.statusText = "Busy";
} else {
this.statusText = "";
}
}
public String getStatusText() {
return this.statusText;
}
public void setStatusText(String statusText) {
this.statusText = statusText;
}
public Object getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public static <M> ApiResponse<M> ok() {
return new ApiResponse();
}
public static <T> ApiResponse<T> ok(T data) {
return new ApiResponse(data);
}
}
package org.nafmii.result; package org.nafmii.common.response;
import com.github.pagehelper.PageInfo; import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
......
package org.nafmii.common.response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
/**
* @author lvyp
* @date 2021/4/26
*/
@Component
public class Springs implements ApplicationListener {
@Autowired
private ApplicationContext applicationContext;
private static ApplicationContext context;
public Springs() {
}
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof ContextRefreshedEvent) {
this.setContextStatic();
}
}
private synchronized void setContextStatic() {
context = this.applicationContext;
}
public static <T> T getBean(Class<? extends T> beanClass, String beanName) {
assertContextNotNull();
return context.getBean(beanName, beanClass);
}
public static Object getBean(String beanName) {
assertContextNotNull();
return context.getBean(beanName);
}
public static <T> T getBean(Class<? extends T> beanClass) {
assertContextNotNull();
return context.getBean(beanClass);
}
private static void assertContextNotNull() {
Assert.notNull(context, "The spring applicationContext was not initialized");
}
}
package org.nafmii.common.utils;
import com.github.pagehelper.Page;
import org.nafmii.common.param.PageResult;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author by zhangbr
* @date 2020/3/26.
*/
public class BeanTransferUtils {
public static <T> T transfer(Object text, Class<T> clazz) {
T t;
try {
t = clazz.newInstance();
if (text != null){
org.springframework.beans.BeanUtils.copyProperties(text, t);
}
return t;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> transferList(List<?> list, Class<T> clazz) {
if(CollectionUtils.isEmpty(list)){
return Collections.emptyList();
}
List<T> result =new ArrayList<>();
for(Object each : list) {
result.add(transfer(each,clazz));
}
return result;
}
public static <T> PageResult<T> toPagedResult(List<?> list, Class<T> clazz) {
PageResult<T> result = new PageResult();
if (list instanceof Page) {
Page page = (Page)list;
result.setTotal(page.getTotal());
} else if (list != null) {
result.setTotal((long)list.size());
}
if (list != null && !list.isEmpty()) {
result.setList(transferList(list, clazz));
}
return result;
}
}
package org.nafmii.utils; package org.nafmii.common.utils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
......
//package org.nafmii.common.utils;
//
//import com.alibaba.excel.util.DateUtils;
//import com.google.common.collect.Maps;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.FileUtils;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.net.ftp.FTPClient;
//import org.apache.commons.net.ftp.FTPFile;
//import org.apache.commons.net.ftp.FTPReply;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.web.multipart.MultipartFile;
//import org.springframework.web.multipart.MultipartHttpServletRequest;
//import org.springframework.web.multipart.commons.CommonsMultipartResolver;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.*;
//import java.net.MalformedURLException;
//import java.nio.charset.StandardCharsets;
//import java.util.*;
//
///**
// * @author:zhoujh
// * @Function:TODO
// * @date 2020/5/21 15:13
// * @ClassName:
// * @version:
// * @remark:
// */
//@Slf4j
//@Configuration
//public class FtpUtil {
// /**访问地址*/
// @Value("${ftp.att.upload.path}")
// private static String path;
//
// /**存放地址*/
// @Value("${ftp.att.upload.docBase}")
// private static String docBase;
//
// //ftp服务器地址
// @Value("${ftp.att.hostname}")
// private String hostname;
// //ftp服务器端口号默认为21
// @Value("${ftp.att.port}")
// private Integer port;
// //ftp登录账号
// @Value("${ftp.att.username}")
// private String username;
// //ftp登录密码
// @Value("${ftp.att.password}")
// private String password;
//
// public FTPClient ftpClient = null;
//
// public Map<String, Object> upload(HttpServletRequest request){
// final Map<String, Object> result = new HashMap<>();
// //初始化多部份解析器
// CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// //检查了request是否为null,请求是否为post,form中是否有enctype="multipart/form-data"
// if(multipartResolver.isMultipart(request)){
// //转换为多部份request
// MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// //获取multiRequest中所有文件名
// Iterator it = multiRequest.getFileNames();
// while (it.hasNext()){
// MultipartFile file = multiRequest.getFile(it.next().toString());
// if(file != null){
// //获取文件名
// String fileName = file.getOriginalFilename();
// // 文件后缀
// String suffixes = fileName.substring(fileName.lastIndexOf("."));
// // 重命名文件
// String nowName = getNewName(suffixes);
// final ByteArrayOutputStream fileStream = new ByteArrayOutputStream();
// // 存放位置
// String savePath = getFilePath(docBase, nowName);
// try {
// // 复制文件内容
// IOUtils.copy(file.getInputStream(), fileStream);
// //向session中存入文件内容的引用,为保存文件做准备
// request.getSession().setAttribute(nowName,fileStream);
// // 复制文件
// FileUtils.copyInputStreamToFile(new ByteArrayInputStream(fileStream.toByteArray()), new File(savePath));
// } catch (Exception e) {
// return null;
// }
// result.put("nowName",nowName);
// result.put("savePath",savePath);
// result.put("fileSize",file.getSize());
// result.put("url",getFilePath(path,nowName));
// } else {
// return result;
// }
// }
// }
// return result;
// }
//
// public static Map<String, String> upload(String imgBase64){
// log.info("==============开始上传图片=============");
// Map<String, String> result = new HashMap<>();
// if(imgBase64 != null){
// // 文件后缀
// String suffixes = ".jpg";
// // 重命名
// String nowName = getNewName(suffixes);
// // 存放位置
// String savePath = getFilePath(docBase, nowName);
// try {
//// IOUtils.copy(file.getInputStream(), fileStream);
// mkdir(savePath.substring(0,savePath.lastIndexOf("/")));
// FtpUtil.base64MultipartFile(imgBase64,savePath);
//// file.transferTo(new File(savePath));
// log.info("==============上传成功==============");
// } catch (Exception e) {
// log.error("==============出现异常,上传失败==============");
// return null;
// }
// result.put("nowName",nowName);
// result.put("path",getFilePath(nowName));
// result.put("savePath",savePath);
//// result.put("url",getFilePath(path,nowName));
// }
// return result;
// }
//
// public static void main(String[] args) {
// FtpUtil ft = new FtpUtil();
// ft.initFtpClient();
// }
// /**
// * 初始化ftp服务器
// */
// public void initFtpClient() {
// hostname="192.168.202.38";
// port = 21;
// username = "ypenglv";
// password = "peng1003";
// ftpClient = new FTPClient();
// ftpClient.setControlEncoding("utf-8");
// try {
// log.info("...ftp服务器:connecting"+hostname+":"+port+"...."+ DateUtils.format(new Date()));
// ftpClient.connect(hostname, port); //连接ftp服务器
// if(!ftpClient.isConnected()){
// ftpClient.connect(hostname, port);
// }
// ftpClient.login(username, password); //登录ftp服务器
// int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
// if(!FTPReply.isPositiveCompletion(replyCode)){
// log.info("connect failed...ftp服务器:"+hostname+":"+port+"...."+DateUtils.format(new Date()));
// }
// log.info("connect successfu...ftp服务器:"+hostname+":"+port+"...."+DateUtils.format(new Date()));
// }catch (MalformedURLException e) {
// e.printStackTrace();
// }catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * 上传文件
// * @param pathname ftp服务保存地址
// * @param fileName 上传到ftp的文件名
// * @param originfilename 待上传文件的名称(绝对地址) *
// * @return
// */
// public boolean uploadFile( String pathname, String fileName,String originfilename){
// boolean flag = false;
// InputStream inputStream = null;
// try{
// log.info("开始上传文件");
// inputStream = new FileInputStream(new File(originfilename));
// initFtpClient();
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// CreateDirecroty(pathname);
// ftpClient.makeDirectory(pathname);
// ftpClient.changeWorkingDirectory(pathname);
// ftpClient.storeFile(fileName, inputStream);
// inputStream.close();
// ftpClient.logout();
// flag = true;
// log.info("上传文件成功");
// }catch (Exception e) {
// log.info("上传文件失败");
// e.printStackTrace();
// }finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// if(null != inputStream){
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// return true;
// }
// /**
// * 上传文件
// * @param path ftp服务保存地址
// * @param fileName 上传到ftp的文件名重命名的文件名
// * @param inputStream 输入文件流
// * @return
// */
// public Map<Boolean,String> uploadArrFile(String path, LinkedList<String> fileName, LinkedList<InputStream> inputStream){
// boolean flag = false;
// Map<Boolean,String> map = Maps.newHashMap();
// String realPath = "";
// try{
// log.info("======开始上传文件======");
// log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
// initFtpClient();
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// realPath = path + "/" + fileName;
// CreateDirecroty(path);
// ftpClient.makeDirectory(path);
// ftpClient.changeWorkingDirectory(path);
// for(int i=0;i<fileName.size();i++){
// ftpClient.storeFile(fileName.get(i), inputStream.get(i));
// inputStream.get(i).close();
// }
// ftpClient.logout();
// flag = true;
// log.info("======上传文件成功======");
// }catch (Exception e) {
// log.error("======上传文件失败======");
// e.printStackTrace();
// }finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// for(int i=0;i<inputStream.size();i++){
// if(null != inputStream.get(i)){
// try {
// inputStream.get(i).close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// }
// map.put(flag,realPath);
// return map;
// }
// /**
// * 上传文件
// * @param path ftp服务保存地址
// * @param fileName 上传到ftp的文件名重命名的文件名
// * @param inputStream 输入文件流
// * @return
// */
// public Map<Boolean,String> uploadFile(String path, String fileName, InputStream inputStream){
// boolean flag = false;
// Map<Boolean,String> map = Maps.newHashMap();
// String realPath = "";
// try{
// log.info("======开始上传文件======");
// log.info("======上传文件地址======"+path+"====系统存储文件名=="+fileName);
// initFtpClient();
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// realPath = path + "/" + fileName;
// CreateDirecroty(path);
// ftpClient.makeDirectory(path);
// ftpClient.changeWorkingDirectory(path);
// ftpClient.storeFile(fileName, inputStream);
// inputStream.close();
// ftpClient.logout();
// flag = true;
// log.info("======上传文件成功======");
// }catch (Exception e) {
// log.error("======上传文件失败======");
// e.printStackTrace();
// }finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// if(null != inputStream){
// try {
// inputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// map.put(flag,realPath);
// return map;
// }
// //改变目录路径
// public boolean changeWorkingDirectory(String directory) {
// boolean flag = true;
// try {
// flag = ftpClient.changeWorkingDirectory(directory);
// } catch (IOException ioe) {
// ioe.printStackTrace();
// }
// return flag;
// }
//
// //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
// public boolean CreateDirecroty(String remote) throws IOException {
// boolean success = true;
// String directory = remote + "/";
// // 如果远程目录不存在,则递归创建远程服务器目录
// if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(directory)) {
// int start = 0;
// int end = 0;
// if (directory.startsWith("/")) {
// start = 1;
// } else {
// start = 0;
// }
// end = directory.indexOf("/", start);
// String path = "";
// String paths = "";
// while (true) {
// String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), StandardCharsets.ISO_8859_1);
// path = path + "/" + subDirectory;
// if (!existFile(path)) {
// if (makeDirectory(subDirectory)) {
// changeWorkingDirectory(subDirectory);
// } else {
// log.info("创建目录[" + subDirectory + "]失败");
// changeWorkingDirectory(subDirectory);
// }
// } else {
// changeWorkingDirectory(subDirectory);
// }
//
// paths = paths + "/" + subDirectory;
// start = end + 1;
// end = directory.indexOf("/", start);
// // 检查所有目录是否创建完毕
// if (end <= start) {
// break;
// }
// }
// }
// return success;
// }
//
// //判断ftp服务器文件是否存在
// public boolean existFile(String path) throws IOException {
// boolean flag = false;
// FTPFile[] ftpFileArr = ftpClient.listFiles(path);
// if (ftpFileArr.length > 0) {
// flag = true;
// }
// return flag;
// }
// //创建目录
// public boolean makeDirectory(String dir) {
// boolean flag = true;
// try {
// flag = ftpClient.makeDirectory(dir);
// } catch (Exception e) {
// e.printStackTrace();
// }
// return flag;
// }
//
// /** * 下载文件 *
// * @param pathname FTP服务器文件目录 *
// * @param filename 文件名称 *
// * @param localpath 下载后的文件路径 *
// * @return */
// public boolean downloadFile(String pathname, String filename, String localpath){
// boolean flag = false;
// OutputStream os=null;
// try {
// log.info("======开始下载文件======");
// initFtpClient();
// //切换FTP目录
// ftpClient.changeWorkingDirectory(pathname);
// FTPFile[] ftpFiles = ftpClient.listFiles();
// for(FTPFile file : ftpFiles){
// if(filename.equalsIgnoreCase(file.getName())){
// File localFile = new File(localpath + "/" + file.getName());
// os = new FileOutputStream(localFile);
// ftpClient.retrieveFile(file.getName(), os);
// os.close();
// }
// }
// ftpClient.logout();
// flag = true;
// log.info("======下载文件成功======");
// } catch (Exception e) {
// log.error("======下载文件失败======");
// e.printStackTrace();
// } finally{
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// if(null != os){
// try {
// os.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// return flag;
// }
//
// /** * 删除文件 *
// * @param pathname FTP服务器保存目录 *
// * @param filename 要删除的文件名称 *
// * @return */
// public boolean deleteFile(String pathname, String filename){
// boolean flag = false;
// try {
// log.info("======开始删除文件======");
// initFtpClient();
// //切换FTP目录
// ftpClient.changeWorkingDirectory(pathname);
// ftpClient.dele(filename);
// ftpClient.logout();
// flag = true;
// log.info("======删除文件成功======");
// } catch (Exception e) {
// log.error("======删除文件失败======");
// e.printStackTrace();
// } finally {
// if(ftpClient.isConnected()){
// try{
// ftpClient.disconnect();
// }catch(IOException e){
// e.printStackTrace();
// }
// }
// }
// return flag;
// }
//
// public static void mkdir(String path) {
// File dir = new File(path);
// if (dir.exists()) {
// if (!dir.isFile()) {
// return;
// }
// dir.delete();
// }
// dir.mkdirs();
// }
//
// /**
// * 获取文件绝对路径
// * @param request
// * @param host
// * @return
// */
// public static String getFileUrl(HttpServletRequest request, String host) {
// String path = request.getScheme() + "://" + host + request.getContextPath() + "/";
// int port = request.getServerPort();
// if (80 != port) {
// path = request.getScheme() + "://" + host + ":" + request.getServerPort() + request.getContextPath() + "/";
// }
// return path;
// }
//
// /**
// * 文件路径
// * @param pathname
// * @return
// */
// public static String getFilePath(String pathname) {
// StringBuilder sb = new StringBuilder().append(DateUtils.format(new Date())).append("/").append(pathname);
// return sb.toString();
// }
//
// /**
// * 文件路径
// * @param filepath
// * @param filename
// * @return
// */
// public static String getFilePath(String filepath, String filename) {
// StringBuilder sb = new StringBuilder(filepath).append(DateUtils.format(new Date())).append("/").append(filename);
// return sb.toString();
// }
//
// /**
// * 文件重命名
// * @param suffixes
// * @return
// */
// public static String getNewName(String suffixes){
// return UUID.randomUUID().toString().replaceAll("\\-", "") + suffixes;
// }
//
// /**
// * 删除文件
// * @param path
// */
// public static void delFiles(String path) {
// File file = new File(path);
// if (file.exists()) {
// file.delete();
// }
// }
// public static boolean base64MultipartFile(String imgStr, String imagePath){
// if (imgStr == null){
// return false;
// }
// try {
// String[] baseStr = imgStr.split(",");
// Base64.Decoder decoder= Base64.getMimeDecoder();
// byte[] b = new byte[0];
// b = decoder.decode(baseStr[1]);
// for(int i = 0; i < b.length; ++i) {
// if (b[i] < 0) {
// b[i] += 256;
// }
// }
// OutputStream out = new FileOutputStream(imagePath);
// out.write(b);
// out.flush();
// out.close();
// return true;
// }catch (Exception e){
// e.printStackTrace();
// return false;
// }
// }
//}
package org.nafmii.common.utils;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author lvyp
* @date 2021/2/19
*/
public class GeneratorCodeConfig {
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF8&useSSL=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("Moxi123#");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
String moduleName = scanner("模块名");
pc.setParent(scanner("包名"));
pc.setController("controller");
pc.setEntity("entity");
pc.setMapper("dao");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir")+"/"+moduleName;
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("zjh");
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
gc.setEntityName("%sPO");
gc.setMapperName("%sMapper");
//实体属性 Swagger2 注解
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
//String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath +"/src/main/resources/mapper/"+ tableInfo.getEntityName().substring(0,tableInfo.getEntityName().length()-2) + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
templateConfig.setEntity("/templates/entity.java");
templateConfig.setController("/templates/controller.java");
templateConfig.setService("/templates/service.java");
templateConfig.setServiceImpl("/templates/serviceImpl.java");
templateConfig.setXml(null);
templateConfig.setMapper("/templates/mapper.java");
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setTablePrefix("t_"); // 该设置可以截取表名中的前缀字段
strategy.setEntityTableFieldAnnotationEnable(true);
// 公共父类
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
package org.nafmii.common.utils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.Synchronized;
import java.util.concurrent.TimeUnit;
/**
* @Author: zjh
* @Date: 2020/7/8 13:28
* @Description:
*/
public class GuavaUtil {
private static Cache<String, Object> guavaCache;
private static Cache<String, Object> guavaCacheForFaceData;
public GuavaUtil() {
}
/**
* 跟踪连缓存
* @return
*/
public static Cache<String, Object> getGuavaCache() {
if (guavaCache == null) {
guavaCache = CacheBuilder.newBuilder().concurrencyLevel(10)
// 存活时间 10 分钟
.expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(100000000).build();
}
return guavaCache;
}
/**
*
* @return
*/
public static Cache<String, Object> getGuavaCacheForFaceData() {
if (guavaCacheForFaceData == null) {
guavaCacheForFaceData = CacheBuilder.newBuilder().concurrencyLevel(10)
.expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100000000).build();
}
return guavaCacheForFaceData;
}
@Synchronized
public static Object putTrackGuava(String str, Object obj){
if (guavaCache == null) {
guavaCache = CacheBuilder.newBuilder().concurrencyLevel(10)
.expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100000000).build();
}
return guavaCache.asMap().put(str,obj);
}
public static Object getTrackGuava(String str){
if (guavaCache == null) {
guavaCache = CacheBuilder.newBuilder().build();
}
return guavaCache.asMap().get(str);
}
public static void deleteTrackGuava(String str){
guavaCache =CacheBuilder.newBuilder().build();
guavaCache.invalidate(str);
}
@Synchronized
public static Object putFaceGuava(String str, Object obj){
return guavaCacheForFaceData.asMap().put(str,obj);
}
public static Object getFaceGuava(String str){
return guavaCacheForFaceData.asMap().get(str);
}
public static void deleteFaceGuava(String str){
guavaCacheForFaceData.invalidate(str);
}
public static void main(String[] args) {
// Cache<String, Object> guavaCache = GuavaUtil.getGuavaCache();
//
// guavaCache.asMap().put("asd","asd");
// String asd = (String) guavaCache.asMap().get("asd");
// System.out.println(asd);
GuavaUtil.putTrackGuava("test","1");
String test = (String) GuavaUtil.getTrackGuava("test");
System.out.println(test);
}
}
package org.nafmii.common.utils;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author lvyp
* @date 2021/4/27
*/
public class IpUtils extends ClassicConverter {
public IpUtils() {
}
public String convert(ILoggingEvent event) {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
}
package org.nafmii.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
* Created by zhangzhenfang on 2018/6/5.
*/
public class JsonUtils {
private static final SerializeConfig config;
static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null
};
public static String toJsonString(Object object) {
return JSON.toJSONString(object, config, features);
}
// public static String toJSONNoFeatures(Object object) {
// return JSON.toJSONString(object, config);
// }
public static Object parse(String text) {
return JSON.parse(text);
}
public static <T> T parse(String text, Class<T> clazz) {
return JSON.parseObject(text, clazz);
}
}
package org.nafmii.common.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.nafmii.common.constant.HttpClientHeaderEnum;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* zjh
*/
@Slf4j
public class JwtUtils {
public static final String TOKEN_HEADER = "Authorization";
public static final long EXPIRITION = 1000 * 60 * 60 * 24 * 7;
// public static final long EXPIRITION = 1000 * 60;
public static final String APPSECRET_KEY = "qwertyuiop123456780";
public static String generateJsonWebToken(Map<String,Object> param,long timeOut) {
if(timeOut < 0){
timeOut = EXPIRITION;
}
if (param.isEmpty()) {
return null;
}
return Jwts
.builder()
.claim(HttpClientHeaderEnum.USER_VO.getCode(),param)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + timeOut))
.signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact();
}
public static Claims checkJWT(String token) {
try {
final Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
     * 获取用户信息
     * @param token
     * @return
     */
public static Claims getUserInfo(String token){
return Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
}
/**
   * 是否过期
   * @param token
   * @return
   */
public static boolean isExpiration(String token){
try {
Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody();
return claims.getExpiration().before(new Date());
} catch (Exception e){
log.error("令牌已过期");
return true;
}
}
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
map.put("userId",12312321313L);
String token = generateJsonWebToken(map,EXPIRITION);
System.out.println(token);
Claims claims = getUserInfo(token);
Map<String,Object> map1 = (Map<String, Object>) claims.get(HttpClientHeaderEnum.USER_VO.getCode());
System.out.println(map.get(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode()));
System.out.println(isExpiration(token));
}
}
package org.nafmii.common.utils;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* @author by zhangbr
* @date 2020/4/3.
*/
public class PageResult<T> {
@ApiModelProperty("数据")
private List<T> list;
@ApiModelProperty("总条数")
private long total;
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
}
package org.nafmii.utils; package org.nafmii.common.utils;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
......
package org.nafmii.utils; package org.nafmii.common.utils;
import org.nafmii.constant.HttpClientHeaderEnum; import org.apache.commons.lang.StringUtils;
import org.nafmii.constant.MessageEnum; import org.nafmii.common.constant.MessageEnum;
import org.nafmii.exception.BusinessException; import org.nafmii.common.constant.HttpClientHeaderEnum;
import org.springframework.util.StringUtils; import org.nafmii.common.exception.BusinessException;
import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public class RequestUtils { public class RequestUtils {
...@@ -25,15 +27,21 @@ public class RequestUtils { ...@@ -25,15 +27,21 @@ public class RequestUtils {
} }
public static Long getUserId(){ public static Long getUserId(){
String userId = getRequest().getHeader(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode()); //token 获取用户信息
if (!StringUtils.isEmpty(userId)){ String token = getToken();
if (StringUtils.isBlank(token)){
throw new BusinessException("令牌不能为空");
}
Map<String,Object> map = (Map<String, Object>) JwtUtils.getUserInfo(token).get(HttpClientHeaderEnum.USER_VO.getCode());
String userId = map.get(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode()).toString();
if (StringUtils.isNotBlank(userId)){
try { try {
return Long.valueOf(userId); return Long.valueOf(userId);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
return null; return null;
} }
} }
return null; throw new BusinessException("用户主键不能为空");
} }
public static String getToken(){ public static String getToken(){
......
package org.nafmii.common.utils;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* @description: 雪花算法
* @author: DINGZIYAO
* @date: 2020/9/14 13:59
* @version: v1.0
*/
public class SnowFlakeUtil {
private final static long TWEPOCH = 12888349746579L;
// 机器标识位数
private final static long WORKER_ID_BITS = 5L;
// 数据中心标识位数
private final static long DATACENTER_ID_BITS = 5L;
// 毫秒内自增位数
private final static long SEQUENCE_BITS = 12L;
// 机器ID偏左移12位
private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
// 数据中心ID左移17位
private final static long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
// 时间毫秒左移22位
private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
//sequence掩码,确保sequnce不会超出上限
private final static long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);
//上次时间戳
private static long lastTimestamp = -1L;
//序列
private long sequence = 0L;
//服务器ID
private long workerId = 1L;
private static final long WORKER_MASK = ~(-1L << WORKER_ID_BITS);
//进程编码
private long processId = 1L;
private static final long PROCESS_MASK = ~(-1L << DATACENTER_ID_BITS);
private static SnowFlakeUtil snowFlake = null;
static{
snowFlake = new SnowFlakeUtil();
}
public static synchronized long nextId(){
return snowFlake.getNextId();
}
private SnowFlakeUtil() {
//获取机器编码
this.workerId=this.getMachineNum();
//获取进程编码
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
this.processId= Long.parseLong(runtimeMXBean.getName().split("@")[0]);
//避免编码超出最大值
this.workerId=workerId & WORKER_MASK;
this.processId=processId & PROCESS_MASK;
}
public synchronized long getNextId() {
//获取时间戳
long timestamp = timeGen();
//如果时间戳小于上次时间戳则报错
if (timestamp < lastTimestamp) {
try {
throw new Exception("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
} catch (Exception e) {
e.printStackTrace();
}
}
//如果时间戳与上次时间戳相同
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1,与sequenceMask确保sequence不会超出上限
sequence = (sequence + 1) & SEQUENCE_MASK;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (processId << DATACENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT) | sequence;
return nextId;
}
/**
* 再次获取时间戳直到获取的时间戳与现有的不同
* @param lastTimestamp
* @return 下一个时间戳
*/
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* 获取机器编码
* @return
*/
private long getMachineNum(){
long machinePiece;
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = null;
try {
e = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e1) {
e1.printStackTrace();
}
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
sb.append(ni.toString());
}
machinePiece = sb.toString().hashCode();
return machinePiece;
}
public static void main(String[] args) {
System.out.println(SnowFlakeUtil.nextId());
// 8073480304000524288
// 8073480926335623168
}
}
package org.nafmii.utils; package org.nafmii.common.utils;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
...@@ -6,10 +6,7 @@ import org.springframework.context.ApplicationContextAware; ...@@ -6,10 +6,7 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Component @Component
...@@ -37,9 +34,4 @@ public class SpringUtils implements ApplicationContextAware { ...@@ -37,9 +34,4 @@ public class SpringUtils implements ApplicationContextAware {
return requestAttrs.getRequest(); return requestAttrs.getRequest();
} }
public static String getMessage(String code, Object... args) {
LocaleResolver localeResolver = getBean(LocaleResolver.class);
Locale locale = localeResolver.resolveLocale(getCurrentReq());
return applicationContext.getMessage(code, args, locale);
}
} }
package org.nafmii.common.utils;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* String字符串操作工具类
* @author sea
* @version 1.2.0
*/
public class StringUtil {
/**
* 过滤文本HTML标签
* @param html
* @return
*/
public static String removeHTML(String html){
String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式
Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
Matcher m_script=p_script.matcher(html);
html=m_script.replaceAll(""); //过滤script标签
Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
Matcher m_style=p_style.matcher(html);
html=m_style.replaceAll(""); //过滤style标签
Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
Matcher m_html=p_html.matcher(html);
html=m_html.replaceAll(""); //过滤html标签
return html.trim(); //返回文本字符串
}
/**
* 判断字符是否为null,为null就返回空字符串
* @param object
* @return
*/
public static String getEmptyString(Object object){
try {
if(object==null){
return "";
}
String content=String.valueOf(object);
return content;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 判断字符是否为null,为null就返回false
* @param object
* @return
*/
public static boolean isEmptyString(Object object){
return object != null && !"".equals(object.toString().trim());
}
/**
* 校验日期格式
* @param pattern
* @param dateString
* @return
*/
public static boolean isValidDateFormat(String pattern, String dateString) {
try {
SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
format.setLenient(false);
format.parse(dateString);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 判断对象的值是否包含在该目标数组中(数组为空时候,只判断对象自己)
* @param object
* @param filters
* @return
*/
public static boolean isContain(Integer object,int[] filters){
if(object==null){
return false;
}
if(filters!=null && filters.length>0){
for (int i = 0; i <filters.length ; i++) {
if(object.intValue()==filters[i]){
return true;
}
}
return false;
}
return true;
}
/**
* 获取相应的显示格式时候
* @param dateTime
* @return
*/
public static String getShowDate(String dateTime){
String createDate="";
try {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
SimpleDateFormat formatShow=new SimpleDateFormat("MM-dd HH:mm");
Date oldDate=format.parse(dateTime);
Date nowDate=new Date();
long longTime=nowDate.getTime()-oldDate.getTime();
long day=longTime/(24*60*60*1000);
long hour=(longTime/(60*60*1000)-day*24);
long min=((longTime/(60*1000))-day*24*60-hour*60);
long s=(longTime/1000-day*24*60*60-hour*60*60-min*60);
if(day>0){
createDate=formatShow.format(oldDate);
}else{
if(hour>0){
createDate=hour+"小时前";
}else{
if(min>0){
createDate=min+"分钟前";
}else{
createDate=s+"秒前";
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
return createDate;
}
/**
* 获取时间天数
* @param startDate
* @param endDate
* @return
*/
public static Long getDay(String startDate,String endDate) {
try {
if(!StringUtil.isEmptyString(startDate) || !StringUtil.isEmptyString(endDate)){
return -10000L;
}
if(startDate.length()>20){
startDate=startDate.substring(0, 20);
}
if(endDate.length()>20){
endDate=endDate.substring(0, 20);
}
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd",Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date oldDate=format.parse(startDate);
Date nowDate=format.parse(endDate);
return getDay(oldDate,nowDate);
} catch (Exception e) {
return -10000L;
}
}
/**
* 获取时间天数
* @param startDate
* @param endDate
* @return
*/
public static Long getDay(Date startDate,Date endDate) {
try {
long longTime=endDate.getTime()-startDate.getTime();
long day=longTime/(24*60*60*1000);
return day;
} catch (Exception e) {
return -10000L;
}
}
/**
* unicode转UTF-8
* @param theString
* @return
*/
public static String unicodeToUtf8(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
/**
* ISO-8859-1 转 UTF-8
* @param content
* @return
*/
public static String isoToUtf8(String content) {
if(!StringUtil.isEmptyString(content)){
return content;
}
try {
content=new String(content.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
/**
* 保留小数点后两位数字
* @param number
* @return
*/
public static String doubleFormatByTwo(Double number) {
if(number==null){
return "";
}
if(number.doubleValue()==0){
return "0";
}
DecimalFormat df = new DecimalFormat("0.00");
return df.format(number);
}
/**
* 保留小数点后两位数字(不保留四舍五入)
* @param number
* @return
*/
public static String doubleFormatByTwoA(Double number) {
if(number==null){
return "";
}
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setGroupingSize(0);
df.setRoundingMode(RoundingMode.FLOOR);
return df.format(number);
}
/**
* 保留小数点后一位数字
* @param number
* @return
*/
public static String doubleFormatByOne(Double number) {
if(number==null){
return "";
}
if(number.doubleValue()==0){
return "0";
}
DecimalFormat df = new DecimalFormat("0.0");
return df.format(number);
}
/**
* 过滤JSON格式内容
* @param content
* @return
*/
public static String replaceAllByJson(String content) {
if(!StringUtil.isEmptyString(content)){
return content;
}
content=content.replaceAll("'", "");
content=content.replaceAll("\"", "");
content=content.replaceAll(":", "");
content=content.replaceAll(";", "");
content=content.replaceAll("[\\[\\]]","");
content=content.replaceAll("[\\{\\}]","");
return content;
}
/**
* 将数字补全后返回字符串(9->009)
* @param pattern 补全格式(000)
* @param number 数字
* @return
*/
public static String numberFormat(String pattern,long number){
DecimalFormat df = new DecimalFormat(pattern);
return df.format(number);
}
/**
* 获取随机数(按时间)
* @return
*/
public static String getRandomOrderNumber(){
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmssSSS",Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
int randomNumber=(int)(Math.random()*10000);
String number=StringUtil.numberFormat("00000", randomNumber);
return format.format(new Date())+ number;
}
/**
* 获取随机数(按时间)
* @return
*/
public static String getRandomFiveNumber(){
int randomNumber=(int)(Math.random()*10000);
String number=StringUtil.numberFormat("00000", randomNumber);
return number;
}
/**
* 获取随机数(按时间)
* @return
*/
public static String getRandomSixNumber(){
int randomNumber=(int)(Math.random()*100000);
String number=StringUtil.numberFormat("000000", randomNumber);
return number;
}
/**
* 获取日期数字
*
* @param randomNumber
* @return
*/
public static String getRandomOrderNumber(int randomNumber) {
return getRandomOrderNumber(randomNumber, 5);
}
/**
* 获取日期数字
*
* @param randomNumber
* @param index
* @return
*/
public static String getRandomOrderNumber(int randomNumber, int index) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
String pattern = "";
for (int i = 0; i < index; i++) {
pattern += "0";
}
String number = StringUtil.numberFormat(pattern, randomNumber);
return format.format(new Date()) + number;
}
/**
* 获取随机字符串
*
* @return
*/
public static String getRandomOrderNumberString() {
String chars = "abcdefghijklmnopqrstuvwxyz";
int index1 = (int) (Math.random() * 26);
int index2 = (int) (Math.random() * 26);
int index3 = (int) (Math.random() * 26);
int index4 = (int) (Math.random() * 26);
int index5 = (int) (Math.random() * 26);
char[] charArray = new char[]{
chars.charAt(index1),
chars.charAt(index2),
chars.charAt(index3),
chars.charAt(index4),
chars.charAt(index5)
};
return String.valueOf(charArray);
}
/**
* 过滤emoji 或者 其他非文字类型的字符
* @param source
* @return
*/
public static String removeFourChar(String source) {
if (!containsEmoji(source)) {
return source;// 如果不包含,直接返回
}
// 到这里铁定包含
StringBuilder buf = null;
int len = source.length();
for (int i = 0; i < len; i++) {
char codePoint = source.charAt(i);
if (isEmojiCharacter(codePoint)) {
if (buf == null) {
buf = new StringBuilder(source.length());
}
buf.append(codePoint);
}
}
if (buf == null) {
return source;// 如果没有找到 emoji表情,则返回源字符串
} else {
if (buf.length() == len) {
buf = null;
return source;
} else {
return buf.toString();
}
}
}
/**
* 检测是否有emoji字符
* @param source
* @return
*/
private static boolean containsEmoji(String source) {
if (source == null || "".equals(source.trim())) {
return false;
}
int len = source.length();
for (int i = 0; i < len; i++) {
char codePoint = source.charAt(i);
if (isEmojiCharacter(codePoint)) {
// do nothing,判断到了这里表明,确认有表情字符
return true;
}
}
return false;
}
/**
* 检测是否有emoji字符
* @param codePoint
* @return
*/
private static boolean isEmojiCharacter(char codePoint) {
return (codePoint == 0x0) || (codePoint == 0x9)
|| (codePoint == 0xA) || (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD));
}
/**
* 把输入字符串分割成指定长度的字符串列表
* @param inputString
* @param length
* @return
*/
public static List<String> splitStringByLength(String inputString, int length) {
int size = inputString.length() / length;
if (inputString.length() % length != 0) {
size += 1;
}
List<String> list = new ArrayList<String>();
if (length > inputString.length()){
list.add(inputString);
return list;
}
String childStr = null;
for (int index = 0; index < size; index++) {
int f = index * length;
int t = (index + 1) * length;
if (f > inputString.length())
break;
if (t > inputString.length() )
childStr = inputString.substring(f);
else
childStr = inputString.substring(f,t);
list.add(childStr);
}
return list;
}
public static void main(String[] args) {
System.out.println(getRandomFiveNumber());
}
}
package org.nafmii.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
/**
* @author lvyp
* @Description Tree
* @date 2021/5/8
*/
public class TreeUtil {
/**
* jsonArray 转成 List
* @param array
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> arrayToList(JSONArray array, Class<T> clazz){
String jsonStr = JSON.toJSONString(array);
return JSONObject.parseArray(jsonStr,clazz);
}
/**
- listToTree
- <p>方法说明<p>
- 将JSONArray数组转为树状结构
- @param arr 需要转化的数据
- @param id 数据唯一的标识键值
- @param pid 父id唯一标识键值
- @param child 子节点键值
- @return JSONArray
*/
public static JSONArray listToTree(JSONArray arr, String id, String pid, String child) {
JSONArray r = new JSONArray();
JSONObject hash = new JSONObject();
//将数组转为Object的形式,key为数组中的id
for (int i = 0; i < arr.size(); i++) {
JSONObject json = (JSONObject) arr.get(i);
hash.put(json.getString(id), json);
}
//遍历结果集
for (int j = 0; j < arr.size(); j++) {
//单条记录
JSONObject aVal = (JSONObject) arr.get(j);
//在hash中取出key为单条记录中pid的值
String pidStr = "";
Object pidObj = aVal.get(pid);
if (aVal.get(pid) != null) {
pidStr = aVal.get(pid).toString();
}
JSONObject hashVP = (JSONObject) hash.get(pidStr);
//如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中
if (hashVP != null) {
//检查是否有child属性
if (hashVP.get(child) != null) {
JSONArray ch = (JSONArray) hashVP.get(child);
ch.add(aVal);
hashVP.put(child, ch);
} else {
JSONArray ch = new JSONArray();
ch.add(aVal);
hashVP.put(child, ch);
}
} else {
r.add(aVal);
}
}
return r;
}
}
package org.nafmii.common.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author:zhoujh
* @Function:TODO
* @date 2021/4/25 10:22
* @ClassName:
* @version:
* @remark:
*/
@Data
@ApiModel("用户返回报文")
public class UserJwtVO {
private Long id;
@ApiModelProperty(value = "昵称")
private String userName;
@ApiModelProperty(value = "登录密码")
private String loginPwd;
@ApiModelProperty(value = "中文姓名")
private String realName;
@ApiModelProperty(value = "手机号/登录账号")
private String phone;
@ApiModelProperty(value = "出生日期")
private String birthday;
@ApiModelProperty(value = "邮箱")
private String email;
@ApiModelProperty(value = "头像图片地址")
private String headPicture;
@ApiModelProperty(value = "国籍")
private String nationality;
@ApiModelProperty(value = "单位全称")
private String unitName;
@ApiModelProperty(value = "微信OPENT_ID")
private String openId;
@ApiModelProperty(value = "是否开启指纹登录 0 未开启 1 已开启")
private String figerprintFalg;
@ApiModelProperty(value = "是否开启人脸识别登录 0 未开启 1 已开启")
private String faceidFalg;
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
@ApiModelProperty(value = "是否有效标识 0 有效用户 1无效用户")
private String isEnable;
}
package org.nafmii.param;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author by zhangbr
* @date 2020/4/13.
*/
@Data
public class OrderBy {
@ApiModelProperty(value = "排序字段", example = "createTime")
private String column;
@ApiModelProperty(value = "排序方式(ASC:正序,DESC:倒序,默认:ASC)", example = "ASC")
private String type;
}
package org.nafmii.param;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
@Data
public class PageQuery {
@ApiModelProperty("页码")
private Integer pageNo = 1;
@ApiModelProperty("每页条数,默认10")
private Integer pageSize = 10;
@ApiModelProperty(value = "关键字")
private String key;
@ApiModelProperty(value = "排序集合")
private List<OrderBy> orderByList;
@ApiModelProperty(value = "是否分页,默认:true")
private Boolean isPage = true;
@JsonIgnore
private Integer maxPageSize = 1000;
@JsonIgnore
public <T> Page<T> getPage(){
if (isPage){
return new Page<>(pageNo <= 0 ? 1 : pageNo, pageSize <= 0 ? 10 : pageSize);
}
return new Page<>(0, maxPageSize);
}
}
package org.nafmii.result;
import lombok.Data;
import org.nafmii.constant.MessageEnum;
/**
* 通用返回对象
* Created by macro on 2019/4/19.
*/
@Data
public class Result<T> {
private Long code;
private Integer intCode;
private String message;
private T data;
public Result(Long code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Result(Long code, String message) {
this.code = code;
this.message = message;
}
public Result(Integer intCode, String message) {
this.intCode = intCode;
this.message = message;
}
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <T> Result<T> success(T data) {
return new Result<T>(MessageEnum.SUCCESS.getCode(), MessageEnum.SUCCESS.getRemarks(), data);
}
/**
* 成功返回结果
*
* @param data 获取的数据
* @param message 提示信息
*/
public static <T> Result<T> success(T data, String message) {
return new Result<T>(MessageEnum.SUCCESS.getCode(), message, data);
}
/**
* 失败返回结果
* @param message 提示信息
*/
public static <T> Result<T> failed(String message) {
return new Result<T>(MessageEnum.FAIL.getCode(), message, null);
}
/**
* 参数验证失败返回结果
*/
public static <T> Result<T> validateFailed() {
return new Result<T>(MessageEnum.FAIL_PARAM_VALIDATE.getCode(),MessageEnum.FAIL_PARAM_VALIDATE.getRemarks());
}
/**
* 参数验证失败返回结果
* @param message 提示信息
*/
public static <T> Result<T> validateFailed(String message) {
return new Result<T>(MessageEnum.FAIL_PARAM_VALIDATE.getCode(), message, null);
}
/**
* 未登录返回结果
*/
public static <T> Result<T> unauthorized() {
return new Result<T>(MessageEnum.NO_LOGIN.getCode(), MessageEnum.NO_LOGIN.getRemarks());
}
}
package org.nafmii.utils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
@Data
public class PagedResult<T> {
@ApiModelProperty("数据")
private List<T> list;
@ApiModelProperty("总条数")
private long total;
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration = \
org.nafmii.common.config.RedisConfig,\
org.nafmii.common.utils.SpringUtils,\
org.nafmii.common.config.JsonSerializerConfig,\
org.nafmii.common.exception.BusinessExceptionHandler,\
org.nafmii.common.config.EncryptConfig
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<!--<include resource="org/springframework/boot/logging/logback/base.xml" /> -->
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<springProperty scope="context" name="daoUri" source="nafmii.dao-uri"/>
<springProperty scope="context" name="logPath" source="nafmii.log-path"/>
<property name="log.path" value="${logPath}/${springAppName}" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>50</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="${daoUri}" level="DEBUG" />
<root level="info">
<appender-ref ref="CONSOLE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<springProfile name="!dev">
<logger name="${daoUri}" level="info"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<!--<springProfile name="pro">-->
<!--<root level="info">-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="DEBUG_FILE" />-->
<!--<appender-ref ref="INFO_FILE" />-->
<!--<appender-ref ref="ERROR_FILE" />-->
<!--<appender-ref ref="WARN_FILE" />-->
<!--</root>-->
<!--</springProfile>-->
</configuration>
package org.nafmii;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NafmiiCommonApplicationTests {
@Test
void contextLoads() {
}
}
...@@ -14,31 +14,50 @@ ...@@ -14,31 +14,50 @@
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
<!--区分环境打包-->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!--指定默认激活-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency> </dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<scope>test</scope> <version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-dependencies &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org.springframework.cloud</groupId>-->
<!--<artifactId>spring-cloud-dependencies</artifactId>-->
<!--<version>2020.0.1</version>-->
<!--<type>pom</type>-->
<!--<scope>runtime</scope>-->
<!--</dependency>-->
</dependencies> </dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
...@@ -47,6 +66,28 @@ ...@@ -47,6 +66,28 @@
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
<finalName>${project.artifactId}-${project.version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>application-dev.yml</exclude>
<exclude>application-test.yml</exclude>
<exclude>application-prod.yml</exclude>
</excludes>
</resource>
<!--需要动态添加的资源-->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<!--读取打包命令中指定的环境-->
<include>application-${env}.yml</include>
<include>application.yml</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>
package org.nafmii.nafmiieu; package org.nafmii.eureka;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
...@@ -6,10 +6,10 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; ...@@ -6,10 +6,10 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication @SpringBootApplication
@EnableEurekaServer @EnableEurekaServer
public class NafmiiEuApplication { public class NafmiiEurekaApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(NafmiiEuApplication.class, args); SpringApplication.run(NafmiiEurekaApplication.class, args);
} }
} }
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.cloud.client.ip-address}:${server.port}/eureka/
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.cloud.client.ip-address}:${server.port}/eureka/
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.cloud.client.ip-address}:${server.port}/eureka/
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
server.port=8761
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=false
spring.application.name=nafmii-eureka
eureka.server.enable-self-preservation=false
server:
port: 20000
tomcat:
uri-encoding: UTF-8
spring:
profiles:
active: @env@
application:
name: eurka-server
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<!--<include resource="org/springframework/boot/logging/logback/base.xml" /> -->
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<springProperty scope="context" name="logPath" source="nafmii.log-path"/>
<property name="log.path" value="${logPath}/${springAppName}" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>info</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="org.nafmii.eureka" level="debug"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<springProfile name="!dev">
<logger name="org.nafmii.eureka" level="info"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<!--<springProfile name="pro">-->
<!--<root level="info">-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="DEBUG_FILE" />-->
<!--<appender-ref ref="INFO_FILE" />-->
<!--<appender-ref ref="ERROR_FILE" />-->
<!--<appender-ref ref="WARN_FILE" />-->
<!--</root>-->
<!--</springProfile>-->
</configuration>
package org.nafmii.nafmiieu;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NafmiiEuApplicationTests {
@Test
void contextLoads() {
}
}
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.nafmii</groupId> <groupId>org.nafmii</groupId>
<artifactId>nafmii-parent</artifactId> <artifactId>nafmii-parent</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.nafmii</groupId> <groupId>org.nafmii</groupId>
<artifactId>nafmii-gateway</artifactId> <artifactId>nafmii-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>nafmii-gateway</name> <name>nafmii-gateway</name>
<description>Demo project for Spring Boot</description> <description>nafmii-gateway project for Spring Boot</description>
<properties>
<java.version>8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<!--区分环境打包-->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!--指定默认激活-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties> <properties>
<java.version>1.8</java.version> <env>test</env>
</properties> </properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<dependencies> <dependencies>
<!-- https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-starter-client -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.4.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId> <artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.2.3.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.nafmii</groupId>
<artifactId>nafmii-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
...@@ -33,6 +94,28 @@ ...@@ -33,6 +94,28 @@
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
<finalName>${project.artifactId}-${project.version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>application-dev.yml</exclude>
<exclude>application-test.yml</exclude>
<exclude>application-prod.yml</exclude>
</excludes>
</resource>
<!--需要动态添加的资源-->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<!--读取打包命令中指定的环境-->
<include>application-${env}.yml</include>
<include>application.yml</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>
package org.nafmii; package org.nafmii.gateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class},scanBasePackages={"org.nafmii","org.nafmii.exception"})
@EnableEurekaClient
@EnableDiscoveryClient @EnableDiscoveryClient
public class NafmiiGatewayApplication { public class NafmiiGatewayApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(NafmiiGatewayApplication.class, args); SpringApplication.run(NafmiiGatewayApplication.class, args);
} }
......
package org.nafmii.gateway.config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nafmii.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
/**
* Created by zhangzhenfang on 2018/4/17.
// */
@Slf4j
@Component
public class AccessFilter implements GlobalFilter, Ordered {
@Autowired
private AntPathMatcher antPathMatcher; //路径匹配器
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String url = exchange.getRequest().getURI().getPath();
//相关不需要的接口地址
String skip0 ="/nafmii-app/app/nafmii/user/userLogin";
String skip1 ="/nafmii-admin/nafmii/admin/user/login";
String skip2 ="/nafmii-app/v2/api-docs";
String skip3 ="/nafmii-admin/v2/api-docs";
//跳过不需要验证的url
if (antPathMatcher.match(skip0, url)
||antPathMatcher.match(skip1,url)
||antPathMatcher.match(skip2,url)
||antPathMatcher.match(skip3,url) ){
return chain.filter(exchange);
}
//获取token
String token = exchange.getRequest().getHeaders().getFirst(JwtUtils.TOKEN_HEADER);
if (StringUtils.isBlank(token)){
//没有token
return interceptMsg(exchange,"token不能为空");
}else {
try {
//解析token
boolean expiration = JwtUtils.isExpiration(token);
if (!expiration){ //签名验证通过
return chain.filter(exchange);
}else {
return interceptMsg(exchange,"认证过期");
}
} catch (Exception e) {
log.error("检查token时异常: " + e);
if (e.getMessage().contains("JWT expired")){
return interceptMsg(exchange,"认证过期");
}
else{
return interceptMsg(exchange,"无效令牌");
}
}
}
}
/**
* 自定义错误
*
* @param exchange 请求
* @param msg 消息
* @return
*/
public static Mono<Void> interceptMsg(ServerWebExchange exchange, String msg) {
Map<String, Object> resultMap = new HashMap<>(8);
resultMap.put("status", 401);
resultMap.put("statusText", StringUtils.isBlank(msg) ? "服务异常!" : msg);
resultMap.put("data",null);
return Mono.defer(() -> {
byte[] bytes = new byte[0];
try {
bytes = new ObjectMapper().writeValueAsBytes(resultMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
DataBuffer buffer = response.bufferFactory().wrap(bytes);
return response.writeWith(Flux.just(buffer));
});
}
@Override
public int getOrder() {
return -999;
}
}
package org.nafmii.gateway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
@Configuration
public class AuthConfig {
@Bean
public AntPathMatcher antPathMatcher(){
return new AntPathMatcher();
}
}
package org.nafmii.gateway.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author lvyp
* @date 2021/4/29
*/
@Component
@Primary
public class MySwaggerResourceProvider implements SwaggerResourcesProvider {
/**
* swagger2默认的url后缀
*/
private static final String SWAGGER2URL = "/v2/api-docs";
/**
* 网关路由
*/
private final RouteLocator routeLocator;
private final String serverName1= "NAFMII-APP";
private final String serverName2= "NAFMII-GATEWAY";
private final String serverName3= "NAFMII-ADMIN";
private final String serverName4= "NAFMII-QUARTZ";
/**
* 网关应用名称
*/
@Value("${spring.application.name}")
private String self;
public MySwaggerResourceProvider(RouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routeHosts = new ArrayList<>();
// 由于我的网关采用的是负载均衡的方式,因此我需要拿到所有应用的serviceId
// 获取所有可用的host:serviceId
routeLocator.getRoutes().filter(route -> route.getUri().getHost() != null)
.filter(route -> !serverName1.equals(route.getUri().getHost()))
.filter(route -> !serverName2.equals(route.getUri().getHost()))
.filter(route -> !serverName3.equals(route.getUri().getHost()))
.filter(route -> !serverName4.equals(route.getUri().getHost()))
.subscribe(route -> routeHosts.add(route.getUri().getHost()));
// 记录已经添加过的server,存在同一个应用注册了多个服务在nacos上
Set<String> dealed = new HashSet<>();
routeHosts.forEach(instance -> {
// 拼接url,样式为/serviceId/v2/api-info,当网关调用这个接口时,会自动通过负载均衡寻找对应的主机
String url = "/" + instance + SWAGGER2URL;
if (!dealed.contains(url)) {
dealed.add(url);
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setUrl(url);
swaggerResource.setName(instance);
resources.add(swaggerResource);
}
});
return resources;
}
}
package org.nafmii.gateway.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import springfox.documentation.swagger.web.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* @author lvyp
* @date 2021/4/29
*/
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
@Resource
private final SwaggerResourcesProvider swaggerResources;
public SwaggerResourceController(SwaggerResourcesProvider resourcesProvider) {
this.swaggerResources = resourcesProvider;
}
@GetMapping("/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("")
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}
eureka:
client:
serviceUrl:
defaultZone: http://localhost:20000/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
statusPageUrl: http://127.0.0.1:24000/swagger-ui.html
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true # 服务名小写
routes:
- id: nafmii-app
uri: lb://nafmii-app
predicates:
- Path=/nafmii-app/**
filters:
- StripPrefix=1 # 加上StripPrefix=1,否则转发到后端服务时会带上nafmii-app前缀
- id: nafmii-admin
uri: lb://nafmii-admin
predicates:
- Path=/nafmii-admin/**
filters:
- StripPrefix=1
zipkin:
base-url: http://localhost:9411
enabled: true
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
eureka:
client:
serviceUrl:
defaultZone: http://localhost:20000/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
statusPageUrl: http://127.0.0.1:24000/swagger-ui.html
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
- id: nafmii-app
uri: lb://nafmii-app
predicates:
- Path=/nafmii-app/**
filters:
- StripPrefix=1
zipkin:
base-url: http://localhost:9411
enabled: true
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
eureka:
client:
serviceUrl:
defaultZone: http://localhost:20000/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
statusPageUrl: http://127.0.0.1:24000/swagger-ui.html
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
- id: nafmii-app
uri: lb://nafmii-app
predicates:
- Path=/nafmii-app/**
filters:
- StripPrefix=1
zipkin:
base-url: http://localhost:9411
enabled: true
sleuth:
web:
client:
enabled: true
sampler:
probability: 1.0 #zipkin采集率 0.1表示 10%采集率
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
server: server:
port: 8201 port: 24000
#eureka.client.serviceUrl.defaultZone=http://127.0.0.1:8761/eureka tomcat:
eureka: uri-encoding: UTF-8
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka
spring: spring:
cloud: profiles:
gateway: active: @env@
discovery:
locator:
enabled: true
lower-case-service-id: true #使用小写service-id
routes: #配置路由路径
- id: nafmii-admin
uri: lb://nafmii-admin
predicates:
- Path=/nafmii-admin/**
filters:
- StripPrefix=1
- id: nafmii-app
uri: lb://nafmii-app
predicates:
- Path=/nafmii-app/**
filters:
- StripPrefix=1
application: application:
name: nafmii-gateway name: nafmii-gateway
\ No newline at end of file \ No newline at end of file
management: #开启SpringBoot Admin的监控
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<!--<include resource="org/springframework/boot/logging/logback/base.xml" /> -->
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<springProperty scope="context" name="logPath" source="nafmii.log-path"/>
<property name="log.path" value="${logPath}/${springAppName}" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>info</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="org.nafmii.gateway" level="debug"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<springProfile name="!dev">
<logger name="org.nafmii.gateway" level="info"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<!--<springProfile name="pro">-->
<!--<root level="info">-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="DEBUG_FILE" />-->
<!--<appender-ref ref="INFO_FILE" />-->
<!--<appender-ref ref="ERROR_FILE" />-->
<!--<appender-ref ref="WARN_FILE" />-->
<!--</root>-->
<!--</springProfile>-->
</configuration>
package org.nafmii;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NafmiiGatewayApplicationTests {
@Test
void contextLoads() {
}
}
...@@ -14,37 +14,36 @@ ...@@ -14,37 +14,36 @@
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
</dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>org.nafmii</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>nafmii-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.mybatis.generator</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>mybatis-generator-core</artifactId>
<scope>test</scope> <version>1.3.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency> </dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency> <dependency>
<groupId>com.github.xiaoymin</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId> <artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependency>
</dependencies> </dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
......
...@@ -4,8 +4,6 @@ import org.mybatis.generator.api.MyBatisGenerator; ...@@ -4,8 +4,6 @@ import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback; import org.mybatis.generator.internal.DefaultShellCallback;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
......
package org.nafmii.nafmiimbg.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.nafmii.nafmiimbg.model.TStudent;
import org.nafmii.nafmiimbg.model.TStudentExample;
public interface TStudentMapper {
long countByExample(TStudentExample example);
int deleteByExample(TStudentExample example);
int deleteByPrimaryKey(Integer id);
int insert(TStudent record);
int insertSelective(TStudent record);
List<TStudent> selectByExample(TStudentExample example);
TStudent selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") TStudent record, @Param("example") TStudentExample example);
int updateByExample(@Param("record") TStudent record, @Param("example") TStudentExample example);
int updateByPrimaryKeySelective(TStudent record);
int updateByPrimaryKey(TStudent record);
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiimbg.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class TStudent implements Serializable {
@ApiModelProperty(value = "id")
private Integer id;
private String name;
private Short sex;
private Date createTime;
private Date updateTime;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Short getSex() {
return sex;
}
public void setSex(Short sex) {
this.sex = sex;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", sex=").append(sex);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiimbg.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TStudentExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public TStudentExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andSexIsNull() {
addCriterion("sex is null");
return (Criteria) this;
}
public Criteria andSexIsNotNull() {
addCriterion("sex is not null");
return (Criteria) this;
}
public Criteria andSexEqualTo(Short value) {
addCriterion("sex =", value, "sex");
return (Criteria) this;
}
public Criteria andSexNotEqualTo(Short value) {
addCriterion("sex <>", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThan(Short value) {
addCriterion("sex >", value, "sex");
return (Criteria) this;
}
public Criteria andSexGreaterThanOrEqualTo(Short value) {
addCriterion("sex >=", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThan(Short value) {
addCriterion("sex <", value, "sex");
return (Criteria) this;
}
public Criteria andSexLessThanOrEqualTo(Short value) {
addCriterion("sex <=", value, "sex");
return (Criteria) this;
}
public Criteria andSexIn(List<Short> values) {
addCriterion("sex in", values, "sex");
return (Criteria) this;
}
public Criteria andSexNotIn(List<Short> values) {
addCriterion("sex not in", values, "sex");
return (Criteria) this;
}
public Criteria andSexBetween(Short value1, Short value2) {
addCriterion("sex between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andSexNotBetween(Short value1, Short value2) {
addCriterion("sex not between", value1, value2, "sex");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
\ No newline at end of file \ No newline at end of file
jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC jdbc.connectionURL=jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.userId=root jdbc.userId=root
jdbc.password=123456
\ No newline at end of file \ No newline at end of file
jdbc.password=Moxi123#
\ No newline at end of file \ No newline at end of file
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
<javaClientGenerator type="XMLMAPPER" targetPackage="org.nafmii.nafmiimbg.mapper" <javaClientGenerator type="XMLMAPPER" targetPackage="org.nafmii.nafmiimbg.mapper"
targetProject="nafmii-mbg\src\main\java"/> targetProject="nafmii-mbg\src\main\java"/>
<!--生成全部表tableName设为%--> <!--生成全部表tableName设为%-->
<table tableName="%"> <table tableName="APP_USER">
<!--<generatedKey column="id" sqlStatement="MySql" identity="true"/>--> <!--<generatedKey column="id" sqlStatement="MySql" identity="true"/>-->
</table> </table>
</context> </context>
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.nafmii.nafmiimbg.mapper.TStudentMapper">
<resultMap id="BaseResultMap" type="org.nafmii.nafmiimbg.model.TStudent">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="SMALLINT" property="sex" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
<result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, name, sex, create_time, update_time
</sql>
<select id="selectByExample" parameterType="org.nafmii.nafmiimbg.model.TStudentExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from t_student
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_student
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from t_student
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="org.nafmii.nafmiimbg.model.TStudentExample">
delete from t_student
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="org.nafmii.nafmiimbg.model.TStudent">
insert into t_student (id, name, sex,
create_time, update_time)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{sex,jdbcType=SMALLINT},
#{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="org.nafmii.nafmiimbg.model.TStudent">
insert into t_student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="sex != null">
sex,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=SMALLINT},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="org.nafmii.nafmiimbg.model.TStudentExample" resultType="java.lang.Long">
select count(*) from t_student
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update t_student
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.name != null">
name = #{record.name,jdbcType=VARCHAR},
</if>
<if test="record.sex != null">
sex = #{record.sex,jdbcType=SMALLINT},
</if>
<if test="record.createTime != null">
create_time = #{record.createTime,jdbcType=TIMESTAMP},
</if>
<if test="record.updateTime != null">
update_time = #{record.updateTime,jdbcType=TIMESTAMP},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update t_student
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=VARCHAR},
sex = #{record.sex,jdbcType=SMALLINT},
create_time = #{record.createTime,jdbcType=TIMESTAMP},
update_time = #{record.updateTime,jdbcType=TIMESTAMP}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="org.nafmii.nafmiimbg.model.TStudent">
update t_student
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=SMALLINT},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="org.nafmii.nafmiimbg.model.TStudent">
update t_student
set name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=SMALLINT},
create_time = #{createTime,jdbcType=TIMESTAMP},
update_time = #{updateTime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiimbg;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NafmiiMbgApplicationTests {
@Test
void contextLoads() {
}
}
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* 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
*
* https://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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# https://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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.nafmii</groupId>
<artifactId>nafmii-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>org.nafmii</groupId>
<artifactId>nafmii-monitor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>nafmii-monitor</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 增加admin server 和 ui支持 -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-server-ui -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>2.3.0</version>
</dependency>
<!-- 增加对hystrix的UI支持,需要服务依赖了hystrix -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-hystrix</artifactId>
<version>1.5.7</version>
</dependency>
<!-- 增加对turbine的集成支持,需要指定相关turbine参数信息 -->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui-turbine</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package org.nafmii.monitor;
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableAdminServer
public class NafmiiMonitorApplication {
public static void main(String[] args) {
SpringApplication.run(NafmiiMonitorApplication.class, args);
}
}
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.cloud.client.ip-address}:${server.port}/eureka/
server:
port: 24000
spring:
application:
name: monitor-server
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
endpoints:
restart:
enabled: true
shutdown:
enabled: true
sensitive: false
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.cloud.client.ip-address}:${server.port}/eureka/
management:
security:
enabled: false
server:
port: 24000
spring:
application:
name: monitor-server
boot:
admin:
routes:
endpoints: env,metrics,dump,jolokia,info,configprops,trace,logfile,refresh,flyway,liquibase,heapdump,loggers,auditevents,hystrix.stream
turbine:
location: crm-turbine
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
endpoints:
restart:
enabled: true
shutdown:
enabled: true
sensitive: false
eureka:
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${spring.cloud.client.ip-address}:${server.port}/eureka/
management:
security:
enabled: false
server:
port: 24000
spring:
application:
name: monitor-server
boot:
admin:
routes:
endpoints: env,metrics,dump,jolokia,info,configprops,trace,logfile,refresh,flyway,liquibase,heapdump,loggers,auditevents,hystrix.stream
turbine:
location: crm-turbine
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
\ No newline at end of file \ No newline at end of file
spring:
profiles:
active: dev
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<!--<include resource="org/springframework/boot/logging/logback/base.xml" /> -->
<springProperty scope="context" name="springAppName" source="spring.application.name"/>
<springProperty scope="context" name="logPath" source="nafmii.log-path"/>
<property name="log.path" value="${logPath}/${springAppName}" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>info</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="org.nafmii.eureka" level="debug"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<springProfile name="!dev">
<logger name="org.nafmii.eureka" level="info"/>
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<!--<springProfile name="pro">-->
<!--<root level="info">-->
<!--<appender-ref ref="CONSOLE" />-->
<!--<appender-ref ref="DEBUG_FILE" />-->
<!--<appender-ref ref="INFO_FILE" />-->
<!--<appender-ref ref="ERROR_FILE" />-->
<!--<appender-ref ref="WARN_FILE" />-->
<!--</root>-->
<!--</springProfile>-->
</configuration>
...@@ -14,31 +14,37 @@ ...@@ -14,31 +14,37 @@
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties> </properties>
<!--区分环境打包-->
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<!--指定默认激活-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions><!-- 去掉springboot默认配置 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> </dependency>
<!--quartz定时调度依赖--> <!--quartz定时调度依赖-->
...@@ -47,22 +53,34 @@ ...@@ -47,22 +53,34 @@
<artifactId>spring-boot-starter-quartz</artifactId> <artifactId>spring-boot-starter-quartz</artifactId>
</dependency> </dependency>
<!--数据源--> <!--数据源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId> <artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency> </dependency>
<!--<dependency>-->
<!--<groupId>org.mybatis</groupId>-->
<!--<artifactId>mybatis</artifactId>-->
<!--</dependency>-->
<dependency> <dependency>
<groupId>org.mybatis</groupId> <groupId>org.nafmii</groupId>
<artifactId>mybatis-spring</artifactId> <artifactId>nafmii-common</artifactId>
<version>1.3.2</version> <version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
</dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
...@@ -70,6 +88,28 @@ ...@@ -70,6 +88,28 @@
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
<finalName>${project.artifactId}-${project.version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>application-dev.yml</exclude>
<exclude>application-test.yml</exclude>
<exclude>application-prod.yml</exclude>
</excludes>
</resource>
<!--需要动态添加的资源-->
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<!--读取打包命令中指定的环境-->
<include>application-${env}.yml</include>
<include>application.yml</include>
</includes>
</resource>
</resources>
</build> </build>
</project> </project>
package org.nafmii.nafmiiquartz; package org.nafmii.quartz;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication @SpringBootApplication
@EnableEurekaClient
public class NafmiiQuartzApplication { public class NafmiiQuartzApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.annotation; package org.nafmii.quartz.datasource.annotation;
import java.lang.annotation.*; import java.lang.annotation.*;
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.aspect; package org.nafmii.quartz.datasource.aspect;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
...@@ -14,8 +14,8 @@ import org.aspectj.lang.annotation.Around; ...@@ -14,8 +14,8 @@ import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.nafmii.nafmiiquartz.datasource.annotation.DataSource; import org.nafmii.quartz.datasource.annotation.DataSource;
import org.nafmii.nafmiiquartz.datasource.config.DynamicContextHolder; import org.nafmii.quartz.datasource.config.DynamicContextHolder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered; import org.springframework.core.Ordered;
...@@ -36,8 +36,8 @@ import java.lang.reflect.Method; ...@@ -36,8 +36,8 @@ import java.lang.reflect.Method;
public class DataSourceAspect { public class DataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(getClass()); protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(org.nafmii.nafmiiquartz.datasource.annotation.DataSource) " + @Pointcut("@annotation(org.nafmii.quartz.datasource.annotation.DataSource) " +
"|| @within(org.nafmii.nafmiiquartz.datasource.annotation.DataSource)") "|| @within(org.nafmii.quartz.datasource.annotation.DataSource)")
public void dataSourcePointCut() { public void dataSourcePointCut() {
} }
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.config; package org.nafmii.quartz.datasource.config;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.Deque; import java.util.Deque;
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.config; package org.nafmii.quartz.datasource.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
......
...@@ -6,11 +6,11 @@ ...@@ -6,11 +6,11 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.config; package org.nafmii.quartz.datasource.config;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import org.nafmii.nafmiiquartz.datasource.properties.DataSourceProperties; import org.nafmii.quartz.datasource.properties.DataSourceProperties;
import org.nafmii.nafmiiquartz.datasource.properties.DynamicDataSourceProperties; import org.nafmii.quartz.datasource.properties.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
...@@ -19,7 +19,6 @@ import org.springframework.context.annotation.Configuration; ...@@ -19,7 +19,6 @@ import org.springframework.context.annotation.Configuration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.logging.Logger;
/** /**
* 配置多数据源 * 配置多数据源
......
...@@ -6,10 +6,10 @@ ...@@ -6,10 +6,10 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.config; package org.nafmii.quartz.datasource.config;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import org.nafmii.nafmiiquartz.datasource.properties.DataSourceProperties; import org.nafmii.quartz.datasource.properties.DataSourceProperties;
import java.sql.SQLException; import java.sql.SQLException;
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.properties; package org.nafmii.quartz.datasource.properties;
/** /**
* 多数据源属性 * 多数据源属性
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* 版权所有,侵权必究! * 版权所有,侵权必究!
*/ */
package org.nafmii.nafmiiquartz.datasource.properties; package org.nafmii.quartz.datasource.properties;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
......
package org.nafmii.nafmiiquartz.scheduler; package org.nafmii.quartz.scheduler;
import org.nafmii.nafmiiquartz.scheduler.job.TestJob; import org.nafmii.quartz.scheduler.job.TestJob;
import org.quartz.*; import org.quartz.*;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationArguments;
......
package org.nafmii.nafmiiquartz.scheduler.job; package org.nafmii.quartz.scheduler.job;
import org.nafmii.nafmiiquartz.datasource.annotation.DataSource; import org.nafmii.quartz.datasource.annotation.DataSource;
import org.quartz.DisallowConcurrentExecution; import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext; import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution; import org.quartz.PersistJobDataAfterExecution;
......
eureka:
client:
serviceUrl:
defaultZone: http://localhost:20000/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
statusPageUrl: http://127.0.0.1:23000/swagger-ui.html
spring:
quartz:
job-store-type: jdbc
properties:
org:
quartz:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: Moxi123#
scheduler:
instancName: clusteredScheduler
instanceId: AUTO
jobStore:
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: QRTZ_
isClustered: true
clusterCheckinInterval: 1000
useProperties: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 20
threadPriority: 5
jdbc:
initialize-schema: always
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
dynamic:
#其他数据源
datasource:
dm:
#dm数据源 在相应的方法上使用 @DataSource("dm")
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.quartz
eureka:
client:
serviceUrl:
defaultZone: http://localhost:20000/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
statusPageUrl: http://127.0.0.1:23000/swagger-ui.html
spring:
quartz:
job-store-type: jdbc
properties:
org:
quartz:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: Moxi123#
scheduler:
instancName: clusteredScheduler
instanceId: AUTO
jobStore:
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: QRTZ_
isClustered: true
clusterCheckinInterval: 1000
useProperties: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 20
threadPriority: 5
jdbc:
initialize-schema: always
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
dynamic:
#其他数据源
datasource:
dm:
#dm数据源 在相应的方法上使用 @DataSource("dm")
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.quartz
eureka:
client:
serviceUrl:
defaultZone: http://localhost:20000/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
statusPageUrl: http://127.0.0.1:23000/swagger-ui.html
spring:
quartz:
job-store-type: jdbc
properties:
org:
quartz:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: Moxi123#
scheduler:
instancName: clusteredScheduler
instanceId: AUTO
jobStore:
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
tablePrefix: QRTZ_
isClustered: true
clusterCheckinInterval: 1000
useProperties: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 20
threadPriority: 5
jdbc:
initialize-schema: always
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 50
minimum-idle: 10
idle-timeout: 60000
auto-commit: true
connection-timeout: 3000
pool-name: NFMII_HikariCP
connection-test-query: SELECT 1
dynamic:
#其他数据源
datasource:
dm:
#dm数据源 在相应的方法上使用 @DataSource("dm")
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/NAFMII_2.1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
logging:
config: classpath:logback-spring.xml
nafmii:
log-path: D:/NAFMII
dao-uri: org.nafmii.quartz
server: server:
port: 10900 port: 23000
tomcat:
uri-encoding: UTF-8
spring: spring:
profiles: profiles:
active: dev active: @env@
quartz: application:
job-store-type: jdbc #�־û������ݿ� name: nafmii-quartz
properties:
org:
quartz:
datasource:
# �°�������com.mysql.jdbc.Driver���Ϊcom.mysql.cj.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
# ����Դ��Ҫ���ʱ���׼��ָ�������ʽ������� You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
url: jdbc:mysql://140.143.249.40:3306/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: 123456
scheduler:
instancName: clusteredScheduler
instanceId: AUTO
jobStore:
class: org.quartz.impl.jdbcjobstore.JobStoreTX
driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate #StdJDBCDelegate˵��֧�ּ�Ⱥ
tablePrefix: QRTZ_
isClustered: true
clusterCheckinInterval: 1000
useProperties: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 20
threadPriority: 5
jdbc:
initialize-schema: always
datasource:
druid:
password: 123456
url: jdbc:mysql://140.143.249.40:3306/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
dynamic:
#其他数据源
datasource:
dm:
#dm数据源 在相应的方法上使用 @DataSource("dm")
password: 123456
url: jdbc:mysql://140.143.249.40:3308/edz?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
#type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
\ No newline at end of file \ No newline at end of file
package org.nafmii.nafmiiquartz;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootTest
class NafmiiQuartzApplicationTests {
@Test
void contextLoads() {
}
}
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version> <version>2.1.13.RELEASE</version>
<relativePath/> <relativePath/>
</parent> </parent>
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<description>nafmii 2.0 父级工程</description> <description>nafmii 2.0 父级工程</description>
<!--nafmii-parent管理的模块-->
<modules> <modules>
<module>nafmii-admin</module> <module>nafmii-admin</module>
<module>nafmii-eureka</module> <module>nafmii-eureka</module>
...@@ -24,193 +25,7 @@ ...@@ -24,193 +25,7 @@
<module>nafmii-quartz</module> <module>nafmii-quartz</module>
<module>nafmii-app</module> <module>nafmii-app</module>
<module>nafmii-mbg</module> <module>nafmii-mbg</module>
<module>nafmii-monitor</module>
</modules> </modules>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<skipTests>true</skipTests>
<docker.host>http://192.168.3.101:2375</docker.host>
<docker.maven.plugin.version>1.2.2</docker.maven.plugin.version>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
<spring-cloud-alibaba.version>2.2.0.RELEASE</spring-cloud-alibaba.version>
<pagehelper-starter.version>1.3.0</pagehelper-starter.version>
<pagehelper.version>5.2.0</pagehelper.version>
<druid.version>1.1.23</druid.version>
<hutool.version>5.4.0</hutool.version>
<mybatis-generator.version>1.4.0</mybatis-generator.version>
<mybatis.version>3.5.5</mybatis.version>
<mysql-connector.version>8.0.20</mysql-connector.version>
<spring-data-commons.version>2.3.0.RELEASE</spring-data-commons.version>
<jjwt.version>0.9.0</jjwt.version>
<aliyun-oss.version>2.5.0</aliyun-oss.version>
<logstash-logback.version>5.3</logstash-logback.version>
<admin-starter-server.version>2.2.3</admin-starter-server.version>
<minio.version>7.1.0</minio.version>
<knife4j.version>2.0.4</knife4j.version>
<nimbus-jose-jwt.version>8.16</nimbus-jose-jwt.version>
<mall-common.version>1.0-SNAPSHOT</mall-common.version>
<mall-mbg.version>1.0-SNAPSHOT</mall-mbg.version>
<ojdbc.version>10.2.0.4</ojdbc.version>
</properties>
<dependencies>
<!--<dependency>-->
<!--&lt;!&ndash; 引入log4j2依赖 &ndash;&gt;-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-slf4j</artifactId>-->
<!---->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.nafmii</groupId>
<artifactId>nafmii-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<!--Spring Cloud 相关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--MyBatis分页插件starter-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper-starter.version}</version>
</dependency>
<!--MyBatis分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${pagehelper.version}</version>
</dependency>
<!--集成druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!--Hutool Java工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!--Knife4j API文档生产工具-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-micro-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<!-- MyBatis 生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis-generator.version}</version>
</dependency>
<!-- MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--SpringData工具包-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring-data-commons.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.oracle/ojdbc14 -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>${ojdbc.version}</version>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<!--JWT(Json Web Token)登录支持-->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>${nimbus-jose-jwt.version}</version>
</dependency>
<!--集成logstash-->
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>${logstash-logback.version}</version>
</dependency>
<!--集成SpringBoot Admin监控-->
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>${admin-starter-server.version}</version>
</dependency>
<!--Mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<!--<plugin>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-maven-plugin</artifactId>-->
<!--</plugin>-->
</plugins>
</build>
</project> </project>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!