Commit 8f4946ac by XiaHou

万科文档下载

parent 2ea78370
package com.macro.mall.config;
import cn.hutool.setting.dialect.Props;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class SourceConfiguration extends WebMvcConfigurerAdapter {
@Value("${aliyun.oss.filepath}")
private String filepath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* @Description: 对文件的路径进行配置,创建一个虚拟路径/file/** ,即只要在<img src="/file/images/20180522/9aa64b2b-a558-421e-929c-537ff0aecdba.jpg" />便可以直接引用图片
*这是图片的物理路径 "file:/+本地图片的地址"
* @Date: Create in 14:08 2017/12/20
*
*/
registry.addResourceHandler("/files/**").addResourceLocations("file:"+filepath);
super.addResourceHandlers(registry);
}
}
...@@ -3,16 +3,17 @@ package com.macro.mall.controller; ...@@ -3,16 +3,17 @@ package com.macro.mall.controller;
import com.macro.mall.common.api.CommonPage; import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult; import com.macro.mall.common.api.CommonResult;
import com.macro.mall.core.annotion.BussinessLog; import com.macro.mall.core.annotion.BussinessLog;
import com.macro.mall.domain.dto.AdminManageParam;
import com.macro.mall.dto.AdminUpdateParam; import com.macro.mall.dto.AdminUpdateParam;
import com.macro.mall.dto.UmsAdminLoginParam; import com.macro.mall.dto.UmsAdminLoginParam;
import com.macro.mall.domain.dto.UmsAdminParam; import com.macro.mall.domain.dto.UmsAdminParam;
import com.macro.mall.model.UmsAdmin; import com.macro.mall.model.*;
import com.macro.mall.model.UmsPermission; import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.UmsRole;
import com.macro.mall.service.UmsRoleService; import com.macro.mall.service.UmsRoleService;
import com.macro.mall.service.system.UmsAdminService; import com.macro.mall.service.system.UmsAdminService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -22,6 +23,7 @@ import org.springframework.web.bind.annotation.*; ...@@ -22,6 +23,7 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal; import java.security.Principal;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
...@@ -44,31 +46,16 @@ public class UmsAdminController { ...@@ -44,31 +46,16 @@ public class UmsAdminController {
@Value("${jwt.tokenHead}") @Value("${jwt.tokenHead}")
private String tokenHead; private String tokenHead;
@ApiOperation(value = "用户注册")
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam, BindingResult result) {
UmsAdmin umsAdmin = adminService.register(umsAdminParam);
if (umsAdmin == null) {
CommonResult.failed();
}
return CommonResult.success(umsAdmin);
}
@ApiOperation(value = "平台登陆:登录以后返回token") @ApiOperation(value = "平台登陆:登录以后返回token")
@RequestMapping(value = "/login", method = RequestMethod.POST) @RequestMapping(value = "/login", method = RequestMethod.POST)
@BussinessLog(value = "登陆", module = "后台用户管理") @BussinessLog(value = "登陆", module = "后台用户管理")
@ResponseBody @ResponseBody
public CommonResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam, BindingResult result, HttpServletResponse response) { public CommonResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam, BindingResult result, HttpServletResponse response,HttpServletRequest request) {
return adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword(),1); //获取session 中的验证码 然后传给Sevice校验
} HttpSession session = request.getSession();
Object sessionAuthCode = session.getAttribute("RANDOMKEY");
@ApiOperation(value = "商家登录登录以后返回token") return adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword(),umsAdminLoginParam.getAuthCode(),(String)sessionAuthCode,1);
@RequestMapping(value = "/mchtLogin", method = RequestMethod.POST)
@BussinessLog(value = "登陆", module = "后台用户管理")
@ResponseBody
public CommonResult mchtLogin(@RequestBody UmsAdminLoginParam umsAdminLoginParam, BindingResult result, HttpServletResponse response) {
return adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword(),2);
} }
@ApiOperation(value = "刷新token") @ApiOperation(value = "刷新token")
...@@ -165,14 +152,6 @@ public class UmsAdminController { ...@@ -165,14 +152,6 @@ public class UmsAdminController {
return commonResult; return commonResult;
} }
@ApiOperation("更换绑定手机号码")
@BussinessLog(value = "修改", module = "后台用户管理")
@RequestMapping(value = "/updateBindPhone", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateBindPhone(@RequestBody AdminUpdateParam adminUpdateParam) {
CommonResult commonResult = adminService.updateBindPhone(adminUpdateParam.getUserId(),adminUpdateParam.getCode(),adminUpdateParam.getPhone());
return commonResult;
}
@ApiOperation("给用户分配角色") @ApiOperation("给用户分配角色")
@BussinessLog(value = "修改", module = "后台用户管理") @BussinessLog(value = "修改", module = "后台用户管理")
...@@ -214,4 +193,37 @@ public class UmsAdminController { ...@@ -214,4 +193,37 @@ public class UmsAdminController {
List<UmsPermission> permissionList = adminService.getPermissionList(adminId); List<UmsPermission> permissionList = adminService.getPermissionList(adminId);
return CommonResult.success(permissionList); return CommonResult.success(permissionList);
} }
@ApiOperation("万科后台_用户分页操作")
@RequestMapping(value = "/getPageList", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<AdminManageParam>> getPageList(@ApiParam(value="分页大小") @RequestParam(value = "pageSize", required = false) Integer pageSize,
@ApiParam(value="分页页数") @RequestParam(value = "pageNum", required = false) Integer pageNum) {
UmsAdmin umsAdmin = new UmsAdmin();
return CommonResult.success(CommonPage.restPage(this.adminService.getPageList(pageNum,pageSize,umsAdmin)));
}
@ApiOperation("万科后台_新增管理员")
@RequestMapping(value = "/insertAdmin", method = RequestMethod.POST)
@ResponseBody
public CommonResult insertAdmin(@ApiParam(value="会员对象") @RequestBody UmsAdmin umsAdmin
) {
ResultMsg res = this.adminService.insertAdmin(umsAdmin);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_根据id修改一条数据")
@RequestMapping(value = "/updateAdmin", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateAdmin(@ApiParam(value="会员对象") @RequestBody UmsAdmin umsAdmin
) {
ResultMsg res = this.adminService.updateAdmin(umsAdmin);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
} }
package com.macro.mall.controller.system;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.dto.Vo.ValidateCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@Controller
@Api(tags = "万科物资_验证码相关接口", description = "验证码控制器")
@RequestMapping("/validateCode")
public class ValidateCodeController {
@ApiOperation(value = "生成验证码,返回的是图片")
@RequestMapping(value="/getCaptchaImage", method = RequestMethod.GET)
@ResponseBody
public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expire", "0");
response.setHeader("Pragma", "no-cache");
ValidateCode validateCode = new ValidateCode();
// 直接返回图片
validateCode.getRandomCodeImage(request, response);
} catch (Exception e) {
System.out.println(e);
}
}
@ApiOperation(value = "生成验证码,返回的是 base64")
@RequestMapping(value="/getCaptchaBase64", method = RequestMethod.GET)
@ResponseBody
public CommonResult getCaptchaBase64(HttpServletRequest request, HttpServletResponse response) {
Map result = new HashMap();
try {
response.setContentType("image/png");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expire", "0");
response.setHeader("Pragma", "no-cache");
ValidateCode validateCode = new ValidateCode();
// 直接返回图片
// validateCode.getRandomCode(request, response);
// 返回base64
String base64String = validateCode.getRandomCodeBase64(request, response);
result.put("url", "data:image/png;base64," + base64String);
result.put("message", "created successfull");
System.out.println("test=" + result.get("url"));
} catch (Exception e) {
System.out.println(e);
}
return CommonResult.success(result,"获取成功");
}
@ApiOperation(value = "测试sessionKey,后续不用需要删除")
@RequestMapping(value="/testSessionKey",method = RequestMethod.GET)
@ResponseBody
public CommonResult testSessionKey(HttpServletRequest request, HttpServletResponse response) {
//获取session
HttpSession session = request.getSession();
Object obj = session.getAttribute("RANDOMKEY");
return CommonResult.success(null, (String)obj);
}
}
package com.macro.mall.controller.vanke;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.VankeFile;
import com.macro.mall.model.vanke.FileDto;
import com.macro.mall.service.vanke.IVankeFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.UUID;
@Api(tags = "万科文档后台_文件上传下载相关接口", description = "文件上传下载控制器")
@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {
@Value("${aliyun.oss.filepath}")
private String filepath;
@Value("${aliyun.oss.fileUrl}")
private String fileUrl;
@Autowired
private IVankeFileService vankeFileService;
/**
* 处理文件上传
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ApiOperation(value = "文件上传")
@ResponseBody
public CommonResult uploading(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
if(file == null){
return CommonResult.failed("传入文件为空");
}
//获取uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//获取文件名的后缀名 截取.之后字符串
String preffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
//重命名操作
String newFileName =uuid + "."+ preffix;
File targetFile = new File(filepath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try (FileOutputStream out = new FileOutputStream(filepath + newFileName);){
out.write(file.getBytes());
} catch (Exception e) {
e.printStackTrace();
return CommonResult.failed("文件上传失败!");
}
//拼接起来 图片路径
FileDto fileDto = new FileDto();
fileDto.setFileName(newFileName);
fileDto.setFilePath(fileUrl+newFileName);
return CommonResult.success(fileDto,"文件上传成功!");
}
@RequestMapping(value="/downloadByFileId", method = RequestMethod.POST)
@ApiOperation(value = "文件下载根据文件id")
@ResponseBody
public CommonResult downloadByFileId(HttpServletResponse response,@ApiParam(value="文件Id") @RequestParam(value = "fileId", required = false) Long fileId) throws UnsupportedEncodingException {
VankeFile vankeFile = this.vankeFileService.selectById(fileId);
if(vankeFile == null){
return CommonResult.failed("不存在此文件");
}
this.vankeFileService.updateFileTimes(fileId);
File file = new File(filepath + "/" + vankeFile.getFileName());
if(file.exists()){
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(vankeFile.getFileName(),"utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
try(FileInputStream fis= new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
os = response.getOutputStream();
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return CommonResult.success(null,"操作成功");
}
@RequestMapping(value="/download", method = RequestMethod.POST)
@ApiOperation(value = "文件下载")
@ResponseBody
public void downLoad(HttpServletResponse response, @ApiParam(value="文件名") @RequestParam(value = "fileName")String fileName) throws UnsupportedEncodingException {
File file = new File(filepath + "/" + fileName);
if(file.exists()){
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
try(FileInputStream fis= new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
os = response.getOutputStream();
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@RequestMapping(value="/deleteFile", method = RequestMethod.POST)
@ApiOperation(value = "文件删除")
@ResponseBody
public CommonResult deleteFile(HttpServletRequest request, @ApiParam(value="文件名") @RequestParam(value = "fileName")String fileName){
if(fileName == null || "".equals(fileName)){
return CommonResult.failed("传入文件名为空");
}
File file = new File(filepath + "/" + fileName);
if(file.isFile() && file.exists()) {
file.delete();
return CommonResult.success(null,"删除成功");
}else{
return CommonResult.failed("不存在此文件名的文件");
}
}
}
package com.macro.mall.controller.vanke;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.VankeFile;
import com.macro.mall.model.VankeFileType;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileDto;
import com.macro.mall.model.vanke.VankeFileTimesDto;
import com.macro.mall.service.vanke.IVankeFileService;
import com.macro.mall.service.vanke.IVankeFileTimesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Api(tags = "万科文档后台_文件相关接口", description = "文件控制器")
@Controller
@RequestMapping("/vankeFile")
public class VankeFileController {
@Autowired
private IVankeFileService vankeFileService;
@Autowired
private IVankeFileTimesService vankeFileTimesService;
@ApiOperation("万科后台_文件分页操作")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<VankeFileDto>> list(@ApiParam(value="分页大小") @RequestParam(value = "pageSize", required = false) Integer pageSize,
@ApiParam(value="分页页数") @RequestParam(value = "pageNum", required = false) Integer pageNum,
@ApiParam(value="文档名称搜索") @RequestParam(value = "name", required = false) String name,
@ApiParam(value="如果根据时间倒序查询 传入1") @RequestParam(value = "isByTime", required = false) Integer isByTime,
@ApiParam(value="如果根据下载排行倒序查询 传入1") @RequestParam(value = "isByDownloadTimes", required = false) Integer isByDownloadTimes
) {
VankeFileDto vankeFileDto = new VankeFileDto();
vankeFileDto.setName(name);
vankeFileDto.setIsByTime(isByTime);
vankeFileDto.setIsByDownloadTimes(isByDownloadTimes);
return CommonResult.success(CommonPage.restPage(this.vankeFileService.getPageList(pageNum,pageSize,vankeFileDto)));
}
@ApiOperation("万科后台_更新文件下载数")
@RequestMapping(value = "/updateFileTimes", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateFileTimes(@ApiParam(value="文件Id") @RequestParam(value = "fileId", required = false) Long fileId
) {
ResultMsg res = this.vankeFileService.updateFileTimes(fileId);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_获取今日下载文件分页操作")
@RequestMapping(value = "/todayList", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<VankeFileTimesDto>> todayList(@ApiParam(value="分页大小") @RequestParam(value = "pageSize", required = false) Integer pageSize,
@ApiParam(value="分页页数") @RequestParam(value = "pageNum", required = false) Integer pageNum
) {
VankeFileTimesDto vankeFileTimesDto = new VankeFileTimesDto();
return CommonResult.success(CommonPage.restPage(this.vankeFileTimesService.getPageList(pageNum,pageSize,vankeFileTimesDto)));
}
@ApiOperation("万科后台_文件新增操作")
@RequestMapping(value = "/insertFile", method = RequestMethod.POST)
@ResponseBody
public CommonResult insertFile(@ApiParam(value="文件对象") @RequestBody VankeFile vankeFile
) {
ResultMsg res = this.vankeFileService.insertFile(vankeFile);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_根据id修改文件类型对象")
@RequestMapping(value = "/updateFile", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateFile(@ApiParam(value="文件对象") @RequestBody VankeFile vankeFile
) {
ResultMsg res = this.vankeFileService.updateFile(vankeFile);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_得到首页数据")
@RequestMapping(value = "/getHomeData", method = RequestMethod.GET)
@ResponseBody
public CommonResult getHomeData(){
return CommonResult.success(this.vankeFileService.homeData(),"查询成功");
}
}
package com.macro.mall.controller.vanke;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.VankeFileType;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileDto;
import com.macro.mall.service.vanke.IVankeFileTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Api(tags = "万科文档后台_文档分类相关接口", description = "文档分类控制器")
@Controller
@RequestMapping("/vankeFileType")
public class VankeFileTypeController {
@Autowired
private IVankeFileTypeService vankeFileTypeService;
@ApiOperation("万科后台_文件类型分页操作")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<VankeFileType>> list(@ApiParam(value="分页大小") @RequestParam(value = "pageSize", required = false) Integer pageSize,
@ApiParam(value="分页页数") @RequestParam(value = "pageNum", required = false) Integer pageNum
) {
return CommonResult.success(CommonPage.restPage(this.vankeFileTypeService.getPageList(pageNum,pageSize)));
}
@ApiOperation("万科后台_文件类型新增操作")
@RequestMapping(value = "/insertFileType", method = RequestMethod.POST)
@ResponseBody
public CommonResult insertFileType(@ApiParam(value="文件类型对象") @RequestBody VankeFileType vankeFileType
) {
ResultMsg res = this.vankeFileTypeService.insertFileType(vankeFileType);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_根据id修改文件类型对象")
@RequestMapping(value = "/updateById", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateById(@ApiParam(value="文件类型对象") @RequestBody VankeFileType vankeFileType
) {
ResultMsg res = this.vankeFileTypeService.updateById(vankeFileType);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
}
...@@ -3,6 +3,8 @@ package com.macro.mall.dto; ...@@ -3,6 +3,8 @@ package com.macro.mall.dto;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotBlank;
/** /**
* 用户登录参数 * 用户登录参数
* Created by macro on 2018/4/26. * Created by macro on 2018/4/26.
...@@ -14,6 +16,18 @@ public class UmsAdminLoginParam { ...@@ -14,6 +16,18 @@ public class UmsAdminLoginParam {
@ApiModelProperty(value = "密码", required = true) @ApiModelProperty(value = "密码", required = true)
@NotEmpty(message = "密码不能为空") @NotEmpty(message = "密码不能为空")
private String password; private String password;
@ApiModelProperty(value = "验证码", required = true)
@NotEmpty(message = "验证码不能传入为空")
private String authCode;
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public String getAuthCode() {
return authCode;
}
public String getUsername() { public String getUsername() {
return username; return username;
......
package com.macro.mall.dto.Vo;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Random;
public class ValidateCode {
private static Random random = new Random();
private int width = 160;// 宽
private int height = 40;// 高
private int lineSize = 30;// 干扰线数量
private int stringNum = 4;//随机产生字符的个数
private String randomString = "0123456789abcdefghijklmnopqrstuvwxyz";
private final String sessionKey = "RANDOMKEY";
/*
* 获取字体
*/
private Font getFont() {
return new Font("Times New Roman", Font.ROMAN_BASELINE, 40);
}
/*
* 获取颜色
*/
private static Color getRandomColor(int fc, int bc) {
fc = Math.min(fc, 255);
bc = Math.min(bc, 255);
int r = fc + random.nextInt(bc - fc - 16);
int g = fc + random.nextInt(bc - fc - 14);
int b = fc + random.nextInt(bc - fc - 12);
return new Color(r, g, b);
}
/*
* 绘制干扰线
*/
private void drawLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(20);
int yl = random.nextInt(10);
g.drawLine(x, y, x + xl, y + yl);
}
/*
* 获取随机字符
*/
private String getRandomString(int num) {
num = num > 0 ? num : randomString.length();
return String.valueOf(randomString.charAt(random.nextInt(num)));
}
/*
* 绘制字符串
*/
private String drawString(Graphics g, String randomStr, int i) {
g.setFont(getFont());
g.setColor(getRandomColor(108, 190));
System.out.println(random.nextInt(randomString.length()));
String rand = getRandomString(random.nextInt(randomString.length()));
randomStr += rand;
g.translate(random.nextInt(3), random.nextInt(6));
g.drawString(rand, 40 * i + 10, 25);
return randomStr;
}
/*
* 生成随机图片
*/
public void getRandomCodeImage(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.fillRect(0, 0, width, height);
g.setColor(getRandomColor(105, 189));
g.setFont(getFont());
// 绘制干扰线
for (int i = 0; i < lineSize; i++) {
drawLine(g);
}
// 绘制随机字符
String random_string = "";
for (int i = 0; i < stringNum; i++) {
random_string = drawString(g, random_string, i);
}
System.out.println(random_string);
g.dispose();
session.removeAttribute(sessionKey);
session.setAttribute(sessionKey, random_string);
String base64String = "";
try {
// 直接返回图片
ImageIO.write(image, "PNG", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 生成随机图片,返回 base64 字符串
*/
public String getRandomCodeBase64(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.fillRect(0, 0, width, height);
g.setColor(getRandomColor(105, 189));
g.setFont(getFont());
// 绘制干扰线
for (int i = 0; i < lineSize; i++) {
drawLine(g);
}
// 绘制随机字符
String random_string = "";
for (int i = 0; i < stringNum; i++) {
random_string = drawString(g, random_string, i);
}
System.out.println(random_string);
g.dispose();
session.removeAttribute(sessionKey);
session.setAttribute(sessionKey, random_string);
String base64String = "";
try {
// 直接返回图片
// ImageIO.write(image, "PNG", response.getOutputStream());
//返回 base64
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", bos);
byte[] bytes = bos.toByteArray();
Base64.Encoder encoder = Base64.getEncoder();
base64String = encoder.encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return base64String;
}
}
...@@ -68,16 +68,12 @@ public class UmsRoleServiceImpl implements UmsRoleService { ...@@ -68,16 +68,12 @@ public class UmsRoleServiceImpl implements UmsRoleService {
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public CommonResult delete(List<Long> ids) throws Exception { public CommonResult delete(List<Long> ids) throws Exception {
UmsRoleExample example = new UmsRoleExample(); UmsRole ur = new UmsRole();
example.createCriteria().andIdIn(ids); ur.setDeleteStatus(1);
List<UmsRole> roles = roleMapper.selectByExample(example); ids.forEach(id ->{
for (UmsRole role : roles) { ur.setId(id);
role.setDeleteStatus(1); roleMapper.updateByPrimaryKey(ur);
int i = roleMapper.updateByPrimaryKey(role); });
if (i == 0) {
throw new Exception();
}
}
return CommonResult.success("删除成功"); return CommonResult.success("删除成功");
} }
......
...@@ -2,9 +2,9 @@ server: ...@@ -2,9 +2,9 @@ server:
port: 8182 port: 8182
spring: spring:
datasource: datasource:
url: jdbc:mysql://47.98.234.186:3306/quanxing?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai url: jdbc:mysql://115.29.198.90:3306/vanke_download?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root username: root
password: liufang@xm999.COM password: root
druid: druid:
initial-size: 5 #连接池初始化大小 initial-size: 5 #连接池初始化大小
min-idle: 10 #最小空闲连接数 min-idle: 10 #最小空闲连接数
...@@ -14,6 +14,14 @@ spring: ...@@ -14,6 +14,14 @@ spring:
stat-view-servlet: #访问监控网页的登录用户名和密码 stat-view-servlet: #访问监控网页的登录用户名和密码
login-username: druid login-username: druid
login-password: druid login-password: druid
servlet:
multipart:
enabled: true
#最大支持文件大小
max-file-size: 100MB
#最大支持请求大小
max-request-size: 100MB
redis: redis:
host: 115.29.198.90 # Redis服务器地址 host: 115.29.198.90 # Redis服务器地址
database: 0 # Redis数据库索引(默认为0) database: 0 # Redis数据库索引(默认为0)
...@@ -85,6 +93,8 @@ secure: ...@@ -85,6 +93,8 @@ secure:
- /**/*.css - /**/*.css
- /**/*.png - /**/*.png
- /**/*.ico - /**/*.ico
- /**/*.jpg
- /**/*.zip
- /webjars/springfox-swagger-ui/** - /webjars/springfox-swagger-ui/**
- /actuator/** - /actuator/**
- /druid/** - /druid/**
...@@ -93,16 +103,19 @@ secure: ...@@ -93,16 +103,19 @@ secure:
- /admin/register - /admin/register
- /admin/info - /admin/info
- /admin/logout - /admin/logout
- /validateCode/**
aliyun: aliyun:
oss: oss:
endpoint: oss-cn-shenzhen.aliyuncs.com # oss对外服务的访问域名 endpoint: oss-cn-shenzhen.aliyuncs.com # oss对外服务的访问域名
accessKeyId: LTAI4FjFVYmaqrMi1sZS1TRf # 访问身份验证中用到用户标识 accessKeyId: LTAI4FjFVYmaqrMi1sZS1TRf # 访问身份验证中用到用户标识
accessKeySecret: MThxbXZvJC38FxnL6KEr9LDfl0rHjm # 用户用于加密签名字符串和oss用来验证签名字符串的密钥 accessKeySecret: MThxbXZvJC38FxnL6KEr9LDfl0rHjm # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
bucketName: haihaigo # oss的存储空间 bucketName: haihaigo # oss的存储空间
filepath: D:/files/ #本地文件存储路径
fileUrl: 192.168.31.127:8401/mall-admin/files/ #本地访问上传文件 如果部署到线上需要通过nginx去配置
policy: policy:
expire: 300 # 签名有效期(S) expire: 300 # 签名有效期(S)
maxSize: 1024 # 上传文件大小(M) maxSize: 1024 # 上传文件大小(M)
callback: http://115.29.198.90:8201/aliyun/oss/callback # 文件上传成功后的回调地址 callback: http://115.29.198.90:8202/aliyun/oss/callback # 文件上传成功后的回调地址
dir: dir:
prefix: mall/images/ # 上传文件夹路径前缀 prefix: mall/images/ # 上传文件夹路径前缀
# 自定义redis键值 # 自定义redis键值
......
...@@ -19,7 +19,7 @@ public class GlobalCorsConfig { ...@@ -19,7 +19,7 @@ public class GlobalCorsConfig {
public CorsWebFilter corsFilter() { public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration(); CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*"); config.addAllowedMethod("*");
// config.setAllowCredentials(true); config.setAllowCredentials(true);
config.addAllowedOrigin("*"); config.addAllowedOrigin("*");
config.addAllowedHeader("*"); config.addAllowedHeader("*");
......
...@@ -12,7 +12,7 @@ public class UmsAdmin implements Serializable { ...@@ -12,7 +12,7 @@ public class UmsAdmin implements Serializable {
@GeneratedValue(strategy= GenerationType.IDENTITY) @GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id; private Long id;
@ApiModelProperty(value = "用户类型 1平台 2商家 3服务商") @ApiModelProperty(value = "用户类型 1超级管理员 2普通管理员")
private Integer type; private Integer type;
private String username; private String username;
......
package com.macro.mall.model.vanke;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class FileDto {
@ApiModelProperty("文件名")
private String fileName;
@ApiModelProperty("文件位置")
private String filePath;
}
package com.macro.mall.model.vanke;
import com.macro.mall.model.VankeFile;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
@Data
public class VankeFileDto extends VankeFile implements Serializable {
@ApiModelProperty("关联创建人名称")
private String adminName;
@ApiModelProperty("文档分类名称")
private String fileTypeName;
@ApiModelProperty("如果根据时间倒序查询 传入1")
private Integer isByTime;
@ApiModelProperty("如果根据下载排行倒序查询 传入1")
private Integer isByDownloadTimes;
@ApiModelProperty("查询时间")
private String queryTime;
}
package com.macro.mall.model.vanke;
import com.macro.mall.model.VankeFileTimes;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
@Data
public class VankeFileTimesDto extends VankeFileTimes implements Serializable {
@ApiModelProperty("查询时间")
private String queryTime;
@ApiModelProperty("文件名")
private String fileName;
}
jdbc.driverClass=com.mysql.cj.jdbc.Driver jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://115.29.198.90:3306/quanxing?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai jdbc.connectionURL=jdbc:mysql://115.29.198.90:3306/vanke_download?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.userId=root jdbc.userId=root
jdbc.password=root jdbc.password=root
\ No newline at end of file
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
<javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.mapper" <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.mapper"
targetProject="mall-mbg/src/main/java"/> targetProject="mall-mbg/src/main/java"/>
<!--生成全部表tableName设为%--> <!--生成全部表tableName设为%-->
<table tableName="pms_product"> <table tableName="ums_admin">
<generatedKey column="id" sqlStatement="MySql" identity="true"/> <generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table> </table>
......
package com.macro.mall.portal.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class SourceConfiguration extends WebMvcConfigurerAdapter {
@Value("${aliyun.oss.filepath}")
private String filepath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* @Description: 对文件的路径进行配置,创建一个虚拟路径/file/** ,即只要在<img src="/file/images/20180522/9aa64b2b-a558-421e-929c-537ff0aecdba.jpg" />便可以直接引用图片
*这是图片的物理路径 "file:/+本地图片的地址"
* @Date: Create in 14:08 2017/12/20
*
*/
registry.addResourceHandler("/files/**").addResourceLocations("file:"+filepath);
super.addResourceHandlers(registry);
}
}
package com.macro.mall.portal.controller.vanke;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.VankeFile;
import com.macro.mall.model.vanke.FileDto;
import com.macro.mall.service.vanke.IVankeFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;
@Api(tags = "万科文档后台_文件上传下载相关接口", description = "文件上传下载控制器")
@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {
@Value("${aliyun.oss.filepath}")
private String filepath;
@Value("${aliyun.oss.fileUrl}")
private String fileUrl;
@Autowired
private IVankeFileService vankeFileService;
/**
* 处理文件上传
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ApiOperation(value = "文件上传")
@ResponseBody
public CommonResult uploading(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
if(file == null){
return CommonResult.failed("传入文件为空");
}
//获取uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//获取文件名的后缀名 截取.之后字符串
String preffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
//重命名操作
String newFileName =uuid + "."+ preffix;
File targetFile = new File(filepath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try (FileOutputStream out = new FileOutputStream(filepath + newFileName);){
out.write(file.getBytes());
} catch (Exception e) {
e.printStackTrace();
return CommonResult.failed("文件上传失败!");
}
//拼接起来 图片路径
FileDto fileDto = new FileDto();
fileDto.setFileName(newFileName);
fileDto.setFilePath(fileUrl+newFileName);
return CommonResult.success(fileDto,"文件上传成功!");
}
@RequestMapping(value="/downloadByFileId", method = RequestMethod.POST)
@ApiOperation(value = "文件下载根据文件id")
@ResponseBody
public CommonResult downloadByFileId(HttpServletResponse response,@ApiParam(value="文件Id") @RequestParam(value = "fileId", required = false) Long fileId) throws UnsupportedEncodingException {
VankeFile vankeFile = this.vankeFileService.selectById(fileId);
if(vankeFile == null){
return CommonResult.failed("不存在此文件");
}
this.vankeFileService.updateFileTimes(fileId);
File file = new File(filepath + "/" + vankeFile.getFileName());
if(file.exists()){
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(vankeFile.getFileName(),"utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
try(FileInputStream fis= new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
os = response.getOutputStream();
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return CommonResult.success(null,"操作成功");
}
@RequestMapping(value="/download", method = RequestMethod.POST)
@ApiOperation(value = "文件下载")
@ResponseBody
public void downLoad(HttpServletResponse response, @ApiParam(value="文件名") @RequestParam(value = "fileName")String fileName) throws UnsupportedEncodingException {
File file = new File(filepath + "/" + fileName);
if(file.exists()){
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName,"utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
try(FileInputStream fis= new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);) {
os = response.getOutputStream();
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@RequestMapping(value="/deleteFile", method = RequestMethod.POST)
@ApiOperation(value = "文件删除")
@ResponseBody
public CommonResult deleteFile(HttpServletRequest request, @ApiParam(value="文件名") @RequestParam(value = "fileName")String fileName){
if(fileName == null || "".equals(fileName)){
return CommonResult.failed("传入文件名为空");
}
File file = new File(filepath + "/" + fileName);
if(file.isFile() && file.exists()) {
file.delete();
return CommonResult.success(null,"删除成功");
}else{
return CommonResult.failed("不存在此文件名的文件");
}
}
}
package com.macro.mall.portal.controller.vanke;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.VankeFile;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileDto;
import com.macro.mall.model.vanke.VankeFileTimesDto;
import com.macro.mall.service.vanke.IVankeFileService;
import com.macro.mall.service.vanke.IVankeFileTimesService;
import com.netflix.discovery.converters.Auto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Api(tags = "万科文档后台_文件相关接口", description = "文件控制器")
@Controller
@RequestMapping("/vankeFile")
public class VankeFileController {
@Autowired
private IVankeFileService vankeFileService;
@ApiOperation("万科后台_文件分页操作")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<VankeFileDto>> list(@ApiParam(value="分页大小") @RequestParam(value = "pageSize", required = false) Integer pageSize,
@ApiParam(value="分页页数") @RequestParam(value = "pageNum", required = false) Integer pageNum,
@ApiParam(value="文档名称搜索") @RequestParam(value = "name", required = false) String name,
@ApiParam(value="文档类型id") @RequestParam(value = "typeId", required = false) Long typeId,
@ApiParam(value="如果根据时间倒序查询 传入1") @RequestParam(value = "isByTime", required = false) Integer isByTime,
@ApiParam(value="如果根据下载排行倒序查询 传入1") @RequestParam(value = "isByDownloadTimes", required = false) Integer isByDownloadTimes
) {
VankeFileDto vankeFileDto = new VankeFileDto();
vankeFileDto.setName(name);
vankeFileDto.setIsByTime(isByTime);
vankeFileDto.setIsByDownloadTimes(isByDownloadTimes);
vankeFileDto.setTypeId(typeId);
return CommonResult.success(CommonPage.restPage(this.vankeFileService.getPageList(pageNum,pageSize,vankeFileDto)));
}
@ApiOperation("万科后台_文件新增操作")
@RequestMapping(value = "/insertFile", method = RequestMethod.POST)
@ResponseBody
public CommonResult insertFile(@ApiParam(value="文件对象") @RequestBody VankeFile vankeFile
) {
ResultMsg res = this.vankeFileService.insertFile(vankeFile);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_根据id修改文件类型对象")
@RequestMapping(value = "/updateFile", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateFile(@ApiParam(value="文件对象") @RequestBody VankeFile vankeFile
) {
ResultMsg res = this.vankeFileService.updateFile(vankeFile);
if(res.isFlag()){
return CommonResult.success(null,res.getMsg());
}
return CommonResult.failed(res.getMsg());
}
@ApiOperation("万科后台_得到首页数据")
@RequestMapping(value = "/getHomeData", method = RequestMethod.GET)
@ResponseBody
public CommonResult getHomeData(){
return CommonResult.success(this.vankeFileService.homeData(),"查询成功");
}
}
...@@ -2,9 +2,9 @@ server: ...@@ -2,9 +2,9 @@ server:
port: 8086 port: 8086
spring: spring:
datasource: datasource:
url: jdbc:mysql://47.98.234.186:3306/quanxing?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai url: jdbc:mysql://115.29.198.90:3306/quanxing?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root username: root
password: liufang@xm999.COM password: root
druid: druid:
initial-size: 5 #连接池初始化大小 initial-size: 5 #连接池初始化大小
min-idle: 10 #最小空闲连接数 min-idle: 10 #最小空闲连接数
...@@ -81,6 +81,8 @@ secure: ...@@ -81,6 +81,8 @@ secure:
- /**/*.css - /**/*.css
- /**/*.png - /**/*.png
- /**/*.ico - /**/*.ico
- /**/*.jpg
- /**/*.zip
- /webjars/springfox-swagger-ui/** - /webjars/springfox-swagger-ui/**
- /druid/** - /druid/**
- /actuator/** - /actuator/**
...@@ -118,17 +120,19 @@ aliyun: ...@@ -118,17 +120,19 @@ aliyun:
accessKeyId: LTAI4FjFVYmaqrMi1sZS1TRf # 访问身份验证中用到用户标识 accessKeyId: LTAI4FjFVYmaqrMi1sZS1TRf # 访问身份验证中用到用户标识
accessKeySecret: MThxbXZvJC38FxnL6KEr9LDfl0rHjm # 用户用于加密签名字符串和oss用来验证签名字符串的密钥 accessKeySecret: MThxbXZvJC38FxnL6KEr9LDfl0rHjm # 用户用于加密签名字符串和oss用来验证签名字符串的密钥
bucketName: haihaigo # oss的存储空间 bucketName: haihaigo # oss的存储空间
filepath: D:/files/ #本地文件存储路径
fileUrl: 192.168.31.127:8401/mall-admin/files/ #本地访问上传文件 如果部署到线上需要通过nginx去配置
policy: policy:
expire: 300 # 签名有效期(S) expire: 300 # 签名有效期(S)
maxSize: 1024 # 上传文件大小(M) maxSize: 1024 # 上传文件大小(M)
callback: http://115.29.198.90:8201/aliyun/oss/callback # 文件上传成功后的回调地址 callback: http://115.29.198.90:8202/aliyun/oss/callback # 文件上传成功后的回调地址
dir: dir:
prefix: mall/images/ # 上传文件夹路径前缀 prefix: mall/images/ # 上传文件夹路径前缀
swagger: swagger:
enable: true #关闭swagger配置 true开启 false关闭 enable: true #关闭swagger配置 true开启 false关闭
pay: pay:
wx: wx:
url: http://115.29.198.90:8201/mall-portal/api/z url: http://115.29.198.90:8202/mall-portal/api/z
youzanupload: youzanupload:
# url: D:/pic/ # url: D:/pic/
url: /opt/ url: /opt/
......
package com.macro.mall.portal; package com.macro.mall.portal;
import com.macro.mall.api.KdniaoSubscribeAPI; import java.io.IOException;
import com.macro.mall.common.api.KdniaoSubscribeParam; import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
...@@ -12,13 +26,165 @@ import org.springframework.test.context.junit4.SpringRunner; ...@@ -12,13 +26,165 @@ import org.springframework.test.context.junit4.SpringRunner;
public class MallPortalApplicationTests { public class MallPortalApplicationTests {
@Test @Test
public void contextLoads() { public void ADLogin1() {
String userName = "xiexy";//AD域认证,用户的登录UserName
String password = "Xie04-21";//AD域认证,用户的登录PassWord
String host = "10.0.1.1";//AD域IP,必须填写正确
String domain = "@vanke.com";//域名后缀,例.@noker.cn.com
String port = "389"; //端口,一般默认389
String url = new String("ldap://" + host + ":" + port);//固定写法
String user = userName.indexOf(domain) > 0 ? userName : userName
+ domain;//网上有别的方法,但是在我这儿都不好使,建议这么使用
Hashtable env = new Hashtable();//实例化一个Env
DirContext ctx = null;
env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式,这么写就行
env.put(Context.SECURITY_PRINCIPAL, user); //用户名
env.put(Context.SECURITY_CREDENTIALS, password);//密码
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
env.put(Context.PROVIDER_URL, url);//Url
try {
ctx = new InitialDirContext(env);// 初始化上下文
System.out.println("身份验证成功!");
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@Test
public void validateAd() {
String userid="admin";
String password="admin";
// ldap认证
boolean flag = false;
LdapContext ctx = null;
Hashtable env = new Hashtable();
try{
// 采用简单模式
env.put(Context.SECURITY_AUTHENTICATION, "simple");
// ldap默认端口为389
env.put(Context.PROVIDER_URL, "ldap://192.168.31.127:389");
// 被验证的用户。ps:需带上域或者邮箱后缀
env.put(Context.SECURITY_PRINCIPAL, "global\\"+userid);
// 被验证用户的密码。
env.put(Context.SECURITY_CREDENTIALS, password);
// LDAP工厂类
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
// 连接超时设置为3秒
//env.put(com.sun.jndi.ldap.connect.timeout, 3000);
// 初始化上下文
ctx = new InitialLdapContext(env, null);
flag = true;
}catch(Exception exception) {
System.out.println(userid+"用户,身份验证未知异常!");
exception.printStackTrace();
}finally{
if(null!=ctx){
try { try {
KdniaoSubscribeAPI kdniaoSubscribeAPI = new KdniaoSubscribeAPI(); ctx.close();
// KdniaoSubscribeParam param = kdniaoSubscribeAPI.getOrderTracesByJson("ANE", "210001633605"); ctx=null;
// System.out.println(param);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}
System.out.println(flag);
}
@Test
public void test1(){
Properties env = new Properties();
String adminName = "administrator@2003.com";//username@domain
String adminPassword = "admin";//password
String ldapURL = "LDAP://192.168.31.127:389";//ip:port
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");//"none","simple","strong"
env.put(Context.SECURITY_PRINCIPAL, adminName);
env.put(Context.SECURITY_CREDENTIALS, adminPassword);
env.put(Context.PROVIDER_URL, ldapURL);
try {
LdapContext ctx = new InitialLdapContext(env, null);
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
String searchBase = "DC=2003,DC=com";
String returnedAtts[] = {"memberOf"};
searchCtls.setReturningAttributes(returnedAtts);
NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter,searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
System.out.println("<<<::[" + sr.getName()+"]::>>>>");
}
ctx.close();
}catch (NamingException e) {
e.printStackTrace();
System.err.println("Problem searching directory: " + e);
}
}
@Test
public void test2(){
String userName = "username";//AD域认证,用户的登录UserName
String password = "";//AD域认证,用户的登录PassWord
String host = "xxx.xxx.xxx.xxx";//AD域IP,必须填写正确
String domain = "@xxx.xx";//域名后缀,例.@noker.cn.com
String port = "389"; //端口,一般默认389
String url = new String("ldap://" + host + ":" + port);//固定写法
String user = userName.indexOf(domain) > 0 ? userName : userName
+ domain;//网上有别的方法,但是在我这儿都不好使,建议这么使用
Hashtable env = new Hashtable();//实例化一个Env
DirContext ctx = null;
env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式,这么写就行
env.put(Context.SECURITY_PRINCIPAL, user); //用户名
env.put(Context.SECURITY_CREDENTIALS, password);//密码
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
env.put(Context.PROVIDER_URL, url);//Url
try {
ctx = new InitialDirContext(env);// 初始化上下文
System.out.println("身份验证成功!");
} catch (AuthenticationException e) {
System.out.println("身份验证失败!");
e.printStackTrace();
} catch (javax.naming.CommunicationException e) {
System.out.println("AD域连接失败!");
e.printStackTrace();
} catch (Exception e) {
System.out.println("身份验证未知异常!");
e.printStackTrace();
} finally{
if(null!=ctx){
try {
ctx.close();
ctx=null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} }
...@@ -27,7 +27,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { ...@@ -27,7 +27,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired(required = false) @Autowired(required = false)
private DynamicSecurityService dynamicSecurityService; private DynamicSecurityService dynamicSecurityService;
private static String[] WHITE_LIST = {"/pmsSupplierAudit/auditSupplier"};//添加注册接口为白名单 private static String[] WHITE_LIST = {};//添加注册接口为白名单
@Override @Override
protected void configure(HttpSecurity httpSecurity) throws Exception { protected void configure(HttpSecurity httpSecurity) throws Exception {
......
...@@ -2,6 +2,7 @@ package com.macro.mall.dao; ...@@ -2,6 +2,7 @@ package com.macro.mall.dao;
import com.macro.mall.domain.dto.AdminManageParam; import com.macro.mall.domain.dto.AdminManageParam;
import com.macro.mall.domain.dto.UmsAdminQueryParam; import com.macro.mall.domain.dto.UmsAdminQueryParam;
import com.macro.mall.model.UmsAdmin;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import java.util.List; import java.util.List;
...@@ -26,4 +27,11 @@ public interface UmsAdminDao { ...@@ -26,4 +27,11 @@ public interface UmsAdminDao {
* @return * @return
*/ */
List<AdminManageParam> getOne(@Param("id") Long id); List<AdminManageParam> getOne(@Param("id") Long id);
/**
* 查询管理员List
* @param umsAdmin
* @return
*/
List<AdminManageParam> selectPageList(UmsAdmin umsAdmin);
} }
package com.macro.mall.dao.vanke;
import com.macro.mall.model.vanke.VankeFileDto;
import java.util.List;
public interface VankeFileDao {
/**
* 分页查询
* @return
*/
List<VankeFileDto> selectPageList(VankeFileDto vankeFileDto);
/**
* 查询今日下载量
* @param queryTime
* @return
*/
Integer selectFileNum(VankeFileDto vankeFileDto);
/**
* 查询累计下载次数
* @return
*/
Long selectUploadTimes();
}
package com.macro.mall.dao.vanke;
import com.macro.mall.model.VankeFileTimes;
import com.macro.mall.model.vanke.VankeFileTimesDto;
import java.util.List;
public interface VankeFileTimesDao {
/**
* 分页查询
* @param vankeFileTimesDto
* @return
*/
List<VankeFileTimesDto> getPageList(VankeFileTimesDto vankeFileTimesDto);
/**
* 根据时间和文件id查询
* @param vankeFileTimesDto
* @return
*/
VankeFileTimes selectByFileIdAndTime(VankeFileTimesDto vankeFileTimesDto);
/**
* 根据时间查询下载次数
* @param queryTime
* @return
*/
Integer selectTimesNum(String queryTime);
}
...@@ -9,6 +9,7 @@ import com.macro.mall.model.UmsAdmin; ...@@ -9,6 +9,7 @@ import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsPermission; import com.macro.mall.model.UmsPermission;
import com.macro.mall.model.UmsResource; import com.macro.mall.model.UmsResource;
import com.macro.mall.model.UmsRole; import com.macro.mall.model.UmsRole;
import com.macro.mall.model.common.ResultMsg;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -46,6 +47,17 @@ public interface UmsAdminService { ...@@ -46,6 +47,17 @@ public interface UmsAdminService {
UmsAdmin register(UmsAdminParam umsAdminParam); UmsAdmin register(UmsAdminParam umsAdminParam);
/** /**
* 得到会员对象
* @return
*/
UmsAdmin getCurrentUmsAdmin();
/**
* 得到会员对象Id
* @return
*/
Long getCurrentUmsAdminId();
/**
* 登录功能 * 登录功能
* *
* @param username 用户名 * @param username 用户名
...@@ -53,7 +65,7 @@ public interface UmsAdminService { ...@@ -53,7 +65,7 @@ public interface UmsAdminService {
* @param type * @param type
* @return 生成的JWT的token * @return 生成的JWT的token
*/ */
CommonResult login(String username, String password, Integer type); CommonResult login(String username, String password,String authCode,String sessionAuthCode, Integer type);
/** /**
* 刷新token的功能 * 刷新token的功能
...@@ -176,4 +188,24 @@ public interface UmsAdminService { ...@@ -176,4 +188,24 @@ public interface UmsAdminService {
* @return * @return
*/ */
int updateAdmin(Long id, AdminUpdateParam admin); int updateAdmin(Long id, AdminUpdateParam admin);
/**
* 分页查询
* @return
*/
List<AdminManageParam> getPageList(Integer pageNum,Integer pageSize,UmsAdmin umsAdmin);
/**
* 新增一个管理员
* @param umsAdmin
* @return
*/
ResultMsg insertAdmin(UmsAdmin umsAdmin);
/**
* 根据id修改一条数据
* @param umsAdmin
* @return
*/
ResultMsg updateAdmin(UmsAdmin umsAdmin);
} }
...@@ -12,6 +12,7 @@ import com.macro.mall.domain.dto.UmsAdminParam; ...@@ -12,6 +12,7 @@ import com.macro.mall.domain.dto.UmsAdminParam;
import com.macro.mall.domain.dto.UmsAdminQueryParam; import com.macro.mall.domain.dto.UmsAdminQueryParam;
import com.macro.mall.mapper.*; import com.macro.mall.mapper.*;
import com.macro.mall.model.*; import com.macro.mall.model.*;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.security.admin.AdminUserDetails; import com.macro.mall.security.admin.AdminUserDetails;
import com.macro.mall.security.admin.DgbSecurityUserHelper; import com.macro.mall.security.admin.DgbSecurityUserHelper;
import com.macro.mall.security.util.JwtTokenUtil; import com.macro.mall.security.util.JwtTokenUtil;
...@@ -101,6 +102,28 @@ public class UmsAdminServiceImpl implements UmsAdminService { ...@@ -101,6 +102,28 @@ public class UmsAdminServiceImpl implements UmsAdminService {
} }
@Override @Override
public UmsAdmin getCurrentUmsAdmin() {
SecurityContext ctx = SecurityContextHolder.getContext();
Authentication auth = ctx.getAuthentication();
if (auth != null) {
AdminUserDetails adminUserDetails = (AdminUserDetails)auth.getPrincipal();
return adminUserDetails.getUmsAdmin();
}
return null;
}
@Override
public Long getCurrentUmsAdminId() {
SecurityContext ctx = SecurityContextHolder.getContext();
Authentication auth = ctx.getAuthentication();
if (auth != null && auth.getPrincipal() instanceof MemberDetails) {
AdminUserDetails adminUserDetails = (AdminUserDetails)auth.getPrincipal();
return adminUserDetails.getUmsAdmin().getId();
}
return null;
}
@Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public UmsAdmin register(UmsAdminParam umsAdminParam) { public UmsAdmin register(UmsAdminParam umsAdminParam) {
UmsAdmin umsAdmin = new UmsAdmin(); UmsAdmin umsAdmin = new UmsAdmin();
...@@ -128,19 +151,14 @@ public class UmsAdminServiceImpl implements UmsAdminService { ...@@ -128,19 +151,14 @@ public class UmsAdminServiceImpl implements UmsAdminService {
} }
@Override @Override
public CommonResult login(String username, String password, Integer type) { public CommonResult login(String username, String password, String authCode,String sessionAuthCode, Integer type) {
String token = null; String token = null;
//密码需要客户端加密后传递 //密码需要客户端加密后传递
boolean isMcht = false; boolean isMcht = false;
boolean isService = false; boolean isService = false;
try { try {
UmsAdmin admin = getAdminByUsername(username); UmsAdmin admin = getAdminByUsername(username);
if (admin != null) { if (admin == null) {
Integer type1 = admin.getType();
if (!type.equals(type1)) {
return CommonResult.failed("不是该平台的用户");
}
} else {
return CommonResult.failed("用户不存在"); return CommonResult.failed("用户不存在");
} }
if (admin.getDeleteStatus().equals(1)) { if (admin.getDeleteStatus().equals(1)) {
...@@ -150,6 +168,14 @@ public class UmsAdminServiceImpl implements UmsAdminService { ...@@ -150,6 +168,14 @@ public class UmsAdminServiceImpl implements UmsAdminService {
if (!passwordEncoder.matches(password, userDetails.getPassword())) { if (!passwordEncoder.matches(password, userDetails.getPassword())) {
return CommonResult.failed("密码不正确"); return CommonResult.failed("密码不正确");
} }
//校验验证码
if(authCode == null || "".equals(authCode)){
return CommonResult.failed("验证码为空");
}
if ( !authCode.toLowerCase().equals(sessionAuthCode)) {
return CommonResult.failed("输入验证码错误");
}
Integer status = admin.getStatus(); Integer status = admin.getStatus();
if (status == 0) { if (status == 0) {
return CommonResult.failed("您已被禁用请联系平台管理员!"); return CommonResult.failed("您已被禁用请联系平台管理员!");
...@@ -642,5 +668,60 @@ public class UmsAdminServiceImpl implements UmsAdminService { ...@@ -642,5 +668,60 @@ public class UmsAdminServiceImpl implements UmsAdminService {
return umsAdminRoleRelations.get(0).getRoleId(); return umsAdminRoleRelations.get(0).getRoleId();
} }
/**
* 分页查询
* @return
*/
@Override
public List<AdminManageParam> getPageList(Integer pageNum,Integer pageSize,UmsAdmin umsAdmin){
if(pageNum != null && pageSize != null){
PageHelper.startPage(pageNum, pageSize);
}
return this.adminDao.selectPageList(umsAdmin);
}
/**
* 新增一个管理员
* @param umsAdmin
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg insertAdmin(UmsAdmin umsAdmin){
ResultMsg res = this.checkUmsAdmin(umsAdmin);
if(!res.isFlag()){
return new ResultMsg(false,res.getMsg());
}
this.adminMapper.insertSelective(umsAdmin);
return new ResultMsg(true,"操作成功");
}
/**
* 根据id修改一条数据
* @param umsAdmin
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg updateAdmin(UmsAdmin umsAdmin){
if(umsAdmin.getId() == null){
return new ResultMsg(false,"传入id为空");
}
this.adminMapper.updateByPrimaryKeySelective(umsAdmin);
return new ResultMsg(true,"修改成功");
}
private ResultMsg checkUmsAdmin(UmsAdmin umsAdmin){
if(umsAdmin.getUsername() == null || "".equals(umsAdmin.getUsername())){
return new ResultMsg(false,"传入账号为空");
}
if(umsAdmin.getPassword() == null || "".equals(umsAdmin.getPassword())){
return new ResultMsg(false,"传入密码为空");
}
if(umsAdmin.getName() == null || "".equals(umsAdmin.getName())){
return new ResultMsg(false,"传入姓名为空");
}
return new ResultMsg(true,"校验通过");
}
} }
package com.macro.mall.service.vanke;
import com.macro.mall.model.VankeFile;
import com.macro.mall.model.VankeFileType;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileDto;
import java.util.List;
public interface IVankeFileService {
/**
* 分页操作
* @param vankeFileDto
* @return
*/
List<VankeFileDto> getPageList(Integer pageNum, Integer pageSize,VankeFileDto vankeFileDto);
/**
* 插入一条文件
* @param vankeFile
* @return
*/
ResultMsg insertFile(VankeFile vankeFile );
/**
* 更新文件下载数量
* @param fileId
* @return
*/
ResultMsg updateFileTimes(Long fileId);
/**
* 根据id修改一条数据
* @param vankeFile
* @return
*/
ResultMsg updateFile(VankeFile vankeFile);
/**
* 获取首页数据
* @return
*/
ResultMsg homeData();
/**
* 根据主键查询
* @param id
* @return
*/
VankeFile selectById(Long id);
}
package com.macro.mall.service.vanke;
import com.macro.mall.model.VankeFileTimes;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileTimesDto;
import java.util.List;
public interface IVankeFileTimesService {
/**
* 更新下载次数
* @return
*/
ResultMsg updateTimes(Long fileId);
/**
* 分页查询
* @param pageNum
* @param pageSize
* @param vankeFileTimesDto
* @return
*/
List<VankeFileTimesDto> getPageList(Integer pageNum,Integer pageSize,VankeFileTimesDto vankeFileTimesDto);
}
package com.macro.mall.service.vanke;
import com.macro.mall.model.VankeFileType;
import com.macro.mall.model.common.ResultMsg;
import java.util.List;
public interface IVankeFileTypeService {
/**
* 分页操作
* @param pageNum
* @param pageSize
* @return
*/
List<VankeFileType> getPageList(Integer pageNum, Integer pageSize);
/**
* 插入万科文档分类名称
* @param vankeFileType
* @return
*/
ResultMsg insertFileType(VankeFileType vankeFileType);
/**
* 根据id修改对应的数据
* @param vankeFileType
* @return
*/
ResultMsg updateById(VankeFileType vankeFileType);
}
package com.macro.mall.service.vanke.impl;
import com.github.pagehelper.PageHelper;
import com.macro.mall.dao.vanke.VankeFileDao;
import com.macro.mall.dao.vanke.VankeFileTimesDao;
import com.macro.mall.mapper.VankeFileMapper;
import com.macro.mall.model.VankeFile;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileDto;
import com.macro.mall.service.vanke.IVankeFileService;
import com.macro.mall.service.vanke.IVankeFileTimesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class VankeFileServiceImpl implements IVankeFileService {
@Resource
private VankeFileDao vankeFileDao;
@Resource
private VankeFileMapper vankeFileMapper;
@Resource
private VankeFileTimesDao vankeFileTimesDao;
@Autowired
private IVankeFileTimesService vankeFileTimesService;
/**
* 分页操作
* @param vankeFileDto
* @return
*/
@Override
public List<VankeFileDto> getPageList(Integer pageNum, Integer pageSize,VankeFileDto vankeFileDto){
if(pageNum != null && pageSize != null){
PageHelper.startPage(pageNum, pageSize);
}
return this.vankeFileDao.selectPageList(vankeFileDto);
}
/**
* 更新文件下载数量
* @param fileId
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg updateFileTimes(Long fileId){
//更新文件下载次数
VankeFile vankeFile = this.vankeFileMapper.selectByPrimaryKey(fileId);
if(vankeFile == null){
return new ResultMsg(false,"不存在此文件");
}else{
vankeFile.setTimes(vankeFile.getTimes() + 1);
this.vankeFileMapper.updateByPrimaryKeySelective(vankeFile);
}
//更新今日下载数
this.vankeFileTimesService.updateTimes(fileId);
return new ResultMsg(true,"操作成功");
}
/**
* 插入一条文件
* @param vankeFile
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg insertFile(VankeFile vankeFile){
ResultMsg res = this.checkFile(vankeFile);
if(!res.isFlag()){
return new ResultMsg(false,res.getMsg());
}
this.vankeFileMapper.insertSelective(vankeFile);
return new ResultMsg(true,"操作成功");
}
private ResultMsg checkFile(VankeFile vankeFile){
if(vankeFile.getName() == null || "".equals(vankeFile.getName())){
return new ResultMsg(false,"传入文档名称为空");
}
if(vankeFile.getTypeId() == null){
return new ResultMsg(false,"传入文档类型id为空");
}
return new ResultMsg(true,"校验通过");
}
/**
* 根据id修改一条数据
* @param vankeFile
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg updateFile(VankeFile vankeFile){
if(vankeFile.getId() == null){
return new ResultMsg(false,"传入id为空");
}
this.vankeFileMapper.updateByPrimaryKeySelective(vankeFile);
return new ResultMsg(true,"操作成功");
}
/**
* 获取首页数据
* @return
*/
@Override
public ResultMsg homeData(){
//得到现在时间
String queryTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
String queryTime2="";//有些查询需要根据时间 有些不需要 所以再初始化一个空的查询时间
//初始化查询对象
VankeFileDto vankeFileDto = new VankeFileDto();
vankeFileDto.setQueryTime(queryTime);
//初始化返回数据对象
Map<String,Object> map = new HashMap<>();
//查询今日上传数量
map.put("todayUpload",this.vankeFileDao.selectFileNum(vankeFileDto));
//查询今日下载
map.put("todayDownload",this.vankeFileTimesDao.selectTimesNum(queryTime));
//累计上传
vankeFileDto.setQueryTime(queryTime2);
map.put("totalUpload",this.vankeFileDao.selectFileNum(vankeFileDto));
//累计下载次数
map.put("totalDownload",this.vankeFileDao.selectUploadTimes());
return new ResultMsg(true,"查询成功",map);
}
/**
* 根据主键查询
* @param id
* @return
*/
@Override
public VankeFile selectById(Long id){
return this.vankeFileMapper.selectByPrimaryKey(id);
}
}
package com.macro.mall.service.vanke.impl;
import com.github.pagehelper.PageHelper;
import com.macro.mall.dao.vanke.VankeFileTimesDao;
import com.macro.mall.mapper.VankeFileTimesMapper;
import com.macro.mall.model.VankeFileTimes;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.model.vanke.VankeFileTimesDto;
import com.macro.mall.service.vanke.IVankeFileTimesService;
import org.junit.Test;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class VankeFileTimesServiceImpl implements IVankeFileTimesService {
@Resource
private VankeFileTimesMapper vankeFileTimesMapper;
@Resource
private VankeFileTimesDao vankeFileTimesDao;
/**
* 分页查询
* @param pageNum
* @param pageSize
* @param vankeFileTimesDto
* @return
*/
@Override
public List<VankeFileTimesDto> getPageList(Integer pageNum, Integer pageSize, VankeFileTimesDto vankeFileTimesDto){
//分页操作
if(pageNum != null && pageSize!= null){
PageHelper.startPage(pageNum, pageSize);
}
vankeFileTimesDto.setQueryTime( new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString());
return this.vankeFileTimesDao.getPageList(vankeFileTimesDto);
}
/**
* 根据文件id更新下载次数
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg updateTimes(Long fileId){
//1、得到当前年月日 eg: 2020-07-07
String nowDays = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
//初始化查询对象
VankeFileTimesDto vankeFileTimesDto = new VankeFileTimesDto();
vankeFileTimesDto.setQueryTime(nowDays);
vankeFileTimesDto.setFileId(fileId);
//根据服务器当前时间 查询是否存在
VankeFileTimes vankeFileTimes = vankeFileTimesDao.selectByFileIdAndTime(vankeFileTimesDto);
if(vankeFileTimes == null){
vankeFileTimes = new VankeFileTimes();
vankeFileTimes.setFileId(fileId);
vankeFileTimes.setTimes(1);
this.vankeFileTimesMapper.insertSelective(vankeFileTimes);
}else{
vankeFileTimes.setTimes(vankeFileTimes.getTimes()+1);
this.vankeFileTimesMapper.updateByPrimaryKeySelective(vankeFileTimes);
}
return new ResultMsg(true,"操作成功");
}
@Test
public void test(){
//1、普通的时间转换
String string = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString();
System.out.println(string);
}
}
package com.macro.mall.service.vanke.impl;
import com.github.pagehelper.PageHelper;
import com.macro.mall.mapper.VankeFileTypeMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.VankeFileType;
import com.macro.mall.model.VankeFileTypeExample;
import com.macro.mall.model.common.ResultMsg;
import com.macro.mall.service.system.UmsAdminService;
import com.macro.mall.service.vanke.IVankeFileTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
public class VankeFileTypeServiceImpl implements IVankeFileTypeService {
@Resource
private VankeFileTypeMapper vankeFileTypeMapper;
@Autowired
private UmsAdminService umsAdminService;
/**
* 分页操作
* @param pageNum
* @param pageSize
* @return
*/
@Override
public List<VankeFileType> getPageList(Integer pageNum, Integer pageSize){
if(pageNum != null && pageSize != null){
PageHelper.startPage(pageNum, pageSize);
}
VankeFileTypeExample example = new VankeFileTypeExample();
VankeFileTypeExample.Criteria criteria = example.createCriteria();
criteria.andDeleteStatusEqualTo(1);//'1未删除 0已删除'
return this.vankeFileTypeMapper.selectByExample(example);
}
/**
* 插入万科文档分类名称
* @param vankeFileType
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg insertFileType(VankeFileType vankeFileType){
if(vankeFileType.getName() == null || "".equals(vankeFileType.getName())){
return new ResultMsg(false,"传入分类名称为空");
}
vankeFileType.setCreateBy(umsAdminService.getCurrentUmsAdminId());
this.vankeFileTypeMapper.insertSelective(vankeFileType);
return new ResultMsg(true,"操作成功");
}
/**
* 根据id修改对应的数据
* @param vankeFileType
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public ResultMsg updateById(VankeFileType vankeFileType){
if(vankeFileType.getId() == null ){
return new ResultMsg(false,"传入id为空");
}
this.vankeFileTypeMapper.updateByPrimaryKeySelective(vankeFileType);
return new ResultMsg(true,"操作成功");
}
}
...@@ -59,4 +59,11 @@ ...@@ -59,4 +59,11 @@
</if> </if>
</where> </where>
</select> </select>
<select id="selectPageList" parameterType="com.macro.mall.model.UmsAdmin" resultMap="resultMap">
select * from ums_admin
where delete_status = 0
order by create_time desc
</select>
</mapper> </mapper>
\ 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="com.macro.mall.dao.vanke.VankeFileDao">
<resultMap id="BaseResultMap" type="com.macro.mall.model.vanke.VankeFileDto" extends="com.macro.mall.mapper.VankeFileMapper.BaseResultMap">
<result column="adminName" jdbcType="VARCHAR" property="adminName" />
<result column="fileTypeName" jdbcType="VARCHAR" property="fileTypeName" />
</resultMap>
<select id="selectPageList" parameterType="com.macro.mall.model.vanke.VankeFileDto" resultMap="BaseResultMap">
select a.* , b.name adminName, c.name fileTypeName from vanke_file a
left join ums_admin b ON a.create_by = b.id
left join vanke_file_type c ON a.type_id = c.id
where a.delete_status = 1
<if test="name != null and name != ''">
and a.name like CONCAT(#{name},'%')
</if>
<if test="typeId != null">
and a.type_id = #{typeId}
</if>
<if test="isByTime!= null and isByTime == 1">
order by a.createtime desc
</if>
<if test="isByDownloadTimes!= null and isByDownloadTimes == 1">
order by a.times desc
</if>
</select>
<select id="selectFileNum" parameterType="com.macro.mall.model.vanke.VankeFileDto" resultType="java.lang.Integer">
select count(id) from vanke_file
<where>
<if test=" queryTime != null and queryTime != ''">
and #{queryTime} = date_format( createtime, '%Y-%m-%d' )
</if>
</where>
</select>
<select id="selectUploadTimes" resultType="java.lang.Long">
SELECT SUM(times)from vanke_file
</select>
</mapper>
\ 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="com.macro.mall.dao.vanke.VankeFileTimesDao">
<resultMap id="BaseResultMap" type="com.macro.mall.model.vanke.VankeFileTimesDto" extends="com.macro.mall.mapper.VankeFileTimesMapper.BaseResultMap">
<result column="fileName" jdbcType="VARCHAR" property="fileName" />
</resultMap>
<select id="getPageList" parameterType="com.macro.mall.model.vanke.VankeFileTimesDto" resultMap="BaseResultMap">
select a.*,b.name fileName from vanke_file_times a
left join vanke_file b ON a.file_id = b.id
<where>
<if test="queryTime != null and queryTime != ''">
#{queryTime} = date_format( a.createtime, '%Y-%m-%d' )
</if>
</where>
order by a.times desc
</select>
<select id="selectByFileIdAndTime" parameterType="com.macro.mall.model.vanke.VankeFileTimesDto" resultMap="BaseResultMap">
select * from vanke_file_times
where #{queryTime} = date_format( createtime, '%Y-%m-%d' )
and file_id = #{fileId}
</select>
<select id="selectTimesNum" parameterType="java.lang.String" resultType="java.lang.Integer">
select IFNULL(SUM(times),0) from vanke_file_times
where #{queryTime} = date_format( createtime, '%Y-%m-%d' )
</select>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment