This commit is contained in:
xiangwbs
2018-06-19 22:17:03 +08:00
parent 2ddba378d7
commit 0907e01a13
31 changed files with 893 additions and 241 deletions
@@ -40,10 +40,10 @@ public class ApplicationContextConfig {
*
* @return
*/
@Bean
@Bean(name = "multipartResolver")
public CommonsMultipartResolver getCommonsMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(104857600);
multipartResolver.setMaxUploadSize(5 * 1024 * 1024);//5M
multipartResolver.setDefaultEncoding("UTF-8");
return multipartResolver;
}
@@ -71,3 +71,4 @@ public class ApplicationContextConfig {
return poolTaskExecutor;
}
}
@@ -5,8 +5,11 @@ import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.xwbing.handler.LoginInterceptor;
import com.xwbing.handler.UrlPermissionsInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
@@ -21,18 +24,28 @@ import java.util.List;
* 创建时间: 2017/5/10 16:36
* 作者: xiangwb
*/
@Slf4j
@Configuration
@PropertySource("classpath:config.properties")
public class DispatcherServletConfig extends WebMvcConfigurerAdapter {
@Value("${loginInterceptorEnable}")
private boolean loginInterceptorEnable;
@Value("${urlPermissionsInterceptorEnable}")
private boolean urlPermissionsInterceptorEnable;
/***
* 添加拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//登录拦截器
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
//权限拦截器
registry.addInterceptor(urlPermissionsInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
if(loginInterceptorEnable){
log.info("注册登录拦截器LoginInterceptor ======================= ");
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
}
if(urlPermissionsInterceptorEnable){
log.info("注册权限拦截器UrlPermissionsInterceptor ======================= ");
registry.addInterceptor(urlPermissionsInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");
}
super.addInterceptors(registry);
}
@@ -124,6 +137,7 @@ public class DispatcherServletConfig extends WebMvcConfigurerAdapter {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
mediaTypes.add(MediaType.MULTIPART_FORM_DATA);
mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
mediaTypes.add(MediaType.TEXT_HTML);
messageConverter.setSupportedMediaTypes(mediaTypes);
@@ -139,3 +153,4 @@ public class DispatcherServletConfig extends WebMvcConfigurerAdapter {
return messageConverter;
}
}
@@ -1,10 +1,14 @@
package com.xwbing.configuration;
import com.xwbing.handler.FormRepeatFilter;
import com.xwbing.util.captcha.CaptchaServlet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 说明: 统一servlet/filter配置
@@ -14,24 +18,29 @@ import org.springframework.context.annotation.Configuration;
*/
@Slf4j
@Configuration
@PropertySource("classpath:config.properties")
public class ServletFilterConfig {
@Value("${formSaveFilterEnable}")
private boolean formSaveFilterEnable;
@Bean
public ServletRegistrationBean captchaServlet() {
log.info("注册登陆验证码servlet ======================= ");
log.info("注册登陆验证码CaptchaServlet ======================= ");
ServletRegistrationBean registration = new ServletRegistrationBean(new CaptchaServlet());
registration.addUrlMappings("/captcha");
return registration;
}
/*servlet*****************************************************filter*/
// @Bean
// public FilterRegistrationBean formSaveFilter() {
// log.info("注册表单重复提交过滤器formSaveFilter ======================= ");
// FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new FormRepeatFilter());
// filterRegistrationBean.addUrlPatterns("/*");
// filterRegistrationBean.addInitParameter("excludePath", "/doc,/captcha,/v2/api-docs,/swagger-resources,/configuration/ui,/configuration/security,/druid");
// filterRegistrationBean.addInitParameter("excludeType", ".js,.css,.gif,.jpg,.png,.ico,.jsp,.html,/druid/");
// return filterRegistrationBean;
// }
@Bean
public FilterRegistrationBean formSaveFilter() {
log.info("注册表单重复提交过滤器FormRepeatFilter ======================= ");
FilterRegistrationBean registration = new FilterRegistrationBean(new FormRepeatFilter());
registration.setEnabled(formSaveFilterEnable);
registration.addUrlPatterns("/*");
registration.addInitParameter("excludePath", "/doc,/captcha,/v2/api-docs,/swagger-resources,/configuration/ui,/configuration/security,/druid");
registration.addInitParameter("excludeType", ".js,.css,.gif,.jpg,.png,.ico,.jsp,.html,/druid/");
return registration;
}
}
@@ -2,31 +2,29 @@ package com.xwbing.controller.rest;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.annotation.LogInfo;
import com.xwbing.domain.entity.ExpressInfo;
import com.xwbing.domain.entity.sys.SysUser;
import com.xwbing.domain.entity.vo.ExpressInfoVo;
import com.xwbing.domain.mapper.sys.SysUserMapper;
import com.xwbing.rabbit.Sender;
import com.xwbing.redis.RedisService;
import com.xwbing.domain.entity.rest.FilesUpload;
import com.xwbing.domain.repository.FilesUploadRepository;
import com.xwbing.service.rest.CookieSessionService;
import com.xwbing.service.rest.ExpressDeliveryService;
import com.xwbing.service.rest.QRCodeZipService;
import com.xwbing.util.HttpUtil;
import com.xwbing.util.EncodeUtils;
import com.xwbing.util.JsonResult;
import com.xwbing.util.RSAUtil;
import com.xwbing.util.RestMessage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* 说明: 测试控制层
@@ -39,79 +37,12 @@ import java.util.concurrent.CompletableFuture;
@RestController
@RequestMapping("/test/")
public class TestControl {
@Resource
private RedisService redisService;
@Resource
private ExpressDeliveryService expressDeliveryService;
@Resource
private QRCodeZipService qrCodeZipService;
@Resource
private CookieSessionService cookieSessionService;
@Resource
private Sender sender;
@Resource
private SysUserMapper sysUserMapper;
@Transactional
@PostMapping("save")
public JSONObject save(@RequestBody SysUser sysUser) {
List<SysUser> findall = sysUserMapper.findall();
findall.forEach(sysUser1 -> sysUser1.setCreate("aaa"));
return JsonResult.toJSONObj(findall,"");
}
@GetMapping("send")
public void sendM(@RequestParam String[] msg) {
sender.sendM(msg);
}
@LogInfo("redis功能测试")
@GetMapping("redis")
public void redis() {
redisService.set("redis", "xwbing");
String s = redisService.get("redis");
log.info("redis获取的数据为:" + s);
}
@LogInfo("log功能测试")
@GetMapping("log")
public void log() {
log.info("info test");
log.error("error test");
}
@LogInfo("获取快递列表")
@GetMapping("listShipperCode")
public JSONObject listShipperCode() {
List<JSONObject> list = expressDeliveryService.listShipperCode();
return JsonResult.toJSONObj(list, "");
}
@LogInfo("快递查询")
@PostMapping("expressInfo")
public JSONObject getExpressInfo(@RequestBody ExpressInfo info) {
if (StringUtils.isEmpty(info.getLogisticCode()) || StringUtils.isEmpty(info.getShipperCode())) {
return JsonResult.toJSONObj("快递公司或物流单号不能为空");
}
ExpressInfoVo infoVo = expressDeliveryService.queryOrderTraces(info);
return JsonResult.toJSONObj(infoVo, "查询快递信息成功");
}
@LogInfo("生成二维码")
@PostMapping("createQRCode")
public JSONObject createQRCode(@RequestParam String name, @RequestParam String text) {
RestMessage qrCode = qrCodeZipService.createQRCode(name, text);
return JsonResult.toJSONObj(qrCode);
}
@LogInfo("解析二维码")
@GetMapping("decode")
public JSONObject decode(@RequestParam String path) {
if (StringUtils.isEmpty(path)) {
return JsonResult.toJSONObj("二维码图片路径不能为空");
}
File file = new File(path);
RestMessage decode = qrCodeZipService.decode(file);
return JsonResult.toJSONObj(decode);
}
private FilesUploadRepository uploadRepository;
@LogInfo("导出zip")
@GetMapping("batchGetImage")
@@ -123,21 +54,24 @@ public class TestControl {
return JsonResult.toJSONObj(restMessage);
}
@LogInfo("rsa")
@GetMapping("rsa")
public void rsa() {
String en = RSAUtil.encrypt("123456");
String de = RSAUtil.decrypt(en);
System.out.println(de);
}
@LogInfo("httpUtil")
@PostMapping("httpUtil")
public JSONObject httpUtil(@RequestBody JSONObject param) {
// String url = "http://localhost:8080/user/listAll";
// return HttpClientUtil.get(url);
String url = "http://localhost:8080/user/save";
return HttpUtil.postByJson(url, param);
@LogInfo("获取数据库图片")
@GetMapping("getDbPic")
public void getDbPic(HttpServletResponse response, @RequestParam String name) throws IOException {
if (StringUtils.isNotEmpty(name)) {
List<FilesUpload> files = uploadRepository.getByName(name, new Sort(Sort.Direction.DESC, "createTime"));
if (CollectionUtils.isNotEmpty(files)) {
String data = files.get(0).getData();
byte[] bytes = EncodeUtils.base64Decode(data);
// 设置相应类型,告诉浏览器输出的内容为图片
response.setContentType("image/jpeg");
// 禁止图像缓存。
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expire", 0);
OutputStream out = response.getOutputStream();
out.write(bytes);
}
}
}
@LogInfo("session")
@@ -151,37 +85,5 @@ public class TestControl {
public JSONObject cookie(HttpServletRequest request, HttpServletResponse response) {
return JsonResult.toJSONObj(cookieSessionService.cookie(response, request));
}
@LogInfo("completableFuture")
@GetMapping("completableFuture")
public JSONObject completableFuture() {
return JsonResult.toJSONObj(thenCombine(), "");
}
private JSONObject thenCombine() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}).thenCombine(CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//出现异常,异常会被限制在执行任务的线程范围内
if (1 == 1) {
throw new RuntimeException("545456");
}
return "world";
}), (s1, s2) -> {
JSONObject object = new JSONObject();
object.put("s1", s1);
object.put("s2", s2);
return object;
}).join();
}
}
@@ -5,11 +5,11 @@ import com.xwbing.annotation.LogInfo;
import com.xwbing.domain.entity.vo.RestMessageVo;
import com.xwbing.service.rest.CommonService;
import com.xwbing.util.JsonResult;
import com.xwbing.util.RestMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@@ -34,4 +34,12 @@ public class CommonControl {
String sign = commonService.getSign(request);
return JsonResult.toJSONObj(sign, "");
}
@LogInfo("上传文件")
@PostMapping("upload")
public JSONObject upload(@RequestParam(required = false) CommonsMultipartFile file) {
RestMessage restMessage = commonService.upload(file);
return JsonResult.toJSONObj(restMessage);
}
}
@@ -0,0 +1,6 @@
formSaveFilterEnable:false
loginInterceptorEnable:false
urlPermissionsInterceptorEnable:false
@@ -1,16 +0,0 @@
package com.xwbing;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Test
public void contextLoads() {
}
}
@@ -0,0 +1,29 @@
package com.xwbing;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* 说明:
* 项目名称: boot-module-demo
* 创建时间: 2018/5/10 16:36
* 作者: xiangwb
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
@Rollback(false)
@WebAppConfiguration
public class BaseTest {
@Autowired
protected MockMvc mvc;
}
@@ -0,0 +1,68 @@
package com.xwbing.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.BaseTest;
import com.xwbing.domain.entity.sys.SysRole;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.text.MessageFormat;
/**
* 说明:
* 项目名称: boot-module-demo
* 创建时间: 2018/5/10 16:36
* 作者: xiangwb
*/
@Slf4j
public class SysRoleControlTest extends BaseTest {
@Test
public void all() throws Exception {
//save
SysRole sysRole = new SysRole();
sysRole.setCode("apiTest");
sysRole.setEnable("Y");
sysRole.setName("apiTest");
sysRole.setRemark("apiTest");
String saveStr = mvc.perform(MockMvcRequestBuilders
.post("/role/save")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(JSONObject.toJSONString(sysRole)))
.andReturn().getResponse().getContentAsString();
log.info(saveStr);
//getById
JSONObject response = JSONObject.parseObject(saveStr);
String getByIdStr = mvc.perform(MockMvcRequestBuilders
.get("/role/getById")
.param("id", response.getString("id")))
.andReturn().getResponse().getContentAsString();
log.info(getByIdStr);
response = JSONObject.parseObject(getByIdStr);
sysRole = JSON.toJavaObject(response.getJSONObject("data"), SysRole.class);
//listByEnable
String listByEnableString = mvc.perform(MockMvcRequestBuilders
.get("/role/listByEnable")
.param("enable", "Y"))
.andReturn().getResponse().getContentAsString();
log.info(listByEnableString);
//update
sysRole.setName("updateTest");
String updateStr = mvc.perform(MockMvcRequestBuilders
.put("/role/update")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(JSONObject.toJSONString(sysRole)))
.andReturn().getResponse().getContentAsString();
log.info(updateStr);
//removeById
String removeByIdStr = mvc.perform(MockMvcRequestBuilders
.delete(MessageFormat.format("/role/removeById/{0}", sysRole.getId())))
.andReturn().getResponse().getContentAsString();
log.info(removeByIdStr);
// mvc.perform(MockMvcRequestBuilders
// .delete(MessageFormat.format("/role/removeById/{0}", sysRole.getId())))
// .andExpect(MockMvcResultMatchers.status().isOk());
}
}
@@ -0,0 +1,128 @@
package com.xwbing.service;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.BaseTest;
import com.xwbing.domain.entity.ExpressInfo;
import com.xwbing.domain.entity.sys.SysRole;
import com.xwbing.domain.entity.vo.ExpressInfoVo;
import com.xwbing.domain.mapper.sys.SysRoleMapper;
import com.xwbing.rabbit.Sender;
import com.xwbing.redis.RedisService;
import com.xwbing.service.rest.ExpressDeliveryService;
import com.xwbing.service.rest.QRCodeZipService;
import com.xwbing.service.sys.SysRoleService;
import com.xwbing.util.RSAUtil;
import com.xwbing.util.RestMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/1 13:20
* 作者: xiangwb
* 说明: 服务层功能测试
*/
@Slf4j
public class ServiceTest extends BaseTest {
@Resource
private RedisService redisService;
@Resource
private ExpressDeliveryService expressDeliveryService;
@Resource
private QRCodeZipService qrCodeZipService;
@Resource
private Sender sender;
@Resource
private SysRoleService sysRoleService;
@Resource
private SysRoleMapper sysRoleMapper;
@Transactional("jpaTransactionManager")
@Test
public void jpaTransactionTest() {
log.info("jpa数据源事务回滚");
SysRole sysRole = new SysRole();
sysRole.setName("serviceTest");
sysRole.setCode("serviceTest");
sysRole.setEnable("Y");
sysRole.setRemark("serviceTest");
Assert.assertTrue(sysRoleService.save(sysRole).isSuccess());
}
@Transactional
@Test
public void mybatisTransactionTest() {
log.info("mybatis数据源事务回滚");
SysRole sysRole = new SysRole();
sysRole.setName("serviceTest");
sysRole.setCode("serviceTest");
sysRole.setEnable("Y");
sysRole.setRemark("serviceTest");
int insert = sysRoleMapper.insert(sysRole);
Assert.assertEquals(1, insert);
}
@Test
public void listShipperCodeTest() {
log.debug("获取快递列表");
List<JSONObject> list = expressDeliveryService.listShipperCode();
Assert.assertSame(12, list.size());
}
@Test
public void expressInfoTest() {
log.debug("快递查询");
ExpressInfo info = new ExpressInfo();
info.setLogisticCode("1179751819114");
info.setShipperCode("EMS");
if (StringUtils.isEmpty(info.getLogisticCode()) || StringUtils.isEmpty(info.getShipperCode())) {
log.error("快递公司或物流单号不能为空");
}
ExpressInfoVo infoVo = expressDeliveryService.queryOrderTraces(info);
Assert.assertTrue(infoVo.isSuccess());
}
@Test
public void createQRCodeTest() {
RestMessage qrCode = qrCodeZipService.createQRCode("test", "test");
Assert.assertTrue(qrCode.isSuccess());
}
@Test
public void decodeQRCodeTest() throws IOException {
ClassPathResource pic = new ClassPathResource("pic");
String path = pic.getFile().getAbsolutePath();
File file = new File(path + File.separator + "QRCode.png");
RestMessage decode = qrCodeZipService.decode(file);
Assert.assertTrue(decode.isSuccess());
}
@Test
public void rsaTest() {
String en = RSAUtil.encrypt("123456");
String de = RSAUtil.decrypt(en);
Assert.assertEquals("123456", de);
}
@Test
public void sendTest() {
sender.sendMessage(new String[]{"mq测试"});
}
@Test
public void redisTest() {
redisService.set("redis", "xwbing");
String s = redisService.get("redis");
Assert.assertEquals("xwbing", s);
}
}
@@ -0,0 +1,49 @@
package com.xwbing.service;
import com.xwbing.BaseTest;
import com.xwbing.domain.entity.sys.SysRole;
import com.xwbing.domain.mapper.sys.SysRoleMapper;
import com.xwbing.service.sys.SysRoleService;
import com.xwbing.util.RestMessage;
import org.junit.Assert;
import org.junit.Test;
import javax.annotation.Resource;
/**
* 项目名称: boot-module-demo
* 创建时间: 2018/6/1 13:20
* 作者: xiangwb
* 说明: 权限服务层测试
*/
public class SysRoleServiceTest extends BaseTest {
@Resource
private SysRoleService sysRoleService;
@Resource
private SysRoleMapper sysRoleMapper;
@Test
public void all() {
//save
SysRole sysRole = new SysRole();
sysRole.setCode("serviceTest");
sysRole.setEnable("Y");
sysRole.setName("serviceTest");
sysRole.setRemark("serviceTest");
RestMessage rest = sysRoleService.save(sysRole);
Assert.assertTrue(rest.getMessage(), rest.isSuccess());
//getById
sysRole = sysRoleService.getById(rest.getId());
Assert.assertNotNull(sysRole);
//update
sysRole.setName("updateTest");
rest = sysRoleService.update(sysRole);
Assert.assertTrue(rest.getMessage(), rest.isSuccess());
Assert.assertNotSame("修改失败", sysRole, sysRoleService.getById(rest.getId()));
//listAllByEnable
Assert.assertNotNull(sysRoleService.listAllByEnable("Y"));
//removeById
Assert.assertTrue("删除失败", sysRoleService.removeById(rest.getId()).isSuccess());
//............................
}
}