Commit 5147293c authored by 技术部-任文超's avatar 技术部-任文超

Merge branch 'master' into feature/20180108

# Conflicts:
#	src/main/java/cn/quantgroup/xyqb/controller/external/user/InnerController.java
parents 2a077f4f 55158c49
......@@ -22,9 +22,10 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<junit.version>4.12</junit.version>
<junit.jupiter.version>5.0.2</junit.jupiter.version>
<maven.test.skip>true</maven.test.skip>
<org.springframework.security.version>3.2.7.RELEASE</org.springframework.security.version>
</properties>
<dependencies>
......@@ -56,7 +57,6 @@
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -93,6 +93,26 @@
<scope>test</scope>
</dependency>
<!-- jUnit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
......@@ -128,7 +148,7 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.3</version>
<version>4.4</version>
</dependency>
<dependency>
......@@ -139,7 +159,7 @@
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
<version>4.4.1</version>
</dependency>
<!-- hibernate end -->
......@@ -230,12 +250,6 @@
<artifactId>apollo-client</artifactId>
<version>0.10.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>cn.quantgroup</groupId>-->
<!--<artifactId>quantgroup-config-sdk</artifactId>-->
<!--<version>1.0.3-SNAPSHOT</version>-->
<!--</dependency>-->
<!-- motan -->
<dependency>
<groupId>com.weibo</groupId>
......
......@@ -19,11 +19,9 @@ import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan(basePackages = {"cn.quantgroup.sms", "cn.quantgroup.xyqb"})
@EnableAutoConfiguration
@SpringBootApplication
@EnableCaching
//@EnableApolloConfig({"application", "tech.msg.sdk", "cash.common"})
@EnableApolloConfig
@PropertySource(value = {"classpath:application.properties", "classpath:xyqb.properties"}, ignoreResourceNotFound = true)
@Configuration
......@@ -35,7 +33,6 @@ public class Bootstrap {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Bootstrap.class);
springApplication.addInitializers(new ApolloPropertySourceInitializer("application", "tech.msg.sdk", "cash.common","tech.service.urls"));
springApplication.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
......@@ -46,7 +43,6 @@ public class Bootstrap {
springApplication.setRegisterShutdownHook(true);
springApplication.run(args);
log.info("server start...");
Sentry.init("http://13ef5642903a414c910f8d0e0a2c56ee:8b351ad1abf44de3b4c25f39105fb927@172.16.4.89:9000/6");
}
}
package cn.quantgroup.xyqb.controller.external.user;
import cn.quantgroup.user.enums.Relation;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.aspect.logcaller.LogHttpCaller;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.exception.UserNotExistException;
import cn.quantgroup.xyqb.model.*;
import cn.quantgroup.xyqb.service.api.IUserApiService;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.register.IUserRegisterService;
import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.service.user.*;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.*;
......@@ -26,27 +25,20 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by Miraculous on 2016/12/19.
*/
......@@ -78,8 +70,7 @@ public class InnerController implements IBaseController {
private ISessionService sessionService;
@Autowired
private IUserApiService userApiService;
@Autowired
private ISmsService smsService;
@Autowired
private IHttpService httpService;
@Autowired
......@@ -97,7 +88,6 @@ public class InnerController implements IBaseController {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MAPPER.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true);
}
private static final char[] PWD_BASE = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
......@@ -128,8 +118,8 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult("", userRet);
}
@RequestMapping("/userInfo/search/uuid")
@LogHttpCaller
@RequestMapping("/userInfo/search/uuid")
public JsonResult findUserInfoByUuid(@RequestParam(value = "uuid") String uuid) {
LOGGER.info("需要查询的用户uuidid, uuid:" + uuid);
......@@ -137,19 +127,19 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult(null, null);
}
User user = userService.findByUuidInDb(uuid);
if (null != user) {
if (!user.getEnable()) {
if(null!=user){
if(!user.getEnable()){
return JsonResult.buildSuccessResult("", null);
}
UserDetail userDetail = userDetailService.findByUserId(user.getId());
UserInfo info = new UserInfo(user, userDetail);
UserInfo info = new UserInfo(user,userDetail);
return JsonResult.buildSuccessResult("", info);
}
return JsonResult.buildSuccessResult("", null);
}
@RequestMapping("/userInfo/search/phone")
@LogHttpCaller
@RequestMapping("/userInfo/search/phone")
public JsonResult findUserInfoByPhone(@RequestParam(value = "phone") String phone) {
LOGGER.info("需要查询的用户phone, phone:" + phone);
......@@ -157,12 +147,12 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult(null, null);
}
User user = userService.findByPhoneInDb(phone);
if (null != user) {
if (!user.getEnable()) {
if(null!=user){
if(!user.getEnable()){
return JsonResult.buildSuccessResult("", null);
}
UserDetail userDetail = userDetailService.findByUserId(user.getId());
UserInfo info = new UserInfo(user, userDetail);
UserInfo info = new UserInfo(user,userDetail);
return JsonResult.buildSuccessResult("", info);
}
return JsonResult.buildSuccessResult("", null);
......@@ -190,7 +180,7 @@ public class InnerController implements IBaseController {
public JsonResult saveUser(
String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt,
String password, String uuid) {
LOGGER.info("保存用户,phoneNo:{},registeredFrom;{},uuid:{}", phoneNo, registeredFrom, uuid);
LOGGER.info("保存用户,phoneNo:{},registeredFrom;{},uuid:{}",phoneNo,registeredFrom,uuid);
//参数验证
if (StringUtils.isBlank(phoneNo)) {
return JsonResult.buildErrorStateResult("用户手机号不能为空.", null);
......@@ -199,7 +189,7 @@ public class InnerController implements IBaseController {
registeredFrom = 0L;
}
if (StringUtils.isBlank(password)) {
password = genRandomPwd();
password= genRandomPwd();
password = PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT);
}
if (StringUtils.isBlank(uuid)) {
......@@ -213,7 +203,7 @@ public class InnerController implements IBaseController {
if (user == null) {
user = new User();
} else if (!user.getEnable()) {
LOGGER.info("用户已经注销,phoneNo:{}", phoneNo);
LOGGER.info("用户已经注销,phoneNo:{},",phoneNo);
return JsonResult.buildErrorStateResult("用户已经注销", null);
}
if (org.apache.commons.lang.StringUtils.isEmpty(user.getUuid())) {
......@@ -229,7 +219,7 @@ public class InnerController implements IBaseController {
user = userService.saveUser(user);
UserRet userRet = null;
if (user != null) {
userRet = MqUtils.sendRegisterMessage(registeredFrom, null, user);
userRet = MqUtils.sendRegisterMessage(registeredFrom, null,user);
}
return JsonResult.buildSuccessResult(null, userRet);
}
......@@ -241,7 +231,7 @@ public class InnerController implements IBaseController {
@RequestMapping("/user_detail/save")
public JsonResult saveUserDetail(Long userId, String phoneNo, String name, String idNo,
String email, Long id) {
LOGGER.info("保存用户详细信息,phoneNo:{},userId;{},name:{},idNo:{},email;{}", phoneNo, userId, name, idNo, email);
LOGGER.info("保存用户详细信息,phoneNo:{},userId;{},name:{},idNo:{},email;{}",phoneNo,userId,name,idNo,email);
//参数验证
if (userId == null || userId == 0L) {
return JsonResult.buildErrorStateResult("用户id为空.", null);
......@@ -268,9 +258,9 @@ public class InnerController implements IBaseController {
if (Objects.isNull(info) || !info.isValid()) {
return JsonResult.buildErrorStateResult("身份证号码错误", null);
}
UserDetail userDetail = userDetailService.findByUserId(userId);
UserDetail userDetail=userDetailService.findByUserId(userId);
Timestamp time = new Timestamp(System.currentTimeMillis());
if (null == userDetail) {
if(null==userDetail){
userDetail = new UserDetail();
userDetail.setCreatedAt(time);
}
......@@ -327,7 +317,6 @@ public class InnerController implements IBaseController {
/**
* 根据phone查找用户完整信息
*
* @param phoneNo
* @return
*/
......@@ -348,7 +337,6 @@ public class InnerController implements IBaseController {
/**
* 根据uuid查找用户完整信息
*
* @param uuid
* @return
*/
......@@ -391,7 +379,7 @@ public class InnerController implements IBaseController {
@RequestMapping("/contact/save/contacts")
public JsonResult save2Contact(Long userId, @RequestParam(value = "contacts") String contactsStr) {
LOGGER.info("保存用户联系人:userId:{}, contacts:{}", userId, contactsStr);
LOGGER.info("保存用户联系人:userId:{}, contacts:{}",userId, contactsStr);
if (StringUtils.isEmpty(contactsStr)) {
return JsonResult.buildErrorStateResult(null, null);
}
......@@ -404,7 +392,7 @@ public class InnerController implements IBaseController {
LOGGER.info("联系人不能空");
return JsonResult.buildErrorStateResult(null, null);
}
for (Contact contact : contacts) {
for(Contact contact : contacts){
if (!contact.valid()) {
LOGGER.info("用户手机号或姓名错误, phoneNo:{},name:{}", contact.getPhoneNo(), contact.getName());
return JsonResult.buildErrorStateResult(null, null);
......@@ -418,12 +406,12 @@ public class InnerController implements IBaseController {
public JsonResult updateContact(@RequestParam Long contactId, @RequestParam(required = false) String name,
@RequestParam(required = false) String phoneNo,
@RequestParam(required = false) Relation relation, String key,
@RequestParam String reason, HttpServletRequest request) {
@RequestParam String reason,HttpServletRequest request) {
if (!"@qwsdedad131323213w!".equals(key) || contactId == null) {
return JsonResult.buildErrorStateResult("参数不合法", null);
}
if (StringUtils.isEmpty(name) && StringUtils.isEmpty(phoneNo)) {
if (StringUtils.isEmpty(name) && StringUtils.isEmpty(phoneNo) ){
return JsonResult.buildErrorStateResult("修改联系人修改条件不能都为空", null);
}
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
......@@ -434,7 +422,7 @@ public class InnerController implements IBaseController {
LOGGER.info("用户姓名错误, name:{}", name);
return JsonResult.buildErrorStateResult("用户姓名错误", null);
}
if (StringUtils.isEmpty(reason)) {
if(StringUtils.isEmpty(reason)){
return JsonResult.buildErrorStateResult("修改原因不能为空", null);
}
Contact contact = contactService.findById(contactId);
......@@ -442,7 +430,7 @@ public class InnerController implements IBaseController {
return JsonResult.buildErrorStateResult("修改联系人不存在", null);
}
contact = contactService.saveContact(name, phoneNo, relation, contact);
LOGGER.info("修改后联系人信息:{},修改原因:{},操作ip:{}", contact, reason, IPUtil.getRemoteIP(request));
LOGGER.info("修改后联系人信息:{},修改原因:{},操作ip:{}",contact,reason,IPUtil.getRemoteIP(request));
return JsonResult.buildSuccessResult("修改联系人成功", contact);
}
......@@ -463,9 +451,9 @@ public class InnerController implements IBaseController {
public JsonResult saveAddress(
Long userId, Long provinceCode, Long cityCode, String city,
Long districtCode, String district, String address, String province) {
LOGGER.info("保存地址详情:city:{},province:{},district:{}, address:{},userId:{}", city, province, district, address, userId);
LOGGER.info("保存地址详情:city:{},province:{},district:{}, address:{},userId:{}" , city, province, district, address, userId);
if (userId == null || provinceCode == null || cityCode == null || StringUtils.isBlank(address)) {
LOGGER.info("错误保存地址详情,其中参数不能为空:city:{},province:{},district:{}, address:{},userId:{}", city, province, district, address, userId);
LOGGER.info("错误保存地址详情,其中参数不能为空:city:{},province:{},district:{}, address:{},userId:{}" , city, province, district, address, userId);
return JsonResult.buildErrorStateResult("参数不能为空", null);
}
Address addressObj = addressService.findByUserId(userId);
......@@ -484,7 +472,7 @@ public class InnerController implements IBaseController {
addressObj.setAddress(address);
addressObj.setProvince(province);
addressObj = addressService.save(addressObj);
LOGGER.info("保存后地址详情:{}", addressObj);
LOGGER.info("保存后地址详情:{}",addressObj);
return JsonResult.buildSuccessResult(null, AddressRet.address2AddressRet(addressObj));
}
......@@ -593,44 +581,8 @@ public class InnerController implements IBaseController {
}
/**
* 按照用户主键、账号或uuid查询用户详细信息
*
* @param id - 用户表主键
* @param phoneNo - 用户账号
* @param uuid - 用户全球唯一键(uuid)
* @return 详细信息包含:
* {
* 账号信息
* 个人信息
* }
*/
@LogHttpCaller
@RequestMapping("/user-association/search")
public JsonResult findUserAssociationModel(Long id, String phoneNo, String uuid) {
User user = null;
if (!Objects.isNull(id) && id > 0) {
user = userService.findById(id);
}else if (ValidationUtil.validatePhoneNo(phoneNo)) {
user = userService.findByPhoneWithCache(phoneNo);
}else if (StringUtils.isNotBlank(uuid)) {
user = userService.findByUuidWithCache(uuid);
}
UserDetail userDetail = null;
if (!Objects.isNull(user) && !Objects.isNull(user.getId()) && user.getId() > 0) {
userDetail = userDetailService.findByUserId(user.getId());
}
if (Objects.isNull(user)) {
return JsonResult.buildErrorStateResult("用户不存在", "");
}else{
return JsonResult.buildSuccessResult("", new UserInfo(user, userDetail));
}
}
/**
* 查询用户综合信息模型
*
* @param user - 用户User
* @return 综合信息模型包含:
* 按照用户主键查询用户综合信息模型
* 综合信息模型包含:
* {
* 账号信息
* 个人信息
......@@ -638,15 +590,17 @@ public class InnerController implements IBaseController {
* 地址信息
* 联系人信息
* }
* @param userId - 用户表主键
* @return
*/
private UserAssociationModel findUserAssociationModelByUser(User user) {
if (Objects.isNull(user) || Objects.isNull(user.getId()) || user.getId() < 1) {
return null;
@RequestMapping("/user-association/search/userId")
@LogHttpCaller
public JsonResult findUserAssociationModelByUserId(Long userId) {
if(Objects.isNull(userId) || userId < 0){
return JsonResult.buildErrorStateResult("", "");
}
UserAssociationModel bean = new UserAssociationModel();
bean.setUuid(user.getUuid());
bean.setRegisterFrom(user.getRegisteredFrom());
UserDetail userDetail = userDetailService.findByUserId(user.getId());
UserDetail userDetail = userDetailService.findByUserId(userId);
if (!Objects.isNull(userDetail)) {
bean.setId(userDetail.getUserId());
bean.setPhoneNo(userDetail.getPhoneNo());
......@@ -655,25 +609,30 @@ public class InnerController implements IBaseController {
bean.setQq(userDetail.getQq());
bean.setGender(Optional.ofNullable(userDetail.getGender()).orElse(cn.quantgroup.xyqb.model.Gender.UNKNOWN).getName());
}
UserBtRegister userBtRegister = userBtRegisterService.findByUserId(user.getId());
User user = userService.findById(userId);
if (!Objects.isNull(user)) {
bean.setUuid(user.getUuid());
bean.setRegisterFrom(user.getRegisteredFrom());
}
UserBtRegister userBtRegister = userBtRegisterService.findByUserId(userId);
if (!Objects.isNull(userBtRegister)) {
bean.setMerchantId(userBtRegister.getRegisterBtMerchantId());
}
UserExtInfo extInfo = userExtInfoService.findByUserId(userDetail.getUserId());
if (!Objects.isNull(extInfo)) {
if (null == extInfo.getEducationEnum()) {
if(null==extInfo.getEducationEnum()){
bean.setEducationEnum(cn.quantgroup.user.enums.EducationEnum.UNKNOWN.getName());
} else {
}else{
bean.setEducationEnum(extInfo.getEducationEnum().getName());
}
if (null == extInfo.getOccupationEnum()) {
if(null==extInfo.getOccupationEnum()){
bean.setOccupationEnum(cn.quantgroup.user.enums.OccupationEnum.UNKNOWN.getName());
} else {
}else{
bean.setOccupationEnum(extInfo.getOccupationEnum().getName());
}
if (null == extInfo.getMarryStatus()) {
if(null==extInfo.getMarryStatus()){
bean.setMarryStatus(cn.quantgroup.user.enums.MaritalStatus.UNKNOWN.getDescription());
} else {
}else{
bean.setMarryStatus(extInfo.getMarryStatus().getDescription());
}
}
......@@ -685,20 +644,6 @@ public class InnerController implements IBaseController {
if (!Objects.isNull(address)) {
bean.putContactList(contacts);
}
return bean;
}
@LogHttpCaller
@RequestMapping("/user-association/search/userId")
public JsonResult findUserAssociationModelByUserId(Long userId) {
if (Objects.isNull(userId) || userId < 1) {
return JsonResult.buildErrorStateResult("", "");
}
UserAssociationModel bean = null;
User user = userService.findById(userId);
if (!Objects.isNull(user)) {
bean = findUserAssociationModelByUser(user);
}
return JsonResult.buildSuccessResult("", bean);
}
......@@ -710,8 +655,8 @@ public class InnerController implements IBaseController {
return JsonResult.buildSuccessResult("", bean);
}
@LogHttpCaller
@RequestMapping("/user-association/search/uid")
@LogHttpCaller
public JsonResult findUserAssociationByUid(Long uid) {
UserDetail userDetail = userDetailService.findByUserId(uid);
UserAssociation bean = getUserAssociation(userDetail);
......@@ -720,11 +665,10 @@ public class InnerController implements IBaseController {
/**
* 获取用户综合信息
*
* @param userDetail
* @return
*/
private UserAssociation getUserAssociation(UserDetail userDetail) {
private UserAssociation getUserAssociation(UserDetail userDetail){
UserAssociation bean = new UserAssociation();
if (null != userDetail) {
Address address = addressService.findByUserId(userDetail.getUserId());
......@@ -743,19 +687,19 @@ public class InnerController implements IBaseController {
bean.setAddress(address.getAddress());
}
if (null != extInfo) {
if (null == extInfo.getEducationEnum()) {
if(null==extInfo.getEducationEnum()){
bean.setEducationEnum(cn.quantgroup.user.enums.EducationEnum.UNKNOWN.getName());
} else {
}else{
bean.setEducationEnum(extInfo.getEducationEnum().getName());
}
if (null == extInfo.getOccupationEnum()) {
if(null==extInfo.getOccupationEnum()){
bean.setOccupationEnum(cn.quantgroup.user.enums.OccupationEnum.UNKNOWN.getName());
} else {
}else{
bean.setOccupationEnum(extInfo.getOccupationEnum().getName());
}
if (null == extInfo.getMarryStatus()) {
if(null==extInfo.getMarryStatus()){
bean.setMarryStatus(cn.quantgroup.user.enums.MaritalStatus.UNKNOWN.getDescription());
} else {
}else{
bean.setMarryStatus(extInfo.getMarryStatus().getDescription());
}
}
......@@ -790,7 +734,6 @@ public class InnerController implements IBaseController {
}
return contactRets;
}
@RequestMapping("/user/wechat/phone_no")
@LogHttpCaller
public JsonResult queryOpenIdByPhoneNo(String phoneNo) {
......@@ -826,7 +769,6 @@ public class InnerController implements IBaseController {
/**
* 清除用户缓存信息
*
* @param phoneNo
* @return
*/
......@@ -844,7 +786,6 @@ public class InnerController implements IBaseController {
LOGGER.info("删除用户缓存信息,phoneNo:{},userId:{},", user.getPhoneNo(), user.getId());
return JsonResult.buildSuccessResult("用户缓存信息已经删除", null);
}
@RequestMapping("/user/spouse/save")
public JsonResult saveSpouse(Long userId, MaritalStatus status, String spousePhone, String spouseName) {
if (userId == null || userId == 0) {
......@@ -909,7 +850,6 @@ public class InnerController implements IBaseController {
/**
* 手机号批量查询uuid
*
* @param userPhones
* @return
*/
......@@ -918,7 +858,6 @@ public class InnerController implements IBaseController {
return JsonResult.buildErrorStateResult("主库不提供查询", null);
}
/**
* 重置密码接口,供内部人员使用(例如绝影)
*/
......@@ -959,7 +898,7 @@ public class InnerController implements IBaseController {
String districtCode,
String district,
String address,
String contacts, @RequestParam(defaultValue = "0", required = false) Long btRegisterChannelId) {
String contacts,@RequestParam(defaultValue = "0",required =false ) Long btRegisterChannelId) {
LOGGER.info("[/innerapi/user/save_multi]保存用户、联系人、地址信息:registeredFrom:[{}], phoneNo[{}],name[{}],idNo[{}],provinceCode[{}],cityCode[{}],districtCode[{}]," +
"address[{}],contacts[{}]", registeredFrom, phoneNo, name, idNo, provinceCode, cityCode, districtCode, address, contacts);
......@@ -1011,7 +950,7 @@ public class InnerController implements IBaseController {
return JsonResult.buildErrorStateResult("用户已存在,手机号被占用", null);
}
user = userRegisterService.register(Long.valueOf(registeredFrom), Long.valueOf(channelId), phoneNo, name, idNo, provinceCode, province, cityCode, city, districtCode, district, address, contacts, btRegisterChannelId);
user = userRegisterService.register(Long.valueOf(registeredFrom), Long.valueOf(channelId), phoneNo, name, idNo, provinceCode, province, cityCode, city, districtCode, district, address, contacts,btRegisterChannelId);
UserRet userRet = new UserRet(user);
return JsonResult.buildSuccessResult(null, userRet);
......@@ -1037,11 +976,11 @@ public class InnerController implements IBaseController {
@RequestMapping("/contract/queryRegisterUsers")
@LogHttpCaller
public JsonResult findRegisterUserByTime(String beginTime, String endTime) {
if (null == beginTime || endTime == null) {
public JsonResult findRegisterUserByTime(String beginTime,String endTime) {
if (null == beginTime||endTime==null) {
return JsonResult.buildErrorStateResult(null, null);
}
List<User> userList = userService.findRegisterUserByTime(beginTime, endTime);
List<User> userList=userService.findRegisterUserByTime(beginTime,endTime);
return JsonResult.buildSuccessResult(null, userList);
}
......@@ -1058,13 +997,13 @@ public class InnerController implements IBaseController {
if (null == str || !str.equals(userId.toString())) {
return JsonResult.buildErrorStateResult("解密有误", null);
}
int affectedRows = wechatService.forbiddenUserWeChat(userId);
LOGGER.info("用户微信禁用,userId:{},禁用的原因reason:{},受影响的行数affectedRows:{}", userId, reason, affectedRows);
int affectedRows=wechatService.forbiddenUserWeChat(userId);
LOGGER.info("用户微信禁用,userId:{},禁用的原因reason:{},受影响的行数affectedRows:{}",userId,reason,affectedRows);
return JsonResult.buildSuccessResult("用户禁用微信成功", affectedRows);
}
@RequestMapping("/updateIdCard")
public JsonResult updateIdCard(@RequestParam(required = false) String name, @RequestParam(required = false) String idNo,
public JsonResult updateIdCard(@RequestParam(required = false)String name, @RequestParam(required = false)String idNo,
@RequestParam String phoneNo, @RequestParam String reason, @RequestParam String content) {
//密文
if (null != content) {
......@@ -1074,18 +1013,18 @@ public class InnerController implements IBaseController {
if (null == str || !str.equals(phoneNo)) {
return JsonResult.buildErrorStateResult("解密有误", null);
}
if (StringUtils.isBlank(name) && StringUtils.isBlank(idNo)) {
if(StringUtils.isBlank(name) && StringUtils.isBlank(idNo)){
return JsonResult.buildErrorStateResult("不能全为空", null);
}
if (StringUtils.isBlank(phoneNo) || StringUtils.isBlank(reason)) {
if ( StringUtils.isBlank(phoneNo) || StringUtils.isBlank(reason)) {
return JsonResult.buildErrorStateResult("参数有误", null);
}
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
LOGGER.info("手机号有误, phoneNo:{}", phoneNo);
return JsonResult.buildErrorStateResult("用户手机号错误", null);
}
int affectedRows = userDetailService.updateIdCard(name, idNo, phoneNo);
LOGGER.info("更新用户的信息,name;{},idNo:{},phoneNo:{},操作的理由reason:{},受影响的行数affectedRows:{}", name, idNo, phoneNo, reason, affectedRows);
int affectedRows=userDetailService.updateIdCard(name, idNo, phoneNo);
LOGGER.info("更新用户的信息,name;{},idNo:{},phoneNo:{},操作的理由reason:{},受影响的行数affectedRows:{}", name, idNo, phoneNo, reason,affectedRows);
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
builder.put("phoneNo", phoneNo);
builder.put("name", name);
......@@ -1117,8 +1056,8 @@ public class InnerController implements IBaseController {
return JsonResult.buildErrorStateResult("用户手机号错误", null);
}
int affectedRows = userService.forbiddenUser(enable, phoneNo);
LOGGER.info("禁用或者重启用户的理由,reason:{},手机号phoneNo:{},受影响的行数affectedRows:{}", reason, phoneNo, affectedRows);
int affectedRows=userService.forbiddenUser(enable, phoneNo);
LOGGER.info("禁用或者重启用户的理由,reason:{},手机号phoneNo:{},受影响的行数affectedRows:{}", reason, phoneNo,affectedRows);
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
builder.put("phoneNo", phoneNo);
builder.put("enable", String.valueOf(enable));
......@@ -1129,7 +1068,6 @@ public class InnerController implements IBaseController {
httpService.get(hanguguanUrl.concat("/innerapi/forbiddenUserOrNot"), param);
return JsonResult.buildSuccessResult("用户禁用或重启成功成功", affectedRows);
}
private String genRandomPwd() {
int pwdMax = PWD_BASE.length;
// 生成的随机数
......@@ -1148,91 +1086,4 @@ public class InnerController implements IBaseController {
}
return pwd.toString();
}
/**
* 验证手机号和验证码是否匹配
* 仅供可信任的内部服务调用,不执行限次记数、销毁等安全策略
*
* @param phoneNo 手机号
* @param verificationCode 验证码(短信/语音)
* @return
*/
@LogHttpCaller
@RequestMapping("/verifyPhoneAndCode")
public JsonResult verifyPhoneAndCode(@RequestParam String phoneNo, @RequestParam String verificationCode) {
User user = null;
if (smsService.verifyPhoneAndCode(phoneNo, verificationCode)) {
user = userService.findByPhoneWithCache(phoneNo);
}else {
return JsonResult.buildErrorStateResult("校验失败", "");
}
if (Objects.isNull(user)) {
return JsonResult.buildErrorStateResult("用户不存在", "");
}else{
return JsonResult.buildSuccessResult("校验成功", new UserRet(user));
}
}
@LogHttpCaller
@RequestMapping("/login")
public JsonResult login(@RequestParam String phoneNo, @RequestParam String password) {
User user = checkPhoneNoAndPassword(phoneNo, password);
if (user == null) {
return JsonResult.buildErrorStateResult("用户名或密码不正确", null);
}
UserRet model = new UserRet(user);
return JsonResult.buildSuccessResult("校验成功", model);
}
private User checkPhoneNoAndPassword(String phoneNo, String password) {
byte[] byPhoneNo = Base64.decodeBase64(phoneNo);
String bufPhoneNo = "";
try {
bufPhoneNo = new String(byPhoneNo, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("不支持的编码: ", e);
}
if (!ValidationUtil.validatePhoneNo(bufPhoneNo)) {
LOGGER.info("手机号错误, phoneNo:{}", bufPhoneNo);
throw new UserNotExistException("手机号错误");
}
byte[] byPassword = Base64.decodeBase64(password);
String bufPassword = "";
try {
bufPassword = new String(byPassword, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.error("不支持的编码: ", e);
}
User user = userService.findByPhoneWithCache(bufPhoneNo);
if (Objects.isNull(user) || Objects.equals(Boolean.FALSE, user.getEnable())) {
return null;
}
//验证密码
if (!Objects.equals(PasswordUtil.MD5(bufPassword.toLowerCase() + Constants.PASSWORD_SALT), user.getPassword())) {
return null;
}
return user;
}
/**
* 查询用户是否存在
*
* @param phoneNo
* @return
*/
@RequestMapping("/user/enable")
public JsonResult isEnable(String phoneNo) {
boolean flag = false;
Map validMap = Maps.newHashMap();
validMap.put("valid", flag);
User user = userService.findByPhoneInDb(phoneNo);
if (user != null && user.getEnable()) {
validMap.put("valid", true);
validMap.put("id", user.getId());
validMap.put("uuid", user.getUuid());
return JsonResult.buildSuccessResult("查询成功", validMap);
}
return JsonResult.buildErrorStateResult("用户不存在", validMap);
}
}
\ No newline at end of file
......@@ -182,7 +182,8 @@ public class UserDetailServiceImpl implements IUserDetailService {
return userDetailRepository.findAll(spec, pageRequest);
}
@Override public void fixedIdNoAndGender() {
@Override
public void fixedIdNoAndGender() {
List<UserDetail> details=userDetailRepository.selectUserDetailsBy();
if(!CollectionUtils.isEmpty(details)){
for (UserDetail detail:details){
......
app.id=xyqb-user2
namespace=application, tech.msg.sdk, cash.common,tech.service.urls
\ No newline at end of file
namespace=application,tech.msg.sdk,cash.common,tech.service.urls
\ No newline at end of file
//package demo;
//
//import cn.quantgroup.xyqb.Bootstrap;
//import cn.quantgroup.xyqb.controller.internal.sms.SmsController;
//import cn.quantgroup.xyqb.controller.internal.user.UserController;
//import cn.quantgroup.xyqb.model.JsonResult;
//import org.junit.Assert;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//import org.springframework.test.context.web.WebAppConfiguration;
//
//@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest(classes = Bootstrap.class)
//@WebAppConfiguration
//public class DemoApplicationTests {
//
// @Autowired
// private UserController userController;
//
// @Autowired
// private SmsController smsController;
//
// private String smsRegCode = "";
//
// @Test
// public void sendRegCode() {
// JsonResult jsonResult = smsController.sendRegistCode("18611428880", null);
// System.out.print(jsonResult.getMsg());
// Assert.assertEquals(jsonResult.getCode(), "0000");
// Assert.assertEquals(jsonResult.getBusinessCode(), "0000");
//
// }
//
// @Test
// public void registerFast() {
//// JsonResult jsonResult = userController.registerFast("18611428880", "000000", null, null, "");
//// Assert.assertEquals(jsonResult.getCode(), "0000");
// }
//
// @Test
// public void sendLoginCode() {
// JsonResult jsonResult = smsController.sendLoginCode("18611428880", null);
// Assert.assertEquals(jsonResult.getCode(), "0000");
// }
//
// @Test
// public void loginFast() {
//
// }
//
//
//}
package demo;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.function.ThrowingConsumer;
import java.util.*;
import java.util.function.Function;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.DynamicContainer.dynamicContainer;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
/**
* 动态批量测试
* @author renwc
* @date 2018-01-05
*/
@Tag("Test Factory")
public class DynamicTests {
// This will result in a JUnitException!
@Disabled
@TestFactory
List<String> dynamicTestsWithInvalidReturnType() {
return Arrays.asList("Hello");
}
@TestFactory
Collection<DynamicTest> dynamicTestsFromCollection() {
return Arrays.asList(
dynamicTest("1st dynamic test", () -> assertTrue(true)),
dynamicTest("2nd dynamic test", () -> assertEquals(4, 2 * 2))
);
}
@TestFactory
Iterable<DynamicTest> dynamicTestsFromIterable() {
return Arrays.asList(
dynamicTest("3rd dynamic test", () -> assertTrue(true)),
dynamicTest("4th dynamic test", () -> assertEquals(4, 2 * 2))
);
}
@TestFactory
Iterator<DynamicTest> dynamicTestsFromIterator() {
return Arrays.asList(
dynamicTest("5th dynamic test", () -> assertTrue(true)),
dynamicTest("6th dynamic test", () -> assertEquals(4, 2 * 2))
).iterator();
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromStream() {
return Stream.of("A", "B", "C")
.map(str -> dynamicTest("test" + str, () -> { /* ... */ }));
}
@TestFactory
Stream<DynamicTest> dynamicTestsFromIntStream() {
// Generates tests for the first 10 even integers.
return IntStream.iterate(0, n -> n + 2).limit(10)
.mapToObj(n -> dynamicTest("test" + n, () -> assertTrue(n % 2 == 0)));
}
@TestFactory
Stream<DynamicTest> generateRandomNumberOfTests() {
// Generates random positive integers between 0 and 100 until
// a number evenly divisible by 7 is encountered.
Iterator<Integer> inputGenerator = new Iterator<Integer>() {
Random random = new Random();
int current;
@Override
public boolean hasNext() {
current = random.nextInt(100);
return current % 7 != 0;
}
@Override
public Integer next() {
return current;
}
};
// Generates display names like: input:5, input:37, input:85, etc.
Function<Integer, String> displayNameGenerator = (input) -> "input:" + input;
// Executes tests based on the current input value.
ThrowingConsumer<Integer> testExecutor = (input) -> assertTrue(input % 7 != 0);
// Returns a stream of dynamic tests.
return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
@TestFactory
Stream<DynamicNode> dynamicTestsWithContainers() {
return Stream.of("A", "B", "C")
.map(input -> dynamicContainer("Container " + input, Stream.of(
dynamicTest("not null", () -> assertNotNull(input)),
dynamicContainer("properties", Stream.of(
dynamicTest("length > 0", () -> assertTrue(input.length() > 0)),
dynamicTest("not empty", () -> assertFalse(input.isEmpty()))
))
)));
}
}
\ No newline at end of file
package demo;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.config.data.JpaConfig;
import cn.quantgroup.xyqb.config.data.RedisConfig;
import cn.quantgroup.xyqb.controller.internal.user.UserController;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import jdk.nashorn.internal.runtime.regexp.joni.Config;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest({UserController.class})
@ContextConfiguration(classes = {JpaConfig.class, RedisConfig.class}, initializers = ApolloPropertySourceInitializer.class)
public class MockMvcTests {
@Autowired
private MockMvc mvc;
@MockBean
private IUserService userService;
/**
* 测试Server是否可达
* @throws Exception
*/
@Test
public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
public void mvcTest() throws Exception {
String uri = "/lock/key";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)
.header("lock_ipv4", Constants.CLEAR_LOCK_FOR_IPV4)
.param("act", Boolean.TRUE.toString()))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = new JSONObject(content);
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.get("data");
Assert.assertNotNull(data);
}
@Test
public void testExample() throws Exception {
String phone = "13461067662";
User user = new User();
user.setPhoneNo(phone);
given(userService.findByPhoneInDb(phone)).willReturn(user);
mvc.perform(get("/log/list").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Honda Civic"));
}
}
package token;
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
......@@ -12,7 +12,8 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
......@@ -20,19 +21,13 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import java.util.Base64;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
@WebAppConfiguration
public class OneTimeTokenTests {
final String userName = "root";
final String password = "!QAZ2wsx";
final String phoneNo = "13461067662";
public class MvcTests {
private MockMvc mvc;
@Autowired
WebApplicationContext webApplicationConnect;
......@@ -40,7 +35,6 @@ public class OneTimeTokenTests {
@Before
public void setUp() throws JsonProcessingException {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
}
/**
......@@ -51,87 +45,22 @@ public class OneTimeTokenTests {
public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/token/oneTime").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
/**
* 测试OneTime-Token发放服务
* @throws Exception
*/
@Test
public void testOneTimeToken() throws Exception{
String tokenOnceUri = "/token/oneTime";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(tokenOnceUri).accept(MediaType.APPLICATION_JSON))
public void mvcTest() throws Exception {
String uri = "/lock/key";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)
.header("lock_ipv4", Constants.CLEAR_LOCK_FOR_IPV4)
.param("act", Boolean.TRUE.toString()))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = JSON.parseObject(new String(content));
JSONObject jsonResult = new JSONObject(content);
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.getString("data");
Object data = jsonResult.get("data");
Assert.assertNotNull(data);
String oneTimeToken = String.valueOf(data);
Assert.assertNotEquals("", oneTimeToken);
}
/**
* 测试OneTime-Token切面
* @throws Exception
*/
// TODO 用户注册先不加OneTime-Token校验,进一步确认后再添加或删除本用例
//@Test
public void testAspect() throws Exception{
// 获取OneTime-Token
String oneTimeTokenUri = "/token/oneTime";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(oneTimeTokenUri).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = JSON.parseObject(new String(content));
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.getString("data");
Assert.assertNotNull(data);
String oneTimeToken = String.valueOf(data);
Assert.assertNotEquals("", oneTimeToken);
// 第一次使用OneTime-Token
String aspectUri = "/user/loginForH5";
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", userName)
.param("password", password))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Object businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0000", code);
Assert.assertNotEquals("0002", businessCode);
// 使用过期的TokenOnce
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", userName)
.param("password", password))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
// 不使用TokenOnce
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", userName)
.param("password", password))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
}
}
package demo;
import org.junit.Test;
import org.junit.jupiter.api.Tag;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
/**
* jUnit4风格参数化批量测试(用例)
* @author renwc
* @date 2018-01-05
*/
@Tag("Parameters")
@RunWith(value = Parameterized.class)
public class ParametersJunit4Tests {
private String key;
private int value;
public ParametersJunit4Tests(String key, int value) {
this.key = key;
this.value = value;
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] {{"1", 1}, {"2", 2}, {"3", 3}, {"4", 4}};
return Arrays.asList(data);
}
@Test
public void pushTest() {
System.out.println("Parameterized is : key="+ key+", value="+value);
}
}
\ No newline at end of file
package demo;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* jUnit5风格参数化批量测试(用例)
* @author renwc
* @date 2018-01-05
*/
@Tag("Parameters")
public class ParametersJunit5Tests {
@ParameterizedTest
@ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
void palindromes(String candidate) {
Assert.assertNotNull(candidate);
}
@Ignore("Not Ready to Run")
@Test
public void loginFast() {
System.out.println("Not Ready to Run");
}
@Ignore("Not Ready to Run")
@DisplayName("My 1st JUnit 5 test! 😎")
@org.junit.jupiter.api.Test
public void myFirstTest(TestInfo testInfo) {
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
assertEquals("My 1st JUnit 5 test! 😎", testInfo.getDisplayName(), () -> "TestInfo is injected correctly");
}
}
\ No newline at end of file
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.config.data.JpaConfig;
import cn.quantgroup.xyqb.config.data.RedisConfig;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.repository.IUserRepository;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;
/**
* 持久层测试用例
* @author renwc
* @date 2018-01-05
*/
@Rollback
@Transactional
@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(classes = {JpaConfig.class, RedisConfig.class}, initializers = ApolloPropertySourceInitializer.class)
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class RepsitoryJpaTests {
@Autowired
private TestEntityManager entityManager;
@Autowired
private IUserRepository userRepository;
@Test(expected = PersistenceException.class)
public void testSaveExample() throws Exception {
String phone = "13461067662";
User user = new User();
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
@Test
public void testExample() throws Exception {
String phone = "13461067662";
String password = "318e235d3e52648b236faa3f748000d5";//123456
User user = new User();
user.setPhoneNo(phone);
user.setPassword(password);
user.setCreatedAt(Timestamp.from(Instant.now()));
user.setUpdatedAt(user.getCreatedAt());
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
}
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.repository.IUserRepository;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;
/**
* 持久层测试用例
* @author renwc
* @date 2018-01-05
*/
@Rollback
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class RepsitoryTests {
@Autowired
private IUserRepository userRepository;
@Test
public void testSaveExample() throws Exception {
String phone = "13461067662";
User user = new User();
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
@Test
public void testInsertExample() throws Exception {
String phone = "13461067662";
String password = "318e235d3e52648b236faa3f748000d5";//123456
User user = new User();
user.setPhoneNo(phone);
user.setPassword(password);
user.setCreatedAt(Timestamp.from(Instant.now()));
user.setUpdatedAt(user.getCreatedAt());
user = userRepository.save(user);
User userRep = userRepository.findByPhoneNo(phone);
Assert.assertEquals(user, userRep);
}
}
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.PersistenceException;
import java.sql.Timestamp;
import java.time.Instant;
/**
* 业务层测试用例
* @author renwc
* @date 2018-01-05
*/
@Rollback
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class ServiceTests {
@Autowired
private IUserService userService;
@Test
public void testSaveExample() throws Exception {
String phone = "13461067662";
User user = new User();
user = userService.saveUser(user);
User userRep = userService.findByPhoneInDb(phone);
Assert.assertEquals(user, userRep);
}
@Test
public void testInsertExample() throws Exception {
String phone = "13461067662";
String password = "318e235d3e52648b236faa3f748000d5";//123456
User user = new User();
user.setPhoneNo(phone);
user.setPassword(password);
user.setCreatedAt(Timestamp.from(Instant.now()));
user.setUpdatedAt(user.getCreatedAt());
user = userService.saveUser(user);
User userRep = userService.findByPhoneInDb(phone);
Assert.assertEquals(user, userRep);
}
}
package demo;
import cn.quantgroup.xyqb.Bootstrap;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 控制层测试用例
* @author renwc
* @date 2018-01-05
*/
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Bootstrap.class, webEnvironment= WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
public class WebTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void contextLoads() {
Assert.assertTrue(true);
}
@Test
public void test() {
ResponseEntity<String> phil = restTemplate.getForEntity("/{model}/list", String.class, "log");
Assert.assertEquals(phil.getStatusCode(), HttpStatus.OK);
}
}
package login;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.octo.captcha.service.CaptchaServiceException;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Optional;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Bootstrap.class)
@WebAppConfiguration
public class LoginForH5Tests {
final String phoneNo = "13461067662";
final String userName = "root";
final String password = "!QAZ2wsx";
private MockMvc mvc;
@Autowired
WebApplicationContext webApplicationConnect;
@Before
public void setUp() throws JsonProcessingException {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build();
}
/**
* 测试Server是否可达
* @throws Exception
*/
@Test
public void testServer() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/user/loginForH5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/user/login/fastForH5").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/api/captcha").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mvc.perform(MockMvcRequestBuilders.get("/api/sms/send_login_code").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
/**
* 测试图形验证码账密登录
* @throws Exception
*/
@Test
public void testLoginFoH5() throws Exception{
Assert.assertTrue(false);
}
/**
* 测试TokenOnce切面
* @throws Exception
*/
@Test
public void testLoginFastFoH5() throws Exception{
// 获取TokenOnce
String oneTimeTokenUri = "/token/oneTime";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(oneTimeTokenUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", phoneNo))
.andExpect(status().isOk())
.andReturn();
String content = mvcResult.getResponse().getContentAsString();
JSONObject jsonResult = JSON.parseObject(new String(content));
Object code = jsonResult.get("code");
Assert.assertEquals("0000", code);
Object data = jsonResult.get("data");
Assert.assertNotNull(data);
String oneTimeToken = String.valueOf(data);
Assert.assertNotEquals("", oneTimeToken);
String smsUri = "/api/sms/send_login_code";
mvcResult = mvc.perform(MockMvcRequestBuilders.get(oneTimeTokenUri).accept(MediaType.APPLICATION_JSON)
.param("phoneNo", phoneNo))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
data = jsonResult.get("data");
Assert.assertNotNull(data);
String verificationCode = "1234";
StringBuilder verificationBuilder = new StringBuilder();
String authorization = "Verification " + new String(Base64.getEncoder().encodeToString(verificationBuilder.append(phoneNo).append(":").append(verificationCode).toString().getBytes(Charset.forName("UTF-8"))));
// 第一次使用TokenOnce
String aspectUri = "/user/login/fastForH5";
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.header("authorization", authorization))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Object businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0000", code);
Assert.assertNotEquals("0002", businessCode);
// 使用过期的TokenOnce与verificationCode
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON)
.header("authorization", authorization))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
// 不使用TokenOnce和verificationCode
mvcResult = mvc.perform(MockMvcRequestBuilders.get(aspectUri).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
content = mvcResult.getResponse().getContentAsString();
jsonResult = JSON.parseObject(new String(content));
code = jsonResult.get("code");
Assert.assertEquals("0000", code);
businessCode = jsonResult.get("businessCode");
Assert.assertEquals("0002", businessCode);
}
}
package user;
package login;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.Constants;
......@@ -6,14 +6,10 @@ import cn.quantgroup.xyqb.controller.external.user.InnerController;
import cn.quantgroup.xyqb.controller.internal.user.UserController;
import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
......@@ -24,14 +20,9 @@ import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.IOException;
......
package service;
import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.entity.Address;
import cn.quantgroup.xyqb.service.user.IAddressService;
import cn.quantgroup.xyqb.service.user.IContactService;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.config.ApolloPropertySourceInitializer;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Created by xuran on 2017/12/26.
*/
@ContextConfiguration(initializers = ApolloPropertySourceInitializer.class)
@SpringBootTest(classes = Bootstrap.class )
@Slf4j
@Rollback
@Transactional
@RunWith(Parameterized.class)
public class TestUserService {
private TestContextManager testContextManager;
@Autowired
private IAddressService addressService;
@Autowired
private IContactService contactService;
private Address addressObj;
public TestUserService(Address addressObj) {
super();
this.addressObj = addressObj;
}
@Before
public void setUpContext() throws Exception {
//this is where the magic happens, we actually do "by hand" what the spring runner would do for us,
// read the JavaDoc for the class bellow to know exactly what it does, the method names are quite accurate though
this.testContextManager = new TestContextManager(getClass());
this.testContextManager.prepareTestInstance(this);
}
@Parameterized.Parameters
public static Collection data() {
Address addressObj =new Address();
addressObj.setUserId(123456L);
addressObj.setCity("悉尼");
addressObj.setCityCode(1L);
addressObj.setDistrict("悉尼");
addressObj.setDistrictCode(1L);
addressObj.setProvince("悉尼");
addressObj.setProvinceCode(1L);
addressObj.setAddress("嘻哈");
Timestamp timestamp=Timestamp.valueOf( LocalDateTime.now());
addressObj.setCreatedAt(timestamp);
addressObj.setUpdateAt(timestamp);
return Arrays.asList(new Object[][]{{addressObj}});
}
@Test
public void testAddress() {
addressService.save(addressObj);
addressObj=addressService.findByUserId(addressObj.getUserId());
System.out.println("测试地址"+addressObj);
List<Long> userIds= Lists.newArrayList();
userIds.add(123456L);
List<Address> addresses= addressService.findByUserIds(userIds);
System.out.println("测试地址集合"+addresses.get(0));
}
}
app.id=xyqb-user2
namespace=application
\ No newline at end of file
namespace=application,tech.msg.sdk,cash.common,tech.service.urls
\ 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