Commit 65324010 authored by Java-刘 彧阳's avatar Java-刘 彧阳

Merge branch 'master' into log_without_phone

Conflicts:
	src/main/java/cn/quantgroup/xyqb/controller/external/user/WeChatController.java
	src/test/java/user/TestUserLogin.java
parents 3cc775b3 0c126d5d
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
...@@ -40,6 +40,12 @@ ...@@ -40,6 +40,12 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -207,6 +213,78 @@ ...@@ -207,6 +213,78 @@
<artifactId>quantgroup-config-sdk</artifactId> <artifactId>quantgroup-config-sdk</artifactId>
<version>1.0.3-SNAPSHOT</version> <version>1.0.3-SNAPSHOT</version>
</dependency> </dependency>
<!-- motan -->
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-core</artifactId>
<version>0.2.2</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
<exclusion>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>hession-bugfix</artifactId>
<version>4.0.38</version>
</dependency>
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-transport-netty</artifactId>
<version>0.2.2</version>
</dependency>
<!-- only needed for spring-based features -->
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-springsupport</artifactId>
<version>0.2.2</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.quantgroup</groupId>
<artifactId>xyqb-user-rpc-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.weibo</groupId>
<artifactId>motan-registry-zookeeper</artifactId>
<version>0.2.1</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- spring security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.7.RELEASE</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
...@@ -249,49 +327,49 @@ ...@@ -249,49 +327,49 @@
</build> </build>
</profile> </profile>
<profile> <profile>
<id>dev</id> <id>dev</id>
<properties> <properties>
<profiles.activation>dev</profiles.activation> <profiles.activation>dev</profiles.activation>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>cn.quantgroup</groupId> <groupId>cn.quantgroup</groupId>
<artifactId>quantgroup-sms-sdk</artifactId> <artifactId>quantgroup-sms-sdk</artifactId>
<version>2.0.0.3-SNAPSHOT</version> <version>2.0.0.3-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<resources> <resources>
<resource> <resource>
<directory> <directory>
${project.basedir}/src/main/resources/config/dev ${project.basedir}/src/main/resources/config/dev
</directory> </directory>
</resource> </resource>
</resources> </resources>
</build> </build>
</profile> </profile>
<profile> <profile>
<id>test</id> <id>test</id>
<properties> <properties>
<profiles.activation>test</profiles.activation> <profiles.activation>test</profiles.activation>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>cn.quantgroup</groupId> <groupId>cn.quantgroup</groupId>
<artifactId>quantgroup-sms-sdk</artifactId> <artifactId>quantgroup-sms-sdk</artifactId>
<version>1.0.5-SNAPSHOT</version> <version>1.0.5-SNAPSHOT</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<resources> <resources>
<resource> <resource>
<directory> <directory>
${project.basedir}/src/main/resources/config/test ${project.basedir}/src/main/resources/config/test
</directory> </directory>
</resource> </resource>
</resources> </resources>
</build> </build>
</profile> </profile>
</profiles> </profiles>
</project> </project>
package cn.quantgroup.xyqb; package cn.quantgroup.xyqb;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableAsync;
@ComponentScan(basePackages = {"cn.quantgroup.xyqb", "cn.quantgroup.cloudconfig"}) @ComponentScan(basePackages = {"cn.quantgroup.xyqb", "cn.quantgroup.cloudconfig"})
...@@ -18,9 +23,20 @@ import org.springframework.scheduling.annotation.EnableAsync; ...@@ -18,9 +23,20 @@ import org.springframework.scheduling.annotation.EnableAsync;
@Configuration @Configuration
@EnableAspectJAutoProxy @EnableAspectJAutoProxy
@EnableAsync @EnableAsync
@Slf4j
public class Bootstrap { public class Bootstrap {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args); SpringApplication springApplication = new SpringApplication(Bootstrap.class);
} springApplication.addListeners(new ApplicationListener<ContextRefreshedEvent>() {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
log.info("注册zookeeper成功");
}
});
springApplication.setRegisterShutdownHook(true);
springApplication.run(args);
log.info("server start...");
}
} }
package cn.quantgroup.xyqb; package cn.quantgroup.xyqb;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
public interface Constants { public interface Constants {
// zero fill with 4 chars... // zero fill with 4 chars...
String ZERO_FILL_TEMPLATE = "%04d"; String ZERO_FILL_TEMPLATE = "%04d";
String PASSWORD_SALT = "_lkb"; String PASSWORD_SALT = "_lkb";
String IMAGE_CAPTCHA_KEY = "img_captcha:"; String IMAGE_CAPTCHA_KEY = "img_captcha:";
String REDIS_CAPTCHA_KEY = "auth:"; String REDIS_CAPTCHA_KEY = "auth:";
String REDIS_CAPTCHA_KEY_PATTERN = REDIS_CAPTCHA_KEY + IMAGE_CAPTCHA_KEY + "*"; String REDIS_CAPTCHA_KEY_PATTERN = REDIS_CAPTCHA_KEY + IMAGE_CAPTCHA_KEY + "*";
String CONFIG_CAPTCHA = "cfg_captcha_%"; String CONFIG_CAPTCHA = "cfg_captcha_%";
// app 后端白名单 // app 后端白名单
String CONFIG_CAPTCHA_WHITEIP_LIST = "cfg_captcha_white_ip_appbackend"; String CONFIG_CAPTCHA_WHITEIP_LIST = "cfg_captcha_white_ip_appbackend";
// 每个 IP 每分钟 captcha 限制 // 每个 IP 每分钟 captcha 限制
String CONFIG_CAPTCHA_PERIP_PERMIN = "cfg_captcha_per_ip_per_min"; String CONFIG_CAPTCHA_PERIP_PERMIN = "cfg_captcha_per_ip_per_min";
// 是否启用万能验证码 // 是否启用万能验证码
String CONFIG_CAPTCHA_MAGIC_CODE_ENABLED = "cfg_captcha_magic_code_enabled"; String CONFIG_CAPTCHA_MAGIC_CODE_ENABLED = "cfg_captcha_magic_code_enabled";
String REDIS_PREFIX_VERIFICATION_CODE = "verificationCode_"; String REDIS_PREFIX_VERIFICATION_CODE = "verificationCode_";
/** /**
* redis中token的key值前缀 * redis中token的key值前缀
*/ */
String SESSION_PREFIX = "spring:session:sessions:"; String SESSION_PREFIX = "spring:session:sessions:";
interface Jr58 { interface Jr58 {
int ERROR_PHONE_NUMBER = 20007; // 手机号码格式不正确 int ERROR_PHONE_NUMBER = 20007; // 手机号码格式不正确
int ERROR_ID_CARD = 20009; // 身份证格式不正确 int ERROR_ID_CARD = 20009; // 身份证格式不正确
int ERROR_ACCOUNT = 20010; // 授权账号为空 int ERROR_ACCOUNT = 20010; // 授权账号为空
int ERROR_AUTH_TYPE = 20011; // 授权类型为空 int ERROR_AUTH_TYPE = 20011; // 授权类型为空
} }
interface Channel { interface Channel {
long LKB = 1; // 量化派 long LKB = 1; // 量化派
long JR58 = 175; // 58金融 long JR58 = 175; // 58金融
long BAITIAO = 222L; long BAITIAO = 222L;
String LKB_CODE = "0002"; // 量化派channnel_code String LKB_CODE = "0002"; // 量化派channnel_code
long WECHAT = 198L; long WECHAT = 198L;
} }
interface Session{ interface Session {
String USER_SESSION_CACHE = "user:session:"; String USER_SESSION_CACHE = "user:session:";
String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:"; String USER_SESSION_ID_CACHE = "userid-sessionvalue:cache:";
Long ONE_DAY = 24 * 60 * 60L; Long ONE_DAY = 24 * 60 * 60L;
} }
interface WeChat { interface WeChat {
String APP_ID = "wx0a7c0bce0c3ac523"; String APP_ID = "wx0a7c0bce0c3ac523";
String REDIRECT_URL = "http://wechattest.xyqb.com/webchat/receiveCode"; String REDIRECT_URL = "http://wechattest.xyqb.com/webchat/receiveCode";
String SCOPE = "snsapi_userinfo"; String SCOPE = "snsapi_userinfo";
} }
} }
...@@ -40,82 +40,82 @@ import java.util.UUID; ...@@ -40,82 +40,82 @@ import java.util.UUID;
@Component @Component
public class CaptchaValidateAdvisor { public class CaptchaValidateAdvisor {
private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaValidateAdvisor.class); private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaValidateAdvisor.class);
private static final String SUPER_CAPTCHA_ID = UUID.nameUUIDFromBytes("__QG_APPCLIENT_AGENT__".getBytes(Charset.forName("UTF-8"))).toString(); private static final String SUPER_CAPTCHA_ID = UUID.nameUUIDFromBytes("__QG_APPCLIENT_AGENT__".getBytes(Charset.forName("UTF-8"))).toString();
private static final String SUPER_CAPTCHA = "__SUPERQG__"; private static final String SUPER_CAPTCHA = "__SUPERQG__";
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate; private RedisTemplate<String, String> redisTemplate;
@Autowired @Autowired
@Qualifier("customCaptchaService") @Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService; private AbstractManageableImageCaptchaService imageCaptchaService;
/** /**
* 自动化测试忽略验证码 * 自动化测试忽略验证码
*/ */
@Value("${xyqb.auth.captcha.autotest.enable:false}") @Value("${xyqb.auth.captcha.autotest.enable:false}")
private boolean autoTestCaptchaEnabled; private boolean autoTestCaptchaEnabled;
/** /**
* 图形验证码切面 * 图形验证码切面
*/ */
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator)") @Pointcut("@annotation(cn.quantgroup.xyqb.aspect.captcha.CaptchaValidator)")
private void needCaptchaValidate() { private void needCaptchaValidate() {
}
/**
* 在受图形验证码保护的接口方法执行前, 执行图形验证码校验
*
* @param pjp
* @return
* @throws Throwable
*/
@Around("needCaptchaValidate()")
private Object doCapchaValidate(ProceedingJoinPoint pjp) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String registerFrom = Optional.ofNullable(request.getParameter("registerFrom")).orElse("");
String captchaId = Optional.ofNullable(request.getParameter("captchaId")).orElse("");
Object captchaValue = request.getParameter("captchaValue");
if (shouldSkipCaptchaValidate(registerFrom, captchaId, captchaValue)) {
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, request.getRemoteAddr());
return pjp.proceed();
} }
JsonResult result = JsonResult.buildSuccessResult("图形验证码错误, 请重新输入", "");
/** result.setBusinessCode("0002");
* 在受图形验证码保护的接口方法执行前, 执行图形验证码校验 if (captchaValue != null) {
* String captcha = String.valueOf(captchaValue);
* @param pjp // 忽略用户输入的大小写
* @return captcha = StringUtils.lowerCase(captcha);
* @throws Throwable // 验证码校验
*/ Boolean validCaptcha = false;
@Around("needCaptchaValidate()") try {
private Object doCapchaValidate(ProceedingJoinPoint pjp) throws Throwable { validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captcha);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } catch (CaptchaServiceException ex) {
String registerFrom = Optional.ofNullable(request.getParameter("registerFrom")).orElse(""); LOGGER.error("验证码校验异常, {}, {}", ex.getMessage(), ex);
String captchaId = Optional.ofNullable(request.getParameter("captchaId")).orElse(""); }
Object captchaValue = request.getParameter("captchaValue");
if (validCaptcha) {
if (shouldSkipCaptchaValidate(registerFrom, captchaId, captchaValue)) { return pjp.proceed();
LOGGER.info("使用超级图形验证码校验, registerFrom={}, clientIp={}", registerFrom, request.getRemoteAddr()); }
return pjp.proceed();
}
JsonResult result = JsonResult.buildSuccessResult("图形验证码错误, 请重新输入", "");
result.setBusinessCode("0002");
if (captchaValue != null) {
String captcha = String.valueOf(captchaValue);
// 忽略用户输入的大小写
captcha = StringUtils.lowerCase(captcha);
// 验证码校验
Boolean validCaptcha = false;
try {
validCaptcha = imageCaptchaService.validateResponseForID(Constants.IMAGE_CAPTCHA_KEY + captchaId, captcha);
} catch (CaptchaServiceException ex) {
LOGGER.error("验证码校验异常, {}, {}", ex.getMessage(), ex);
}
if (validCaptcha) {
return pjp.proceed();
}
}
return result;
} }
private boolean shouldSkipCaptchaValidate(String registerFrom, String captchaId, Object captchaValue) { return result;
}
// 如果启用了超级验证码功能, 检查超级验证码, 超级验证码区分大小写 private boolean shouldSkipCaptchaValidate(String registerFrom, String captchaId, Object captchaValue) {
if (autoTestCaptchaEnabled) {
return true;
}
return StringUtils.equals(SUPER_CAPTCHA_ID, String.valueOf(captchaId)) && StringUtils.equals(SUPER_CAPTCHA, String.valueOf(captchaValue)); // 如果启用了超级验证码功能, 检查超级验证码, 超级验证码区分大小写
if (autoTestCaptchaEnabled) {
return true;
} }
return StringUtils.equals(SUPER_CAPTCHA_ID, String.valueOf(captchaId)) && StringUtils.equals(SUPER_CAPTCHA, String.valueOf(captchaValue));
}
} }
package cn.quantgroup.xyqb.aspect.captcha; package cn.quantgroup.xyqb.aspect.captcha;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* 类名称:CaptchaValidate * 类名称:CaptchaValidate
......
package cn.quantgroup.xyqb.aspect.fplock; package cn.quantgroup.xyqb.aspect.fplock;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* Created by Miraculous on 15/11/10. * Created by Miraculous on 15/11/10.
...@@ -14,6 +10,7 @@ import java.lang.annotation.Target; ...@@ -14,6 +10,7 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface FPLock { public @interface FPLock {
String uniqueName(); String uniqueName();
FPRestriction[] restrictions() default {};
FPRestriction[] restrictions() default {};
} }
package cn.quantgroup.xyqb.aspect.fplock; package cn.quantgroup.xyqb.aspect.fplock;
import java.lang.annotation.Documented; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
...@@ -14,12 +10,15 @@ import java.util.concurrent.TimeUnit; ...@@ -14,12 +10,15 @@ import java.util.concurrent.TimeUnit;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface FPRestriction { public @interface FPRestriction {
// 持续时间 // 持续时间
int duration() default 1; int duration() default 1;
// 持续时间单位
TimeUnit type() default TimeUnit.MINUTES; // 持续时间单位
// 限制值, -1表示不限制 TimeUnit type() default TimeUnit.MINUTES;
int limit() default -1;
// 使用可覆盖 // 限制值, -1表示不限制
boolean override() default true; int limit() default -1;
// 使用可覆盖
boolean override() default true;
} }
...@@ -34,217 +34,237 @@ import java.util.stream.Stream; ...@@ -34,217 +34,237 @@ import java.util.stream.Stream;
@Order(value = Ordered.HIGHEST_PRECEDENCE) @Order(value = Ordered.HIGHEST_PRECEDENCE)
public class FirstParamLockAspect { public class FirstParamLockAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(FirstParamLockAspect.class); private static final Logger LOGGER = LoggerFactory.getLogger(FirstParamLockAspect.class);
private static final HashMap<String, FPRestrictionWraper> LOCK_PARAM;
@Autowired private static final Long MAX_COUNTER = 1L;
@Qualifier("stringRedisTemplate") private static final Long MAX_TO_LIVE = 10L;
private RedisTemplate<String, String> stringRedisTemplate;
static {
private static final HashMap<String, FPRestrictionWraper> LOCK_PARAM; FastHashMap fastHashMap = new FastHashMap();
private static final Long MAX_COUNTER = 1L; fastHashMap.setFast(true);
private static final Long MAX_TO_LIVE = 10L; LOCK_PARAM = fastHashMap;
}
static {
FastHashMap fastHashMap = new FastHashMap(); @Autowired
fastHashMap.setFast(true); @Qualifier("stringRedisTemplate")
LOCK_PARAM = fastHashMap; private RedisTemplate<String, String> stringRedisTemplate;
} /* 自定义限制策略 (FPRestriction) 的情况下, 可配置的限制数值 */
@Value("${xyqb.fplock.limit.byhour:3}")
/* 自定义限制策略 (FPRestriction) 的情况下, 可配置的限制数值 */ private Integer limitByHour; // 每小时限制值
@Value("${xyqb.fplock.limit.byhour:3}") @Value("${xyqb.fplock.limit.byday:5}")
private Integer limitByHour; // 每小时限制值 private Integer limitByDay; // 每天限制值
@Value("${xyqb.fplock.limit.byday:5}")
private Integer limitByDay; // 每天限制值 @Pointcut("@annotation(cn.quantgroup.xyqb.aspect.fplock.FPLock)")
private void fplockPointCut() {
@Pointcut("@annotation(cn.quantgroup.xyqb.aspect.fplock.FPLock)")
private void fplockPointCut() { }
@Around("fplockPointCut()")
private Object preventDuplicateSubmit(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
if (args == null || args.length == 0) {
return pjp.proceed();
} }
@Around("fplockPointCut()") MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
private Object preventDuplicateSubmit(ProceedingJoinPoint pjp) throws Throwable { Method method = methodSignature.getMethod();
Object[] args = pjp.getArgs(); FPLock fpLock = method.getAnnotation(cn.quantgroup.xyqb.aspect.fplock.FPLock.class);
if (args == null || args.length == 0) { Object fp = args[0];
return pjp.proceed();
} if (fpLock.restrictions().length < 1) {
String lockName = fpLock.uniqueName() + fp.toString();
MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Long ret = stringRedisTemplate.opsForValue().increment(lockName, 1L);
Method method = methodSignature.getMethod(); if (MAX_COUNTER < ret) {
FPLock fpLock = method.getAnnotation(cn.quantgroup.xyqb.aspect.fplock.FPLock.class); stringRedisTemplate.expire(lockName, MAX_TO_LIVE, TimeUnit.SECONDS);
Object fp = args[0]; throw new ResubmissionException();
}
if (fpLock.restrictions().length < 1) { try {
String lockName = fpLock.uniqueName() + fp.toString(); return pjp.proceed();
Long ret = stringRedisTemplate.opsForValue().increment(lockName, 1L); } finally {
if (MAX_COUNTER < ret) { stringRedisTemplate.expire(lockName, MAX_TO_LIVE, TimeUnit.SECONDS);
stringRedisTemplate.expire(lockName, MAX_TO_LIVE, TimeUnit.SECONDS); }
throw new ResubmissionException(); } else {
} String uniqueName = fpLock.uniqueName();
try {
return pjp.proceed();
} finally {
stringRedisTemplate.expire(lockName, MAX_TO_LIVE, TimeUnit.SECONDS);
}
} else {
String uniqueName = fpLock.uniqueName();
/* 加入自定义限制策略 */ /* 加入自定义限制策略 */
FPRestrictionWraper[] restrictionWrapers = wrapFPRestrictions(uniqueName, fpLock.restrictions()); FPRestrictionWraper[] restrictionWrapers = wrapFPRestrictions(uniqueName, fpLock.restrictions());
// 执行检查 // 执行检查
boolean restrictionsPass = preRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers); boolean restrictionsPass = preRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers);
if (restrictionsPass) { if (restrictionsPass) {
// 检查通过 // 检查通过
try { try {
Object proceed = pjp.proceed(); Object proceed = pjp.proceed();
if (JsonResult.class == proceed.getClass()) { if (JsonResult.class == proceed.getClass()) {
JsonResult result = (JsonResult) proceed; JsonResult result = (JsonResult) proceed;
if (!"0000".equals(result.getCode()) || !"0000".equals(result.getBusinessCode())) { if (!"0000".equals(result.getCode()) || !"0000".equals(result.getBusinessCode())) {
// 业务操作失败 // 业务操作失败
postRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers); postRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers);
}
}
return proceed;
} catch (Exception e) {
// 业务操作异常
postRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers);
throw e;
}
} else {
// 检查不通过
LOGGER.warn("接口首参数保护! api:{}, variable:{}", method.getName(), String.valueOf(fp));
postRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers);
throw new ResubmissionException();
} }
}
return proceed;
} catch (Exception e) {
// 业务操作异常
postRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers);
throw e;
} }
} else {
// 检查不通过
LOGGER.warn("接口首参数保护! api:{}, variable:{}", method.getName(), String.valueOf(fp));
postRestrictionsCheck(uniqueName, String.valueOf(fp), restrictionWrapers);
throw new ResubmissionException();
}
} }
}
public void parseFpLockAnnotaion(Method method) {
FPLock fpLock = method.getAnnotation(cn.quantgroup.xyqb.aspect.fplock.FPLock.class); public void parseFpLockAnnotaion(Method method) {
wrapFPRestrictions(fpLock.uniqueName(), fpLock.restrictions()); FPLock fpLock = method.getAnnotation(cn.quantgroup.xyqb.aspect.fplock.FPLock.class);
wrapFPRestrictions(fpLock.uniqueName(), fpLock.restrictions());
}
/**
* 重设限制参数
*/
public void setLimitation(String key, Integer duration, Integer limit) {
FPRestrictionWraper restriction = LOCK_PARAM.get(key);
if (restriction != null) {
if (duration != null) restriction.duration(duration);
if (limit != null) restriction.limit(limit);
} }
/** }
* 重设限制参数
*/ /**
public void setLimitation(String key, Integer duration, Integer limit) { * 读取限制参数
FPRestrictionWraper restriction = LOCK_PARAM.get(key); */
if (restriction != null) { public FPRestrictionWraper readLimitation(String key) {
if(duration != null) restriction.duration(duration); return LOCK_PARAM.get(key);
if(limit != null) restriction.limit(limit); }
}
/**
* 包装注解
*
* @param uniqueName
* @param restrictions
* @return
*/
private FPRestrictionWraper[] wrapFPRestrictions(String uniqueName, FPRestriction[] restrictions) {
FPRestrictionWraper[] wrapers = new FPRestrictionWraper[restrictions.length];
for (int i = 0; i < wrapers.length; i++) {
FPRestriction restriction = restrictions[i];
// 将restriction 配置参数读入 map
String key = uniqueName + restriction.type().toString();
if (LOCK_PARAM.containsKey(key)) {
wrapers[i] = LOCK_PARAM.get(key);
} else {
FPRestrictionWraper wraper = new FPRestrictionWraper(restriction);
wrapers[i] = wraper;
LOCK_PARAM.put(key, wraper);
}
} }
return wrapers;
/** }
* 读取限制参数
*/ /**
public FPRestrictionWraper readLimitation(String key) { * 前置检查, 根据用户设置的锁策略进行锁检查
return LOCK_PARAM.get(key); *
* @param uniqeName
* @param variable
* @param restrictions
* @return
*/
private boolean preRestrictionsCheck(String uniqeName, String variable, FPRestrictionWraper[] restrictions) {
for (FPRestrictionWraper restriction : restrictions) {
TimeUnit timeUnit = restriction.timeUnit();
int duration = restriction.duration();
int limit = restriction.limit();
String lockName = uniqeName + restriction.getLockKey() + ":" + variable;
// 根据锁名获取缓存的:已操作的次数
Long action = stringRedisTemplate.opsForValue().increment(lockName, 1L);
restriction.setProceed(true);
if (action > limit) {
// 已超过规定值, 本次操作不允许
return false;
}
restriction.setSuccess(true);
// 本条限制通过, 设置过期策略, 等待下次操作请求
stringRedisTemplate.expire(lockName, duration, timeUnit);
} }
/** return true;
* 包装注解 }
*
* @param uniqueName /**
* @param restrictions * 后置检查, 用户锁值操作已成功, 但是业务操作失败的情况, 回滚 redis 计数
* @return *
*/ * @param uniqeName
private FPRestrictionWraper[] wrapFPRestrictions(String uniqueName, FPRestriction[] restrictions) { * @param variable
FPRestrictionWraper[] wrapers = new FPRestrictionWraper[restrictions.length]; * @param restrictions
for (int i = 0; i < wrapers.length; i++) { * @return
FPRestriction restriction = restrictions[i]; */
// 将restriction 配置参数读入 map private boolean postRestrictionsCheck(String uniqeName, String variable, FPRestrictionWraper[] restrictions) {
String key = uniqueName + restriction.type().toString(); Stream<FPRestrictionWraper> restrictions1 = Stream.of(restrictions);
if (LOCK_PARAM.containsKey(key)) { restrictions1.filter(FPRestrictionWraper::isProceed).forEach(res -> {
wrapers[i] = LOCK_PARAM.get(key); // 由于业务操作失败, "回滚"计数值
} else { String lockName = uniqeName + res.getLockKey() + ":" + variable;
FPRestrictionWraper wraper = new FPRestrictionWraper(restriction); stringRedisTemplate.opsForValue().increment(lockName, -1L);
wrapers[i] = wraper; });
LOCK_PARAM.put(key, wraper); return true;
} }
}
return wrapers; /**
* 根据时间单位获取Redis锁名
*
* @return
*/
private String getLockKeyByTimeUnit(TimeUnit timeUnit) {
Calendar calendar = Calendar.getInstance();
String unit = timeUnit.toString();
switch (timeUnit) {
case DAYS:
return unit + DateFormatUtils.format(calendar, "yyyyMMdd");
case HOURS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHH");
case MINUTES:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmm");
case SECONDS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmmss");
default:
return unit;
} }
}
/**
* 前置检查, 根据用户设置的锁策略进行锁检查 /**
* * 注解包装类
* @param uniqeName */
* @param variable public class FPRestrictionWraper {
* @param restrictions private FPRestriction restriction;
* @return private int limit;
*/ private int duration;
private boolean preRestrictionsCheck(String uniqeName, String variable, FPRestrictionWraper[] restrictions) { private TimeUnit timeUnit;
for (FPRestrictionWraper restriction : restrictions) { private boolean isSuccess;
TimeUnit timeUnit = restriction.timeUnit(); private boolean isProceed;
int duration = restriction.duration();
int limit = restriction.limit(); public FPRestrictionWraper(FPRestriction restriction) {
String lockName = uniqeName + restriction.getLockKey() + ":" + variable; this.restriction = restriction;
// 根据锁名获取缓存的:已操作的次数 this.timeUnit = restriction.type();
Long action = stringRedisTemplate.opsForValue().increment(lockName, 1L); this.limit = restriction.limit();
restriction.setProceed(true); this.duration = restriction.duration();
if (action > limit) {
// 已超过规定值, 本次操作不允许
return false;
}
restriction.setSuccess(true);
// 本条限制通过, 设置过期策略, 等待下次操作请求
stringRedisTemplate.expire(lockName, duration, timeUnit);
}
return true;
} }
/** public TimeUnit timeUnit() {
* 后置检查, 用户锁值操作已成功, 但是业务操作失败的情况, 回滚 redis 计数 return this.timeUnit;
*
* @param uniqeName
* @param variable
* @param restrictions
* @return
*/
private boolean postRestrictionsCheck(String uniqeName, String variable, FPRestrictionWraper[] restrictions) {
Stream<FPRestrictionWraper> restrictions1 = Stream.of(restrictions);
restrictions1.filter(FPRestrictionWraper::isProceed).forEach(res -> {
// 由于业务操作失败, "回滚"计数值
String lockName = uniqeName + res.getLockKey() + ":" + variable;
stringRedisTemplate.opsForValue().increment(lockName, -1L);
});
return true;
} }
/** public int duration() {
* 注解包装类 return this.duration;
*/ }
public class FPRestrictionWraper {
private FPRestriction restriction;
private int limit;
private int duration;
private TimeUnit timeUnit;
private boolean isSuccess;
private boolean isProceed;
public FPRestrictionWraper(FPRestriction restriction) {
this.restriction = restriction;
this.timeUnit = restriction.type();
this.limit = restriction.limit();
this.duration = restriction.duration();
}
public TimeUnit timeUnit() {
return this.timeUnit;
}
public int duration() {
return this.duration;
}
public void duration(int duration) { public void duration(int duration) {
this.duration = duration; this.duration = duration;
} }
public int limit() { public int limit() {
return this.limit; return this.limit;
/* int _limit = this.restriction.limit(); /* int _limit = this.restriction.limit();
switch (restriction.type()) { switch (restriction.type()) {
case DAYS: case DAYS:
...@@ -254,56 +274,34 @@ public class FirstParamLockAspect { ...@@ -254,56 +274,34 @@ public class FirstParamLockAspect {
default: default:
return -1; return -1;
}*/ }*/
} }
public void limit(int limit) {
this.limit = limit;
}
public boolean isSuccess() { public void limit(int limit) {
return isSuccess; this.limit = limit;
} }
public void setSuccess(boolean success) { public boolean isSuccess() {
isSuccess = success; return isSuccess;
} }
public boolean isProceed() { public void setSuccess(boolean success) {
return isProceed; isSuccess = success;
} }
public void setProceed(boolean proceed) { public boolean isProceed() {
isProceed = proceed; return isProceed;
} }
public String getLockKey() { public void setProceed(boolean proceed) {
return getLockKeyByTimeUnit(timeUnit()); isProceed = proceed;
} }
public String desc() { public String getLockKey() {
return "timeUnit:" + timeUnit + ", duration:" + this.duration + ", limit:" + limit; return getLockKeyByTimeUnit(timeUnit());
}
} }
/** public String desc() {
* 根据时间单位获取Redis锁名 return "timeUnit:" + timeUnit + ", duration:" + this.duration + ", limit:" + limit;
*
* @return
*/
private String getLockKeyByTimeUnit(TimeUnit timeUnit) {
Calendar calendar = Calendar.getInstance();
String unit = timeUnit.toString();
switch (timeUnit) {
case DAYS:
return unit + DateFormatUtils.format(calendar, "yyyyMMdd");
case HOURS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHH");
case MINUTES:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmm");
case SECONDS:
return unit + DateFormatUtils.format(calendar, "yyyyMMddHHmmss");
default:
return unit;
}
} }
}
} }
...@@ -23,23 +23,23 @@ import org.springframework.data.redis.core.RedisTemplate; ...@@ -23,23 +23,23 @@ import org.springframework.data.redis.core.RedisTemplate;
@Configuration @Configuration
public class CaptchaConfig { public class CaptchaConfig {
@Bean @Bean
public CaptchaEngine initCaptchaEngine() { public CaptchaEngine initCaptchaEngine() {
return new CustomJCaptchaEngine(); return new CustomJCaptchaEngine();
} }
@Bean @Bean
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
public CaptchaStore initStringCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) { public CaptchaStore initStringCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) {
return new RedisCaptchaStore(stringRedisTemplate); return new RedisCaptchaStore(stringRedisTemplate);
} }
@Bean(name = "customCaptchaService") @Bean(name = "customCaptchaService")
@Autowired @Autowired
public AbstractManageableImageCaptchaService initCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) { public AbstractManageableImageCaptchaService initCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
return new CustomJCaptchaService(captchaStore, captchaEngine); return new CustomJCaptchaService(captchaStore, captchaEngine);
} }
} }
...@@ -35,44 +35,44 @@ import java.awt.image.ImageFilter; ...@@ -35,44 +35,44 @@ import java.awt.image.ImageFilter;
*/ */
public class CustomJCaptchaEngine extends ListImageCaptchaEngine { public class CustomJCaptchaEngine extends ListImageCaptchaEngine {
private static final int MIN_WORD_LEN = 4; private static final int MIN_WORD_LEN = 4;
private static final int MAX_WORD_LEN = 4; private static final int MAX_WORD_LEN = 4;
@Override @Override
protected void buildInitialFactories() { protected void buildInitialFactories() {
int minWordLength = 4; int minWordLength = 4;
int maxWordLength = 4; int maxWordLength = 4;
int fontSize = 16; int fontSize = 16;
int imageWidth = 80; int imageWidth = 80;
int imageHeight = 28; int imageHeight = 28;
WordGenerator wordGenerator = new RandomWordGenerator("1234567890"); WordGenerator wordGenerator = new RandomWordGenerator("1234567890");
SingleColorGenerator colorGenerator = new SingleColorGenerator(Color.WHITE); SingleColorGenerator colorGenerator = new SingleColorGenerator(Color.WHITE);
//文字干扰器--- 可以创建多个 //文字干扰器--- 可以创建多个
BaffleTextDecorator baffleTextDecorator = new BaffleTextDecorator(1,colorGenerator, 1);//气泡干扰 BaffleTextDecorator baffleTextDecorator = new BaffleTextDecorator(1, colorGenerator, 1);//气泡干扰
// LineTextDecorator lineTextDecorator = new LineTextDecorator(1,colorGenerator, 1);//曲线干扰 // LineTextDecorator lineTextDecorator = new LineTextDecorator(1,colorGenerator, 1);//曲线干扰
// TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator, lineTextDecorator}; // TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator, lineTextDecorator};
TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator}; TextDecorator[] textDecorators = new TextDecorator[]{baffleTextDecorator};
TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength, TextPaster randomPaster = new DecoratedRandomTextPaster(minWordLength,
maxWordLength, new RandomListColorGenerator(new Color[]{ maxWordLength, new RandomListColorGenerator(new Color[]{
new Color(23, 170, 27), new Color(220, 34, 11), new Color(23, 170, 27), new Color(220, 34, 11),
new Color(23, 67, 172)}), textDecorators); new Color(23, 67, 172)}), textDecorators);
BackgroundGenerator background = new UniColorBackgroundGenerator(imageWidth, imageHeight, colorGenerator); BackgroundGenerator background = new UniColorBackgroundGenerator(imageWidth, imageHeight, colorGenerator);
FontGenerator font = new RandomFontGenerator(fontSize, fontSize, FontGenerator font = new RandomFontGenerator(fontSize, fontSize,
new Font[]{new Font("nyala", Font.BOLD, fontSize), new Font[]{new Font("nyala", Font.BOLD, fontSize),
new Font("Bell MT", Font.PLAIN, fontSize), new Font("Bell MT", Font.PLAIN, fontSize),
new Font("Credit valley", Font.BOLD, fontSize)}); new Font("Credit valley", Font.BOLD, fontSize)});
ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[]{}); ImageDeformation postDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[]{}); ImageDeformation backDef = new ImageDeformationByFilters(new ImageFilter[]{});
ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[]{}); ImageDeformation textDef = new ImageDeformationByFilters(new ImageFilter[]{});
WordToImage word2image = new DeformedComposedWordToImage(font, WordToImage word2image = new DeformedComposedWordToImage(font,
background, randomPaster, backDef, textDef, postDef); background, randomPaster, backDef, textDef, postDef);
addFactory(new CustomGimpyFactory(wordGenerator, word2image)); addFactory(new CustomGimpyFactory(wordGenerator, word2image));
} }
} }
...@@ -24,84 +24,84 @@ import java.util.Locale; ...@@ -24,84 +24,84 @@ import java.util.Locale;
*/ */
public class CustomJCaptchaService extends AbstractManageableImageCaptchaService { public class CustomJCaptchaService extends AbstractManageableImageCaptchaService {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomJCaptchaService.class); private static final Logger LOGGER = LoggerFactory.getLogger(CustomJCaptchaService.class);
/* /*
* 验证码管理策略: * 验证码管理策略:
* 1, 生成验证码时, 会进行配额检查, 当达到配额时, 进行垃圾验证码清理 * 1, 生成验证码时, 会进行配额检查, 当达到配额时, 进行垃圾验证码清理
* 2, 一个验证码校验完成后, 不管成功失败, 都会直接失效, 删除? * 2, 一个验证码校验完成后, 不管成功失败, 都会直接失效, 删除?
* */ * */
private static final Integer MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS = 120; // 默认值, 执行垃圾清理时, 存活超过180s的验证码都会被清除 private static final Integer MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS = 120; // 默认值, 执行垃圾清理时, 存活超过180s的验证码都会被清除
private static final Integer MAX_CAPTCHA_STORE_SIZE = 70000; // 最大容量, 默认值是10w private static final Integer MAX_CAPTCHA_STORE_SIZE = 70000; // 最大容量, 默认值是10w
private static final Integer CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION = 52500; // 配额, 超过此配额时执行一次垃圾清除, 默认值是:75000 private static final Integer CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION = 52500; // 配额, 超过此配额时执行一次垃圾清除, 默认值是:75000
public CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
this(captchaStore, captchaEngine, MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS, MAX_CAPTCHA_STORE_SIZE, CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION);
}
public CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine) {
this(captchaStore, captchaEngine, MIN_GUARANTED_STORAGE_DELAY_IN_SECONDS, MAX_CAPTCHA_STORE_SIZE, CAPTCHA_STORE_LOAD_BEFORE_GARBAGE_COLLECTION);
}
protected CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
}
@Override
public long getCustomStoreSize() {
return this.store.getSize();
}
/** protected CustomJCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
* 重写校验, 需要将原来的 key 失效 super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
* }
* @param id
* @param response
* @return
* @throws CaptchaServiceException
*/
@Override
public Boolean validateResponseForID(String id, Object response) throws CaptchaServiceException {
if (StringUtils.isBlank(id)) {
return false;
}
boolean valid;
try {
Captcha captcha = this.store.getCaptcha(id);
if (null == captcha || captcha.hasGetChalengeBeenCalled()) {
return false;
}
valid = captcha.validateResponse(response);
} catch (Exception ex) {
LOGGER.warn("can not get captcha from redis");
valid = false;
}
this.getTimes().remove(id); @Override
if(valid) { public long getCustomStoreSize() {
addNumberOfCorrectResponse(1); return this.store.getSize();
} else { }
addNumberOfUncorrectResponse(1);
}
return valid; /**
* 重写校验, 需要将原来的 key 失效
*
* @param id
* @param response
* @return
* @throws CaptchaServiceException
*/
@Override
public Boolean validateResponseForID(String id, Object response) throws CaptchaServiceException {
if (StringUtils.isBlank(id)) {
return false;
} }
boolean valid;
/** try {
* 请求新的图形验证码 Captcha captcha = this.store.getCaptcha(id);
* if (null == captcha || captcha.hasGetChalengeBeenCalled()) {
* @param ID return false;
* @param locale }
* @return valid = captcha.validateResponse(response);
* @throws CaptchaServiceException } catch (Exception ex) {
*/ LOGGER.warn("can not get captcha from redis");
public Object getChallengeForID(String ID, Locale locale) throws CaptchaServiceException { valid = false;
Captcha captcha = this.generateAndStoreCaptcha(locale, ID);
Object challenge = this.getChallengeClone(captcha);
captcha.disposeChallenge();
return challenge;
} }
@Override this.getTimes().remove(id);
public void garbageCollectCaptchaStore() { if (valid) {
super.garbageCollectCaptchaStore(); addNumberOfCorrectResponse(1);
} else {
addNumberOfUncorrectResponse(1);
} }
return valid;
}
/**
* 请求新的图形验证码
*
* @param ID
* @param locale
* @return
* @throws CaptchaServiceException
*/
public Object getChallengeForID(String ID, Locale locale) throws CaptchaServiceException {
Captcha captcha = this.generateAndStoreCaptcha(locale, ID);
Object challenge = this.getChallengeClone(captcha);
captcha.disposeChallenge();
return challenge;
}
@Override
public void garbageCollectCaptchaStore() {
super.garbageCollectCaptchaStore();
}
} }
...@@ -26,87 +26,87 @@ import java.util.concurrent.TimeUnit; ...@@ -26,87 +26,87 @@ import java.util.concurrent.TimeUnit;
*/ */
public class RedisCaptchaStore implements CaptchaStore { public class RedisCaptchaStore implements CaptchaStore {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisCaptchaStore.class); private static final Logger LOGGER = LoggerFactory.getLogger(RedisCaptchaStore.class);
private static final long DEFAULT_EXPIRED_IN = 120L; private static final long DEFAULT_EXPIRED_IN = 120L;
private static final TimeUnit DEFAULT_EXPIRED_TIMEUNIT = TimeUnit.SECONDS; private static final TimeUnit DEFAULT_EXPIRED_TIMEUNIT = TimeUnit.SECONDS;
protected RedisTemplate<String, String> stringRedisTemplate; protected RedisTemplate<String, String> stringRedisTemplate;
public RedisCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) { public RedisCaptchaStore(RedisTemplate<String, String> stringRedisTemplate) {
super(); super();
this.stringRedisTemplate = stringRedisTemplate; this.stringRedisTemplate = stringRedisTemplate;
} }
@Override @Override
public boolean hasCaptcha(String captchaId) { public boolean hasCaptcha(String captchaId) {
return stringRedisTemplate.hasKey(buildCaptcharKey(captchaId)); return stringRedisTemplate.hasKey(buildCaptcharKey(captchaId));
} }
@Override @Override
public void storeCaptcha(String s, Captcha captcha) throws CaptchaServiceException { public void storeCaptcha(String s, Captcha captcha) throws CaptchaServiceException {
stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT); stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT);
} }
@Override @Override
public void storeCaptcha(String s, Captcha captcha, Locale locale) throws CaptchaServiceException { public void storeCaptcha(String s, Captcha captcha, Locale locale) throws CaptchaServiceException {
stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT); stringRedisTemplate.opsForValue().set(buildCaptcharKey(s), ((SimpleCaptcha) captcha).getResponse(), DEFAULT_EXPIRED_IN, DEFAULT_EXPIRED_TIMEUNIT);
} }
@Override @Override
public boolean removeCaptcha(String captchaId) { public boolean removeCaptcha(String captchaId) {
stringRedisTemplate.delete(buildCaptcharKey(captchaId)); stringRedisTemplate.delete(buildCaptcharKey(captchaId));
return true; return true;
} }
@Override @Override
public Captcha getCaptcha(String captchaId) throws CaptchaServiceException { public Captcha getCaptcha(String captchaId) throws CaptchaServiceException {
return getFromRedisThenDel(captchaId); return getFromRedisThenDel(captchaId);
} }
@Override @Override
public Locale getLocale(String captchaId) throws CaptchaServiceException { public Locale getLocale(String captchaId) throws CaptchaServiceException {
return Locale.CHINA; return Locale.CHINA;
} }
@Override @Override
public int getSize() { public int getSize() {
return getKeys().size(); return getKeys().size();
} }
@Override @Override
public Collection getKeys() { public Collection getKeys() {
return stringRedisTemplate.keys(Constants.REDIS_CAPTCHA_KEY_PATTERN); return stringRedisTemplate.keys(Constants.REDIS_CAPTCHA_KEY_PATTERN);
} }
@Override @Override
public void empty() { public void empty() {
} }
@Override @Override
public void initAndStart() { public void initAndStart() {
} }
@Override @Override
public void cleanAndShutdown() { public void cleanAndShutdown() {
} }
private Captcha getFromRedis(String captchaId) { private Captcha getFromRedis(String captchaId) {
Object value = stringRedisTemplate.opsForValue().get(buildCaptcharKey(captchaId)); Object value = stringRedisTemplate.opsForValue().get(buildCaptcharKey(captchaId));
return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null; return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null;
} }
private Captcha getFromRedisThenDel(String captchaId) { private Captcha getFromRedisThenDel(String captchaId) {
String captcharKey = buildCaptcharKey(captchaId); String captcharKey = buildCaptcharKey(captchaId);
Object value = stringRedisTemplate.opsForValue().get(captcharKey); Object value = stringRedisTemplate.opsForValue().get(captcharKey);
stringRedisTemplate.delete(captcharKey); stringRedisTemplate.delete(captcharKey);
return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null; return value != null ? new SimpleCaptcha(captchaId, String.valueOf(value)) : null;
} }
protected String buildCaptcharKey(String captchaId) { protected String buildCaptcharKey(String captchaId) {
return Constants.REDIS_CAPTCHA_KEY + captchaId; return Constants.REDIS_CAPTCHA_KEY + captchaId;
} }
} }
...@@ -33,66 +33,65 @@ import java.util.Properties; ...@@ -33,66 +33,65 @@ import java.util.Properties;
@EnableTransactionManagement @EnableTransactionManagement
public class JpaConfig { public class JpaConfig {
@SafeValue("xyqb.data.mysql.jdbc-url") @SafeValue("xyqb.data.mysql.jdbc-url")
private String xyqbJdbcUrl; private String xyqbJdbcUrl;
@SafeValue("xyqb.data.mysql.password") @SafeValue("xyqb.data.mysql.password")
private String password; private String password;
@SafeValue("xyqb.data.mysql.user") @SafeValue("xyqb.data.mysql.user")
private String user; private String user;
@Value("${xyqb.data.mysql.max-pool-size}") @Value("${xyqb.data.mysql.max-pool-size}")
private Integer maxPoolSize; private Integer maxPoolSize;
@Bean @Bean
@DependsOn(value = "dataSource") @DependsOn(value = "dataSource")
public EntityManagerFactory entityManagerFactory() { public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(ApplicationContextHolder.getBean("dataSource")); entityManager.setDataSource(ApplicationContextHolder.getBean("dataSource"));
entityManager.setPackagesToScan("cn.quantgroup.xyqb"); entityManager.setPackagesToScan("cn.quantgroup.xyqb");
entityManager.setPersistenceUnitName("dataSource"); entityManager.setPersistenceUnitName("dataSource");
Properties properties = new Properties(); Properties properties = new Properties();
properties.put("hibernate.jdbc.batch_size", 30); properties.put("hibernate.jdbc.batch_size", 30);
properties.put("hibernate.order_inserts", true); properties.put("hibernate.order_inserts", true);
properties.put("hibernate.order_updates", true); properties.put("hibernate.order_updates", true);
entityManager.setJpaProperties(properties); entityManager.setJpaProperties(properties);
entityManager.setJpaVendorAdapter(jpaVendorAdapter()); entityManager.setJpaVendorAdapter(jpaVendorAdapter());
entityManager.afterPropertiesSet(); entityManager.afterPropertiesSet();
return entityManager.getObject(); return entityManager.getObject();
} }
@Bean @Bean
public DataSource dataSource() { public DataSource dataSource() {
HikariConfig config = new HikariConfig(); HikariConfig config = new HikariConfig();
config.setJdbcUrl(xyqbJdbcUrl); config.setJdbcUrl(xyqbJdbcUrl);
config.setPassword(password); config.setPassword(password);
config.setUsername(user); config.setUsername(user);
config.setMaximumPoolSize(maxPoolSize); config.setMaximumPoolSize(maxPoolSize);
config.setMinimumIdle(20); config.setMinimumIdle(20);
config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
return new HikariDataSource(config); return new HikariDataSource(config);
} }
private JpaVendorAdapter jpaVendorAdapter() { private JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(false); hibernateJpaVendorAdapter.setShowSql(false);
hibernateJpaVendorAdapter.setGenerateDdl(false); hibernateJpaVendorAdapter.setGenerateDdl(false);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL); hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter; return hibernateJpaVendorAdapter;
} }
@Bean
@Bean public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager();
JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory);
transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager;
return transactionManager; }
}
} }
...@@ -6,8 +6,6 @@ import org.springframework.beans.factory.annotation.Value; ...@@ -6,8 +6,6 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode; import org.springframework.data.redis.connection.RedisNode;
...@@ -27,118 +25,118 @@ import java.util.Set; ...@@ -27,118 +25,118 @@ import java.util.Set;
@Configuration @Configuration
public class RedisConfig { public class RedisConfig {
@Value("${xyqb.data.redis.defaultExpiration}") @Value("${xyqb.data.redis.defaultExpiration}")
private Long defaultExpiration; private Long defaultExpiration;
@Value("${xyqb.redis.master.host}") @Value("${xyqb.redis.master.host}")
private String masterHost; private String masterHost;
@Value("${xyqb.redis.master.port}") @Value("${xyqb.redis.master.port}")
private int masterPort; private int masterPort;
@Value("${xyqb.redis.master.name}") @Value("${xyqb.redis.master.name}")
private String masterName; private String masterName;
@Value("${xyqb.redis.sentinel1.host}") @Value("${xyqb.redis.sentinel1.host}")
private String sentinel1Host; private String sentinel1Host;
@Value("${xyqb.redis.sentinel1.port}") @Value("${xyqb.redis.sentinel1.port}")
private int sentinel1port; private int sentinel1port;
@Value("${xyqb.redis.sentinel2.host}") @Value("${xyqb.redis.sentinel2.host}")
private String sentinel2Host; private String sentinel2Host;
@Value("${xyqb.redis.sentinel2.port}") @Value("${xyqb.redis.sentinel2.port}")
private int sentinel2port; private int sentinel2port;
@Value("${xyqb.redis.sentinel3.host}") @Value("${xyqb.redis.sentinel3.host}")
private String sentinel3Host; private String sentinel3Host;
@Value("${xyqb.redis.sentinel3.port}") @Value("${xyqb.redis.sentinel3.port}")
private int sentinel3port; private int sentinel3port;
private RedisConnectionFactory generateDevConnectionFactory() { private RedisConnectionFactory generateDevConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory(); JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(masterHost); factory.setHostName(masterHost);
factory.setPort(masterPort); factory.setPort(masterPort);
factory.setUsePool(true); factory.setUsePool(true);
factory.setConvertPipelineAndTxResults(true); factory.setConvertPipelineAndTxResults(true);
JedisPoolConfig poolConfig = generatePoolConfig(); JedisPoolConfig poolConfig = generatePoolConfig();
factory.setPoolConfig(poolConfig); factory.setPoolConfig(poolConfig);
factory.afterPropertiesSet(); factory.afterPropertiesSet();
return factory; return factory;
} }
private RedisConnectionFactory generateReleaseConnectionFactory() { private RedisConnectionFactory generateReleaseConnectionFactory() {
RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration(); RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration();
RedisNode master = new RedisNode(masterHost, masterPort); RedisNode master = new RedisNode(masterHost, masterPort);
master.setName(masterName); master.setName(masterName);
Set<RedisNode> sentinels = new HashSet<>(); Set<RedisNode> sentinels = new HashSet<>();
RedisNode sentinel1 = new RedisNode(sentinel1Host, sentinel1port); RedisNode sentinel1 = new RedisNode(sentinel1Host, sentinel1port);
RedisNode sentinel2 = new RedisNode(sentinel2Host, sentinel2port); RedisNode sentinel2 = new RedisNode(sentinel2Host, sentinel2port);
RedisNode sentinel3 = new RedisNode(sentinel3Host, sentinel3port); RedisNode sentinel3 = new RedisNode(sentinel3Host, sentinel3port);
sentinels.add(sentinel1); sentinels.add(sentinel1);
sentinels.add(sentinel2); sentinels.add(sentinel2);
sentinels.add(sentinel3); sentinels.add(sentinel3);
sentinelConfiguration.setMaster(master); sentinelConfiguration.setMaster(master);
sentinelConfiguration.setSentinels(sentinels); sentinelConfiguration.setSentinels(sentinels);
JedisPoolConfig poolConfig = generatePoolConfig(); JedisPoolConfig poolConfig = generatePoolConfig();
JedisConnectionFactory factory = new JedisConnectionFactory(sentinelConfiguration, poolConfig); JedisConnectionFactory factory = new JedisConnectionFactory(sentinelConfiguration, poolConfig);
factory.setHostName(masterHost); factory.setHostName(masterHost);
factory.setPort(masterPort); factory.setPort(masterPort);
factory.setTimeout(5000); factory.setTimeout(5000);
factory.setUsePool(true); factory.setUsePool(true);
factory.setConvertPipelineAndTxResults(true); factory.setConvertPipelineAndTxResults(true);
factory.afterPropertiesSet(); factory.afterPropertiesSet();
return factory; return factory;
} }
private JedisPoolConfig generatePoolConfig() { private JedisPoolConfig generatePoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig(); JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMinIdle(20); poolConfig.setMinIdle(20);
poolConfig.setMaxTotal(300); poolConfig.setMaxTotal(300);
poolConfig.setMaxWaitMillis(5000); poolConfig.setMaxWaitMillis(5000);
poolConfig.setTestOnBorrow(true); poolConfig.setTestOnBorrow(true);
return poolConfig; return poolConfig;
} }
@Bean(name = "redisConnectionFactory") @Bean(name = "redisConnectionFactory")
RedisConnectionFactory factory() { RedisConnectionFactory factory() {
if (StringUtils.isEmpty(masterName)) { if (StringUtils.isEmpty(masterName)) {
return generateDevConnectionFactory(); return generateDevConnectionFactory();
} else { } else {
return generateReleaseConnectionFactory(); return generateReleaseConnectionFactory();
}
} }
}
@Bean(name = "redisTemplate") @Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate( public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory factory) { RedisConnectionFactory factory) {
final RedisTemplate<String, Object> template = new RedisTemplate<>(); final RedisTemplate<String, Object> template = new RedisTemplate<>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer(); JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
template.setEnableTransactionSupport(false); template.setEnableTransactionSupport(false);
template.setKeySerializer(stringRedisSerializer); template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jdkSerializationRedisSerializer); template.setValueSerializer(jdkSerializationRedisSerializer);
template.setDefaultSerializer(jdkSerializationRedisSerializer); template.setDefaultSerializer(jdkSerializationRedisSerializer);
template.setConnectionFactory(factory); template.setConnectionFactory(factory);
XyqbSessionContextHolder.redisTemplate = stringRedisTemplate(factory); XyqbSessionContextHolder.redisTemplate = stringRedisTemplate(factory);
return template; return template;
} }
@Bean(name = "stringRedisTemplate") @Bean(name = "stringRedisTemplate")
public RedisTemplate<String, String> stringRedisTemplate( public RedisTemplate<String, String> stringRedisTemplate(
RedisConnectionFactory factory) { RedisConnectionFactory factory) {
final RedisTemplate<String, String> template = new RedisTemplate<>(); final RedisTemplate<String, String> template = new RedisTemplate<>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer(); JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
template.setEnableTransactionSupport(true); template.setEnableTransactionSupport(true);
template.setKeySerializer(stringRedisSerializer); template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jdkSerializationRedisSerializer); template.setValueSerializer(jdkSerializationRedisSerializer);
template.setDefaultSerializer(jdkSerializationRedisSerializer); template.setDefaultSerializer(jdkSerializationRedisSerializer);
template.setConnectionFactory(factory); template.setConnectionFactory(factory);
return template; return template;
} }
@Bean(name = "cacheManager") @Bean(name = "cacheManager")
public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) { public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(defaultExpiration); cacheManager.setDefaultExpiration(defaultExpiration);
cacheManager.setUsePrefix(true); cacheManager.setUsePrefix(true);
return cacheManager; return cacheManager;
} }
} }
package cn.quantgroup.xyqb.config.http; package cn.quantgroup.xyqb.config.http;
import java.security.KeyManagementException; import com.fasterxml.jackson.annotation.JsonInclude;
import java.security.KeyStoreException; import com.fasterxml.jackson.databind.DeserializationFeature;
import java.security.NoSuchAlgorithmException; import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
import javax.net.ssl.SSLContext;
import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.CookieSpecs;
import org.apache.http.config.Registry; import org.apache.http.config.Registry;
...@@ -37,9 +33,11 @@ import org.springframework.core.convert.converter.ConverterRegistry; ...@@ -37,9 +33,11 @@ import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.CharacterEncodingFilter;
import com.fasterxml.jackson.annotation.JsonInclude; import javax.net.ssl.SSLContext;
import com.fasterxml.jackson.databind.DeserializationFeature; import java.security.KeyManagementException;
import com.fasterxml.jackson.databind.SerializationFeature; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
/** /**
* Created by Miraculous on 15/7/12. * Created by Miraculous on 15/7/12.
...@@ -47,94 +45,94 @@ import com.fasterxml.jackson.databind.SerializationFeature; ...@@ -47,94 +45,94 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@Configuration @Configuration
public class HttpConfig { public class HttpConfig {
@Bean @Bean
public FilterRegistrationBean filterRegistrationBean() { public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(); FilterRegistrationBean registrationBean = new FilterRegistrationBean();
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
registrationBean.setFilter(characterEncodingFilter); registrationBean.setFilter(characterEncodingFilter);
characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true); characterEncodingFilter.setForceEncoding(true);
registrationBean.setOrder(Integer.MIN_VALUE); registrationBean.setOrder(Integer.MIN_VALUE);
registrationBean.addUrlPatterns("/*"); registrationBean.addUrlPatterns("/*");
return registrationBean; return registrationBean;
} }
/** /**
* 该方法主要对对象json序列化产生影响,其功能如下: * 该方法主要对对象json序列化产生影响,其功能如下:
* 1. 禁用缩进输出 * 1. 禁用缩进输出
* 2. 日期格式排版 * 2. 日期格式排版
* 3. null被过滤掉 * 3. null被过滤掉
* 4. 将enum转为其ordinal * 4. 将enum转为其ordinal
* *
* @return Jackson2ObjectMapperBuilder * @return Jackson2ObjectMapperBuilder
*/ */
@Bean @Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() { public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.indentOutput(false) builder.indentOutput(false)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd")) .dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.defaultViewInclusion(false) .defaultViewInclusion(false)
.serializationInclusion(JsonInclude.Include.NON_NULL) .serializationInclusion(JsonInclude.Include.NON_NULL)
.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX, .featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_INDEX,
DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS); DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
return builder; return builder;
} }
// hack spring mvc. // hack spring mvc.
@Bean @Bean
public IntegerToEnumConverterFactory getIntegerToEnumConverterFactory( public IntegerToEnumConverterFactory getIntegerToEnumConverterFactory(
ConverterRegistry defaultConversionService, ConverterRegistry mvcConversionService, ConverterRegistry integrationConversionService) { ConverterRegistry defaultConversionService, ConverterRegistry mvcConversionService, ConverterRegistry integrationConversionService) {
IntegerToEnumConverterFactory factory = new IntegerToEnumConverterFactory(); IntegerToEnumConverterFactory factory = new IntegerToEnumConverterFactory();
defaultConversionService.removeConvertible(String.class, Enum.class); defaultConversionService.removeConvertible(String.class, Enum.class);
mvcConversionService.removeConvertible(String.class, Enum.class); mvcConversionService.removeConvertible(String.class, Enum.class);
integrationConversionService.removeConvertible(String.class, Enum.class); integrationConversionService.removeConvertible(String.class, Enum.class);
defaultConversionService.addConverterFactory(factory); defaultConversionService.addConverterFactory(factory);
mvcConversionService.addConverterFactory(factory); mvcConversionService.addConverterFactory(factory);
integrationConversionService.addConverterFactory(factory); integrationConversionService.addConverterFactory(factory);
return factory; return factory;
} }
@Bean(name = "httpClient") @Bean(name = "httpClient")
public CloseableHttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { public CloseableHttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// socket factory // socket factory
ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory(); ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial( SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, (x509Certificates, authType) -> true).build(); null, (x509Certificates, authType) -> true).build();
LayeredConnectionSocketFactory sslSocketFactory = LayeredConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory) .register("http", plainSocketFactory)
.register("https", sslSocketFactory).build(); .register("https", sslSocketFactory).build();
// cookie specification // cookie specification
Registry<CookieSpecProvider> cookieSpecProviderRegistry = RegistryBuilder.<CookieSpecProvider>create() Registry<CookieSpecProvider> cookieSpecProviderRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()) .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
.register("easy", httpContext -> new BrowserCompatSpec() { .register("easy", httpContext -> new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
} }
}).build(); }).build();
// connection manager // connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(10000); connectionManager.setMaxTotal(10000);
connectionManager.setDefaultMaxPerRoute(1000); connectionManager.setDefaultMaxPerRoute(1000);
// retry handler // retry handler
HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(3, false); HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(3, false);
// keep alive strategy // keep alive strategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy(); ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
// httpclient // httpclient
return HttpClients.custom() return HttpClients.custom()
.setConnectionManager(connectionManager) .setConnectionManager(connectionManager)
.setRetryHandler(retryHandler) .setRetryHandler(retryHandler)
.setKeepAliveStrategy(keepAliveStrategy) .setKeepAliveStrategy(keepAliveStrategy)
.setDefaultCookieSpecRegistry(cookieSpecProviderRegistry).build(); .setDefaultCookieSpecRegistry(cookieSpecProviderRegistry).build();
} }
} }
...@@ -7,33 +7,33 @@ import org.springframework.core.convert.converter.ConverterFactory; ...@@ -7,33 +7,33 @@ import org.springframework.core.convert.converter.ConverterFactory;
* Created by Miraculous on 15/7/12. * Created by Miraculous on 15/7/12.
*/ */
final class IntegerToEnumConverterFactory implements ConverterFactory<String, Enum> { final class IntegerToEnumConverterFactory implements ConverterFactory<String, Enum> {
IntegerToEnumConverterFactory() { IntegerToEnumConverterFactory() {
} }
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) { public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
Class<?> enumType = targetType; Class<?> enumType = targetType;
while (enumType != null && !enumType.isEnum()) { while (enumType != null && !enumType.isEnum()) {
enumType = enumType.getSuperclass(); enumType = enumType.getSuperclass();
} }
if (enumType == null) { if (enumType == null) {
throw new IllegalArgumentException("The target type " + targetType.getName() + " does not refer to an enum"); throw new IllegalArgumentException("The target type " + targetType.getName() + " does not refer to an enum");
} else { } else {
return new IntegerToEnumConverterFactory.IntegerToEnum(enumType); return new IntegerToEnumConverterFactory.IntegerToEnum(enumType);
}
} }
}
private class IntegerToEnum<T extends Enum> implements Converter<String, T> { private class IntegerToEnum<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType; private final Class<T> enumType;
public IntegerToEnum(Class<T> enumType) { public IntegerToEnum(Class<T> enumType) {
this.enumType = enumType; this.enumType = enumType;
} }
public T convert(String source) { public T convert(String source) {
T[] ts = enumType.getEnumConstants(); T[] ts = enumType.getEnumConstants();
int ordinal = Integer.parseInt(source); int ordinal = Integer.parseInt(source);
return ordinal < ts.length && ordinal >= 0 ? ts[ordinal] : null; return ordinal < ts.length && ordinal >= 0 ? ts[ordinal] : null;
}
} }
}
} }
\ No newline at end of file
...@@ -11,14 +11,15 @@ import java.sql.Timestamp; ...@@ -11,14 +11,15 @@ import java.sql.Timestamp;
* Created by Miraculous on 2016/12/29. * Created by Miraculous on 2016/12/29.
*/ */
public class Timestamp2LongConverter implements ObjectSerializer { public class Timestamp2LongConverter implements ObjectSerializer {
; ;
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException { @Override
Timestamp time = (Timestamp)object; public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
if (time == null) { Timestamp time = (Timestamp) object;
serializer.write(String.valueOf(0L)); if (time == null) {
} else { serializer.write(String.valueOf(0L));
serializer.write(String.valueOf(time.getTime())); } else {
} serializer.write(String.valueOf(time.getTime()));
} }
}
} }
package cn.quantgroup.xyqb.config.motan;
import com.weibo.api.motan.config.springsupport.AnnotationBean;
import com.weibo.api.motan.config.springsupport.BasicServiceConfigBean;
import com.weibo.api.motan.config.springsupport.ProtocolConfigBean;
import com.weibo.api.motan.config.springsupport.RegistryConfigBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by 11 on 2017/2/27.
*/
@Configuration
public class MotanConfig {
@Bean
public AnnotationBean motanAnnotationBean() {
AnnotationBean motanAnnotationBean = new AnnotationBean();
motanAnnotationBean.setPackage("cn.quantgroup.xyqb.controller.external.motan");
return motanAnnotationBean;
}
@Bean(name = "userMotan")
public ProtocolConfigBean protocolConfig1(
@Value("${protocol.isDefault}") Boolean isDefault, @Value("${protocol.name}") String name,
@Value("${protocol.contentLength}") int contentLength) {
ProtocolConfigBean config = new ProtocolConfigBean();
config.setDefault(isDefault);
config.setName(name);
config.setMaxContentLength(contentLength);
config.setMaxServerConnection(1000);
return config;
}
@Bean(name = "registryConfig")
public RegistryConfigBean registryConfig(@Value("${registry.protocol}") String registryProtocol,
@Value("${registry.address}") String registryAddress
) {
RegistryConfigBean config = new RegistryConfigBean();
config.setRegProtocol(registryProtocol);
config.setAddress(registryAddress);
return config;
}
@Bean
public BasicServiceConfigBean baseServiceConfig(@Value("${motan.port}") int motanPort,
@Value("${motan.user.group}") String userGroup,
@Value("${motan.user.module}") String userModule,
@Value("${motan.application:xyqbUserMotan}") String applicationName) {
BasicServiceConfigBean config = new BasicServiceConfigBean();
config.setExport("userMotan:" + motanPort);
config.setGroup(userGroup);
config.setVersion("1.0");
config.setAccessLog(true);
config.setShareChannel(true);
config.setModule(userModule);
config.setApplication(applicationName);
config.setRegistry("registryConfig");
return config;
}
}
package cn.quantgroup.xyqb.config.web; package cn.quantgroup.xyqb.config.web;
import cn.quantgroup.xyqb.interceptors.ChannelIdInterceptor; import cn.quantgroup.xyqb.interceptors.ChannelIdInterceptor;
import cn.quantgroup.xyqb.interceptors.IPWhiteListInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
...@@ -11,8 +13,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter ...@@ -11,8 +13,12 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration @Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter { public class InterceptorConfig extends WebMvcConfigurerAdapter {
public void addInterceptors(InterceptorRegistry registry) { @Value("${configserver.disable}")
registry.addInterceptor(new ChannelIdInterceptor()).addPathPatterns("/**"); private Integer isDebug;
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new IPWhiteListInterceptor(isDebug)).addPathPatterns("/innerapi/**");
registry.addInterceptor(new ChannelIdInterceptor()).addPathPatterns("/**");
}
} }
...@@ -22,42 +22,41 @@ import javax.servlet.http.HttpServletRequest; ...@@ -22,42 +22,41 @@ import javax.servlet.http.HttpServletRequest;
@RestController @RestController
public class ExceptionHandlingController implements IBaseController { public class ExceptionHandlingController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlingController.class); private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlingController.class);
private static final JsonResult EXCEPTION_RESULT = new JsonResult("internal error", 500L, ""); private static final JsonResult EXCEPTION_RESULT = new JsonResult("internal error", 500L, "");
@ExceptionHandler(NullUserException.class) @ExceptionHandler(NullUserException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult nullUserException(NullUserException nue) { public JsonResult nullUserException(NullUserException nue) {
return new JsonResult(nue.getMessage(), 401L, null); return new JsonResult(nue.getMessage(), 401L, null);
} }
/** /**
* 验证码登陆异常 * 验证码登陆异常
* *
* @param vce * @param vce
* @return * @return
*/ */
@ExceptionHandler(VerificationCodeErrorException.class) @ExceptionHandler(VerificationCodeErrorException.class)
public JsonResult verificationCodeErrorException(VerificationCodeErrorException vce) { public JsonResult verificationCodeErrorException(VerificationCodeErrorException vce) {
return JsonResult.buildErrorStateResult(vce.getMessage(), null, 1L); return JsonResult.buildErrorStateResult(vce.getMessage(), null, 1L);
} }
@ExceptionHandler(UserNotExistException.class) @ExceptionHandler(UserNotExistException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseStatus(HttpStatus.UNAUTHORIZED)
public JsonResult userNotExistException(UserNotExistException unee) { public JsonResult userNotExistException(UserNotExistException unee) {
return new JsonResult(unee.getMessage(), 401L, null); return new JsonResult(unee.getMessage(), 401L, null);
} }
@ExceptionHandler(Exception.class)
@ExceptionHandler(Exception.class) public JsonResult exceptionOccurs(Exception e) {
public JsonResult exceptionOccurs(Exception e) { HttpServletRequest request = getRequest();
HttpServletRequest request = getRequest(); String uri = request.getRequestURI();
String uri = request.getRequestURI(); String registerFrom = request.getParameter("registerFrom");
String registerFrom = request.getParameter("registerFrom"); LOGGER.error("接口异常 URI:{}, registerFrom:{}", uri, registerFrom, e);
LOGGER.error("接口异常 URI:{}, registerFrom:{}", uri, registerFrom, e); return EXCEPTION_RESULT;
return EXCEPTION_RESULT; }
}
} }
...@@ -7,56 +7,61 @@ import org.springframework.web.context.request.RequestContextHolder; ...@@ -7,56 +7,61 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.*;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSession;
import static cn.quantgroup.xyqb.session.XyqbSessionContextHolder.getXSessionFromRedis;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
public interface IBaseController { public interface IBaseController {
default User getCurrentUser() { default User getCurrentUser() {
SessionStruct session = getXSession(); SessionStruct session = getXSession();
if (session == null) { if (session == null) {
return null; return null;
}
return getXSession().getValues().getUser();
}
default SessionStruct getSessionStruct() {
return getXSession();
} }
return getXSession().getValues().getUser();
}
default SessionStruct getSessionStruct() {
return getXSession();
}
default HttpServletRequest getRequest() { default SessionStruct getCurrentSessionFromRedis(){
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder return getXSessionFromRedis();
.getRequestAttributes(); }
return attrs.getRequest();
}
default String getIp() {
HttpServletRequest request = getRequest();
String ip = request.getHeader("x-real-ip"); default HttpServletRequest getRequest() {
if (StringUtils.isEmpty(ip)) { ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
ip = request.getRemoteAddr(); .getRequestAttributes();
} return attrs.getRequest();
}
//过滤反向代理的ip default String getIp() {
String[] stemps = ip.split(","); HttpServletRequest request = getRequest();
if (stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
ip = ip.trim(); String ip = request.getHeader("x-real-ip");
if (ip.length() > 23) { if (StringUtils.isEmpty(ip)) {
ip = ip.substring(0, 23); ip = request.getRemoteAddr();
} }
return ip; //过滤反向代理的ip
String[] stemps = ip.split(",");
if (stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
} }
default String getProtocol() { ip = ip.trim();
return StringUtils.startsWith(getRequest().getHeader("x-forwarded-proto"), "https") ? "https:" : "http:"; if (ip.length() > 23) {
ip = ip.substring(0, 23);
} }
return ip;
}
default String getProtocol() {
return StringUtils.startsWith(getRequest().getHeader("x-forwarded-proto"), "https") ? "https:" : "http:";
}
} }
...@@ -38,52 +38,54 @@ import java.util.UUID; ...@@ -38,52 +38,54 @@ import java.util.UUID;
@RequestMapping("/api") @RequestMapping("/api")
public class ImageCaptchaController implements IBaseController { public class ImageCaptchaController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageCaptchaController.class); private static final Logger LOGGER = LoggerFactory.getLogger(ImageCaptchaController.class);
private static final String IMAGE_FORMAT_PNG = "png"; private static final String IMAGE_FORMAT_PNG = "png";
private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s"; private static final String IMG_BASE64_PATTREN = "data:image/" + IMAGE_FORMAT_PNG + ";base64,%s";
@Autowired @Autowired
@Qualifier("customCaptchaService") @Qualifier("customCaptchaService")
private AbstractManageableImageCaptchaService imageCaptchaService; private AbstractManageableImageCaptchaService imageCaptchaService;
@ModelAttribute("clientIp") @ModelAttribute("clientIp")
public String initClientIp() { public String initClientIp() {
return getIp(); return getIp();
} }
/** /**
* 获取验证码 * 获取验证码
* 默认匹配 GET /captcha, 提供4位数字和字母混合图片验证码 * 默认匹配 GET /captcha, 提供4位数字和字母混合图片验证码
* *
* @return * @return
*/ */
@RequestMapping(value = "/captcha") @RequestMapping(value = "/captcha")
public JsonResult fetchCaptcha(HttpServletRequest request, @ModelAttribute("clientIp") String clientIp) { public JsonResult fetchCaptcha(HttpServletRequest request, @ModelAttribute("clientIp") String clientIp) {
String imageId = UUID.randomUUID().toString(); String imageId = UUID.randomUUID().toString();
BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, request.getLocale()); BufferedImage challenge = imageCaptchaService.getImageChallengeForID(Constants.IMAGE_CAPTCHA_KEY + imageId, request.getLocale());
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try { try {
boolean write = ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream); boolean write = ImageIO.write(challenge, IMAGE_FORMAT_PNG, jpegOutputStream);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return JsonResult.buildErrorStateResult("", "fail"); return JsonResult.buildErrorStateResult("", "fail");
} }
String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray()); String imageBase64 = Base64.encodeBase64String(jpegOutputStream.toByteArray());
Map<String, String> data = new HashMap<>(); Map<String, String> data = new HashMap<>();
data.put("imageId", imageId); data.put("imageId", imageId);
data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64)); data.put("image", String.format(IMG_BASE64_PATTREN, imageBase64));
return JsonResult.buildSuccessResult("", data); return JsonResult.buildSuccessResult("", data);
} }
/** 图片验证码验证*/ /**
@CaptchaValidator * 图片验证码验证
@RequestMapping("/verification_image_code") */
public JsonResult verificationImageCode() { @CaptchaValidator
return JsonResult.buildSuccessResult("", null); @RequestMapping("/verification_image_code")
} public JsonResult verificationImageCode() {
return JsonResult.buildSuccessResult("", null);
}
} }
package cn.quantgroup.xyqb.controller.external.motan;
import cn.quantgroup.xyqb.model.JsonResult;
import com.weibo.api.motan.common.MotanConstants;
import com.weibo.api.motan.util.MotanSwitcherUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/motan")
public class MotanController {
@RequestMapping("/enable/{key}")
public JsonResult reload(@PathVariable String key) {
if (StringUtils.equals(key, "b5140fb2-2c85-4b5a-abcf-3e97528014db")) {
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true);
return JsonResult.buildSuccessResult("加载成功", null);
}
return JsonResult.buildErrorStateResult("无效", null);
}
@RequestMapping("/disable/{key}")
public JsonResult disable(@PathVariable String key) {
if (StringUtils.equals(key, "b5140fb2-2c85-4b5a-abcf-3e97528014db")) {
MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, false);
return JsonResult.buildSuccessResult("加载成功", null);
}
return JsonResult.buildErrorStateResult("无效", null);
}
}
package cn.quantgroup.xyqb.controller.external.motan;
import cn.quantgroup.motan.bean.*;
import cn.quantgroup.motan.retbean.*;
import cn.quantgroup.motan.service.UserMotanService;
import cn.quantgroup.motan.vo.UserSysResult;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.IdCardInfo;
import cn.quantgroup.xyqb.model.IdType;
import cn.quantgroup.xyqb.model.LoginProperties;
import cn.quantgroup.xyqb.model.UserRet;
import cn.quantgroup.xyqb.model.session.LoginInfo;
import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.repository.IUserRepository;
import cn.quantgroup.xyqb.service.auth.IIdCardService;
import cn.quantgroup.xyqb.service.merchant.IMerchantService;
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.user.vo.UserDetailVO;
import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.PasswordUtil;
import cn.quantgroup.xyqb.util.ValidationUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* Created by 11 on 2017/2/27.
*/
@Slf4j
@MotanService(basicService = "baseServiceConfig")
public class MotanUserServiceImpl implements UserMotanService {
private static final ObjectMapper MAPPER = new ObjectMapper();
private final static Random random = new Random();
static {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Autowired
private IIdCardService idCardService;
@Autowired
private IUserService userService;
@Autowired
private IUserDetailService userDetailService;
@Autowired
private IUserRepository userRepository;
@Autowired
private ISmsService smsService;
@Autowired
private ILkbUserService lkbUserService;
@Autowired
private IMerchantService merchantService;
@Autowired
private ISessionService sessionService;
@Autowired
private IContactService contactService;
@Autowired
private IAddressService addressService;
@Autowired
private IUserExtInfoService userExtInfoService;
@Autowired
private IWechatService wechatService;
@Autowired
private IUserSpouseService userSpouseService;
@Override
public UserSysResult<XUser> findUserByPhoneNo(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
User user = userService.findByPhoneInDb(phoneNo);
return returnSuccessValue(fromUser(user));
}
@Override
public UserSysResult<XUser> findUserByUuid(String uuid) {
if (StringUtils.isBlank(uuid)) {
return returnErrorValue("参数不能为空");
}
User user = userService.findByUuidInDb(uuid);
return returnSuccessValue(fromUser(user));
}
@Override
public UserSysResult<XUser> saveUser(UserBean userBean) {
if (null == userBean || !ValidationUtil.validatePhoneNo(userBean.getPhoneNo())) {
return returnErrorValue(userBean == null ? "要保存的用户对象不能为null" : "手机号不正确");
}
Timestamp now = new Timestamp(System.currentTimeMillis());
User user = userService.findByPhoneWithCache(userBean.getPhoneNo());
if (user == null) {
user = new User();
user.setCreatedAt(now);
user.setPhoneNo(userBean.getPhoneNo());
user.setEnable(true);
String password = userBean.getPassword();
if (StringUtils.isBlank(password)) {
password = String.valueOf(random.nextInt(899999) + 100000);
}
user.setPassword(PasswordUtil.MD5(password + Constants.PASSWORD_SALT));
} else {
if (StringUtils.isNotBlank(user.getPassword())) {
user.setPassword(PasswordUtil.MD5(userBean.getPassword() + Constants.PASSWORD_SALT));
}
}
user.setUpdatedAt(now);
user.setUuid(userBean.getUuid());
user.setRegisteredFrom(null==userBean.getRegisteredFrom()?0L:userBean.getRegisteredFrom());
User saveUser = userService.saveUser(user);
return returnSuccessValue(fromUser(saveUser));
}
@Override
public UserSysResult<XUserDetail> findUserDetailByUserId(Long userId) {
if (userId == null || userId < 1) {
return returnErrorValue("参数必须是正整数");
}
UserDetail userDetail = userDetailService.findByUserId(userId);
XUserDetail xUserDetail = fromUserDetail(userDetail);
return returnSuccessValue(xUserDetail);
}
private XUserDetail fromUserDetail(UserDetail userDetail) {
return userDetail == null ? null : userDetail.toXUserDetail();
}
private XUserDetail fromUserDetailVO(UserDetailVO userDetail) {
return userDetail == null ? null : userDetail.toXUserDetail();
}
private XUser fromUser(User user) {
return user == null ? null : user.toXUser();
}
@Override
public UserSysResult<XUser> findUserByUserId(Long id) {
if (id == null || id < 1) {
return returnErrorValue("参数必须是正整数");
}
User user = userService.findById(id);
return returnSuccessValue(fromUser(user));
}
@Override
public UserSysResult<XUserDetail> findUserDetailByPhone(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
UserDetail userDetail = userDetailService.findByPhoneNo(phoneNo);
return returnSuccessValue(fromUserDetail(userDetail));
}
@Override
public UserSysResult<XUserDetail> updateUserDetail(UserDetailUpdateBean userDetailUpdateBean) {
if (null == userDetailUpdateBean) {
return returnErrorValue("要保存的用户详情对象不能为null");
}
UserDetail userDetail = new UserDetail();
if (null != userDetailUpdateBean.getId() && userDetailUpdateBean.getId() > 0L) {
userDetail.setId(userDetailUpdateBean.getId());
}
userDetail.setUserId(userDetailUpdateBean.getUserId());
userDetail.setName(userDetailUpdateBean.getName());
userDetail.setPhoneNo(userDetailUpdateBean.getPhoneNo());
userDetail.setIdNo(userDetailUpdateBean.getIdNo());
Timestamp time = new Timestamp(System.currentTimeMillis());
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
userDetail.setIdType(IdType.ID_CARD);
try {
userDetail.setGender(idCardService.getIdCardInfo(userDetailUpdateBean.getIdNo()).getGender());
} catch (ParseException e) {
log.error("根据身份证获取性别出错,userDetailUpdateBean:{}", JSON.toJSONString(userDetailUpdateBean), e);
return returnErrorValue("根据身份证获取性别出错.");
}
userDetail.setEmail(userDetailUpdateBean.getEmail());
userDetail = userDetailService.saveUserDetail(userDetail);
if (userDetail != null) {
XUserDetail xUserDetail = convertObject(JSON.toJSONString(userDetail), new TypeReference<XUserDetail>() {
});
return returnSuccessValue(xUserDetail);
}
return returnErrorValue("保存失败");
}
@Override
public UserSysResult<XUserDetail> saveUserDetail(UserDetailSaveBean userDetailSaveBean) {
if (userDetailSaveBean == null) {
return returnErrorValue("数据不能为空");
}
Long userId = userDetailSaveBean.getUserId();
if (userId == null || userId == 0L) {
return returnErrorValue("用户id为空");
}
if (StringUtils.isBlank(userDetailSaveBean.getPhoneNo())) {
return returnErrorValue("用户手机号为空");
}
if (StringUtils.isBlank(userDetailSaveBean.getName())) {
return returnErrorValue("用户名为空");
}
if (StringUtils.isBlank(userDetailSaveBean.getIdNo())) {
return returnErrorValue("用户身份证为空");
}
Timestamp time = new Timestamp(System.currentTimeMillis());
UserDetail userDetail = userDetailService.findByUserId(userId);
if (userDetail == null) {
userDetail = new UserDetail();
userDetail.setUserId(userId);
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
} else {
userDetail.setUpdatedAt(time);
}
userDetail.setName(userDetail.getName());
userDetail.setPhoneNo(userDetail.getPhoneNo());
userDetail.setIdType(IdType.ID_CARD);
if (StringUtils.isNotBlank(userDetail.getIdNo())) {
try {
userDetail.setGender(idCardService.getIdCardInfo(userDetail.getIdNo()).getGender());
} catch (ParseException e) {
log.error("根据身份证获取性别出错,身份证号码:{}", userDetail.getIdNo(), e);
return returnErrorValue("身份证信息出错");
}
userDetail.setIdNo(userDetail.getIdNo());
}
userDetail.setEmail(userDetail.getEmail());
userDetail = userDetailService.saveUserDetail(userDetail);
if (userDetail != null) {
return returnSuccessValue(fromUserDetail(userDetail));
}
return returnErrorValue("操作失败");
}
@Override
public UserSysResult<XLoginInfo> appLoginAndFetchLoginInfo(AppLoginParam appLoginParam, String requestIp) {
if (!ValidationUtil.validatePhoneNo(appLoginParam.getPhoneNo())) {
return returnErrorValue("账户或者密码错误");
}
log.info("第三方用户登录, loginFrom:{}, requestIp:{}", appLoginParam.getRegisterFrom(), requestIp);
User user = userService.findByPhoneInDb(appLoginParam.getPhoneNo());
if (user == null) {
user = register(appLoginParam.getRegisterFrom(), appLoginParam.getPhoneNo(), appLoginParam.getIdNo(), appLoginParam.getName());
}
if (user == null) {
return returnErrorValue("账户或者密码错误");
}
Merchant merchant = merchantService.findMerchantByName(appLoginParam.getKey());
if (merchant == null) {
return returnErrorValue("无效的商户");
}
LoginProperties loginProperties = new LoginProperties();
loginProperties.setChannelId(appLoginParam.getChannelId());
loginProperties.setMerchantName(merchant.getName());
loginProperties.setCreatedFrom(appLoginParam.getRegisterFrom());
loginProperties.setAppChannel(appLoginParam.getAppChannel());
SessionStruct sessionStruct = sessionService.createSessionAndPersist(user, loginProperties);
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(user));
loginInfo.setToken(sessionStruct.getSid());
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(sessionStruct.getValues().getLoginProperties().getChannelId());
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom());
context.setAppChannel(appLoginParam.getAppChannel());
loginInfo.setLoginContext(context);
log.info("第三方用户获取信息登录成功, loginFrom:{}, phoneNo:{},appChannel:{}", appLoginParam.getRegisterFrom(), appLoginParam.getPhoneNo(), appLoginParam.getAppChannel());
XLoginInfo xLoginInfo = convertObject(JSON.toJSONString(loginInfo), new TypeReference<XLoginInfo>() {
});
return returnSuccessValue(xLoginInfo);
}
private <T> T convertObject(String json, TypeReference typeReference) {
try {
if (StringUtils.isEmpty(json)) {
return null;
}
return MAPPER.readValue(json, typeReference);
} catch (Exception ex) {
log.error("用户信息转换出错,json:{}", json, ex);
return null;
}
}
@Override
public void updateUserQQ(String qq, Long userId) {
if (StringUtils.isEmpty(qq) || userId == null || userId == 0L) {
log.error("QQ或用户id非法,不允许修改:qq{}, userid:{}", qq, userId);
return;
}
userDetailService.updateUserQQ(userId, qq);
}
@Override
public UserSysResult<List<XContact>> findContactsByUserId(Long userId) {
List<Contact> contacts = contactService.findByUserId(userId);
List<XContact> xContacts = convertObject(JSON.toJSONString(contacts), new TypeReference<List<XContact>>() {
});
return returnSuccessValue(xContacts);
}
@Override
public UserSysResult<List<XContact>> saveContacts(Long userId, List<XContact> contacts) {
if (null == userId || userId == 0L) {
return returnErrorValue("保存联系人列表失败,用户id为空");
}
if (CollectionUtils.isEmpty(contacts)) {
return returnErrorValue("保存联系人列表失败,列表为空");
}
//做一次类型转换,
String jsonContacts = JSON.toJSONString(contacts);
List<Contact> contactList = null;
try {
contactList = MAPPER.readValue(jsonContacts, new TypeReference<List<Contact>>() {
});
} catch (Exception e) {
log.error("联系人列表转换错误", e);
return returnErrorValue("联系人转换错误");
}
Timestamp now = new Timestamp(System.currentTimeMillis());
for (Contact c : contactList) {
c.setId(null);
c.setUserId(userId);
c.setRelation(c.getRelation() == null ? Relation.OTHER : c.getRelation());
c.setCreatedAt(now);
c.setUpdateAt(now);
}
List<Contact> result = contactService.save(contactList);
List<XContact> xResult = convertObject(JSON.toJSONString(result), new TypeReference<List<XContact>>() {
});
return returnSuccessValue(xResult);
}
@Override
public UserSysResult<XAddress> findAddressByUserId(Long userId) {
UserSysResult<XAddress> userSysResult = returnErrorValue(null);
Address address = addressService.findByUserId(userId);
if (null == address) {
return userSysResult;
}
XAddress xAddress = convertObject(JSON.toJSONString(address), new TypeReference<XAddress>() {
});
return returnSuccessValue(xAddress);
}
@Override
public UserSysResult<XAddress> saveAddress(Long userId, Long provinceCode, String province, Long cityCode, String city,
Long districtCode, String district, String address) {
if (null == userId || null == provinceCode || null == cityCode) {
return returnErrorValue("参数不能为空");
}
Address addressObj = addressService.findByUserId(userId);
if (addressObj == null) {
addressObj = new Address();
Timestamp now = new Timestamp(System.currentTimeMillis());
addressObj.setCreatedAt(now);
addressObj.setUpdateAt(now);
}
addressObj.setUserId(userId);
addressObj.setProvinceCode(provinceCode);
addressObj.setCityCode(cityCode);
addressObj.setCity(city);
addressObj.setDistrictCode(districtCode);
addressObj.setDistrict(district);
addressObj.setAddress(address);
addressObj.setProvince(province);
addressObj = addressService.save(addressObj);
XAddress xAddress = convertObject(JSON.toJSONString(addressObj), new TypeReference<XAddress>() {
});
return returnSuccessValue(xAddress);
}
@Override
public UserSysResult<XUserExtInfo> updateUserExtInfo(
Long userId, cn.quantgroup.motan.enums.IncomeEnum incomeEnum, cn.quantgroup.motan.enums.IncomeRangeEnum incomeRangeEnum,
cn.quantgroup.motan.enums.OccupationEnum occupationEnum, cn.quantgroup.motan.enums.EducationEnum educationEnum, Boolean hasCar,
Boolean hasSocialSecurity, Boolean hasHouse, Boolean hasCreditCard, cn.quantgroup.motan.enums.MaritalStatus maritalStatus) {
UserSysResult<XUserExtInfo> userSysResult = returnValue(null, null);
if (null == userId || 0L == userId) {
return returnErrorValue("用户id为空");
}
UserExtInfo info = userExtInfoService.findByUserId(userId);
if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
info = new UserExtInfo();
info.setUserId(userId);
info.setCreatedAt(now);
info.setUpdateAt(now);
}
if (incomeEnum != null) {
info.setIncomeEnum(IncomeEnum.valueOf(incomeEnum.name()));
}
if (incomeRangeEnum != null) {
info.setIncomeRangeEnum(IncomeRangeEnum.valueOf(incomeRangeEnum.name()));
}
if (occupationEnum != null) {
info.setOccupationEnum(OccupationEnum.valueOf(occupationEnum.name()));
}
if (educationEnum != null) {
info.setEducationEnum(EducationEnum.valueOf(educationEnum.name()));
}
if (hasCar != null) {
info.setHasCar(hasCar);
}
if (hasCreditCard != null) {
info.setHasCreditCard(hasCreditCard);
}
if (hasHouse != null) {
info.setHasHouse(hasHouse);
}
if (maritalStatus != null) {
info.setMarryStatus(MaritalStatus.valueOf(maritalStatus.name()));
}
info = userExtInfoService.save(info);
XUserExtInfo userExtInfo = convertObject(JSON.toJSONString(info), new TypeReference<XUserExtInfo>() {
});
return returnSuccessValue(userExtInfo);
}
@Override
public UserSysResult<String> queryOpenIdByXyqbUserId(Long userId) {
if (userId == null || userId < 1) {
return returnErrorValue("用户id不能为空");
}
WechatUserInfo wechatUserInfo = wechatService.queryOpenIdByUserId(userId);
if (wechatUserInfo == null) {
return returnErrorValue("wechat信息为空");
}
return returnValue(wechatUserInfo.getOpenId(), "success");
}
@Override
public UserSysResult<Boolean> disableUser(Long userId) {
return null;
}
@Override
public UserSysResult<String> queryOpenIdByPhoneNo(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
WechatUserInfo wechatUserInfo = wechatService.findWechatUserInfoByPhoneNo(phoneNo);
String openId = null == wechatUserInfo ? null : wechatUserInfo.getOpenId();
return returnSuccessValue(openId);
}
@Override
public UserSysResult<UserRegisterTrace> findRegisterTraceByPhoneNo(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return returnErrorValue("手机号格式不正确");
}
return null;
}
@Override
public UserSysResult<XUserSpouse> findUserSpouseByUserId(Long userId) {
if (userId == null || userId == 0) {
return returnErrorValue("用户不能为空");
}
UserSpouse userSpouse = userSpouseService.findByUserId(userId);
if (userSpouse == null) {
userSpouse = new UserSpouse(userId);
userSpouse.setStatus(MaritalStatus.UNKNOWN);
}
return returnSuccessValue(fromUserSpouse(userSpouse));
}
private XUserSpouse fromUserSpouse(UserSpouse userSpouse) {
if (userSpouse == null) {
return null;
}
XUserSpouse xUserSpouse = new XUserSpouse();
xUserSpouse.setUserId(userSpouse.getUserId());
xUserSpouse.setSpousePhone(userSpouse.getSpousePhone());
xUserSpouse.setSpouseName(userSpouse.getSpouseName());
xUserSpouse.setCreatedAt(userSpouse.getCreatedAt());
xUserSpouse.setUpdateAt(userSpouse.getUpdateAt());
xUserSpouse.setStatus(cn.quantgroup.motan.enums.MaritalStatus.valueOf(userSpouse.getStatus().name()));
return xUserSpouse;
}
@Override
public UserSysResult<XUserExtInfo> findUserExtInfoByUserId(Long userId) {
return null;
}
@Override
public UserSysResult<List<XUserDetail>> queryUserDetailBySpecification(String name, String phoneNo, String idNo) {
List<UserDetailVO> userDetails = userDetailService.searchUserDetailList(name, phoneNo, idNo);
if (CollectionUtils.isEmpty(userDetails)) {
return null;
}
List<XUserDetail> xUserDetails = userDetails.stream().map(user -> fromUserDetailVO(user)).collect(Collectors.toList());
return returnSuccessValue(xUserDetails);
}
@Override
public UserSysResult<String> loginWithUuid(String uuid) {
return null;
}
@Override
public UserSysResult<Boolean> userImportCheck(String phoneNo, String registerFrom) {
return null;
}
@Override
public UserSysResult<XUserSpouse> saveUserSpouse(XUserSpouse xUserSpouse) {
if (xUserSpouse.getUserId() == null || xUserSpouse.getUserId() == 0) {
return returnErrorValue("用户不能为空");
}
cn.quantgroup.motan.enums.MaritalStatus status = xUserSpouse.getStatus();
String spousePhone = xUserSpouse.getSpousePhone();
String spouseName = xUserSpouse.getSpouseName();
if (xUserSpouse.getStatus() == cn.quantgroup.motan.enums.MaritalStatus.MARRIED) {
if (!ValidationUtil.validatePhoneNo(spousePhone)) {
return returnErrorValue("手机号格式错误");
}
if (StringUtils.isBlank(spouseName)) {
return returnErrorValue("配偶姓名不能为空");
}
}
UserSpouse userSpouse = userSpouseService.findByUserId(xUserSpouse.getUserId());
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
if (userSpouse == null) {
userSpouse = new UserSpouse(xUserSpouse.getUserId());
userSpouse.setCreatedAt(timestamp);
}
userSpouse.setSpouseName(status == cn.quantgroup.motan.enums.MaritalStatus.MARRIED ? spouseName : "");
userSpouse.setSpousePhone(status == cn.quantgroup.motan.enums.MaritalStatus.MARRIED ? spousePhone : "");
userSpouse.setStatus(MaritalStatus.valueOf(status.name()));
userSpouse.setUpdateAt(timestamp);
userSpouse = userSpouseService.save(userSpouse);
return returnSuccessValue(fromUserSpouse(userSpouse));
}
@Override
public UserSysResult<AppLoginResultBean> appLogin(AppLoginParam param) {
return null;
}
/**
* 封装返回结果.
*
* @param t
* @param message
* @param <T>
* @return
*/
private <T> UserSysResult<T> returnValue(T t, String message) {
UserSysResult<T> userSysResult = new UserSysResult();
userSysResult.setMsg(message);
/**
* 无返回结果时,返回的code和BusinessCode均是0001
*/
if (null == t) {
userSysResult.setBusinessCode("0001");
userSysResult.setCode("0001");
} else {
userSysResult.setBusinessCode("0000");
userSysResult.setCode("0000");
}
userSysResult.setData(t);
return userSysResult;
}
private <T> UserSysResult<T> returnErrorValue(String message) {
return returnValue(null, message);
}
private <T> UserSysResult<T> returnSuccessValue(T t) {
return returnValue(t, "");
}
/**
* 注册新用户
*
* @return
*/
private User register(Long registerFrom, String phoneNo, String idNo, String name) {
String randomCode = String.valueOf(random.nextInt(899999) + 100000);
String uuid = lkbUserService.registerApp(phoneNo, randomCode);
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
log.info("第三方登录用户,保存 User");
User user = new User();
user.setRegisteredFrom(registerFrom);
user.setUuid(uuid);
user.setEnable(true);
user.setPhoneNo(phoneNo);
user.setPassword(PasswordUtil.MD5(randomCode + Constants.PASSWORD_SALT));
user.setUpdatedAt(currentTime);
user.setCreatedAt(currentTime);
userRepository.saveAndFlush(user);
if (registerFrom != 645L && registerFrom !=900L) {
smsService.sendAfterRegister(phoneNo);
log.info("第三方登录用户注册成功, registerFrom:{}, phoneNo:{},idNo:{},name:{} 并且已发送短信通知", registerFrom, phoneNo, idNo, name);
}else if(registerFrom ==900L){
smsService.sendAfterRegister(phoneNo,"123");
log.info("第三方(聚美)登录用户注册成功, registerFrom:{}, phoneNo:{},idNo:{},name:{} 并且已发送短信通知", registerFrom, phoneNo, idNo, name);
}
if (StringUtils.isNotEmpty(idNo) && StringUtils.isNotEmpty(name)) {
IdCardInfo cardInfo;
try {
cardInfo = idCardService.getIdCardInfoWithExceptions(idNo);
UserDetail userDetail = new UserDetail();
userDetail.setIdNo(cardInfo.getIdNo());
userDetail.setPhoneNo(phoneNo);
userDetail.setName(name);
userDetail.setIdType(IdType.ID_CARD);
userDetail.setCreatedAt(currentTime);
userDetail.setUpdatedAt(currentTime);
userDetail.setUserId(user.getId());
userDetail.setGender(cardInfo.getGender());
userDetailService.saveUserDetail(userDetail);
lkbUserService.userUpdate(user.getUuid(), name, idNo);
} catch (Exception e) {
log.error("保存 UserDetail 出现异常", e);
}
}
return user;
}
}
...@@ -42,7 +42,7 @@ import static cn.quantgroup.xyqb.constant.UserConstant.USER_ERROR_OR_PASSWORD_ER ...@@ -42,7 +42,7 @@ import static cn.quantgroup.xyqb.constant.UserConstant.USER_ERROR_OR_PASSWORD_ER
public class AppController implements IBaseController { public class AppController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class); private static final Logger LOGGER = LoggerFactory.getLogger(AppController.class);
private final static Random random = new Random();
@Autowired @Autowired
private ISessionService sessionService; private ISessionService sessionService;
@Autowired @Autowired
...@@ -53,7 +53,6 @@ public class AppController implements IBaseController { ...@@ -53,7 +53,6 @@ public class AppController implements IBaseController {
private IUserRepository userRepository; private IUserRepository userRepository;
@Autowired @Autowired
private ISmsService smsService; private ISmsService smsService;
@Autowired @Autowired
private IUserDetailService userDetailService; private IUserDetailService userDetailService;
@Autowired @Autowired
...@@ -61,8 +60,6 @@ public class AppController implements IBaseController { ...@@ -61,8 +60,6 @@ public class AppController implements IBaseController {
@Autowired @Autowired
private IMerchantService merchantService; private IMerchantService merchantService;
private final static Random random = new Random();
/** /**
* 第三方用户登录 * 第三方用户登录
*/ */
...@@ -186,14 +183,16 @@ public class AppController implements IBaseController { ...@@ -186,14 +183,16 @@ public class AppController implements IBaseController {
user.setCreatedAt(currentTime); user.setCreatedAt(currentTime);
userRepository.saveAndFlush(user); userRepository.saveAndFlush(user);
if (registerFrom != 645L) { if (registerFrom != 645L && registerFrom != 900L) {
smsService.sendAfterRegister(phoneNo); smsService.sendAfterRegister(phoneNo);
LOGGER.info("第三方登录用户注册成功, registerFrom:{}, phoneNo:{}, 并且已发送短信通知", registerFrom, phoneNo); LOGGER.info("第三方登录用户注册成功, registerFrom:{}, phoneNo:{}, 并且已发送短信通知", registerFrom, phoneNo);
}else if(registerFrom == 900L){
smsService.sendAfterRegister(phoneNo,"123");
LOGGER.info("第三方(聚美)登录用户注册成功, registerFrom:{}, phoneNo:{},idNo:{},name:{} 并且已发送短信通知", registerFrom, phoneNo, idNo, name);
} }
if (StringUtils.isNotEmpty(idNo) && StringUtils.isNotEmpty(name)) { if (StringUtils.isNotEmpty(idNo) && StringUtils.isNotEmpty(name)) {
LOGGER.info("第三方登录用户,保存 UserDetail"); LOGGER.info("第三方登录用户,保存 UserDetail");
IdCardInfo cardInfo; IdCardInfo cardInfo;
try { try {
cardInfo = idCardService.getIdCardInfoWithExceptions(idNo); cardInfo = idCardService.getIdCardInfoWithExceptions(idNo);
......
package cn.quantgroup.xyqb.controller.external.user; package cn.quantgroup.xyqb.controller.external.user;
import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.*; import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.entity.enumerate.*; import cn.quantgroup.xyqb.entity.enumerate.*;
import cn.quantgroup.xyqb.model.*; import cn.quantgroup.xyqb.model.*;
...@@ -15,6 +16,7 @@ import org.apache.commons.lang3.StringUtils; ...@@ -15,6 +16,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils; 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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -23,13 +25,14 @@ import java.sql.Timestamp; ...@@ -23,13 +25,14 @@ import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Created by Miraculous on 2016/12/19. * Created by Miraculous on 2016/12/19.
*/ */
@RestController @RestController
@RequestMapping("/innerapi") @RequestMapping("/innerapi")
public class InnerController { public class InnerController implements IBaseController {
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(InnerController.class); private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(InnerController.class);
...@@ -72,6 +75,22 @@ public class InnerController { ...@@ -72,6 +75,22 @@ public class InnerController {
return JsonResult.buildSuccessResult("", userRet); return JsonResult.buildSuccessResult("", userRet);
} }
@RequestMapping("/user/getPhoneByUserIds")
public JsonResult findByIds(@RequestParam(value = "userIds") String userIdsString) {
LOGGER.info("批量查询用户的手机号列表, userIdsString:" + userIdsString);
if (StringUtils.isEmpty(userIdsString)) {
return JsonResult.buildErrorStateResult(null, null);
}
List<Long> userIds = JSONObject.parseObject(userIdsString, new TypeReference<List<Long>>() {
});
if(!CollectionUtils.isEmpty(userIds) && userIds.size()<=500) {
Map<Long, String> userIdAndPhoneMap = userService.findPhoneByIdsInDb(userIds);
return JsonResult.buildSuccessResult("", userIdAndPhoneMap);
}else {
return JsonResult.buildErrorStateResult("批量查询每次最多进行500条用户信息的查询",null);
}
}
@RequestMapping("/user/save") @RequestMapping("/user/save")
public JsonResult saveUser( public JsonResult saveUser(
String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt, String phoneNo, Long registeredFrom, Long createdAt, Long updatedAt,
...@@ -240,6 +259,12 @@ public class InnerController { ...@@ -240,6 +259,12 @@ public class InnerController {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp now = new Timestamp(System.currentTimeMillis());
convertContactList(userId, contacts, now);
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
}
private void convertContactList(Long userId, List<Contact> contacts, Timestamp now) {
for (Contact c : contacts) { for (Contact c : contacts) {
c.setId(null); c.setId(null);
c.setUserId(userId); c.setUserId(userId);
...@@ -247,8 +272,6 @@ public class InnerController { ...@@ -247,8 +272,6 @@ public class InnerController {
c.setCreatedAt(now); c.setCreatedAt(now);
c.setUpdateAt(now); c.setUpdateAt(now);
} }
List<Contact> result = contactService.save(contacts);
return JsonResult.buildSuccessResult(null, ContactRet.contacts2ContactRets(result));
} }
@RequestMapping("/address/search/user_id") @RequestMapping("/address/search/user_id")
...@@ -300,13 +323,13 @@ public class InnerController { ...@@ -300,13 +323,13 @@ public class InnerController {
return JsonResult.buildErrorStateResult("用户ID不能为空", null); return JsonResult.buildErrorStateResult("用户ID不能为空", null);
} }
UserExtInfo info = userExtInfoService.findByUserId(userId); UserExtInfo info = userExtInfoService.findByUserId(userId);
Timestamp now = new Timestamp(System.currentTimeMillis());
if (info == null) { if (info == null) {
Timestamp now = new Timestamp(System.currentTimeMillis());
info = new UserExtInfo(); info = new UserExtInfo();
info.setUserId(userId); info.setUserId(userId);
info.setCreatedAt(now); info.setCreatedAt(now);
info.setUpdateAt(now);
} }
info.setUpdateAt(now);
if (incomeEnum != null) { if (incomeEnum != null) {
info.setIncomeEnum(incomeEnum); info.setIncomeEnum(incomeEnum);
} }
...@@ -337,6 +360,8 @@ public class InnerController { ...@@ -337,6 +360,8 @@ public class InnerController {
@RequestMapping("/user_detail/search_list") @RequestMapping("/user_detail/search_list")
public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) { public JsonResult searchUserDetailList(String name, String phoneNo, String idNo) {
LOGGER.info("searchUserDetailList ,param.name:{},phone:{},idNo:{},ip:{}",name,phoneNo,idNo,getIp());
if (StringUtils.isBlank(name) && StringUtils.isBlank(phoneNo) && StringUtils.isBlank(idNo)) { if (StringUtils.isBlank(name) && StringUtils.isBlank(phoneNo) && StringUtils.isBlank(idNo)) {
return JsonResult.buildErrorStateResult("至少必须满足一个条件不为空", null); return JsonResult.buildErrorStateResult("至少必须满足一个条件不为空", null);
} }
...@@ -353,7 +378,7 @@ public class InnerController { ...@@ -353,7 +378,7 @@ public class InnerController {
if (userExtInfo == null) { if (userExtInfo == null) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
return JsonResult.buildSuccessResult("success", UserExtInfoRet.getUserExtInfoRet(userExtInfo)); return JsonResult.buildSuccessResult(null, UserExtInfoRet.getUserExtInfoRet(userExtInfo));
} }
@RequestMapping("/user/query/openId") @RequestMapping("/user/query/openId")
...@@ -439,4 +464,29 @@ public class InnerController { ...@@ -439,4 +464,29 @@ public class InnerController {
return JsonResult.buildSuccessResult(null, UserSpouseRet.getUserSpouseRet(userSpouse)); return JsonResult.buildSuccessResult(null, UserSpouseRet.getUserSpouseRet(userSpouse));
} }
/**
* 重置密码接口,供内部人员使用(例如绝影)
* @param key
* @param phone
* @return
*/
@RequestMapping("/user/password/reset/{key}/{phone}")
public JsonResult resetPassword(@PathVariable("key")String key,@PathVariable("phone")String phone) {
LOGGER.info("密码重置请求,phone:[{}]",phone);
if(StringUtils.isBlank(key)){
return JsonResult.buildErrorStateResult("用户密码重置失败.", null);
}
if(!"ecf75c1f-2ccb-4661-8e4b-2874c0f45a2b".equalsIgnoreCase(key)){
LOGGER.error("密码重置失败,key错误!@!,phone:[{}]", phone);
return JsonResult.buildErrorStateResult("用户密码重置失败.", null);
}
try {
userService.resetPassword(phone, "123456"); //默认重置的密码是123456
return JsonResult.buildSuccessResult("用户密码已重置.", "null");
}catch (Exception e){
LOGGER.error("密码重置失败,phone[{}],err:[{}]",phone, e);
}
return JsonResult.buildErrorStateResult("用户密码重置失败.", null);
}
} }
\ No newline at end of file
...@@ -54,235 +54,238 @@ import static cn.quantgroup.xyqb.Constants.Jr58; ...@@ -54,235 +54,238 @@ import static cn.quantgroup.xyqb.Constants.Jr58;
@RequestMapping("/jr58") @RequestMapping("/jr58")
public class Jr58Controller implements ApplicationEventPublisherAware { public class Jr58Controller implements ApplicationEventPublisherAware {
private static final Logger LOGGER = LoggerFactory.getLogger(Jr58Controller.class); private static final Logger LOGGER = LoggerFactory.getLogger(Jr58Controller.class);
private static final String ENTRY_POINT_URL_TEMPLATE = "%s/app-landing?registerFrom=175&channelId=1&token=%s"; private static final String ENTRY_POINT_URL_TEMPLATE = "%s/app-landing?registerFrom=175&channelId=1&token=%s";
private static List<String> authorizationTypeList= new ArrayList<>(); private static List<String> authorizationTypeList = new ArrayList<>();
static {
//授权类型 static {
authorizationTypeList.add("1"); //授权类型
authorizationTypeList.add("2"); authorizationTypeList.add("1");
} authorizationTypeList.add("2");
@Value("${xyqb.url}") }
private String xyqbUrl;
@Value("${xyqb.url}")
@Autowired private String xyqbUrl;
private IAuthApiService authApiService;
@Autowired
// @Value("${xyqb.entrypoint.jr58}") private IAuthApiService authApiService;
// private String xyqbEntryPointForJr58;
// @Value("${xyqb.entrypoint.jr58}")
@Value("${lkb.url}") // private String xyqbEntryPointForJr58;
private String lkbUrl;
@Value("${lkb.url}")
@Value("${lkb.entrypoint.jr58}") private String lkbUrl;
private String lkbEntryPointForJr58;
@Value("${lkb.entrypoint.jr58}")
@Autowired private String lkbEntryPointForJr58;
private IUserService xyqbUserService;
@Autowired
private IIdCardService idCardService;
@Autowired
private Jr58Service jr58Service;
@Autowired
private IUuidPhoneMappingService uuidPhoneMappingService;
private ApplicationEventPublisher applicationEventPublisher;
@RequestMapping("/register")
Map<String, Object> register(Jr58RegisterParam param) {
LOGGER.info("保存58金融用户信息, param:{}", param);
Map<String, Object> result = new HashMap<>();
/********************* 校验参数 ************************/
if (!ValidationUtil.validatePhoneNo(param.getPhone())) {
result.put("errorcode", Jr58.ERROR_PHONE_NUMBER);
return result;
}
if(StringUtils.isBlank(param.getAccount())){
LOGGER.error("58金融授权账号-account={}",param.getAccount());
result.put("errorcode", Jr58.ERROR_ACCOUNT);
return result;
}
if(StringUtils.isBlank(param.getAuthorizationType()) || !authorizationTypeList.contains(param.getAuthorizationType())){
LOGGER.error("58金融授权类型-authorization={} ",param.getAuthorizationType());
result.put("errorcode", Jr58.ERROR_AUTH_TYPE);
return result;
}
try {
param.setIdCardInfo(idCardService.getIdCardInfoWithExceptions(param.getIdcard()));
} catch (IdCardException | ParseException e) {
result.put("errorcode", Jr58.ERROR_ID_CARD);
return result;
}
try {
if(StringUtils.isNotBlank(param.getWbUserName())){
param.setWbUserName(URLDecoder.decode(param.getWbUserName(), "UTF-8"));
}
if(StringUtils.isNotBlank(param.getEmail())){
param.setEmail(URLDecoder.decode(param.getEmail(), "UTF-8"));
}
if(StringUtils.isNotBlank(param.getName())){
param.setName(URLDecoder.decode(param.getName(), "UTF-8"));
}
if(StringUtils.isNotBlank(param.getInfo())){
param.setInfo(URLDecoder.decode(param.getInfo(), "UTF-8"));
}
} catch (Exception e) {
LOGGER.error("URLDecoder error", e);
}
String uuid = jr58Service.register(param);
applicationEventPublisher.publishEvent(new UserinfoChangedEvent(this, uuid, Constants.Channel.JR58));
User user = xyqbUserService.findByUuidWithCache(uuid);
LOGGER.info("58金融运营商授权状态更新开始");
try {
jr58Service.getRidOfFillingProfile(user, param.getAccount());
} catch (Exception e) {
LOGGER.error("58金融运营商授权状态更新失败,异常信息如下所示:error={}", e.getMessage(), e);
}
jr58Service.pushAuthorizationStatus(uuid,param.getAccount(),param.getAuthorizationType());
LOGGER.info("58金融运营商授权状态更新结束");
result.put("customerid", uuid);
result.put("success", true);
result.put("result", 1);
result.put("errorcode", 0);
result.put("monitorPhone", param.getMonitorPhone());//58金融用于监控接口是否正常,无其他意义
LOGGER.info("返还给58用户, result:{}", result);
return result;
}
@RequestMapping("/index") @Autowired
public ResponseEntity index(WebRequest request) throws MissingServletRequestParameterException, UnsupportedEncodingException { private IUserService xyqbUserService;
String userId = request.getParameter("userId");
String from = Strings.nullToEmpty(request.getParameter("from"));
LOGGER.info("收到来自58金融入口的请求, userId:{}, from:{}", userId, from); @Autowired
private IIdCardService idCardService;
if (StringUtils.isEmpty(userId)) { @Autowired
return new ResponseEntity(HttpStatus.BAD_REQUEST); private Jr58Service jr58Service;
}
String uuid = userId.toLowerCase(); @Autowired
Tuple<String, User> entryUrlAndUser = getEntryPointUrl(uuid, from); private IUuidPhoneMappingService uuidPhoneMappingService;
String entryPointUrl = entryUrlAndUser.getKey();
LOGGER.info("将来自58金融入口的用户导流至 {}", entryPointUrl); private ApplicationEventPublisher applicationEventPublisher;
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Location", entryPointUrl); @RequestMapping("/register")
return new ResponseEntity(responseHeaders, HttpStatus.FOUND); Map<String, Object> register(Jr58RegisterParam param) {
LOGGER.info("保存58金融用户信息, param:{}", param);
Map<String, Object> result = new HashMap<>();
/********************* 校验参数 ************************/
if (!ValidationUtil.validatePhoneNo(param.getPhone())) {
result.put("errorcode", Jr58.ERROR_PHONE_NUMBER);
return result;
}
if (StringUtils.isBlank(param.getAccount())) {
LOGGER.error("58金融授权账号-account={}", param.getAccount());
result.put("errorcode", Jr58.ERROR_ACCOUNT);
return result;
}
if (StringUtils.isBlank(param.getAuthorizationType()) || !authorizationTypeList.contains(param.getAuthorizationType())) {
LOGGER.error("58金融授权类型-authorization={} ", param.getAuthorizationType());
result.put("errorcode", Jr58.ERROR_AUTH_TYPE);
return result;
} }
private Tuple<String, User> getEntryPointUrl(String uuid, String from) { try {
// 找到uuid,但是用户不在user表中,说明是老系统用户 param.setIdCardInfo(idCardService.getIdCardInfoWithExceptions(param.getIdcard()));
User userInXyqb = xyqbUserService.findByUuidWithCache(uuid); } catch (IdCardException | ParseException e) {
result.put("errorcode", Jr58.ERROR_ID_CARD);
if (userInXyqb != null) { return result;
String token = authApiService.login(userInXyqb.getPhoneNo(), Constants.Channel.JR58, "xyqb"); }
return new Tuple<>(String.format(ENTRY_POINT_URL_TEMPLATE, xyqbUrl, token), userInXyqb); try {
} if (StringUtils.isNotBlank(param.getWbUserName())) {
param.setWbUserName(URLDecoder.decode(param.getWbUserName(), "UTF-8"));
UuidPhoneMapping phoneMapping = uuidPhoneMappingService.findByUuid(uuid); }
String phoneNo = null; if (StringUtils.isNotBlank(param.getEmail())) {
if(phoneMapping != null){ param.setEmail(URLDecoder.decode(param.getEmail(), "UTF-8"));
phoneNo = phoneMapping.getPhoneNo(); }
}else{ if (StringUtils.isNotBlank(param.getName())) {
LOGGER.error("58金融运营商授权数据导入接口 - uuid对应的UuidPhoneMapping为空"); param.setName(URLDecoder.decode(param.getName(), "UTF-8"));
} }
// 手机号在新系统中存在,说明之前已经注册过 if (StringUtils.isNotBlank(param.getInfo())) {
userInXyqb = xyqbUserService.findByPhoneWithCache(phoneNo); param.setInfo(URLDecoder.decode(param.getInfo(), "UTF-8"));
if (userInXyqb != null) { }
String token = authApiService.login(phoneNo, Constants.Channel.JR58, "xyqb");
return new Tuple<>(String.format(ENTRY_POINT_URL_TEMPLATE, xyqbUrl, token), userInXyqb); } catch (Exception e) {
} else { LOGGER.error("URLDecoder error", e);
// 注册过
userInXyqb = xyqbUserService.registerAndReturn(phoneNo, "abc1234$", Constants.Channel.JR58);
String token = authApiService.login(phoneNo, Constants.Channel.JR58, "xyqb");
return new Tuple<>(String.format(ENTRY_POINT_URL_TEMPLATE, xyqbUrl, token), userInXyqb);
}
} }
String uuid = jr58Service.register(param);
@Override applicationEventPublisher.publishEvent(new UserinfoChangedEvent(this, uuid, Constants.Channel.JR58));
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { User user = xyqbUserService.findByUuidWithCache(uuid);
this.applicationEventPublisher = applicationEventPublisher; LOGGER.info("58金融运营商授权状态更新开始");
try {
jr58Service.getRidOfFillingProfile(user, param.getAccount());
} catch (Exception e) {
LOGGER.error("58金融运营商授权状态更新失败,异常信息如下所示:error={}", e.getMessage(), e);
}
jr58Service.pushAuthorizationStatus(uuid, param.getAccount(), param.getAuthorizationType());
LOGGER.info("58金融运营商授权状态更新结束");
result.put("customerid", uuid);
result.put("success", true);
result.put("result", 1);
result.put("errorcode", 0);
result.put("monitorPhone", param.getMonitorPhone());//58金融用于监控接口是否正常,无其他意义
LOGGER.info("返还给58用户, result:{}", result);
return result;
}
@RequestMapping("/index")
public ResponseEntity index(WebRequest request) throws MissingServletRequestParameterException, UnsupportedEncodingException {
String userId = request.getParameter("userId");
String from = Strings.nullToEmpty(request.getParameter("from"));
LOGGER.info("收到来自58金融入口的请求, userId:{}, from:{}", userId, from);
if (StringUtils.isEmpty(userId)) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
} }
/** String uuid = userId.toLowerCase();
* 58金融运营商授权数据导入接口 Tuple<String, User> entryUrlAndUser = getEntryPointUrl(uuid, from);
* @param authorizationData 入参 String entryPointUrl = entryUrlAndUser.getKey();
* @return JsonResult LOGGER.info("将来自58金融入口的用户导流至 {}", entryPointUrl);
*/ HttpHeaders responseHeaders = new HttpHeaders();
@RequestMapping(value = "/import_authorization_data", method= RequestMethod.POST) responseHeaders.set("Location", entryPointUrl);
public JsonResult importAuthorizationData(@RequestBody Jr58Authorization authorizationData) { return new ResponseEntity(responseHeaders, HttpStatus.FOUND);
String authorizationDataStr = null; }
LOGGER.info("推送的运营商数据userId={}",authorizationData.getUserId());
LOGGER.info("推送的运营商数据sourceFrom={}",authorizationData.getSourceFrom()); private Tuple<String, User> getEntryPointUrl(String uuid, String from) {
if(StringUtils.isEmpty(authorizationData.getAuthorizationData())){ // 找到uuid,但是用户不在user表中,说明是老系统用户
LOGGER.error("58金融运营商授权数据导入接口 - authorizationData不能为空"); User userInXyqb = xyqbUserService.findByUuidWithCache(uuid);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - authorizationData不能为空",null);
} if (userInXyqb != null) {
//try { String token = authApiService.login(userInXyqb.getPhoneNo(), Constants.Channel.JR58, "xyqb");
authorizationDataStr = JR58GzipUtil.bytesTogzip(Base64.decodeBase64(authorizationData.getAuthorizationData()), "utf-8"); return new Tuple<>(String.format(ENTRY_POINT_URL_TEMPLATE, xyqbUrl, token), userInXyqb);
//authorizationDataStr = JR58GzipUtil.bytesTogzip(new BASE64Decoder().decodeBuffer(authorizationData.getAuthorizationData()), "utf-8"); }
LOGGER.info("推送的运营商数据authorizationDataStr={}",authorizationDataStr);
UuidPhoneMapping phoneMapping = uuidPhoneMappingService.findByUuid(uuid);
String phoneNo = null;
if (phoneMapping != null) {
phoneNo = phoneMapping.getPhoneNo();
} else {
LOGGER.error("58金融运营商授权数据导入接口 - uuid对应的UuidPhoneMapping为空");
}
// 手机号在新系统中存在,说明之前已经注册过
userInXyqb = xyqbUserService.findByPhoneWithCache(phoneNo);
if (userInXyqb != null) {
String token = authApiService.login(phoneNo, Constants.Channel.JR58, "xyqb");
return new Tuple<>(String.format(ENTRY_POINT_URL_TEMPLATE, xyqbUrl, token), userInXyqb);
} else {
// 注册过
userInXyqb = xyqbUserService.registerAndReturn(phoneNo, "abc1234$", Constants.Channel.JR58);
String token = authApiService.login(phoneNo, Constants.Channel.JR58, "xyqb");
return new Tuple<>(String.format(ENTRY_POINT_URL_TEMPLATE, xyqbUrl, token), userInXyqb);
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* 58金融运营商授权数据导入接口
*
* @param authorizationData 入参
* @return JsonResult
*/
@RequestMapping(value = "/import_authorization_data", method = RequestMethod.POST)
public JsonResult importAuthorizationData(@RequestBody Jr58Authorization authorizationData) {
String authorizationDataStr = null;
LOGGER.info("推送的运营商数据userId={}", authorizationData.getUserId());
LOGGER.info("推送的运营商数据sourceFrom={}", authorizationData.getSourceFrom());
if (StringUtils.isEmpty(authorizationData.getAuthorizationData())) {
LOGGER.error("58金融运营商授权数据导入接口 - authorizationData不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - authorizationData不能为空", null);
}
//try {
authorizationDataStr = JR58GzipUtil.bytesTogzip(Base64.decodeBase64(authorizationData.getAuthorizationData()), "utf-8");
//authorizationDataStr = JR58GzipUtil.bytesTogzip(new BASE64Decoder().decodeBuffer(authorizationData.getAuthorizationData()), "utf-8");
LOGGER.info("推送的运营商数据authorizationDataStr={}", authorizationDataStr);
/*} catch (IOException e) { /*} catch (IOException e) {
LOGGER.error("58金融生成借款申请失败,base64转换失败"); LOGGER.error("58金融生成借款申请失败,base64转换失败");
return JsonResult.buildErrorStateResult("58金融导入运营商授权数据失败",null); return JsonResult.buildErrorStateResult("58金融导入运营商授权数据失败",null);
}*/ }*/
//authorizationData.setOperator_data(new Gson().fromJson(authorizationDataStr, Jr58Authorization.OperatorData.class)); //authorizationData.setOperator_data(new Gson().fromJson(authorizationDataStr, Jr58Authorization.OperatorData.class));
authorizationData.setOperator_data(JSONObject.parseObject(authorizationDataStr, Jr58Authorization.OperatorData.class)); authorizationData.setOperator_data(JSONObject.parseObject(authorizationDataStr, Jr58Authorization.OperatorData.class));
if(authorizationData == null){ if (authorizationData == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整"); LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入 - 入参不完整",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入 - 入参不完整", null);
} }
String userId = authorizationData.getUserId(); String userId = authorizationData.getUserId();
String phoneNo= null; String phoneNo = null;
if(authorizationData.getOperator_data() != null && authorizationData.getOperator_data().getOriginalData() != null){ if (authorizationData.getOperator_data() != null && authorizationData.getOperator_data().getOriginalData() != null) {
phoneNo= authorizationData.getOperator_data().getOriginalData().getPhone(); phoneNo = authorizationData.getOperator_data().getOriginalData().getPhone();
} }
if(phoneNo == null){ if (phoneNo == null) {
LOGGER.info("推送的运营商数据authorizationData={}",authorizationData.getAuthorizationData()); LOGGER.info("推送的运营商数据authorizationData={}", authorizationData.getAuthorizationData());
LOGGER.error("58金融运营商授权数据导入接口 - phoneNo不能为空"); LOGGER.error("58金融运营商授权数据导入接口 - phoneNo不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整", null);
} }
LOGGER.info("收到来自58金融运营商授权导入请求, userId:{}", userId); LOGGER.info("收到来自58金融运营商授权导入请求, userId:{}", userId);
if (StringUtils.isEmpty(authorizationData.getSourceFrom())) { if (StringUtils.isEmpty(authorizationData.getSourceFrom())) {
LOGGER.error("58金融运营商授权数据导入接口 - sourceFrom不能为空"); LOGGER.error("58金融运营商授权数据导入接口 - sourceFrom不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - sourceFrom不能为空",null); return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - sourceFrom不能为空", null);
}
if (StringUtils.isEmpty(userId)) {
LOGGER.error("58金融运营商授权数据导入接口 - userId不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - userId不能为空",null);
}
if("1".equals(authorizationData.getSourceFrom()) && (null== authorizationData.getOperator_data()
|| null == authorizationData.getOperator_data().getOriginalData())){
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整, sourceFrom : {}, authorizationDataStr={}", authorizationData.getSourceFrom(),authorizationDataStr);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整",null);
}
String uuid = userId.toLowerCase();
Tuple<String, User> entryUrlAndUser = getEntryPointUrl(uuid, String.valueOf(Constants.Channel.JR58));
User user = entryUrlAndUser.getValue();
// 用户不存在
if (user == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 用户不存在,userId=[{}]", userId);
return JsonResult.buildErrorStateResult("用户不存在,userId="+userId,null);
}
// 推送授权to风控
jr58Service.pushAuthorizationData(authorizationData);
LOGGER.info("58金融运营商数据导入结束");
return JsonResult.buildSuccessResult("success",null);
} }
if (StringUtils.isEmpty(userId)) {
LOGGER.error("58金融运营商授权数据导入接口 - userId不能为空");
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - userId不能为空", null);
}
if ("1".equals(authorizationData.getSourceFrom()) && (null == authorizationData.getOperator_data()
|| null == authorizationData.getOperator_data().getOriginalData())) {
LOGGER.error("58金融运营商授权数据导入接口 - 入参不完整, sourceFrom : {}, authorizationDataStr={}", authorizationData.getSourceFrom(), authorizationDataStr);
return JsonResult.buildErrorStateResult("58金融运营商授权数据导入接口 - 入参不完整", null);
}
String uuid = userId.toLowerCase();
Tuple<String, User> entryUrlAndUser = getEntryPointUrl(uuid, String.valueOf(Constants.Channel.JR58));
User user = entryUrlAndUser.getValue();
// 用户不存在
if (user == null) {
LOGGER.error("58金融运营商授权数据导入接口 - 用户不存在,userId=[{}]", userId);
return JsonResult.buildErrorStateResult("用户不存在,userId=" + userId, null);
}
// 推送授权to风控
jr58Service.pushAuthorizationData(authorizationData);
LOGGER.info("58金融运营商数据导入结束");
return JsonResult.buildSuccessResult("success", null);
}
} }
...@@ -4,7 +4,6 @@ import cn.quantgroup.xyqb.entity.User; ...@@ -4,7 +4,6 @@ import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.UserDetail; import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.JsonResult; import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.UserModel; import cn.quantgroup.xyqb.model.UserModel;
import cn.quantgroup.xyqb.repository.IUserDetailRepository;
import cn.quantgroup.xyqb.service.user.IUserDetailService; import cn.quantgroup.xyqb.service.user.IUserDetailService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
...@@ -22,73 +21,73 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -22,73 +21,73 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api/sync") @RequestMapping("/api/sync")
public class SyncUserController { public class SyncUserController {
@Autowired @Autowired
private IUserService userService; private IUserService userService;
@Autowired @Autowired
private IUserDetailService userDetailService; private IUserDetailService userDetailService;
/*@Autowired /*@Autowired
private IUserDetailRepository userDetailRepository;*/ private IUserDetailRepository userDetailRepository;*/
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate; private RedisTemplate<String, String> stringRedisTemplate;
@RequestMapping("/user") @RequestMapping("/user")
public JsonResult fetchUser(String key, String phoneNo) { public JsonResult fetchUser(String key, String phoneNo) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) { if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
if (StringUtils.isEmpty(phoneNo)) { if (StringUtils.isEmpty(phoneNo)) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
User user = userService.findByPhoneInDb(phoneNo); User user = userService.findByPhoneInDb(phoneNo);
if (null == user) { if (null == user) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
UserDetail detail = userDetailService.findByUserId(user.getId()); UserDetail detail = userDetailService.findByUserId(user.getId());
if (null == detail) { if (null == detail) {
// FIXME: 16/4/15 前期不对身份证强制要求.后期对修改 // FIXME: 16/4/15 前期不对身份证强制要求.后期对修改
// return JsonResult.buildErrorStateResult(null, null); // return JsonResult.buildErrorStateResult(null, null);
}
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
} }
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
}
@RequestMapping("/save_detail") @RequestMapping("/save_detail")
public JsonResult saveUserDetail(String key, UserDetail userDetail) { public JsonResult saveUserDetail(String key, UserDetail userDetail) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) { if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
String phoneNo = userDetail.getPhoneNo(); String phoneNo = userDetail.getPhoneNo();
User user = userService.findByPhoneWithCache(phoneNo); User user = userService.findByPhoneWithCache(phoneNo);
if (null == user) { if (null == user) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
}
userDetail.setId(null);
userDetail.setUserId(user.getId());
userDetailService.saveUserDetail(userDetail);
return JsonResult.buildSuccessResult(null, null);
} }
userDetail.setId(null);
userDetail.setUserId(user.getId());
userDetailService.saveUserDetail(userDetail);
return JsonResult.buildSuccessResult(null, null);
}
@RequestMapping("/user_uuid") @RequestMapping("/user_uuid")
public JsonResult fetchUserByUuid(String key, String uuid) { public JsonResult fetchUserByUuid(String key, String uuid) {
if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) { if (StringUtils.isEmpty(key) || !"abc1234".equals(key)) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
if (StringUtils.isEmpty(uuid)) { if (StringUtils.isEmpty(uuid)) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
User user = userService.findByUuidWithCache(uuid); User user = userService.findByUuidWithCache(uuid);
if (null == user) { if (null == user) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
UserDetail detail = userDetailService.findByUserId(user.getId()); UserDetail detail = userDetailService.findByUserId(user.getId());
if (null == detail) { if (null == detail) {
// FIXME: 16/4/15 前期不对身份证强制要求.后期对修改 // FIXME: 16/4/15 前期不对身份证强制要求.后期对修改
// return JsonResult.buildErrorStateResult(null, null); // return JsonResult.buildErrorStateResult(null, null);
}
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
} }
UserModel userModel = new UserModel(user, detail);
return JsonResult.buildSuccessResult(null, userModel);
}
} }
...@@ -18,45 +18,45 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -18,45 +18,45 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/api") @RequestMapping("/api")
public class UserApiController { public class UserApiController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class); private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class);
@Autowired @Autowired
private IUserApiService userApiService; private IUserApiService userApiService;
@Autowired @Autowired
private IUserService userService; private IUserService userService;
@RequestMapping("/user/check") @RequestMapping("/user/check")
public JsonResult userImportCheck(String phoneNo, String registerFrom) { public JsonResult userImportCheck(String phoneNo, String registerFrom) {
if ("244".equals(registerFrom)) { if ("244".equals(registerFrom)) {
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom); LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", false); return JsonResult.buildErrorStateResult("用户导入检查拒绝", false);
}
if (StringUtils.isEmpty(phoneNo) || StringUtils.isEmpty(registerFrom)) {
LOGGER.error("[user_import_check]检查传入的参数,参数不全。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("检查传入的参数,参数不全。", null);
}
boolean checkPassed = userApiService.userImportCheck(phoneNo);
if (checkPassed) {
LOGGER.info("[user_import_check]用户可以导入。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildSuccessResult("用户可以导入", checkPassed);
}
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", checkPassed);
} }
if (StringUtils.isEmpty(phoneNo) || StringUtils.isEmpty(registerFrom)) {
LOGGER.error("[user_import_check]检查传入的参数,参数不全。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("检查传入的参数,参数不全。", null);
}
boolean checkPassed = userApiService.userImportCheck(phoneNo);
if (checkPassed) {
LOGGER.info("[user_import_check]用户可以导入。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildSuccessResult("用户可以导入", checkPassed);
}
LOGGER.info("[user_import_check]用户导入检查拒绝。phoneNo=[{}], registerFrom=[{}]", phoneNo, registerFrom);
return JsonResult.buildErrorStateResult("用户导入检查拒绝", checkPassed);
}
@RequestMapping("/user/is_passwd_set") @RequestMapping("/user/is_passwd_set")
public JsonResult isPasswordSet(String key, String phoneNo) { public JsonResult isPasswordSet(String key, String phoneNo) {
if (!"abc1234".equals(key) || StringUtils.isEmpty(phoneNo)) { if (!"abc1234".equals(key) || StringUtils.isEmpty(phoneNo)) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
User user = userService.findByPhoneWithCache(phoneNo); User user = userService.findByPhoneWithCache(phoneNo);
if (null == user) { if (null == user) {
return JsonResult.buildErrorStateResult(null, null); return JsonResult.buildErrorStateResult(null, null);
} }
if (StringUtils.length(user.getPassword()) == 32) { if (StringUtils.length(user.getPassword()) == 32) {
return JsonResult.buildSuccessResult(null, null); return JsonResult.buildSuccessResult(null, null);
}
return JsonResult.buildErrorStateResult(null, null, 2L);
} }
return JsonResult.buildErrorStateResult(null, null, 2L);
}
} }
...@@ -5,19 +5,15 @@ import cn.quantgroup.xyqb.controller.IBaseController; ...@@ -5,19 +5,15 @@ import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.Merchant; import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo; import cn.quantgroup.xyqb.entity.WechatUserInfo;
import cn.quantgroup.xyqb.event.UserinfoChangedEvent;
import cn.quantgroup.xyqb.model.AuthBean; import cn.quantgroup.xyqb.model.AuthBean;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse; import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse;
import cn.quantgroup.xyqb.service.merchant.IMerchantService; import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import cn.quantgroup.xyqb.service.page.IPageService;
import cn.quantgroup.xyqb.service.session.ISessionService; import cn.quantgroup.xyqb.service.session.ISessionService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.service.wechat.IWechatService; import cn.quantgroup.xyqb.service.wechat.IWechatService;
import cn.quantgroup.xyqb.util.EmojiUtil; import cn.quantgroup.xyqb.util.EmojiUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
...@@ -34,6 +30,7 @@ import javax.servlet.http.HttpServletResponse; ...@@ -34,6 +30,7 @@ import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
/** /**
* Created by 11 on 2017/1/17. * Created by 11 on 2017/1/17.
...@@ -43,410 +40,412 @@ import java.util.Arrays; ...@@ -43,410 +40,412 @@ import java.util.Arrays;
@RequestMapping("/wechat") @RequestMapping("/wechat")
public class WeChatController implements IBaseController { public class WeChatController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(WeChatController.class); private static final Logger LOGGER = LoggerFactory.getLogger(WeChatController.class);
// todo: 配置文件
private static final String TOKEN = "5YihkluEo5QuWAWpFwzvA";
@Autowired // todo: 配置文件
private IWechatService wechatService; private static final String TOKEN = "5YihkluEo5QuWAWpFwzvA";
@Autowired @Autowired
private IMerchantService merchantService; private IWechatService wechatService;
@Autowired @Autowired
private ISessionService sessionService; private IMerchantService merchantService;
@Autowired @Autowired
private IUserService userService; private ISessionService sessionService;
// https://passport.xyqb.com/landing?key=xxx&target=cashTarget5&registerFrom=198&channelId=%d @Autowired
@Value("${xyqb-user.ui}") private IUserService userService;
private String userUIAddr;
// https://passport.xyqb.com/landing?key=xxx&target=cashTarget5&registerFrom=198&channelId=%d
@Value("${xyqb-user.ui}")
private String userUIAddr;
/** @Value("${xyqb.user.domain}")
* 开发者资质认证,有必要吗? private String userDomainStr;
*
* @param request
* @return
*/
@RequestMapping("/checkValid")
public String valid(HttpServletRequest request) {
String echoStr = request.getParameter("echostr");
if (checkSignature(request)) {
return echoStr;
}
return "";
}
/** /**
* 验签:步骤 * 开发者资质认证,有必要吗?
* 1.获取signature, timestamp, nonce三个参数 *
* 2.用timestamp, nonce, token三个参数做字符升序排列 * @param request
* 3.将排列好的字符串进行sha1加密,和signature参数做比较 * @return
* 4.相等返回true,否则返回false */
* @RequestMapping("/checkValid")
* @param request public String valid(HttpServletRequest request) {
* @return String echoStr = request.getParameter("echostr");
*/ if (checkSignature(request)) {
private boolean checkSignature(HttpServletRequest request) { return echoStr;
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String[] arrs = new String[]{TOKEN, timestamp, nonce};
Arrays.sort(arrs);
String joinStr = joinArray(arrs);
joinStr = sha1(joinStr);
return joinStr.equals(signature);
} }
return "";
/** }
* sha1加密算法,
* /**
* @param decript * 验签:步骤
* @return 返回40位16进制字符串 * 1.获取signature, timestamp, nonce三个参数
*/ * 2.用timestamp, nonce, token三个参数做字符升序排列
private String sha1(String decript) { * 3.将排列好的字符串进行sha1加密,和signature参数做比较
try { * 4.相等返回true,否则返回false
MessageDigest digest = java.security.MessageDigest *
.getInstance("SHA-1"); * @param request
digest.update(decript.getBytes()); * @return
byte messageDigest[] = digest.digest(); */
StringBuilder hexString = new StringBuilder(); private boolean checkSignature(HttpServletRequest request) {
// 字节数组转换为十六进制数 String signature = request.getParameter("signature");
for (byte aMessageDigest : messageDigest) { String timestamp = request.getParameter("timestamp");
String shaHex = Integer.toHexString(aMessageDigest & 0xFF); String nonce = request.getParameter("nonce");
if (shaHex.length() < 2) { String[] arrs = new String[]{TOKEN, timestamp, nonce};
hexString.append(0); Arrays.sort(arrs);
} String joinStr = joinArray(arrs);
hexString.append(shaHex); joinStr = sha1(joinStr);
} return joinStr.equals(signature);
return hexString.toString(); }
} catch (NoSuchAlgorithmException e) { /**
log.error("未找到sha1算法." + e.getMessage()); * sha1加密算法,
*
* @param decript
* @return 返回40位16进制字符串
*/
private String sha1(String decript) {
try {
MessageDigest digest = java.security.MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
StringBuilder hexString = new StringBuilder();
// 字节数组转换为十六进制数
for (byte aMessageDigest : messageDigest) {
String shaHex = Integer.toHexString(aMessageDigest & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
} }
return ""; hexString.append(shaHex);
} }
return hexString.toString();
/** } catch (NoSuchAlgorithmException e) {
* 数组分割为字符串 log.error("未找到sha1算法." + e.getMessage());
*
* @param arr
* @return
*/
private String joinArray(String[] arr) {
StringBuilder builder = new StringBuilder();
for (String str : arr) {
builder.append(str);
}
return builder.toString();
} }
return "";
/** }
* 前端微信跳转页面,通过extdata
* /**
* @param response * 数组分割为字符串
* @return *
*/ * @param arr
@RequestMapping("/receiveCode/extdata/{key}/{extdata}") * @return
public void receiveCodeWithExtData( */
private String joinArray(String[] arr) {
StringBuilder builder = new StringBuilder();
for (String str : arr) {
builder.append(str);
}
return builder.toString();
}
/**
* 前端微信跳转页面,通过extdata
*
* @param response
* @return
*/
@RequestMapping("/receiveCode/extdata/{key}/{extdata}")
public void receiveCodeWithExtData(
String code, @PathVariable(value = "key") String systemKey, String code, @PathVariable(value = "key") String systemKey,
@PathVariable(value = "extdata") String extData, HttpServletResponse response @PathVariable(value = "extdata") String extData, HttpServletResponse response
) { ) {
try { try {
String schema = getProtocol(); String schema = getProtocol();
try { try {
extData = new String(Base64.decodeBase64(extData), "UTF-8"); extData = new String(Base64.decodeBase64(extData), "UTF-8");
} catch (Exception ex) { } catch (Exception ex) {
extData = ""; extData = "";
} }
LOGGER.info("从微信extdata版本接口进入:{}, extData:{}", schema, extData); LOGGER.info("从微信extdata版本接口进入:{}, extData:{}", schema, extData);
if (StringUtils.isEmpty(extData)) { if (StringUtils.isEmpty(extData)) {
// 从code获取token
Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code);
if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfo =
wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(),
token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo,
Constants.Channel.WECHAT);
return;
}
if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
User user = userService.findById(userInfoInDb.getUserId());
if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl =
createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
} else {
HashMap<String, Object> extDataObj;
try {
extDataObj =
JSON.parseObject(extData, new TypeReference<HashMap<String, Object>>() {
});
} catch (Exception ex) {
LOGGER.error("解析extData发生错误", ex);
// 从code获取token
Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code);
if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfo =
wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(),
token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfoInDb =
wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo,
Constants.Channel.WECHAT);
return;
}
if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
User user = userService.findById(userInfoInDb.getUserId());
if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl =
createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
return;
}
Long registerFrom = Long.valueOf(extDataObj.getOrDefault("registerFrom", "1").toString());
String redirect = (String) extDataObj.getOrDefault("redirect", "redirect");
LOGGER.info("从微信登录,registerFrom:{}, redirect:{}", registerFrom, redirect);
Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code);
if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, registerFrom);
return;
}
WechatUserInfo userInfo =
wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(),
token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, registerFrom);
return;
}
WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo, registerFrom);
return;
}
if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, registerFrom);
return;
}
User user = userService.findById(userInfoInDb.getUserId());
if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, registerFrom);
return;
}
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl = createUserSession(user, merchant, redirect, schema, registerFrom);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
}
} catch (Exception ex) {
LOGGER.error("发生异常", ex);
throw ex;
}
}
/**
* 通过redirect_url获取code
*
* @param response
* @return
*/
@RequestMapping("/receiveCode/{key}")
public void receiveCodeNoRedirect(String code, @PathVariable(value = "key") String systemKey, HttpServletRequest request, HttpServletResponse response) {
String schema = request.getScheme();
LOGGER.info("HTTP协议no redirect:" + schema);
// 从code获取token // 从code获取token
Merchant merchant = merchantService.findMerchantByName(systemKey); Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code); AccessTokenResponse token = wechatService.getToken(code);
if (token == null) { if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url // 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT); redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return; return;
} }
WechatUserInfo userInfo = wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(), token.getOpenId()); WechatUserInfo userInfo =
wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(),
token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) { if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url // 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT); redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return; return;
} }
WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId()); WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录 // welcome 首次登录
if (userInfoInDb == null) { if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo,
Constants.Channel.WECHAT);
return;
}
if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
User user = userService.findById(userInfoInDb.getUserId());
if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl =
createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
} else {
HashMap<String, Object> extDataObj;
try {
extDataObj =
JSON.parseObject(extData, new TypeReference<HashMap<String, Object>>() {
});
} catch (Exception ex) {
LOGGER.error("解析extData发生错误", ex);
// 从code获取token
Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code);
if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfo =
wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(),
token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
}
WechatUserInfo userInfoInDb =
wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面 // 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if(StringUtils.isNotBlank(userInfo.getNickName())) { if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName()); String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName); userInfo.setNickName(nickName);
} }
userInfo = wechatService.saveWechatUserInfo(userInfo); userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo, Constants.Channel.WECHAT); redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo,
Constants.Channel.WECHAT);
return; return;
} }
if (userInfoInDb.getUserId() == null) { if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面 // 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, Constants.Channel.WECHAT); redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return; return;
}
User user = userService.findById(userInfoInDb.getUserId());
if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb,
Constants.Channel.WECHAT);
return;
}
// 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。
String redirectUrl =
createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
return;
}
Long registerFrom = Long.valueOf(extDataObj.getOrDefault("registerFrom", "1").toString());
String redirect = (String) extDataObj.getOrDefault("redirect", "redirect");
LOGGER.info("从微信登录,registerFrom:{}, redirect:{}", registerFrom, redirect);
Merchant merchant = merchantService.findMerchantByName(systemKey);
AccessTokenResponse token = wechatService.getToken(code);
if (token == null) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, registerFrom);
return;
}
WechatUserInfo userInfo =
wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(),
token.getOpenId());
if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
// 让用户登录,不关联微信, 构造不关联微信的url
redirectNormalUrl(response, merchant, registerFrom);
return;
}
WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
// welcome 首次登录
if (userInfoInDb == null) {
// 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo, registerFrom);
return;
}
if (userInfoInDb.getUserId() == null) {
// 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, registerFrom);
return;
} }
User user = userService.findById(userInfoInDb.getUserId()); User user = userService.findById(userInfoInDb.getUserId());
if (user == null) { if (user == null) {
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, Constants.Channel.WECHAT); redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, registerFrom);
return; return;
} }
// 已经关联了用户 // 已经关联了用户
// create session, 登进去,该怎么玩怎么玩。 // create session, 登进去,该怎么玩怎么玩。
String redirectUrl = createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT); String redirectUrl = createUserSession(user, merchant, redirect, schema, registerFrom);
LOGGER.info("Location={}", redirectUrl); LOGGER.info("Location:[{}]",redirectUrl);
response.setHeader("Location", redirectUrl); response.setHeader("Location", redirectUrl);
response.setStatus(301); response.setStatus(301);
}
} catch (Exception ex) {
LOGGER.error("发生异常", ex);
throw ex;
} }
}
private String createUserSession(User user, Merchant merchant, String redirect, String schema, Long registerFrom) {
//TODO 临时紧急上线修改的.下次上线的时候修复一下,不能这样写. /**
String url = "http://passport.xyqb.com"; * 通过redirect_url获取code
if("https:".equals(schema)) { *
url = "https://passport.xyqb.com"; * @param response
} * @return
if(StringUtils.isEmpty(redirect) || "redirect".equals(redirect)) { */
LOGGER.info("微信登录:redirect为null,走正常流程."); @RequestMapping("/receiveCode/{key}")
if ("baitiao".equals(merchant.getName())) { public void receiveCodeNoRedirect(String code, @PathVariable(value = "key") String systemKey, HttpServletRequest request, HttpServletResponse response) {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget5", Constants.Channel.BAITIAO, url, Constants.Channel.WECHAT); String schema = request.getScheme();
} else if("wechat-pay".equals(merchant.getName())){ LOGGER.info("HTTP协议no redirect:" + schema);
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, registerFrom, "", user, merchant); // 从code获取token
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+ "&channelId=" + Constants.Channel.WECHAT +"&key=" + merchant.getName() +"&target=cashTarget5" ; Merchant merchant = merchantService.findMerchantByName(systemKey);
}else {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget4", 1L, url, registerFrom); AccessTokenResponse token = wechatService.getToken(code);
} if (token == null) {
} else if("local".equals(redirect)){ // 让用户登录,不关联微信, 构造不关联微信的url
LOGGER.info("微信登录:redirect不为null,创建session跳到指定前端页面."); redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, Constants.Channel.WECHAT, "", user, merchant); return;
LOGGER.info("微信登录:跳转地址{}", url + "/weixin/callback?phoneNo=" + user.getPhoneNo() + "&token=" + authBean.getToken());
Long channelId = "baitiao".equals(merchant.getName()) ? 222L : 1L;
String target = "baitiao".equals(merchant.getName()) ? "cashTarget5" : "cashTarget4";
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+
"&channelId=" + channelId +"&key=" + merchant.getName() +"&target=" + target + "&isWechat=true";
}
return null;
} }
WechatUserInfo userInfo = wechatService.getWechatUserInfoFromWechatServer(token.getAccessToken(), token.getOpenId());
private String loginInWechatWithSessionCreated(User user, Merchant merchant, String target, Long channelId, String url, Long registerFrom) { if (userInfo == null || StringUtils.isEmpty(userInfo.getOpenId())) {
AuthBean authBean = sessionService.createSession(channelId, registerFrom, "", user, merchant); // 让用户登录,不关联微信, 构造不关联微信的url
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom+ "&channelId=" + channelId +"&key=" + merchant.getName() +"&target=" + target; redirectNormalUrl(response, merchant, Constants.Channel.WECHAT);
return;
} }
WechatUserInfo userInfoInDb = wechatService.findWechatUserInfoFromDb(userInfo.getOpenId());
private void redirectWechatLoginUrlWithoutLogin(HttpServletResponse response, Merchant merchant, WechatUserInfo userInfo, Long registerFrom) { // welcome 首次登录
String redirectUrl = assembleWechatRedirectUrl(merchant, userInfo, registerFrom); if (userInfoInDb == null) {
response.setHeader("Location", redirectUrl); // 微信用户首次登录界面, 首先保存userInfo, 跳入到微信注册登录界面
response.setStatus(301); if (StringUtils.isNotBlank(userInfo.getNickName())) {
String nickName = EmojiUtil.filter(userInfo.getNickName());
userInfo.setNickName(nickName);
}
userInfo = wechatService.saveWechatUserInfo(userInfo);
redirectWechatLoginUrlWithoutLogin(response, merchant, userInfo, Constants.Channel.WECHAT);
return;
} }
if (userInfoInDb.getUserId() == null) {
private void redirectNormalUrl(HttpServletResponse response, Merchant merchant, Long registerFrom) { // 用户已经微信登录了,但是没有关联信用钱包,跳转到注册页面
String redirectUrl = assembleNormalRedirectUrl(merchant, registerFrom); redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, Constants.Channel.WECHAT);
response.setHeader("Location", redirectUrl); return;
response.setStatus(301);
} }
User user = userService.findById(userInfoInDb.getUserId());
private String assembleNormalRedirectUrl(Merchant merchant, Long registerFrom) { if (user == null) {
if ("baitiao".equals(merchant.getName())) { redirectWechatLoginUrlWithoutLogin(response, merchant, userInfoInDb, Constants.Channel.WECHAT);
return userUIAddr + "/landing?key=baitiao&target=cashTarget5&channelId=222&registerFrom=198"; return;
} else if ("wechat-pay".equals(merchant.getName())) {
return userUIAddr + "/landing?key=wechat-pay&target=cashTarget5&channelId=1&page=landing/4&registerFrom" + registerFrom;
} else {
return userUIAddr + "/landing?key=xyqb&target=cashTarget4&channelId=1&registerFrom=" + registerFrom;
}
} }
// 已经关联了用户
private String assembleWechatRedirectUrl(Merchant merchant, WechatUserInfo userInfo, Long registerFrom) { // create session, 登进去,该怎么玩怎么玩。
if ("baitiao".equals(merchant.getName())) { String redirectUrl = createUserSession(user, merchant, "", schema, Constants.Channel.WECHAT);
return userUIAddr + "/landing?key=baitiao&target=cashTarget5&registerFrom=198&channelId=222&isWechat=true&openId=" + userInfo.getOpenId(); LOGGER.info("Location=[{}]", redirectUrl);
} else if ("wechat-pay".equals(merchant.getName())) { response.setHeader("Location", redirectUrl);
return userUIAddr + "/landing?key=wechat-pay&target=cashTarget5&page=landing/4&registerFrom= " + registerFrom + "&channelId=1&isWechat=true&openId=" + userInfo.getOpenId(); response.setStatus(301);
} else { }
return userUIAddr + "/landing?key=xyqb&target=cashTarget4&registerFrom= " + registerFrom + "&channelId=1&isWechat=true&openId=" + userInfo.getOpenId();
} private String createUserSession(User user, Merchant merchant, String redirect, String schema, Long registerFrom) {
//String url = "http://passport.xyqb.com";
String url = "http://"+userDomainStr;
if ("https:".equals(schema)) {
url = "https://"+userDomainStr;
}
if (StringUtils.isEmpty(redirect) || "redirect".equals(redirect)) {
LOGGER.info("微信登录:redirect为null,走正常流程.");
if ("baitiao".equals(merchant.getName())) {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget5", Constants.Channel.BAITIAO, url, Constants.Channel.WECHAT);
} else if ("wechat-pay".equals(merchant.getName())) {
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, registerFrom, "", user, merchant);
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom + "&channelId=" + Constants.Channel.WECHAT + "&key=" + merchant.getName() + "&target=cashTarget5";
} else {
return loginInWechatWithSessionCreated(user, merchant, "cashTarget4", 1L, url, registerFrom);
}
} else if ("local".equals(redirect)) {
LOGGER.info("微信登录:redirect不为null,创建session跳到指定前端页面.");
AuthBean authBean = sessionService.createSession(Constants.Channel.WECHAT, Constants.Channel.WECHAT, "", user, merchant);
LOGGER.info("微信登录:跳转地址{}", url + "/weixin/callback?phoneNo=" + user.getPhoneNo() + "&token=" + authBean.getToken());
Long channelId = "baitiao".equals(merchant.getName()) ? 222L : 1L;
String target = "baitiao".equals(merchant.getName()) ? "cashTarget5" : "cashTarget4";
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom +
"&channelId=" + channelId + "&key=" + merchant.getName() + "&target=" + target + "&isWechat=true";
}
return null;
}
private String loginInWechatWithSessionCreated(User user, Merchant merchant, String target, Long channelId, String url, Long registerFrom) {
AuthBean authBean = sessionService.createSession(channelId, registerFrom, "", user, merchant);
return url + "/landing?token=" + authBean.getToken() + "&registerFrom=" + registerFrom + "&channelId=" + channelId + "&key=" + merchant.getName() + "&target=" + target;
}
private void redirectWechatLoginUrlWithoutLogin(HttpServletResponse response, Merchant merchant, WechatUserInfo userInfo, Long registerFrom) {
String redirectUrl = assembleWechatRedirectUrl(merchant, userInfo, registerFrom);
LOGGER.info("redirectWechatLoginUrlWithoutLogin redirectUrl:[{}]",redirectUrl);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
}
private void redirectNormalUrl(HttpServletResponse response, Merchant merchant, Long registerFrom) {
String redirectUrl = assembleNormalRedirectUrl(merchant, registerFrom);
LOGGER.info("redirectNormalUrl redirectUrl:[{}]",redirectUrl);
response.setHeader("Location", redirectUrl);
response.setStatus(301);
}
private String assembleNormalRedirectUrl(Merchant merchant, Long registerFrom) {
if ("baitiao".equals(merchant.getName())) {
return userUIAddr + "/landing?key=baitiao&target=cashTarget5&channelId=222&registerFrom=198";
} else if ("wechat-pay".equals(merchant.getName())) {
return userUIAddr + "/landing?key=wechat-pay&target=cashTarget5&channelId=1&page=landing/4&registerFrom" + registerFrom;
} else {
return userUIAddr + "/landing?key=xyqb&target=cashTarget4&channelId=1&registerFrom=" + registerFrom;
}
}
private String assembleWechatRedirectUrl(Merchant merchant, WechatUserInfo userInfo, Long registerFrom) {
if ("baitiao".equals(merchant.getName())) {
return userUIAddr + "/landing?key=baitiao&target=cashTarget5&registerFrom=198&channelId=222&isWechat=true&openId=" + userInfo.getOpenId();
} else if ("wechat-pay".equals(merchant.getName())) {
return userUIAddr + "/landing?key=wechat-pay&target=cashTarget5&page=landing/4&registerFrom= " + registerFrom + "&channelId=1&isWechat=true&openId=" + userInfo.getOpenId();
} else {
return userUIAddr + "/landing?key=xyqb&target=cashTarget4&registerFrom= " + registerFrom + "&channelId=1&isWechat=true&openId=" + userInfo.getOpenId();
} }
}
} }
...@@ -13,11 +13,11 @@ import java.io.PrintWriter; ...@@ -13,11 +13,11 @@ import java.io.PrintWriter;
@RequestMapping("/") @RequestMapping("/")
public class WechatVerifyController { public class WechatVerifyController {
@RequestMapping("/MP_verify_AWiagUn4kZiwmTt0.txt") @RequestMapping("/MP_verify_AWiagUn4kZiwmTt0.txt")
public void verifyWechat(HttpServletResponse response) throws Exception { public void verifyWechat(HttpServletResponse response) throws Exception {
response.setContentType("plain/text"); response.setContentType("plain/text");
PrintWriter writer = response.getWriter(); PrintWriter writer = response.getWriter();
writer.print("AWiagUn4kZiwmTt0"); writer.print("AWiagUn4kZiwmTt0");
writer.close(); writer.close();
} }
} }
package cn.quantgroup.xyqb.controller.internal.login; package cn.quantgroup.xyqb.controller.internal.login;
import cn.quantgroup.xyqb.controller.IBaseController; import cn.quantgroup.xyqb.controller.IBaseController;
import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.JsonResult; import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.UserRet; import cn.quantgroup.xyqb.model.UserRet;
import cn.quantgroup.xyqb.model.session.LoginInfo; import cn.quantgroup.xyqb.model.session.LoginInfo;
import cn.quantgroup.xyqb.model.session.SessionStruct; import cn.quantgroup.xyqb.model.session.SessionStruct;
import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.user.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/** /**
* Created by Miraculous on 2016/12/30. * Created by Miraculous on 2016/12/30.
*/ */
@RestController @RestController
@RequestMapping("/auth") @RequestMapping("/auth")
@Slf4j
public class AuthInfoController implements IBaseController { public class AuthInfoController implements IBaseController {
@RequestMapping("/info/login")
public JsonResult loginInfo() { @Value("${xyqb.auth.url}")
SessionStruct sessionStruct = getSessionStruct(); private String xyqbAuthUrl;
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(sessionStruct.getValues().getUser())); @Autowired
loginInfo.setToken(sessionStruct.getSid()); private IHttpService httpService;
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(sessionStruct.getValues().getLoginProperties().getChannelId()); @Autowired
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom()); private IUserService userService;
context.setAppChannel(sessionStruct.getValues().getLoginProperties().getAppChannel());
loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo); @RequestMapping("/info/login")
public JsonResult loginInfo() {
SessionStruct sessionStruct = getCurrentSessionFromRedis();
if(null != sessionStruct) {
log.info("从用户中心获取到了用户登录信息:phone:[{}]",sessionStruct.getValues().getUser().getPhoneNo());
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(sessionStruct.getValues().getUser()));
loginInfo.setToken(sessionStruct.getSid());
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(sessionStruct.getValues().getLoginProperties().getChannelId());
context.setCreatedFrom(sessionStruct.getValues().getLoginProperties().getCreatedFrom());
context.setAppChannel(sessionStruct.getValues().getLoginProperties().getAppChannel());
loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo); //有ThreadLocal不释放的问题,不可再使用原来方式了
}else {
// 函谷关去查token 返回值高仿
log.info("去向函谷关查询用户信息");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token");
if(StringUtils.isBlank(token) ||token.length() != 36){
return JsonResult.buildErrorStateResult("用户未登录",null);
}
String checkUrl = xyqbAuthUrl+"/innerapi/is_login";
ImmutableMap<String, String> headMap = ImmutableMap.of("x-auth-token", token);
String response = httpService.get(checkUrl, headMap, null);
log.info("去向函谷关查询用户信息,response:[{}]",response);
JsonResult result = JSONObject.parseObject(response, JsonResult.class);
if (result == null || !"0000".equals(result.getCode()) || !"0000".equals(result.getBusinessCode())) {
return JsonResult.buildErrorStateResult("用户未登录",null);
}
String phoneNo = ((Map<String, String>) result.getData()).get("phoneNo");
User user = userService.findByPhoneWithCache(phoneNo);
LoginInfo loginInfo = new LoginInfo();
loginInfo.setUser(UserRet.getUserRet(user));
loginInfo.setToken(token);
LoginInfo.LoginContext context = new LoginInfo.LoginContext();
context.setChannelId(null);
context.setCreatedFrom(user.getRegisteredFrom());
context.setAppChannel("");
loginInfo.setLoginContext(context);
return JsonResult.buildSuccessResult("", loginInfo);
} }
}
} }
...@@ -25,52 +25,51 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -25,52 +25,51 @@ import org.springframework.web.bind.annotation.RestController;
public class PlatformAPIController implements IBaseController { public class PlatformAPIController implements IBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(PlatformAPIController.class); private static final Logger LOGGER = LoggerFactory.getLogger(PlatformAPIController.class);
@Autowired @Autowired
private IPageService pageService; private IPageService pageService;
@Autowired @Autowired
private IMerchantService merchantService; private IMerchantService merchantService;
@RequestMapping("/page/return_url") @RequestMapping("/page/return_url")
public JsonResult returnUrl(String key) { public JsonResult returnUrl(String key) {
Merchant merchant = merchantService.findMerchantByName(key); Merchant merchant = merchantService.findMerchantByName(key);
if (null == merchant) { if (null == merchant) {
return JsonResult.buildErrorStateResult("", null); return JsonResult.buildErrorStateResult("", null);
}
MerchantConfig config= merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (null == config) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", config.getConfigValue());
} }
MerchantConfig config = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
@RequestMapping("/page/next") if (null == config) {
public JsonResult nextPage(String key, String target, @RequestParam(required = false, defaultValue = "") String currentPage) { return JsonResult.buildSuccessResult("", null);
User user = getCurrentUser();
if (null == user) {
return JsonResult.buildErrorStateResult("未找到用户", null);
}
Tuple<String, Boolean> nextPageTuple = pageService.nextPage(user, target, currentPage);
Boolean isFinal = nextPageTuple.getValue();
String nextPage = nextPageTuple.getKey();
if (isFinal) {
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildSuccessResult("", null);
}
MerchantConfig merchantConfig = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (merchantConfig == null) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "external", "transition", merchantConfig.getConfigValue()));
}
if (StringUtils.isEmpty(nextPage)) {
return JsonResult.buildErrorStateResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "user", "transition", nextPage));
} }
return JsonResult.buildSuccessResult("", config.getConfigValue());
}
@RequestMapping("/page/next")
public JsonResult nextPage(String key, String target, @RequestParam(required = false, defaultValue = "") String currentPage) {
User user = getCurrentUser();
if (null == user) {
return JsonResult.buildErrorStateResult("未找到用户", null);
}
Tuple<String, Boolean> nextPageTuple = pageService.nextPage(user, target, currentPage);
Boolean isFinal = nextPageTuple.getValue();
String nextPage = nextPageTuple.getKey();
if (isFinal) {
Merchant merchant = merchantService.findMerchantByName(key);
if (merchant == null) {
return JsonResult.buildSuccessResult("", null);
}
MerchantConfig merchantConfig = merchantService.findConfigByMerchantIdAndConfigName(merchant.getId(), "returnUrl");
if (merchantConfig == null) {
return JsonResult.buildSuccessResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "external", "transition", merchantConfig.getConfigValue()));
}
if (StringUtils.isEmpty(nextPage)) {
return JsonResult.buildErrorStateResult("", null);
}
return JsonResult.buildSuccessResult("", ImmutableMap.of("type", "user", "transition", nextPage));
}
} }
...@@ -26,95 +26,91 @@ import java.util.concurrent.TimeUnit; ...@@ -26,95 +26,91 @@ import java.util.concurrent.TimeUnit;
@RequestMapping("/api/sms") @RequestMapping("/api/sms")
public class SmsController { public class SmsController {
private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class); private static final Logger LOGGER = LoggerFactory.getLogger(SmsController.class);
@Autowired private static final Random random = new Random();
private ISmsService smsService; private static final long EXPIRE_MINUTES = 10;
@Autowired
@Autowired private ISmsService smsService;
@Qualifier("stringRedisTemplate") @Autowired
private RedisTemplate<String, String> redisTemplate; @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate;
@Value("${sms.is.debug}") @Value("${sms.is.debug}")
private boolean smsIsDebug; private boolean smsIsDebug;
private static final Random random = new Random(); /**
* 短信验证码: for H5
private static final long EXPIRE_MINUTES = 10; * 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制
*/
/** @CaptchaValidator
* 短信验证码: for H5 @RequestMapping("/send_sms_verification_code")
* 使用 @FPLock 注解并加入自定义限制参数, 做针对手机号的发送次数限制 public JsonResult verifyPhoneNoH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
*/ LOGGER.info("注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
@CaptchaValidator return sendVerificationCode2(phoneNo);
@RequestMapping("/send_sms_verification_code") }
public JsonResult verifyPhoneNoH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom); @CaptchaValidator
return sendVerificationCode2(phoneNo); @RequestMapping("/send_reset_code")
} public JsonResult resetPasswordH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("重置密码-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
@CaptchaValidator return sendVerificationCode2(phoneNo);
@RequestMapping("/send_reset_code") }
public JsonResult resetPasswordH5(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("重置密码-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom); /**
return sendVerificationCode2(phoneNo); * 快速登陆发送验证码
} *
* @param phoneNo
/** * @param registerFrom
* 快速登陆发送验证码 * @return
* */
* @param phoneNo @CaptchaValidator
* @param registerFrom @RequestMapping("/send_login_code")
* @return public JsonResult sendLoginCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
*/ LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
@CaptchaValidator return sendVerificationCode2(phoneNo);
@RequestMapping("/send_login_code") }
public JsonResult sendLoginCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速登陆-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom); /**
return sendVerificationCode2(phoneNo); * 快速注册发送验证码
*
* @param phoneNo
* @param registerFrom
* @return
*/
@CaptchaValidator
@RequestMapping("/send_regist_code")
public JsonResult sendRegistCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
}
private JsonResult sendVerificationCode2(String phoneNo) {
if (!ValidationUtil.validatePhoneNo(phoneNo)) {
return JsonResult.buildErrorStateResult("手机号格式有误", null);
} }
/** String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
* 快速注册发送验证码 long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES);
* if (expire >= EXPIRE_MINUTES - 1) {
* @param phoneNo return JsonResult.buildSuccessResult("发送成功", null);
* @param registerFrom
* @return
*/
@CaptchaValidator
@RequestMapping("/send_regist_code")
public JsonResult sendRegistCode(@RequestParam String phoneNo, @RequestParam(required = false) String registerFrom) {
LOGGER.info("快速注册-发送验证码, phoneNo:{}, registerFrom:{}", phoneNo, registerFrom);
return sendVerificationCode2(phoneNo);
} }
String randomCode = smsIsDebug ? "000000" : String.valueOf(random.nextInt(899999) + 100000);
String uniqueId = phoneNo + UUID.randomUUID().toString().replaceAll("-", "");
private JsonResult sendVerificationCode2(String phoneNo) { List<String> newList = new ArrayList<>();
if (!ValidationUtil.validatePhoneNo(phoneNo)) { newList.add(randomCode);
return JsonResult.buildErrorStateResult("手机号格式有误", null);
}
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
long expire = redisTemplate.getExpire(key, TimeUnit.MINUTES);
if (expire >= EXPIRE_MINUTES - 1) {
return JsonResult.buildSuccessResult("发送成功", null);
}
String randomCode = smsIsDebug ? "000000" : String.valueOf(random.nextInt(899999) + 100000);
String uniqueId = phoneNo + UUID.randomUUID().toString().replaceAll("-", "");
List<String> newList = new ArrayList<>();
newList.add(randomCode);
/*ConfirmableMsg confirmableMsg = new ConfirmableMsg( /*ConfirmableMsg confirmableMsg = new ConfirmableMsg(
uniqueId, newList, "1", "1", phoneNo uniqueId, newList, "1", "1", phoneNo
);*/ );*/
MsgParams message = new MsgParams(Collections.singletonList(2), phoneNo, "1", "1", Collections.singletonList(randomCode), uniqueId); MsgParams message = new MsgParams(Collections.singletonList(2), phoneNo, "1", "1", Collections.singletonList(randomCode), uniqueId);
try { try {
//smsService.getSmsSender().sendConfirmableMessage(confirmableMsg); //smsService.getSmsSender().sendConfirmableMessage(confirmableMsg);
smsService.getSmsSender().sendMsg(message); smsService.getSmsSender().sendMsg(message);
redisTemplate.opsForValue().set(key, uniqueId + ":" + randomCode, EXPIRE_MINUTES, TimeUnit.MINUTES); redisTemplate.opsForValue().set(key, uniqueId + ":" + randomCode, EXPIRE_MINUTES, TimeUnit.MINUTES);
return JsonResult.buildSuccessResult("发送成功", uniqueId); return JsonResult.buildSuccessResult("发送成功", uniqueId);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("发送短信验证码失败"); LOGGER.error("发送短信验证码失败");
return JsonResult.buildErrorStateResult("发送失败", null); return JsonResult.buildErrorStateResult("发送失败", null);
}
} }
}
} }
...@@ -26,49 +26,49 @@ import java.text.ParseException; ...@@ -26,49 +26,49 @@ import java.text.ParseException;
@RequestMapping("/user_detail") @RequestMapping("/user_detail")
public class UserDetailController implements IBaseController { public class UserDetailController implements IBaseController {
@Autowired private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class);
private IUserDetailService userDetailService; @Autowired
@Autowired private IUserDetailService userDetailService;
private IIdCardService idCardService; @Autowired
private static final Logger LOGGER = LoggerFactory.getLogger(UserDetailController.class); private IIdCardService idCardService;
@RequestMapping("/save") @RequestMapping("/save")
public JsonResult saveUserdetail(String idNo, String name) { public JsonResult saveUserdetail(String idNo, String name) {
try { try {
if (!ValidationUtil.validateChinese(name)) { if (!ValidationUtil.validateChinese(name)) {
return JsonResult.buildErrorStateResult("姓名错误", null); return JsonResult.buildErrorStateResult("姓名错误", null);
} }
IdCardInfo info = idCardService.getIdCardInfo(idNo); IdCardInfo info = idCardService.getIdCardInfo(idNo);
if (!info.isValid()) { if (!info.isValid()) {
return JsonResult.buildErrorStateResult("身份证号码错误", null); return JsonResult.buildErrorStateResult("身份证号码错误", null);
} }
User user = getCurrentUser(); User user = getCurrentUser();
if (user == null) { if (user == null) {
return JsonResult.buildErrorStateResult("系统错误", null); return JsonResult.buildErrorStateResult("系统错误", null);
} }
Timestamp now = new Timestamp(System.currentTimeMillis()); Timestamp now = new Timestamp(System.currentTimeMillis());
UserDetail userDetail = new UserDetail(); UserDetail userDetail = new UserDetail();
userDetail.setIdNo(idNo); userDetail.setIdNo(idNo);
userDetail.setPhoneNo(user.getPhoneNo()); userDetail.setPhoneNo(user.getPhoneNo());
userDetail.setUserId(user.getId()); userDetail.setUserId(user.getId());
userDetail.setCreatedAt(now); userDetail.setCreatedAt(now);
userDetail.setUpdatedAt(now); userDetail.setUpdatedAt(now);
userDetail.setName(name); userDetail.setName(name);
userDetail.setGender(info.getGender()); userDetail.setGender(info.getGender());
userDetail.setEmail(""); userDetail.setEmail("");
userDetail.setIdType(IdType.ID_CARD); userDetail.setIdType(IdType.ID_CARD);
userDetail.setIsAuthenticated(false); userDetail.setIsAuthenticated(false);
userDetail.setQq(""); userDetail.setQq("");
try { try {
userDetailService.saveUserDetail(userDetail); userDetailService.saveUserDetail(userDetail);
} catch (DataIntegrityViolationException ex) { } catch (DataIntegrityViolationException ex) {
return JsonResult.buildSuccessResult("", null); return JsonResult.buildSuccessResult("", null);
} }
return JsonResult.buildSuccessResult("", null); return JsonResult.buildSuccessResult("", null);
} catch (ParseException ex) { } catch (ParseException ex) {
LOGGER.error("身份证号错误, idNo: {}", idNo); LOGGER.error("身份证号错误, idNo: {}", idNo);
return JsonResult.buildErrorStateResult("身份证号码错误", null); return JsonResult.buildErrorStateResult("身份证号码错误", null);
}
} }
}
} }
...@@ -13,32 +13,32 @@ import java.sql.Timestamp; ...@@ -13,32 +13,32 @@ import java.sql.Timestamp;
@Data @Data
@Entity @Entity
@Table(name = "address", uniqueConstraints = @UniqueConstraint(columnNames = "user_id")) @Table(name = "address", uniqueConstraints = @UniqueConstraint(columnNames = "user_id"))
public class Address implements Serializable{ public class Address implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(name = "user_id") @Column(name = "user_id")
private Long userId; private Long userId;
@Column(name = "province_code") @Column(name = "province_code")
private Long provinceCode; private Long provinceCode;
@Column(name = "province") @Column(name = "province")
private String province; private String province;
@Column(name = "city_code") @Column(name = "city_code")
private Long cityCode; private Long cityCode;
@Column(name = "city") @Column(name = "city")
private String city; private String city;
@Column(name = "districtCode") @Column(name = "districtCode")
private Long districtCode; private Long districtCode;
@Column(name = "district") @Column(name = "district")
private String district; private String district;
@Column(name = "address") @Column(name = "address")
private String address; private String address;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updateAt; private Timestamp updateAt;
} }
...@@ -10,52 +10,52 @@ import java.io.Serializable; ...@@ -10,52 +10,52 @@ import java.io.Serializable;
@Table(name = "channel", uniqueConstraints = @UniqueConstraint(columnNames = "channel_code")) @Table(name = "channel", uniqueConstraints = @UniqueConstraint(columnNames = "channel_code"))
public class Channel implements Serializable { public class Channel implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
//渠道代号 //渠道代号
@Column(name = "channel_code") @Column(name = "channel_code")
private String channelCode; private String channelCode;
//渠道名称 //渠道名称
@Column(name = "name") @Column(name = "name")
private String name; private String name;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
public String getChannelCode() { public String getChannelCode() {
return channelCode; return channelCode;
} }
public void setChannelCode(String channelCode) { public void setChannelCode(String channelCode) {
this.channelCode = channelCode; this.channelCode = channelCode;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return "Channel{" + return "Channel{" +
"channelCode='" + channelCode + '\'' + "channelCode='" + channelCode + '\'' +
", id=" + id + ", id=" + id +
", name='" + name + '\'' + ", name='" + name + '\'' +
'}'; '}';
} }
} }
...@@ -14,22 +14,22 @@ import java.sql.Timestamp; ...@@ -14,22 +14,22 @@ import java.sql.Timestamp;
@Entity @Entity
@Table(name = "contact") @Table(name = "contact")
public class Contact implements Serializable { public class Contact implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(name = "user_id") @Column(name = "user_id")
private Long userId; private Long userId;
@Column(name = "name") @Column(name = "name")
private String name; private String name;
@Column(name = "phone_no") @Column(name = "phone_no")
private String phoneNo; private String phoneNo;
@Column(name = "relation") @Column(name = "relation")
private Relation relation; private Relation relation;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updateAt; private Timestamp updateAt;
} }
...@@ -15,18 +15,18 @@ import java.sql.Timestamp; ...@@ -15,18 +15,18 @@ import java.sql.Timestamp;
@Data @Data
@Entity @Entity
@Table(name = "merchant") @Table(name = "merchant")
public class Merchant implements Serializable{ public class Merchant implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
private Long id; private Long id;
@Column(name = "name") @Column(name = "name")
private String name; private String name;
@Column(name = "enable") @Column(name = "enable")
private boolean enable; private boolean enable;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createAt; private Timestamp createAt;
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updateAt; private Timestamp updateAt;
} }
...@@ -17,18 +17,18 @@ import java.sql.Timestamp; ...@@ -17,18 +17,18 @@ import java.sql.Timestamp;
@Table(name = "merchant_config") @Table(name = "merchant_config")
public class MerchantConfig implements Serializable { public class MerchantConfig implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
private Long id; private Long id;
@Column(name = "merchant_id") @Column(name = "merchant_id")
private Long merchantId; private Long merchantId;
@Column(name = "config_name") @Column(name = "config_name")
private String configName; private String configName;
@Column(name = "config_value") @Column(name = "config_value")
private String configValue; private String configValue;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updateAt; private Timestamp updateAt;
} }
package cn.quantgroup.xyqb.entity; package cn.quantgroup.xyqb.entity;
import cn.quantgroup.motan.retbean.XUser;
import cn.quantgroup.xyqb.config.http.Timestamp2LongConverter; import cn.quantgroup.xyqb.config.http.Timestamp2LongConverter;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import lombok.Getter;
import lombok.*; import lombok.Setter;
import lombok.ToString;
import javax.jws.soap.SOAPBinding;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Timestamp; import java.sql.Timestamp;
...@@ -20,41 +21,55 @@ import java.sql.Timestamp; ...@@ -20,41 +21,55 @@ import java.sql.Timestamp;
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "phone_no")) @Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "phone_no"))
public class User implements Serializable { public class User implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
//手机号 //手机号
@Column(name = "phone_no") @Column(name = "phone_no")
private String phoneNo; private String phoneNo;
//uuid //uuid
@Column(name = "password") @Column(name = "password")
private String password; private String password;
//第一次用户来源 channel_id //第一次用户来源 channel_id
@Column(name = "registered_from") @Column(name = "registered_from")
private Long registeredFrom; private Long registeredFrom;
//uuid //uuid
@Column(name = "uuid") @Column(name = "uuid")
private String uuid; private String uuid;
@Column(name = "enable") @Column(name = "enable")
private Boolean enable; private Boolean enable;
//创建时间 //创建时间
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
//上一次修改时间 //上一次修改时间
@Column(name = "updated_at") @Column(name = "updated_at")
@JSONField(serializeUsing = Timestamp2LongConverter.class) @JSONField(serializeUsing = Timestamp2LongConverter.class)
private Timestamp updatedAt; private Timestamp updatedAt;
public XUser toXUser() {
XUser xUser = new XUser();
xUser.setId(this.getId());
xUser.setPassword(this.getPassword());
xUser.setRegisteredFrom(this.getRegisteredFrom());
xUser.setUuid(this.getUuid());
xUser.setEnable(this.getEnable());
xUser.setPhoneNo(this.getPhoneNo());
xUser.setUpdatedAt(this.getUpdatedAt());
xUser.setCreatedAt(this.getCreatedAt());
return xUser;
}
} }
package cn.quantgroup.xyqb.entity; package cn.quantgroup.xyqb.entity;
import cn.quantgroup.motan.retbean.XUserDetail;
import cn.quantgroup.xyqb.model.Gender; import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType; import cn.quantgroup.xyqb.model.IdType;
import lombok.*; import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*; import javax.persistence.*;
import java.io.Serializable; import java.io.Serializable;
...@@ -18,51 +21,73 @@ import java.sql.Timestamp; ...@@ -18,51 +21,73 @@ import java.sql.Timestamp;
@Table(name = "user_detail", uniqueConstraints = @UniqueConstraint(columnNames = "user_id")) @Table(name = "user_detail", uniqueConstraints = @UniqueConstraint(columnNames = "user_id"))
public class UserDetail implements Serializable { public class UserDetail implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(name = "user_id") @Column(name = "user_id")
private Long userId; private Long userId;
@Column(name = "phone_no") @Column(name = "phone_no")
private String phoneNo; private String phoneNo;
@Column(name = "name") @Column(name = "name")
private String name; private String name;
//证件号 //证件号
@Column(name = "id_no") @Column(name = "id_no")
private String idNo; private String idNo;
//0 身份证 1 军官证 2 护照 //0 身份证 1 军官证 2 护照
@Column(name = "id_type") @Column(name = "id_type")
private IdType idType; private IdType idType;
//身份证验真 0 未认证 1认证 //身份证验真 0 未认证 1认证
@Column(name = "is_authenticated") @Column(name = "is_authenticated")
private Boolean isAuthenticated = false; private Boolean isAuthenticated = false;
//0 未知 1 女 2 男 //0 未知 1 女 2 男
@Column(name = "gender") @Column(name = "gender")
private Gender gender; private Gender gender;
@Column(name = "email") @Column(name = "email")
private String email; private String email;
@Column(name = "qq") @Column(name = "qq")
private String qq; private String qq;
//创建时间 //创建时间
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
//上一次修改时间 //上一次修改时间
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updatedAt; private Timestamp updatedAt;
public XUserDetail toXUserDetail() {
XUserDetail xUserDetail = new XUserDetail();
xUserDetail.setId(this.getId());
xUserDetail.setUserId(this.getUserId());
xUserDetail.setPhoneNo(this.getPhoneNo());
xUserDetail.setName(this.getName());
xUserDetail.setIdNo(this.getIdNo());
if (this.getIdType() != null) {
xUserDetail.setIdType(cn.quantgroup.motan.enums.IdType.valueOf(this.getIdType().name()));
}
if (this.getGender() != null) {
xUserDetail.setGender(cn.quantgroup.motan.enums.Gender.valueOf(this.getGender().name()));
}
xUserDetail.setEmail(this.getEmail());
xUserDetail.setQq(this.getQq());
xUserDetail.setId(this.getId());
xUserDetail.setCreatedAt(this.getCreatedAt());
xUserDetail.setUpdatedAt(this.getUpdatedAt());
xUserDetail.setIsAuthenticated(this.getIsAuthenticated());
return xUserDetail;
}
} }
package cn.quantgroup.xyqb.entity; package cn.quantgroup.xyqb.entity;
import cn.quantgroup.xyqb.entity.enumerate.*; import cn.quantgroup.xyqb.entity.enumerate.*;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.Data; import lombok.Data;
import javax.persistence.*; import javax.persistence.*;
...@@ -16,34 +15,34 @@ import java.sql.Timestamp; ...@@ -16,34 +15,34 @@ import java.sql.Timestamp;
@Table(name = "user_ext_info") @Table(name = "user_ext_info")
public class UserExtInfo implements Serializable { public class UserExtInfo implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id") @Column(name = "id")
private Long id; private Long id;
@Column(name = "user_id") @Column(name = "user_id")
private Long userId; private Long userId;
@Column(name = "means_of_income_payment") @Column(name = "means_of_income_payment")
private IncomeEnum incomeEnum = IncomeEnum.UNKNOWN; private IncomeEnum incomeEnum = IncomeEnum.UNKNOWN;
@Column(name = "monthly_income_range") @Column(name = "monthly_income_range")
private IncomeRangeEnum incomeRangeEnum = IncomeRangeEnum.UNKNOWN; private IncomeRangeEnum incomeRangeEnum = IncomeRangeEnum.UNKNOWN;
@Column(name = "occupation") @Column(name = "occupation")
private OccupationEnum occupationEnum = OccupationEnum.UNKNOWN; private OccupationEnum occupationEnum = OccupationEnum.UNKNOWN;
@Column(name = "education") @Column(name = "education")
private EducationEnum educationEnum = EducationEnum.UNKNOWN; private EducationEnum educationEnum = EducationEnum.UNKNOWN;
@Column(name = "has_car") @Column(name = "has_car")
private Boolean hasCar = false; private Boolean hasCar = false;
@Column(name = "has_social_security") @Column(name = "has_social_security")
private Boolean hasSocialSecurity = false; private Boolean hasSocialSecurity = false;
@Column(name = "has_house") @Column(name = "has_house")
private Boolean hasHouse = false; private Boolean hasHouse = false;
@Column(name = "has_credit_card") @Column(name = "has_credit_card")
private Boolean hasCreditCard = false; private Boolean hasCreditCard = false;
@Column(name = "marry_status") @Column(name = "marry_status")
private MaritalStatus marryStatus = MaritalStatus.UNKNOWN; private MaritalStatus marryStatus = MaritalStatus.UNKNOWN;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updateAt; private Timestamp updateAt;
} }
...@@ -19,65 +19,65 @@ import java.sql.Timestamp; ...@@ -19,65 +19,65 @@ import java.sql.Timestamp;
@ToString @ToString
public class UserJr58 implements Serializable { public class UserJr58 implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(name = "user_id") @Column(name = "user_id")
private Long userId; private Long userId;
@Column(name = "wb_id") @Column(name = "wb_id")
private String wbId; private String wbId;
@Column(name = "wb_user_name") @Column(name = "wb_user_name")
private String wbUserName; private String wbUserName;
@Column(name = "customer_id") @Column(name = "customer_id")
private String customerId; private String customerId;
@Column(name = "name") @Column(name = "name")
private String name; private String name;
@Column(name = "id_card") @Column(name = "id_card")
private String idcard; private String idcard;
@Column(name = "email") @Column(name = "email")
private String email; private String email;
@Column(name = "phone") @Column(name = "phone")
private String phone; private String phone;
@Column(name = "info") @Column(name = "info")
private String info; private String info;
@Column(name = "role_id") @Column(name = "role_id")
private String roleId; private String roleId;
@Column(name = "flag") @Column(name = "flag")
private String flag; private String flag;
@Column(name = "city") @Column(name = "city")
private String city; private String city;
@Column(name = "access_mode") @Column(name = "access_mode")
private String accessMode; private String accessMode;
@Column(name = "app_id") @Column(name = "app_id")
private String appId; private String appId;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt; private Timestamp createdAt;
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updatedAt; private Timestamp updatedAt;
@Column(name = "edu") @Column(name = "edu")
private String edu; private String edu;
@Column(name = "income") @Column(name = "income")
private String income; private String income;
@Column(name = "marry") @Column(name = "marry")
private String marry; private String marry;
} }
...@@ -17,18 +17,18 @@ import java.io.Serializable; ...@@ -17,18 +17,18 @@ import java.io.Serializable;
@ToString @ToString
public class UuidPhoneMapping implements Serializable { public class UuidPhoneMapping implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column (name = "uuid") @Column(name = "uuid")
private String uuid; private String uuid;
@Column (name = "phone_no") @Column(name = "phone_no")
private String phoneNo; private String phoneNo;
} }
...@@ -13,35 +13,35 @@ import java.sql.Timestamp; ...@@ -13,35 +13,35 @@ import java.sql.Timestamp;
@Entity @Entity
@Table(name = "wechat_userinfo") @Table(name = "wechat_userinfo")
@Data @Data
public class WechatUserInfo implements Serializable{ public class WechatUserInfo implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
@Id @Id
@Column(name = "id") @Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@Column(name = "user_id") @Column(name = "user_id")
private Long userId; private Long userId;
@Column(name = "open_id") @Column(name = "open_id")
private String openId; private String openId;
@Column(name = "phone_no") @Column(name = "phone_no")
private String phoneNo = ""; private String phoneNo = "";
@Column(name = "nick_name") @Column(name = "nick_name")
private String nickName; private String nickName;
@Column(name = "sex") @Column(name = "sex")
private short sex; private short sex;
@Column(name = "language") @Column(name = "language")
private String language; private String language;
@Column(name = "city") @Column(name = "city")
private String city; private String city;
@Column(name = "province") @Column(name = "province")
private String province; private String province;
@Column(name = "country") @Column(name = "country")
private String country; private String country;
@Column(name = "head_img_url") @Column(name = "head_img_url")
private String headImgUrl; private String headImgUrl;
@Column(name = "created_at") @Column(name = "created_at")
private Timestamp createdAt = new Timestamp(System.currentTimeMillis()); private Timestamp createdAt = new Timestamp(System.currentTimeMillis());
@Column(name = "updated_at") @Column(name = "updated_at")
private Timestamp updatedAt = new Timestamp(System.currentTimeMillis()); private Timestamp updatedAt = new Timestamp(System.currentTimeMillis());
} }
...@@ -4,33 +4,33 @@ package cn.quantgroup.xyqb.entity.enumerate; ...@@ -4,33 +4,33 @@ package cn.quantgroup.xyqb.entity.enumerate;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public enum EducationEnum { public enum EducationEnum {
UNKNOWN("暂无"), UNKNOWN("暂无"),
MASTER("硕士及以上"), MASTER("硕士及以上"),
UNDER_GRADUATE("本科"), UNDER_GRADUATE("本科"),
JUNIOR_COLLEGE("大专"), JUNIOR_COLLEGE("大专"),
TECHNICAL_SECONDARY_SCHOOL("中专"), TECHNICAL_SECONDARY_SCHOOL("中专"),
TECHNICAL_SCHOOL("技校"), TECHNICAL_SCHOOL("技校"),
HIGH_SCHOOL("高中"), HIGH_SCHOOL("高中"),
MIDDLE_SCHOOL("初中"), MIDDLE_SCHOOL("初中"),
PRIMARY_SCHOOL("小学"), PRIMARY_SCHOOL("小学"),
OTHER("其他"); OTHER("其他");
private String name; private String name;
EducationEnum(String name) { EducationEnum(String name) {
this.name = name; this.name = name;
} }
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public String getName() { public void setName(String name) {
return name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return name; return name;
} }
} }
...@@ -4,13 +4,13 @@ package cn.quantgroup.xyqb.entity.enumerate; ...@@ -4,13 +4,13 @@ package cn.quantgroup.xyqb.entity.enumerate;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public enum IncomeEnum { public enum IncomeEnum {
UNKNOWN("未知"), UNKNOWN("未知"),
CASH("现金计算"), CASH("现金计算"),
PAY_CARD("工资卡"), PAY_CARD("工资卡"),
CASH_AND_PAY_CARD("混合"); CASH_AND_PAY_CARD("混合");
private String desc; private String desc;
private IncomeEnum(String desc){ private IncomeEnum(String desc) {
this.desc = desc; this.desc = desc;
} }
} }
\ No newline at end of file
...@@ -4,20 +4,20 @@ package cn.quantgroup.xyqb.entity.enumerate; ...@@ -4,20 +4,20 @@ package cn.quantgroup.xyqb.entity.enumerate;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public enum IncomeRangeEnum { public enum IncomeRangeEnum {
UNKNOWN("暂无"), UNKNOWN("暂无"),
BELOW_1000("小于1000元"), BELOW_1000("小于1000元"),
BELOW_3000("1000至3000元"), BELOW_3000("1000至3000元"),
BELOW_5000("3000至5000元"), BELOW_5000("3000至5000元"),
BELOW_8000("5000至8000元"), BELOW_8000("5000至8000元"),
BELOW_10000("8000至10000元"), BELOW_10000("8000至10000元"),
BELOW_15000("10000至15000元"), BELOW_15000("10000至15000元"),
BELOW_20000("15000至20000元"), BELOW_20000("15000至20000元"),
ABOVE_20000("大于20000元"); ABOVE_20000("大于20000元");
private String desc; private String desc;
private IncomeRangeEnum(String desc){ private IncomeRangeEnum(String desc) {
this.desc = desc; this.desc = desc;
} }
} }
...@@ -5,33 +5,33 @@ package cn.quantgroup.xyqb.entity.enumerate; ...@@ -5,33 +5,33 @@ package cn.quantgroup.xyqb.entity.enumerate;
*/ */
public enum MaritalStatus { public enum MaritalStatus {
UNKNOWN("未知"), UNKNOWN("未知"),
SINGLE("未婚"), // 1 SINGLE("未婚"), // 1
MARRIED("已婚"), // 2 MARRIED("已婚"), // 2
DIVORCED("离异"), // 3 DIVORCED("离异"), // 3
WINDOWED("丧偶"), // 4 WINDOWED("丧偶"), // 4
OTHER("其他"); OTHER("其他");
String description; String description;
MaritalStatus(String desc) { MaritalStatus(String desc) {
description = desc; description = desc;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuffer sb = new StringBuffer("MaritalStatus{"); final StringBuffer sb = new StringBuffer("MaritalStatus{");
sb.append("description='").append(description).append('\''); sb.append("description='").append(description).append('\'');
sb.append('}'); sb.append('}');
return sb.toString(); return sb.toString();
} }
} }
...@@ -4,35 +4,35 @@ package cn.quantgroup.xyqb.entity.enumerate; ...@@ -4,35 +4,35 @@ package cn.quantgroup.xyqb.entity.enumerate;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public enum OccupationEnum { public enum OccupationEnum {
UNKNOWN("暂未填写"), UNKNOWN("暂未填写"),
WORKER("工人"), WORKER("工人"),
TEACHER("教师"), TEACHER("教师"),
WHITE_COLLAR("白领"), WHITE_COLLAR("白领"),
STUDENT("学生"), STUDENT("学生"),
CAREER_BUILDER("创业者"), CAREER_BUILDER("创业者"),
SELF_EMPLOYER("个体户"), SELF_EMPLOYER("个体户"),
EMPLOYEE("公司职员"), EMPLOYEE("公司职员"),
BISUNESS_ENTITY("企业法人"), BISUNESS_ENTITY("企业法人"),
ONLINE_STORE_OWNER("网店店主"), ONLINE_STORE_OWNER("网店店主"),
UNEMPLOYED("暂无职业"), UNEMPLOYED("暂无职业"),
OTHER("其他"); OTHER("其他");
private String name; private String name;
OccupationEnum(String name) { OccupationEnum(String name) {
this.name = name; this.name = name;
} }
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public String getName() { public void setName(String name) {
return name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return name; return name;
} }
} }
...@@ -5,35 +5,35 @@ package cn.quantgroup.xyqb.entity.enumerate; ...@@ -5,35 +5,35 @@ package cn.quantgroup.xyqb.entity.enumerate;
*/ */
public enum Relation { public enum Relation {
PARENT("父母"), PARENT("父母"),
CHILDREN("子女"), CHILDREN("子女"),
BROTHER("兄弟姐妹"), BROTHER("兄弟姐妹"),
COLLEAGUE("同事"), COLLEAGUE("同事"),
CLASSMATE("同学"), CLASSMATE("同学"),
FRIEND("朋友"), FRIEND("朋友"),
SPOUSE("夫妻"), SPOUSE("夫妻"),
SELF("本人"), SELF("本人"),
OTHER("其他"); OTHER("其他");
String description; String description;
Relation(String desc) { Relation(String desc) {
description = desc; description = desc;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuffer sb = new StringBuffer("Relation{"); final StringBuffer sb = new StringBuffer("Relation{");
sb.append("description='").append(description).append('\''); sb.append("description='").append(description).append('\'');
sb.append('}'); sb.append('}');
return sb.toString(); return sb.toString();
} }
} }
...@@ -12,12 +12,12 @@ import org.springframework.context.ApplicationEvent; ...@@ -12,12 +12,12 @@ import org.springframework.context.ApplicationEvent;
@ToString @ToString
public class UserinfoChangedEvent extends ApplicationEvent { public class UserinfoChangedEvent extends ApplicationEvent {
private final String uuid; private final String uuid;
private final Long channelId; private final Long channelId;
public UserinfoChangedEvent(Object source, String uuid, Long channelId) { public UserinfoChangedEvent(Object source, String uuid, Long channelId) {
super(source); super(source);
this.uuid = uuid; this.uuid = uuid;
this.channelId = channelId; this.channelId = channelId;
} }
} }
...@@ -15,53 +15,53 @@ import java.util.Map; ...@@ -15,53 +15,53 @@ import java.util.Map;
@Service @Service
public class Jr58DataSender { public class Jr58DataSender {
private static final Logger LOGGER = LoggerFactory.getLogger(Jr58DataSender.class); private static final Logger LOGGER = LoggerFactory.getLogger(Jr58DataSender.class);
@Autowired @Autowired
private Jr58MessageSigner jr58MessageSigner; private Jr58MessageSigner jr58MessageSigner;
@Autowired @Autowired
private IHttpService httpService; private IHttpService httpService;
@Value("${jr58.notify.userinfo}") @Value("${jr58.notify.userinfo}")
private String jr58nNotifyUserinfo; private String jr58nNotifyUserinfo;
/** /**
* 向58金融同步用户信息 * 向58金融同步用户信息
* *
* @param uuid * @param uuid
*/ */
@Async @Async
public void sendUserinfo(String uuid) { public void sendUserinfo(String uuid) {
try { try {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put("salaryWay", 0); json.put("salaryWay", 0);
json.put("loanPurpose", "12"); json.put("loanPurpose", "12");
json.put("job", 0); json.put("job", 0);
json.put("account", 1000); json.put("account", 1000);
json.put("salary", 0); json.put("salary", 0);
json.put("hourse", 1); json.put("hourse", 1);
json.put("isShebao", 0); json.put("isShebao", 0);
json.put("education", ""); json.put("education", "");
json.put("isCreditCard", "0"); json.put("isCreditCard", "0");
json.put("isOtherLoanOrg", "0"); json.put("isOtherLoanOrg", "0");
String userinfo = json.toString(); String userinfo = json.toString();
String param = uuid + "|1|" + userinfo; String param = uuid + "|1|" + userinfo;
String sign = jr58MessageSigner.sign(param); String sign = jr58MessageSigner.sign(param);
Map<String, String> parameters = ImmutableMap.<String, String>builder() Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("customerId", uuid) .put("customerId", uuid)
.put("authorState", "100") .put("authorState", "100")
.put("baseFlag", "1") .put("baseFlag", "1")
.put("userinfo", userinfo) .put("userinfo", userinfo)
.put("sign", sign) .put("sign", sign)
.build(); .build();
httpService.post(jr58nNotifyUserinfo, parameters); httpService.post(jr58nNotifyUserinfo, parameters);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("向58金融同步用户信息", e); LOGGER.error("向58金融同步用户信息", e);
}
} }
}
} }
...@@ -14,33 +14,33 @@ import java.util.Base64; ...@@ -14,33 +14,33 @@ import java.util.Base64;
@Service @Service
public class Jr58MessageSigner { public class Jr58MessageSigner {
private PrivateKey generatedSigningKey; private PrivateKey generatedSigningKey;
@SafeValue("jr58.sign.key") @SafeValue("jr58.sign.key")
private String signingKeySpec; private String signingKeySpec;
@PostConstruct @PostConstruct
private void init() throws Exception { private void init() throws Exception {
if (StringUtils.isEmpty(signingKeySpec)) return; if (StringUtils.isEmpty(signingKeySpec)) return;
byte[] keyBytes = Base64.getDecoder().decode(signingKeySpec); byte[] keyBytes = Base64.getDecoder().decode(signingKeySpec);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeyFactory keyFactory = KeyFactory.getInstance("RSA");
generatedSigningKey = keyFactory.generatePrivate(pkcs8KeySpec); generatedSigningKey = keyFactory.generatePrivate(pkcs8KeySpec);
} }
public String sign(String s) throws Exception { public String sign(String s) throws Exception {
if (generatedSigningKey == null) return ""; if (generatedSigningKey == null) return "";
byte[] data = s.getBytes(); byte[] data = s.getBytes();
Signature signature = Signature.getInstance("MD5withRSA"); Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(generatedSigningKey); signature.initSign(generatedSigningKey);
signature.update(data); signature.update(data);
byte[] signedBytes = signature.sign(); byte[] signedBytes = signature.sign();
return Base64.getEncoder().encodeToString(signedBytes); return Base64.getEncoder().encodeToString(signedBytes);
} }
} }
...@@ -14,29 +14,29 @@ import org.springframework.stereotype.Service; ...@@ -14,29 +14,29 @@ import org.springframework.stereotype.Service;
@Service @Service
public class Jr58Notifier implements ApplicationListener<UserinfoChangedEvent> { public class Jr58Notifier implements ApplicationListener<UserinfoChangedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(Jr58Notifier.class); private static final Logger LOGGER = LoggerFactory.getLogger(Jr58Notifier.class);
@Autowired @Autowired
private Jr58DataSender jr58DataSender; private Jr58DataSender jr58DataSender;
@Autowired @Autowired
private IUserService userService; private IUserService userService;
@Override @Override
public void onApplicationEvent(UserinfoChangedEvent event) { public void onApplicationEvent(UserinfoChangedEvent event) {
LOGGER.info("向58金融同步信息, event:{}", event); LOGGER.info("向58金融同步信息, event:{}", event);
String uuid = event.getUuid(); String uuid = event.getUuid();
Long channelId = event.getChannelId(); Long channelId = event.getChannelId();
if (StringUtils.isEmpty(uuid) || channelId == null || channelId != Constants.Channel.JR58) { if (StringUtils.isEmpty(uuid) || channelId == null || channelId != Constants.Channel.JR58) {
return; return;
} }
User user = userService.findByUuidWithCache(uuid);
if (user == null || user.getRegisteredFrom() != Constants.Channel.JR58) {
return;
}
jr58DataSender.sendUserinfo(uuid); User user = userService.findByUuidWithCache(uuid);
if (user == null || user.getRegisteredFrom() != Constants.Channel.JR58) {
return;
} }
jr58DataSender.sendUserinfo(uuid);
}
} }
...@@ -5,14 +5,14 @@ package cn.quantgroup.xyqb.exception; ...@@ -5,14 +5,14 @@ package cn.quantgroup.xyqb.exception;
*/ */
public class IdCardException extends RuntimeException { public class IdCardException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public IdCardException() { public IdCardException() {
super("非法的身份证号码"); super("非法的身份证号码");
} }
public IdCardException(String message) { public IdCardException(String message) {
super(message); super(message);
} }
} }
...@@ -5,13 +5,13 @@ package cn.quantgroup.xyqb.exception; ...@@ -5,13 +5,13 @@ package cn.quantgroup.xyqb.exception;
*/ */
public class NullUserException extends RuntimeException { public class NullUserException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public NullUserException() { public NullUserException() {
super("未找到用户"); super("未找到用户");
} }
public NullUserException(String message) { public NullUserException(String message) {
super(message); super(message);
} }
} }
...@@ -6,13 +6,13 @@ package cn.quantgroup.xyqb.exception; ...@@ -6,13 +6,13 @@ package cn.quantgroup.xyqb.exception;
*/ */
public class PasswordErrorException extends RuntimeException { public class PasswordErrorException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public PasswordErrorException(String msg, Throwable t) { public PasswordErrorException(String msg, Throwable t) {
super(msg, t); super(msg, t);
} }
public PasswordErrorException(String msg) { public PasswordErrorException(String msg) {
super(msg); super(msg);
} }
} }
...@@ -7,13 +7,13 @@ package cn.quantgroup.xyqb.exception; ...@@ -7,13 +7,13 @@ package cn.quantgroup.xyqb.exception;
*/ */
public class ResponseException extends RuntimeException { public class ResponseException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public ResponseException(String message) { public ResponseException(String message) {
super(message); super(message);
} }
public ResponseException(String message, Throwable cause) { public ResponseException(String message, Throwable cause) {
super(message, cause); super(message, cause);
} }
} }
...@@ -4,9 +4,9 @@ package cn.quantgroup.xyqb.exception; ...@@ -4,9 +4,9 @@ package cn.quantgroup.xyqb.exception;
* Created by Miraculous on 15/7/29. * Created by Miraculous on 15/7/29.
*/ */
public class ResubmissionException extends RuntimeException { public class ResubmissionException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public ResubmissionException() { public ResubmissionException() {
super("不能重复提交表单"); super("不能重复提交表单");
} }
} }
package cn.quantgroup.xyqb.exception; package cn.quantgroup.xyqb.exception;
/** /**
* @author mengfan.feng * @author mengfan.feng
* @time 2015-09-08 17:43 * @time 2015-09-08 17:43
*/ */
public class UserNotExistException extends RuntimeException{ public class UserNotExistException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public UserNotExistException(String msg, Throwable t) { public UserNotExistException(String msg, Throwable t) {
super(msg, t); super(msg, t);
} }
public UserNotExistException(String msg) { public UserNotExistException(String msg) {
super(msg); super(msg);
} }
} }
...@@ -5,14 +5,14 @@ package cn.quantgroup.xyqb.exception; ...@@ -5,14 +5,14 @@ package cn.quantgroup.xyqb.exception;
*/ */
public class VerificationCodeErrorException extends RuntimeException { public class VerificationCodeErrorException extends RuntimeException {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
public VerificationCodeErrorException() { public VerificationCodeErrorException() {
super("验证码错误"); super("验证码错误");
} }
public VerificationCodeErrorException(String message) { public VerificationCodeErrorException(String message) {
super(message); super(message);
} }
} }
...@@ -22,44 +22,42 @@ import java.util.Set; ...@@ -22,44 +22,42 @@ import java.util.Set;
@Configuration @Configuration
public class CrosFilter implements Filter { public class CrosFilter implements Filter {
@Value("${xyqb.filter.allowedOrigin}") private static final Set<String> DISALLOWED_METHOD = new HashSet<>();
private String allowedOrigin;
static {
@Value("${xyqb.filter.allowedHeaders}") DISALLOWED_METHOD.add("OPTIONS");
private String allowedHeaders; DISALLOWED_METHOD.add("PUT");
DISALLOWED_METHOD.add("DELETE");
private static final Set<String> DISALLOWED_METHOD = new HashSet<>(); }
static { @Value("${xyqb.filter.allowedOrigin}")
DISALLOWED_METHOD.add("OPTIONS"); private String allowedOrigin;
DISALLOWED_METHOD.add("PUT"); @Value("${xyqb.filter.allowedHeaders}")
DISALLOWED_METHOD.add("DELETE"); private String allowedHeaders;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", allowedOrigin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Allow-Headers", allowedHeaders);
response.setHeader("Access-Control-Max-Age", "3600");
if (DISALLOWED_METHOD.contains(request.getMethod())) {
return;
} }
filterChain.doFilter(servletRequest, servletResponse);
}
@Override @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) public void destroy() {
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", allowedOrigin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Allow-Headers", allowedHeaders);
response.setHeader("Access-Control-Max-Age", "3600");
if (DISALLOWED_METHOD.contains(request.getMethod())) {
return;
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override }
public void destroy() {
}
} }
...@@ -25,77 +25,84 @@ import java.io.PrintWriter; ...@@ -25,77 +25,84 @@ import java.io.PrintWriter;
@Order(Ordered.HIGHEST_PRECEDENCE + 100) @Order(Ordered.HIGHEST_PRECEDENCE + 100)
public class RequestFilter implements Filter { public class RequestFilter implements Filter {
@Autowired //private static final String[] ALLOWED_PATTERNS = {
private ISessionService sessionService; // "/innerapi/**", "/user/exist", "/motan/**", "/user/register", "/user/login", "/user/register/fast","/auth/info/login",
// "/user/login/fast", "/user/reset_password", "/user/exist_check",
// "/jr58/**", "/app/login", "/app/login_super", "/wechat/**", "/config/**", "/api/**", "/user/exists_token",
// "/platform/api/page/return_url", "/MP_" +
// "verify_AWiagUn4kZiwmTt0.txt"
//};
private static final String[] ALLOWED_PATTERNS = {
"/innerapi/**", "/user/exist", "/motan/**", "/user/register", "/user/login", "/user/register/fast","/auth/info/login",
"/user/login/fast", "/user/reset_password", "/user/exist_check",
"/jr58/**", "/app/login", "/app/login_super", "/wechat/**", "/config/**", "/api/**", "/user/exists_token",
"/platform/api/page/return_url", "/MP_" +
"verify_AWiagUn4kZiwmTt0.txt"
};
private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null));
@Autowired
private ISessionService sessionService;
private AntPathMatcher matcher = new AntPathMatcher();
private AntPathMatcher matcher = new AntPathMatcher(); @Override
private static final String [] ALLOWED_PATTERNS = { public void init(FilterConfig filterConfig) throws ServletException {
"/innerapi/**", "/user/exist","/user/register","/user/login","/user/register/fast", }
"/user/login/fast", "/user/reset_password","/user/exist_check",
"/jr58/**","/app/login","/app/login_super", "/wechat/**", "/config/**","/api/**","/user/exists_token",
"/platform/api/page/return_url", "/MP_verify_AWiagUn4kZiwmTt0.txt"
};
private static final String UNAUTH_RESULT = JSONObject.toJSONString(JsonResult.buildErrorStateResult("登录失败", null));
@Override @Override
public void init(FilterConfig filterConfig) throws ServletException { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
} HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
@Override String requestPath = getRequestPath(request);
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { SessionStruct sessionStruct;
HttpServletRequest request = (HttpServletRequest) servletRequest; if (!isMatch(requestPath)) {
HttpServletResponse response = (HttpServletResponse) servletResponse; //获取session信息,如果没有获取到session信息则返回错误信息
String requestPath = getRequestPath(request); sessionStruct = XyqbSessionContextHolder.getXSession();
SessionStruct sessionStruct; if (sessionStruct == null) {
if(!isMatch(requestPath)){ response.setStatus(401);
//获取session信息,如果没有获取到session信息则返回错误信息 response.setHeader("Content-Type", "application/json;charset=utf-8");
sessionStruct = XyqbSessionContextHolder.getXSession(); PrintWriter writer = response.getWriter();
if(sessionStruct == null) { writer.print(UNAUTH_RESULT);
response.setStatus(401); writer.close();
response.setHeader("Content-Type", "application/json;charset=utf-8"); return;
PrintWriter writer = response.getWriter(); }
writer.print(UNAUTH_RESULT); try {
writer.close(); filterChain.doFilter(request, response);
return; } finally {
} sessionStruct = XyqbSessionContextHolder.getXSession();
try { if (sessionStruct != null) {
filterChain.doFilter(request, response); try {
} finally { sessionService.persistSession(sessionStruct.getSid(), sessionStruct.getValues());
sessionStruct = XyqbSessionContextHolder.getXSession(); } finally {
if (sessionStruct != null) { XyqbSessionContextHolder.releaseSession();
try { }
sessionService.persistSession(sessionStruct.getSid(), sessionStruct.getValues());
} finally {
XyqbSessionContextHolder.releaseSession();
}
}
}
}else {
filterChain.doFilter(request, response);
} }
}
} else {
filterChain.doFilter(request, response);
} }
private boolean isMatch(String path) { }
for (String pattern : ALLOWED_PATTERNS) {
if (matcher.match(pattern, path)) { private boolean isMatch(String path) {
return true; for (String pattern : ALLOWED_PATTERNS) {
} if (matcher.match(pattern, path)) {
} return true;
return false; }
} }
return false;
}
private String getRequestPath(HttpServletRequest request) { private String getRequestPath(HttpServletRequest request) {
String url = request.getServletPath(); String url = request.getServletPath();
if (request.getPathInfo() != null) { if (request.getPathInfo() != null) {
url += request.getPathInfo(); url += request.getPathInfo();
}
return url;
} }
return url;
}
@Override @Override
public void destroy() { public void destroy() {
} }
} }
...@@ -4,5 +4,5 @@ package cn.quantgroup.xyqb.function; ...@@ -4,5 +4,5 @@ package cn.quantgroup.xyqb.function;
* Created by Miraculous on 2016/12/29. * Created by Miraculous on 2016/12/29.
*/ */
public interface NonArgFunction { public interface NonArgFunction {
void apply(); void apply();
} }
...@@ -5,6 +5,6 @@ package cn.quantgroup.xyqb.function; ...@@ -5,6 +5,6 @@ package cn.quantgroup.xyqb.function;
*/ */
public interface OneArgFunction<S> { public interface OneArgFunction<S> {
void apply(S t); void apply(S t);
} }
...@@ -11,45 +11,45 @@ import javax.servlet.http.HttpServletResponse; ...@@ -11,45 +11,45 @@ import javax.servlet.http.HttpServletResponse;
*/ */
public class ChannelIdInterceptor implements HandlerInterceptor { public class ChannelIdInterceptor implements HandlerInterceptor {
private static final String CHANNEL_ID = "channelId"; private static final String CHANNEL_ID = "channelId";
private static final String CREATED_FROM = "createdFrom"; private static final String CREATED_FROM = "createdFrom";
private static final String APP_CHANNEL = "appChannel"; private static final String APP_CHANNEL = "appChannel";
@Override @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String channelId = request.getParameter(CHANNEL_ID); String channelId = request.getParameter(CHANNEL_ID);
if (channelId == null) { if (channelId == null) {
channelId = (String) request.getAttribute(CHANNEL_ID); channelId = (String) request.getAttribute(CHANNEL_ID);
} }
if (channelId != null) { if (channelId != null) {
request.getSession().setAttribute(CHANNEL_ID, channelId); request.getSession().setAttribute(CHANNEL_ID, channelId);
}
String createdFrom = request.getParameter(CREATED_FROM);
if (createdFrom == null) {
createdFrom = (String) request.getAttribute(CREATED_FROM);
}
if (createdFrom != null) {
request.getSession().setAttribute(CREATED_FROM, createdFrom);
}
String appChannel = request.getParameter(APP_CHANNEL);
if (appChannel == null) {
appChannel = (String) request.getAttribute(APP_CHANNEL);
}
if (appChannel != null) {
request.getSession().setAttribute(APP_CHANNEL, appChannel);
}
return true;
} }
@Override String createdFrom = request.getParameter(CREATED_FROM);
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception { if (createdFrom == null) {
createdFrom = (String) request.getAttribute(CREATED_FROM);
}
if (createdFrom != null) {
request.getSession().setAttribute(CREATED_FROM, createdFrom);
}
String appChannel = request.getParameter(APP_CHANNEL);
if (appChannel == null) {
appChannel = (String) request.getAttribute(APP_CHANNEL);
}
if (appChannel != null) {
request.getSession().setAttribute(APP_CHANNEL, appChannel);
} }
return true;
}
@Override @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception { public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
} }
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
}
} }
package cn.quantgroup.xyqb.interceptors;
import cn.quantgroup.xyqb.util.IPUtil;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Created by Administrator on 2017/5/9.
*/
public class IPWhiteListInterceptor implements HandlerInterceptor {
private Integer isDebug;
private static final Logger LOGGER = LoggerFactory.getLogger(IPWhiteListInterceptor.class);
private static final String patternStr = "172.*";
private static final String [] allowIPs = {"139.198.7.123"};
private static Set<String> allowIPSet = Sets.newHashSet(allowIPs);
private static final Pattern pattern = Pattern.compile(patternStr);
public IPWhiteListInterceptor(Integer isDebug) {
this.isDebug = isDebug;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if(isDebug !=0) return true;
String remoteIP = IPUtil.getRemoteIP(request);
if(StringUtils.isNoneBlank(remoteIP)){
remoteIP = remoteIP.trim();
boolean isMatch = pattern.matcher(remoteIP).matches();
isMatch = Boolean.logicalOr(isMatch,allowIPSet.contains(remoteIP));
if(!isMatch){
LOGGER.info("非法IP尝试访问,ip:[{}]",remoteIP);
}
return isMatch;
}
LOGGER.info("未能获取remoteIP");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
...@@ -8,36 +8,36 @@ import lombok.Data; ...@@ -8,36 +8,36 @@ import lombok.Data;
*/ */
@Data @Data
public class AddressRet { public class AddressRet {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
private Long userId; private Long userId;
private Long provinceCode; private Long provinceCode;
private String province; private String province;
private Long cityCode; private Long cityCode;
private String city; private String city;
private Long districtCode; private Long districtCode;
private String district; private String district;
private String address; private String address;
private Long createdAt; private Long createdAt;
private Long updateAt; private Long updateAt;
public static AddressRet address2AddressRet(Address address) { public static AddressRet address2AddressRet(Address address) {
if (address == null) { if (address == null) {
return null; return null;
}
AddressRet ret = new AddressRet();
ret.setId(address.getId());
ret.setUserId(address.getUserId());
ret.setProvinceCode(address.getProvinceCode());
ret.setCityCode(address.getCityCode());
ret.setDistrictCode(address.getDistrictCode());
ret.setDistrict(address.getDistrict());
ret.setProvince(address.getProvince());
ret.setCity(address.getCity());
ret.setAddress(address.getAddress());
ret.setCreatedAt(address.getCreatedAt().getTime());
ret.setUpdateAt(address.getUpdateAt().getTime());
return ret;
} }
AddressRet ret = new AddressRet();
ret.setId(address.getId());
ret.setUserId(address.getUserId());
ret.setProvinceCode(address.getProvinceCode());
ret.setCityCode(address.getCityCode());
ret.setDistrictCode(address.getDistrictCode());
ret.setDistrict(address.getDistrict());
ret.setProvince(address.getProvince());
ret.setCity(address.getCity());
ret.setAddress(address.getAddress());
ret.setCreatedAt(address.getCreatedAt().getTime());
ret.setUpdateAt(address.getUpdateAt().getTime());
return ret;
}
} }
...@@ -12,21 +12,21 @@ import java.io.Serializable; ...@@ -12,21 +12,21 @@ import java.io.Serializable;
@Builder @Builder
public class AppSmsUserParam implements Serializable { public class AppSmsUserParam implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private String errorMsg; private String errorMsg;
private String phoneNo; private String phoneNo;
private Long registerFrom; private Long registerFrom;
private String idNo; private String idNo;
private String name; private String name;
private String ip; private String ip;
private String appChannel; private String appChannel;
private Long channelId; private Long channelId;
} }
package cn.quantgroup.xyqb.model; package cn.quantgroup.xyqb.model;
import lombok.AllArgsConstructor; import lombok.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
...@@ -21,13 +16,13 @@ import java.io.Serializable; ...@@ -21,13 +16,13 @@ import java.io.Serializable;
@Builder @Builder
public class AppUserParam implements Serializable { public class AppUserParam implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private String phoneNo; private String phoneNo;
private Long registerFrom; private Long registerFrom;
private String idNo; private String idNo;
private String name; private String name;
} }
...@@ -7,31 +7,31 @@ import java.security.Principal; ...@@ -7,31 +7,31 @@ import java.security.Principal;
*/ */
public class AuthBean { public class AuthBean {
private String token; private String token;
private String phoneNo; private String phoneNo;
public AuthBean (String token, Principal user) {
this.token = token;
this.phoneNo = user.getName();
}
public AuthBean() { public AuthBean(String token, Principal user) {
this.token = token;
this.phoneNo = user.getName();
}
} public AuthBean() {
public String getPhoneNo() { }
return phoneNo;
}
public void setPhoneNo(String phoneNo) { public String getPhoneNo() {
this.phoneNo = phoneNo; return phoneNo;
} }
public String getToken() { public void setPhoneNo(String phoneNo) {
return token; this.phoneNo = phoneNo;
} }
public void setToken(String token) { public String getToken() {
this.token = token; return token;
} }
public void setToken(String token) {
this.token = token;
}
} }
...@@ -16,39 +16,39 @@ import java.util.List; ...@@ -16,39 +16,39 @@ import java.util.List;
@Data @Data
public class ContactRet implements Serializable { public class ContactRet implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
private Long userId; private Long userId;
private String name; private String name;
private String phoneNo; private String phoneNo;
private Relation relation; private Relation relation;
private Long createdAt; private Long createdAt;
private Long updateAt; private Long updateAt;
public static ContactRet contact2ContactRet (Contact c) { public static ContactRet contact2ContactRet(Contact c) {
if (c == null) { if (c == null) {
return null; return null;
}
ContactRet ret = new ContactRet();
ret.setId(c.getId());
ret.setUserId(c.getUserId());
ret.setName(c.getName());
ret.setPhoneNo(c.getPhoneNo());
ret.setRelation(c.getRelation());
ret.setCreatedAt(c.getCreatedAt().getTime());
ret.setUpdateAt(c.getUpdateAt().getTime());
return ret;
} }
ContactRet ret = new ContactRet();
ret.setId(c.getId());
ret.setUserId(c.getUserId());
ret.setName(c.getName());
ret.setPhoneNo(c.getPhoneNo());
ret.setRelation(c.getRelation());
ret.setCreatedAt(c.getCreatedAt().getTime());
ret.setUpdateAt(c.getUpdateAt().getTime());
return ret;
}
public static List<ContactRet> contacts2ContactRets(List<Contact> cs) { public static List<ContactRet> contacts2ContactRets(List<Contact> cs) {
if (CollectionUtils.isEmpty(cs)) { if (CollectionUtils.isEmpty(cs)) {
return Collections.emptyList(); return Collections.emptyList();
}
List<ContactRet> contactRets = new ArrayList<>();
for (Contact c : cs) {
contactRets.add(contact2ContactRet(c));
}
return contactRets;
} }
List<ContactRet> contactRets = new ArrayList<>();
for (Contact c : cs) {
contactRets.add(contact2ContactRet(c));
}
return contactRets;
}
} }
...@@ -4,26 +4,26 @@ package cn.quantgroup.xyqb.model; ...@@ -4,26 +4,26 @@ package cn.quantgroup.xyqb.model;
* Created by Miraculous on 15/7/10. * Created by Miraculous on 15/7/10.
*/ */
public enum Gender { public enum Gender {
UNKNOWN("未知"), UNKNOWN("未知"),
FEMALE("女"), FEMALE("女"),
MALE("男"); MALE("男");
private String name; private String name;
Gender(String name) { Gender(String name) {
this.name = name; this.name = name;
} }
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public String getName() { public void setName(String name) {
return name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return name; return name;
} }
} }
...@@ -8,58 +8,58 @@ import java.util.Date; ...@@ -8,58 +8,58 @@ import java.util.Date;
*/ */
public class IdCardInfo implements Serializable { public class IdCardInfo implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private String idNo; private String idNo;
private Gender gender; private Gender gender;
private String province; private String province;
private Date birthDate; private Date birthDate;
private boolean isValid; private boolean isValid;
public IdCardInfo() { public IdCardInfo() {
} }
public boolean isValid() { public boolean isValid() {
return isValid; return isValid;
} }
public void setIsValid(boolean isValid) { public void setIsValid(boolean isValid) {
this.isValid = isValid; this.isValid = isValid;
} }
public Date getBirthDate() { public Date getBirthDate() {
return birthDate; return birthDate;
} }
public void setBirthDate(Date birthDate) { public void setBirthDate(Date birthDate) {
this.birthDate = birthDate; this.birthDate = birthDate;
} }
public Gender getGender() { public Gender getGender() {
return gender; return gender;
} }
public void setGender(Gender gender) { public void setGender(Gender gender) {
this.gender = gender; this.gender = gender;
} }
public String getProvince() { public String getProvince() {
return province; return province;
} }
public void setProvince(String province) { public void setProvince(String province) {
this.province = province; this.province = province;
} }
public String getIdNo() { public String getIdNo() {
return idNo; return idNo;
} }
public void setIdNo(String idNo) { public void setIdNo(String idNo) {
this.idNo = idNo; this.idNo = idNo;
} }
} }
...@@ -4,34 +4,34 @@ package cn.quantgroup.xyqb.model; ...@@ -4,34 +4,34 @@ package cn.quantgroup.xyqb.model;
* Created by FrankChow on 15/7/15. * Created by FrankChow on 15/7/15.
*/ */
public enum IdType { public enum IdType {
ID_CARD("身份证"), ID_CARD("身份证"),
HOUSEHOLD_REGISTER("户口薄"), HOUSEHOLD_REGISTER("户口薄"),
PASSPORT("护照"), PASSPORT("护照"),
OFFICER_CARD("军官证"), OFFICER_CARD("军官证"),
SOLDIERS_CARD("士兵证"), SOLDIERS_CARD("士兵证"),
HK_GATE_PASS("港澳居民来往内地通行证"), HK_GATE_PASS("港澳居民来往内地通行证"),
TW_GATE_PASS("台湾同胞来往内地通行证"), TW_GATE_PASS("台湾同胞来往内地通行证"),
TEMP_ID_CARD("临时身份证"), TEMP_ID_CARD("临时身份证"),
FOREIGN_RESIDENCE_PERMIT("外国人居留证"), FOREIGN_RESIDENCE_PERMIT("外国人居留证"),
POLICER_CARD("警官证"), POLICER_CARD("警官证"),
OTHER("其他证件"); OTHER("其他证件");
private String name; private String name;
IdType(String name) { IdType(String name) {
this.name = name; this.name = name;
} }
public void setName(String name) { public String getName() {
this.name = name; return name;
} }
public String getName() { public void setName(String name) {
return name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return name; return name;
} }
} }
...@@ -9,121 +9,121 @@ import java.io.Serializable; ...@@ -9,121 +9,121 @@ import java.io.Serializable;
*/ */
public class JsonResult implements Serializable { public class JsonResult implements Serializable {
private static final Long SUCCESS_CODE = 0L; private static final Long SUCCESS_CODE = 0L;
private static final Long ERROR_STATE_CODE = 1L; private static final Long ERROR_STATE_CODE = 1L;
private static final Long SUCCESS_BUSSINESS_CODE = 0L; private static final Long SUCCESS_BUSSINESS_CODE = 0L;
private static final Long ERROR_BUSSINESS_CODE = 1L; private static final Long ERROR_BUSSINESS_CODE = 1L;
private String msg = ""; private String msg = "";
// 0成功,1失败 // 0成功,1失败
private String code = "0000"; private String code = "0000";
// 业务错误码 // 业务错误码
private String businessCode = "0000"; private String businessCode = "0000";
private Object data = null; private Object data = null;
public JsonResult() { public JsonResult() {
} }
/** /**
* @param msg * @param msg
* @param code * @param code
* @param data * @param data
*/ */
public JsonResult(String msg, Long code, Object data) { public JsonResult(String msg, Long code, Object data) {
this.msg = msg; this.msg = msg;
this.code = String.format(Constants.ZERO_FILL_TEMPLATE, code); this.code = String.format(Constants.ZERO_FILL_TEMPLATE, code);
this.data = data; this.data = data;
} }
public JsonResult(String msg, Long code, Object data, Long businessCode) { public JsonResult(String msg, Long code, Object data, Long businessCode) {
this.msg = msg; this.msg = msg;
this.code = String.format(Constants.ZERO_FILL_TEMPLATE, code); this.code = String.format(Constants.ZERO_FILL_TEMPLATE, code);
this.data = data; this.data = data;
this.businessCode = String.format(Constants.ZERO_FILL_TEMPLATE, businessCode); this.businessCode = String.format(Constants.ZERO_FILL_TEMPLATE, businessCode);
} }
/** public JsonResult(Object data) {
* 构造成功的JsonResult this.data = data;
* }
* @param msg String
* @param data Object /**
* @return JsonResult * 构造成功的JsonResult
*/ *
public static JsonResult buildSuccessResult(String msg, Object data) { * @param msg String
return new JsonResult(msg, SUCCESS_CODE, data, SUCCESS_BUSSINESS_CODE); * @param data Object
} * @return JsonResult
*/
public static JsonResult buildSuccessResult(String msg, Object data, Long bussinessId) { public static JsonResult buildSuccessResult(String msg, Object data) {
return new JsonResult(msg, SUCCESS_CODE, data, bussinessId); return new JsonResult(msg, SUCCESS_CODE, data, SUCCESS_BUSSINESS_CODE);
} }
/** public static JsonResult buildSuccessResult(String msg, Object data, Long bussinessId) {
* 构造状态不正确的JsonResult return new JsonResult(msg, SUCCESS_CODE, data, bussinessId);
* }
* @param msg String
* @param data Object /**
* @return JsonResult * 构造状态不正确的JsonResult
*/ *
public static JsonResult buildErrorStateResult(String msg, Object data) { * @param msg String
return new JsonResult(msg, SUCCESS_CODE, data, ERROR_BUSSINESS_CODE); * @param data Object
} * @return JsonResult
*/
public static JsonResult buildErrorStateResult(String msg, Object data, Long busniessId) { public static JsonResult buildErrorStateResult(String msg, Object data) {
return new JsonResult(msg, SUCCESS_CODE, data, busniessId); return new JsonResult(msg, SUCCESS_CODE, data, ERROR_BUSSINESS_CODE);
} }
public static JsonResult buildFatalErrorStateResult(String msg, Object data, Long busniessId) { public static JsonResult buildErrorStateResult(String msg, Object data, Long busniessId) {
return new JsonResult(msg, ERROR_STATE_CODE, data, busniessId); return new JsonResult(msg, SUCCESS_CODE, data, busniessId);
} }
public JsonResult(Object data) { public static JsonResult buildFatalErrorStateResult(String msg, Object data, Long busniessId) {
this.data = data; return new JsonResult(msg, ERROR_STATE_CODE, data, busniessId);
} }
public String getMsg() { public String getMsg() {
return msg; return msg;
} }
public void setMsg(String msg) { public void setMsg(String msg) {
this.msg = msg; this.msg = msg;
} }
public Object getData() { public Object getData() {
return data; return data;
} }
public void setData(Object data) { public void setData(Object data) {
this.data = data; this.data = data;
} }
public String getCode() { public String getCode() {
return code; return code;
} }
public void setCode(String code) { public void setCode(String code) {
this.code = code; this.code = code;
} }
public String getBusinessCode() { public String getBusinessCode() {
return businessCode; return businessCode;
} }
public void setBusinessCode(String businessCode) { public void setBusinessCode(String businessCode) {
this.businessCode = businessCode; this.businessCode = businessCode;
} }
@Override @Override
public String toString() { public String toString() {
return "JsonResult{" + return "JsonResult{" +
"businessCode='" + businessCode + '\'' + "businessCode='" + businessCode + '\'' +
", code='" + code + '\'' + ", code='" + code + '\'' +
", data=" + data + ", data=" + data +
'}'; '}';
} }
} }
...@@ -7,8 +7,8 @@ import lombok.Data; ...@@ -7,8 +7,8 @@ import lombok.Data;
*/ */
@Data @Data
public class LoginProperties { public class LoginProperties {
private Long channelId = 1L; private Long channelId = 1L;
private Long createdFrom = 1L; private Long createdFrom = 1L;
private String appChannel = ""; private String appChannel = "";
private String merchantName; private String merchantName;
} }
...@@ -5,32 +5,32 @@ package cn.quantgroup.xyqb.model; ...@@ -5,32 +5,32 @@ package cn.quantgroup.xyqb.model;
*/ */
public final class Tuple<Key, Value> { public final class Tuple<Key, Value> {
private Key key; private Key key;
private Value value; private Value value;
public Tuple(Key key, Value value) { public Tuple(Key key, Value value) {
this.key = key; this.key = key;
this.value = value; this.value = value;
} }
public Tuple() { public Tuple() {
} }
public Key getKey() { public Key getKey() {
return key; return key;
} }
public Value getValue() { public void setKey(Key key) {
return value; this.key = key;
} }
public void setKey(Key key) { public Value getValue() {
this.key = key; return value;
} }
public void setValue(Value value) { public void setValue(Value value) {
this.value = value; this.value = value;
} }
} }
...@@ -4,68 +4,68 @@ import cn.quantgroup.xyqb.entity.UserDetail; ...@@ -4,68 +4,68 @@ import cn.quantgroup.xyqb.entity.UserDetail;
import lombok.Data; import lombok.Data;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import java.io.Serializable; import java.io.Serializable;
/** /**
* Created by 11 on 2016/12/20. * Created by 11 on 2016/12/20.
*/ */
@Data @Data
public class UserDetailRet implements Serializable{ public class UserDetailRet implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
private Long userId; private Long userId;
private String phoneNo; private String phoneNo;
private String name; private String name;
//证件号 //证件号
private String idNo; private String idNo;
//0 身份证 1 军官证 2 护照 //0 身份证 1 军官证 2 护照
private IdType idType; private IdType idType;
//身份证验真 0 未认证 1认证 //身份证验真 0 未认证 1认证
private Boolean isAuthenticated = false; private Boolean isAuthenticated = false;
//0 未知 1 女 2 男 //0 未知 1 女 2 男
private Gender gender; private Gender gender;
private String email; private String email;
private String qq; private String qq;
//创建时间 //创建时间
private Long createdAt; private Long createdAt;
//上一次修改时间 //上一次修改时间
private Long updatedAt; private Long updatedAt;
/** /**
* 转换时间从timestamp到long * 转换时间从timestamp到long
* @param userDetail *
* @return return self * @param userDetail
*/ * @return return self
public static UserDetailRet getUserDetail(UserDetail userDetail){ */
long createTimeStamp = userDetail.getCreatedAt().getTime(); public static UserDetailRet getUserDetail(UserDetail userDetail) {
long updateTimeStamp = userDetail.getUpdatedAt().getTime(); long createTimeStamp = userDetail.getCreatedAt().getTime();
UserDetailRet userDetailRet = new UserDetailRet(); long updateTimeStamp = userDetail.getUpdatedAt().getTime();
userDetailRet.setId(userDetail.getId()); UserDetailRet userDetailRet = new UserDetailRet();
userDetailRet.setName(userDetail.getName()); userDetailRet.setId(userDetail.getId());
userDetailRet.setIdNo(userDetail.getIdNo()); userDetailRet.setName(userDetail.getName());
userDetailRet.setPhoneNo(userDetail.getPhoneNo()); userDetailRet.setIdNo(userDetail.getIdNo());
userDetailRet.setEmail(StringUtils.defaultIfEmpty(userDetail.getEmail(), "")); userDetailRet.setPhoneNo(userDetail.getPhoneNo());
userDetailRet.setGender(userDetail.getGender()); userDetailRet.setEmail(StringUtils.defaultIfEmpty(userDetail.getEmail(), ""));
userDetailRet.setIdType(userDetail.getIdType()); userDetailRet.setGender(userDetail.getGender());
userDetailRet.setIsAuthenticated(userDetail.getIsAuthenticated()); userDetailRet.setIdType(userDetail.getIdType());
userDetailRet.setQq(StringUtils.defaultIfEmpty(userDetail.getQq(), "")); userDetailRet.setIsAuthenticated(userDetail.getIsAuthenticated());
userDetailRet.setUserId(userDetail.getUserId()); userDetailRet.setQq(StringUtils.defaultIfEmpty(userDetail.getQq(), ""));
userDetailRet.setCreatedAt(createTimeStamp); userDetailRet.setUserId(userDetail.getUserId());
userDetailRet.setUpdatedAt(updateTimeStamp); userDetailRet.setCreatedAt(createTimeStamp);
return userDetailRet; userDetailRet.setUpdatedAt(updateTimeStamp);
} return userDetailRet;
}
} }
...@@ -4,51 +4,49 @@ import cn.quantgroup.xyqb.entity.UserExtInfo; ...@@ -4,51 +4,49 @@ import cn.quantgroup.xyqb.entity.UserExtInfo;
import cn.quantgroup.xyqb.entity.enumerate.*; import cn.quantgroup.xyqb.entity.enumerate.*;
import lombok.Data; import lombok.Data;
import java.sql.Timestamp;
/** /**
* Created by Miraculous on 2017/2/13. * Created by Miraculous on 2017/2/13.
*/ */
@Data @Data
public class UserExtInfoRet { public class UserExtInfoRet {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
private Long userId; private Long userId;
private IncomeEnum incomeEnum; private IncomeEnum incomeEnum;
private IncomeRangeEnum incomeRangeEnum; private IncomeRangeEnum incomeRangeEnum;
private OccupationEnum occupationEnum; private OccupationEnum occupationEnum;
private EducationEnum educationEnum; private EducationEnum educationEnum;
private boolean hasCar; private boolean hasCar;
private boolean hasSocialSecurity; private boolean hasSocialSecurity;
private boolean hasHouse; private boolean hasHouse;
private boolean hasCreditCard; private boolean hasCreditCard;
private MaritalStatus marryStatus; private MaritalStatus marryStatus;
private Long createdAt; private Long createdAt;
private Long updateAt; private Long updateAt;
private static boolean defaultBoolean(Boolean k) { private static boolean defaultBoolean(Boolean k) {
return k == null ? false : k; return k == null ? false : k;
} }
public static UserExtInfoRet getUserExtInfoRet(UserExtInfo extInfo) { public static UserExtInfoRet getUserExtInfoRet(UserExtInfo extInfo) {
if (extInfo == null) { if (extInfo == null) {
return null; return null;
}
UserExtInfoRet ret = new UserExtInfoRet();
ret.setUserId(extInfo.getUserId());
ret.setId(extInfo.getId());
ret.setIncomeEnum(extInfo.getIncomeEnum());
ret.setIncomeRangeEnum(extInfo.getIncomeRangeEnum());
ret.setOccupationEnum(extInfo.getOccupationEnum());
ret.setEducationEnum(extInfo.getEducationEnum());
ret.setHasCar(defaultBoolean(extInfo.getHasCar()));
ret.setHasSocialSecurity(defaultBoolean(extInfo.getHasSocialSecurity()));
ret.setHasHouse(defaultBoolean(extInfo.getHasHouse()));
ret.setHasCreditCard(defaultBoolean(extInfo.getHasCreditCard()));
ret.setMarryStatus(extInfo.getMarryStatus());
ret.setCreatedAt(extInfo.getCreatedAt().getTime());
ret.setUpdateAt(extInfo.getUpdateAt().getTime());
return ret;
} }
UserExtInfoRet ret = new UserExtInfoRet();
ret.setUserId(extInfo.getUserId());
ret.setId(extInfo.getId());
ret.setIncomeEnum(extInfo.getIncomeEnum());
ret.setIncomeRangeEnum(extInfo.getIncomeRangeEnum());
ret.setOccupationEnum(extInfo.getOccupationEnum());
ret.setEducationEnum(extInfo.getEducationEnum());
ret.setHasCar(defaultBoolean(extInfo.getHasCar()));
ret.setHasSocialSecurity(defaultBoolean(extInfo.getHasSocialSecurity()));
ret.setHasHouse(defaultBoolean(extInfo.getHasHouse()));
ret.setHasCreditCard(defaultBoolean(extInfo.getHasCreditCard()));
ret.setMarryStatus(extInfo.getMarryStatus());
ret.setCreatedAt(extInfo.getCreatedAt().getTime());
ret.setUpdateAt(extInfo.getUpdateAt().getTime());
return ret;
}
} }
...@@ -12,39 +12,39 @@ import java.io.Serializable; ...@@ -12,39 +12,39 @@ import java.io.Serializable;
@Data @Data
public class UserModel implements Serializable { public class UserModel implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
private String name; private String name;
private String phoneNo; private String phoneNo;
private String idNo; private String idNo;
private String gender; private String gender;
private String passwd; private String passwd;
private Long registerFrom; private Long registerFrom;
private String uuid; private String uuid;
public UserModel() { public UserModel() {
} }
public UserModel(User user, UserDetail userDetail) { public UserModel(User user, UserDetail userDetail) {
assert user != null; assert user != null;
this.id = user.getId(); this.id = user.getId();
this.phoneNo = user.getPhoneNo(); this.phoneNo = user.getPhoneNo();
this.registerFrom = user.getRegisteredFrom(); this.registerFrom = user.getRegisteredFrom();
this.passwd = user.getPassword(); this.passwd = user.getPassword();
this.uuid = user.getUuid(); this.uuid = user.getUuid();
if (userDetail != null) { if (userDetail != null) {
this.name = userDetail.getName(); this.name = userDetail.getName();
this.idNo = userDetail.getIdNo(); this.idNo = userDetail.getIdNo();
this.gender = userDetail.getGender().getName(); this.gender = userDetail.getGender().getName();
}
} }
}
} }
...@@ -10,43 +10,43 @@ import java.io.Serializable; ...@@ -10,43 +10,43 @@ import java.io.Serializable;
* Created by 11 on 2016/12/20. * Created by 11 on 2016/12/20.
*/ */
@Data @Data
public class UserRet implements Serializable{ public class UserRet implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private Long id; private Long id;
//手机号 //手机号
private String phoneNo; private String phoneNo;
//uuid //uuid
private String password; private String password;
//第一次用户来源 channel_id //第一次用户来源 channel_id
private Long registeredFrom; private Long registeredFrom;
//uuid //uuid
private String uuid; private String uuid;
private Boolean enable; private Boolean enable;
//创建时间 //创建时间
private Long createdAt; private Long createdAt;
//上一次修改时间 //上一次修改时间
private Long updatedAt; private Long updatedAt;
public static UserRet getUserRet(User user){ public static UserRet getUserRet(User user) {
Long createTimeStamp = user.getCreatedAt().getTime(); Long createTimeStamp = user.getCreatedAt().getTime();
Long updateTimeStamp = user.getUpdatedAt().getTime(); Long updateTimeStamp = user.getUpdatedAt().getTime();
UserRet userRet = new UserRet(); UserRet userRet = new UserRet();
userRet.setId(user.getId()); userRet.setId(user.getId());
userRet.setPhoneNo(user.getPhoneNo()); userRet.setPhoneNo(user.getPhoneNo());
userRet.setEnable(user.getEnable()); userRet.setEnable(user.getEnable());
userRet.setPassword(StringUtils.defaultIfEmpty(user.getPassword(), "")); userRet.setPassword(StringUtils.defaultIfEmpty(user.getPassword(), ""));
userRet.setRegisteredFrom(user.getRegisteredFrom()); userRet.setRegisteredFrom(user.getRegisteredFrom());
userRet.setUuid(user.getUuid()); userRet.setUuid(user.getUuid());
userRet.setCreatedAt(createTimeStamp); userRet.setCreatedAt(createTimeStamp);
userRet.setUpdatedAt(updateTimeStamp); userRet.setUpdatedAt(updateTimeStamp);
return userRet; return userRet;
} }
} }
...@@ -11,245 +11,240 @@ import lombok.ToString; ...@@ -11,245 +11,240 @@ import lombok.ToString;
@Setter @Setter
@ToString @ToString
public class Jr58Authorization { public class Jr58Authorization {
private String userId; private String userId;
private String sourceFrom; private String sourceFrom;
private String authorizationData; private String authorizationData;
private OperatorData operator_data; private OperatorData operator_data;
@Getter
@Setter
public static class OperatorData {
private OriginalData originalData;
private ReportData reportData;
@Getter @Getter
@Setter @Setter
public static class OperatorData{ public static class OriginalData {
private OriginalData originalData; private String phone;
private ReportData reportData; private PhoneData phoneData;
private PhoneBillDataList[] phoneBillDataList;
@Getter private PhoneCallLogList[] phoneCallLogList;
@Setter private PhoneSmsLogList[] phoneSmsLogList;
public static class OriginalData {
private String phone; @Getter
private PhoneData phoneData; @Setter
private PhoneBillDataList[] phoneBillDataList; public static class PhoneData {
private PhoneCallLogList[] phoneCallLogList; private Long id;
private PhoneSmsLogList[] phoneSmsLogList; private String phoneNum;
private String serialNo;
@Getter private String realName;
@Setter private String idCard;
public static class PhoneData{ private String sourceName;
private Long id; private String authorizeChannel;
private String phoneNum; private String createTime;
private String serialNo; private String updateTime;
private String realName; }
private String idCard;
private String sourceName; @Getter
private String authorizeChannel; @Setter
private String createTime; public static class PhoneBillDataList {
private String updateTime; private String localPhone;
} private String totalCost;
private String planCost;
@Getter private String yearMnth;
@Setter private String authorizeChannel;
public static class PhoneBillDataList{ }
private String localPhone;
private String totalCost;
private String planCost; @Getter
private String yearMnth; @Setter
private String authorizeChannel; public static class PhoneCallLogList {
} private String localPhone;
private String callPhone;
private String callId;
@Getter private String cost;
@Setter private String callType;
public static class PhoneCallLogList{ private String callStyle;
private String localPhone; private String callDuration;
private String callPhone; private String callTime;
private String callId; private String callAddress;
private String cost; private String authorizeChannel;
private String callType; }
private String callStyle;
private String callDuration; @Getter
private String callTime; @Setter
private String callAddress; public static class PhoneSmsLogList {
private String authorizeChannel; private String localPhone;
} private String otherPhone;
private String sendId;
@Getter private String totalCost;
@Setter private String sendAddress;
public static class PhoneSmsLogList{ private String sendTime;
private String localPhone; private String authorizeChannel;
private String otherPhone; }
private String sendId;
private String totalCost;
private String sendAddress;
private String sendTime;
private String authorizeChannel;
}
}
@Getter
@Setter
public static class ReportData{
private String localPhone;
private Behavior behavior;
private Check check;
private CallList[] callList;
private ContactList[] contactList;
private OperatorList[] operatorList;
private RegionList[] regionList;
private ServiceList[] serviceList;
private TripConsumeList[] tripConsumeList;
@Getter
@Setter
public static class Behavior{
private String localPhone;
private String friendCircle;
private String localLivingYear;
private String powerOff;
private String callMacao;
private String call110;
private String call120;
private String callLawyer;
private String callCourt;
private String callLoan;
private String callBank;
private String callCredit;
private String useTime;
private String contactAmount;
private String contactFrequency;
private String livingLocation;
private String workingLocation;
private String nightUse;
private String authorizeChannel;
}
@Getter
@Setter
public static class Check{
private String localPhone;
private String idCardValidate;
private String operatorBinding;
private String nameOperatorMatch;
private String idcardOperatorMatch;
private String nameIdcardBlack;
private String namePhoneBlack;
private String callContact;
private String callHome;
private String callWork;
private String authorizeChannel;
}
@Getter
@Setter
public static class CallList{
private String localPhone;
private String phoneNum;
private String attribution;
private String contactName;
private String needsType;
private String callCount;
private String callInCount;
private String callOutCount;
private String callTime;
private String callInTime;
private String callOutTime;
private String relationSpeculate;
private String contact1week;
private String contact1month;
private String contact3month;
private String contact3monthMore;
private String contactEarlyMorning;
private String contactMorning;
private String contactNoon;
private String contactAfternoon;
private String contactNight;
private String contactWeekday;
private String contactWeekend;
private String contactHoliday;
private String contactAllDay;
private String authorizeChannel;
}
@Setter
@Getter
public static class ContactList{
}
@Getter
@Setter
public static class OperatorList{
private String localPhone;
private String operatorName;
private String operatorZh;
private String phoneNum;
private String attribution;
private String mnth;
private String callCount;
private String callInCount;
private String callOutCount;
private String callInTime;
private String callOutTime;
private String flow;
private String smsCount;
private String totalAmount;
private String authorizeChannel;
}
@Getter
@Setter
public static class RegionList{
private String localphone;
private String regionName;
private String numCount;
private String callInCount;
private String callOutCount;
private String callInTime;
private String callOutTime;
private String callInAvg;
private String callOutAvg;
private String callInCountPct;
private String callOutCountPct;
private String callInTimePct;
private String callOutTimePct;
private String authorizeChannel;
}
@Setter
@Getter
public static class ServiceList{
private String localPhone;
private String companyName;
private String companyType;
private String contactTimes;
private String contactMonth;
private String contactTimesMonth;
private String authorizeChannel;
}
@Setter
@Getter
public static class TripConsumeList{
}
}
} }
@Getter
@Setter
public static class ReportData {
private String localPhone;
private Behavior behavior;
private Check check;
private CallList[] callList;
private ContactList[] contactList;
private OperatorList[] operatorList;
private RegionList[] regionList;
private ServiceList[] serviceList;
private TripConsumeList[] tripConsumeList;
@Getter
@Setter
public static class Behavior {
private String localPhone;
private String friendCircle;
private String localLivingYear;
private String powerOff;
private String callMacao;
private String call110;
private String call120;
private String callLawyer;
private String callCourt;
private String callLoan;
private String callBank;
private String callCredit;
private String useTime;
private String contactAmount;
private String contactFrequency;
private String livingLocation;
private String workingLocation;
private String nightUse;
private String authorizeChannel;
}
@Getter
@Setter
public static class Check {
private String localPhone;
private String idCardValidate;
private String operatorBinding;
private String nameOperatorMatch;
private String idcardOperatorMatch;
private String nameIdcardBlack;
private String namePhoneBlack;
private String callContact;
private String callHome;
private String callWork;
private String authorizeChannel;
}
@Getter
@Setter
public static class CallList {
private String localPhone;
private String phoneNum;
private String attribution;
private String contactName;
private String needsType;
private String callCount;
private String callInCount;
private String callOutCount;
private String callTime;
private String callInTime;
private String callOutTime;
private String relationSpeculate;
private String contact1week;
private String contact1month;
private String contact3month;
private String contact3monthMore;
private String contactEarlyMorning;
private String contactMorning;
private String contactNoon;
private String contactAfternoon;
private String contactNight;
private String contactWeekday;
private String contactWeekend;
private String contactHoliday;
private String contactAllDay;
private String authorizeChannel;
}
@Setter
@Getter
public static class ContactList {
}
@Getter
@Setter
public static class OperatorList {
private String localPhone;
private String operatorName;
private String operatorZh;
private String phoneNum;
private String attribution;
private String mnth;
private String callCount;
private String callInCount;
private String callOutCount;
private String callInTime;
private String callOutTime;
private String flow;
private String smsCount;
private String totalAmount;
private String authorizeChannel;
}
@Getter
@Setter
public static class RegionList {
private String localphone;
private String regionName;
private String numCount;
private String callInCount;
private String callOutCount;
private String callInTime;
private String callOutTime;
private String callInAvg;
private String callOutAvg;
private String callInCountPct;
private String callOutCountPct;
private String callInTimePct;
private String callOutTimePct;
private String authorizeChannel;
}
@Setter
@Getter
public static class ServiceList {
private String localPhone;
private String companyName;
private String companyType;
private String contactTimes;
private String contactMonth;
private String contactTimesMonth;
private String authorizeChannel;
}
@Setter
@Getter
public static class TripConsumeList {
}
}
}
} }
...@@ -14,27 +14,27 @@ import lombok.ToString; ...@@ -14,27 +14,27 @@ import lombok.ToString;
@ToString @ToString
public class Jr58RegisterParam { public class Jr58RegisterParam {
private String wbId; // 58官方注册id private String wbId; // 58官方注册id
private String wbUserName; // 58用户名 private String wbUserName; // 58用户名
private String customerId; // 量化派用户id private String customerId; // 量化派用户id
private String name; // 用户姓名 private String name; // 用户姓名
private String idcard; // 身份证号 private String idcard; // 身份证号
private String email; // 用户邮箱 private String email; // 用户邮箱
private String phone; // 手机号码 private String phone; // 手机号码
private String info; // 用户附加信息(用户是学生,那他的学校、专业之类;用户是上班族:公司之类) private String info; // 用户附加信息(用户是学生,那他的学校、专业之类;用户是上班族:公司之类)
private String roleId; // 角色id(用户职业:例如学生、上班族、企业主、网上店主) private String roleId; // 角色id(用户职业:例如学生、上班族、企业主、网上店主)
private String flag; // 是否第一次登陆,第一次登陆:0;非第一次登陆:1,默认0 private String flag; // 是否第一次登陆,第一次登陆:0;非第一次登陆:1,默认0
private String city; // 城市 private String city; // 城市
private String accessMode; // 接入模式,openApi(目前的方式) weixin h5 private String accessMode; // 接入模式,openApi(目前的方式) weixin h5
private String appId; // 客户提供的appId private String appId; // 客户提供的appId
private IdCardInfo idCardInfo; // 证件信息 private IdCardInfo idCardInfo; // 证件信息
private String edu; // 学历 学历:B:硕士及以上 C:本科 D:专科 E::中专、高中 G:初中及以下 private String edu; // 学历 学历:B:硕士及以上 C:本科 D:专科 E::中专、高中 G:初中及以下
private String income; // 收入情况:3000以下:M1 3000~10000 :M2 10000~20000 : M3 20000以上 :M4 private String income; // 收入情况:3000以下:M1 3000~10000 :M2 10000~20000 : M3 20000以上 :M4
private String marry; // 婚姻状况 :A:已婚 B:未婚 C:离异 D:丧偶 private String marry; // 婚姻状况 :A:已婚 B:未婚 C:离异 D:丧偶
private String monitorPhone; // 58监控请求属性,不存 private String monitorPhone; // 58监控请求属性,不存
/**** 授权*****/ /**** 授权*****/
private String account; //授权账号 private String account; //授权账号
private String authorizationType;//授权类型(运营商:1,支付宝:2) private String authorizationType;//授权类型(运营商:1,支付宝:2)
/**** 授权*****/ /**** 授权*****/
} }
...@@ -13,8 +13,8 @@ import lombok.ToString; ...@@ -13,8 +13,8 @@ import lombok.ToString;
@ToString @ToString
public class Jr58RegisterResult { public class Jr58RegisterResult {
private String errorcode; private String errorcode;
private Boolean success; private Boolean success;
private Boolean hasUser; private Boolean hasUser;
private String customerid; private String customerid;
} }
...@@ -8,31 +8,31 @@ import lombok.ToString; ...@@ -8,31 +8,31 @@ import lombok.ToString;
@ToString @ToString
public class BlacklistMatchResult { public class BlacklistMatchResult {
private boolean flag; private boolean flag;
private String status; private String status;
private String errorMsg; private String errorMsg;
public String getErrorMsg() { public String getErrorMsg() {
return errorMsg; return errorMsg;
} }
public void setErrorMsg(String errorMsg) { public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg; this.errorMsg = errorMsg;
} }
public String getStatus() { public String getStatus() {
return status; return status;
} }
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
} }
public boolean getFlag() { public boolean getFlag() {
return flag; return flag;
} }
public void setFlag(boolean flag) { public void setFlag(boolean flag) {
this.flag = flag; this.flag = flag;
} }
} }
package cn.quantgroup.xyqb.model.session; package cn.quantgroup.xyqb.model.session;
import cn.quantgroup.motan.retbean.XLoginInfo;
import cn.quantgroup.xyqb.model.UserRet; import cn.quantgroup.xyqb.model.UserRet;
import com.alibaba.fastjson.JSON;
import lombok.Data; import lombok.Data;
/** /**
...@@ -9,17 +11,25 @@ import lombok.Data; ...@@ -9,17 +11,25 @@ import lombok.Data;
@Data @Data
public class LoginInfo { public class LoginInfo {
private String token; private String token;
private UserRet user; private UserRet user;
private LoginContext loginContext; private LoginContext loginContext;
@Data public static XLoginInfo getXLoginInfo(LoginInfo loginInfo) {
public static class LoginContext { if (null == loginInfo) {
return null;
}
String userJson = JSON.toJSONString(loginInfo);
return JSON.parseObject(userJson, XLoginInfo.class);
}
private Long channelId; @Data
private Long createdFrom; public static class LoginContext {
private String appChannel;
} private Long channelId;
private Long createdFrom;
private String appChannel;
}
} }
...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.model.session; ...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.model.session;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.apache.commons.collections.map.HashedMap;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
...@@ -14,27 +13,27 @@ import java.util.Map; ...@@ -14,27 +13,27 @@ import java.util.Map;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class SessionStruct implements Serializable { public class SessionStruct implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private String sid; private String sid;
private SessionValue values; private SessionValue values;
public void setAttribute(String key, String value) { public void setAttribute(String key, String value) {
if (value == null) { if (value == null) {
value = ""; value = "";
}
Map<String, String> t = values.getValues();
if (t == null) {
t = new HashMap<>();
}
t.put(key, value);
} }
Map<String, String> t = values.getValues();
if (t == null) {
t = new HashMap<>();
}
t.put(key, value);
}
public String getAttribute(String key) { public String getAttribute(String key) {
Map<String, String> t = values.getValues(); Map<String, String> t = values.getValues();
if (t == null) { if (t == null) {
t = new HashMap<>(); t = new HashMap<>();
}
return t.containsKey(key) ? t.get(key) : "";
} }
return t.containsKey(key) ? t.get(key) : "";
}
} }
...@@ -15,15 +15,15 @@ import java.util.Map; ...@@ -15,15 +15,15 @@ import java.util.Map;
*/ */
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class SessionValue{ public class SessionValue {
private User user; private User user;
private Map<String, String> values; private Map<String, String> values;
@JSONField(serializeUsing = Timestamp2LongConverter.class) @JSONField(serializeUsing = Timestamp2LongConverter.class)
private Timestamp createdAt; private Timestamp createdAt;
@JSONField(serializeUsing = Timestamp2LongConverter.class) @JSONField(serializeUsing = Timestamp2LongConverter.class)
private Timestamp lastAccessTime; private Timestamp lastAccessTime;
private LoginProperties loginProperties; private LoginProperties loginProperties;
} }
...@@ -9,13 +9,13 @@ import java.io.Serializable; ...@@ -9,13 +9,13 @@ import java.io.Serializable;
* 微信获取access_token接口的返回值 * 微信获取access_token接口的返回值
*/ */
@Data @Data
public class AccessTokenResponse implements Serializable{ public class AccessTokenResponse implements Serializable {
private static final long serialVersionUID = -1L; private static final long serialVersionUID = -1L;
private String accessToken; private String accessToken;
private Long expiresIn; private Long expiresIn;
private String refreshToken; private String refreshToken;
private String openId; private String openId;
private String scope; private String scope;
private Long initialTime; private Long initialTime;
} }
...@@ -7,5 +7,5 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -7,5 +7,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public interface IAddressRepository extends JpaRepository<Address, Long> { public interface IAddressRepository extends JpaRepository<Address, Long> {
Address findByUserId(Long userId); Address findByUserId(Long userId);
} }
...@@ -9,5 +9,5 @@ import java.util.List; ...@@ -9,5 +9,5 @@ import java.util.List;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public interface IContactRepository extends JpaRepository<Contact, Long> { public interface IContactRepository extends JpaRepository<Contact, Long> {
List<Contact> findByUserId(Long userId); List<Contact> findByUserId(Long userId);
} }
...@@ -6,5 +6,5 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -6,5 +6,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
/** /**
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public interface IMerchantConfigRepository extends JpaRepository<MerchantConfig, Long>{ public interface IMerchantConfigRepository extends JpaRepository<MerchantConfig, Long> {
} }
...@@ -15,15 +15,15 @@ import java.util.List; ...@@ -15,15 +15,15 @@ import java.util.List;
*/ */
public interface IUserDetailRepository extends JpaRepository<UserDetail, Long> { public interface IUserDetailRepository extends JpaRepository<UserDetail, Long> {
UserDetail findByUserId(Long userId); UserDetail findByUserId(Long userId);
UserDetail findByPhoneNo(String phone); UserDetail findByPhoneNo(String phone);
@Transactional @Transactional
@Modifying @Modifying
@Query(value = "update user_detail set qq = ?1 where user_id = ?2", nativeQuery = true) @Query(value = "update user_detail set qq = ?1 where user_id = ?2", nativeQuery = true)
void updateUserQQ(String qq, Long userId); void updateUserQQ(String qq, Long userId);
List<UserDetail> findAll(Specification<UserDetail> specification); List<UserDetail> findAll(Specification<UserDetail> specification);
} }
...@@ -7,6 +7,6 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -7,6 +7,6 @@ import org.springframework.data.jpa.repository.JpaRepository;
* Created by 11 on 2016/12/30. * Created by 11 on 2016/12/30.
*/ */
public interface IUserExtInfoRepository extends JpaRepository<UserExtInfo, Long> { public interface IUserExtInfoRepository extends JpaRepository<UserExtInfo, Long> {
UserExtInfo findByUserId(Long userId); UserExtInfo findByUserId(Long userId);
} }
...@@ -4,14 +4,18 @@ import cn.quantgroup.xyqb.entity.User; ...@@ -4,14 +4,18 @@ import cn.quantgroup.xyqb.entity.User;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
/** /**
* Created by Miraculous on 15/7/4. * Created by Miraculous on 15/7/4.
*/ */
public interface IUserRepository extends JpaRepository<User, Long> ,JpaSpecificationExecutor<User>{ public interface IUserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
User findByPhoneNo(String phoneNo);
User findByPhoneNo(String phoneNo); User findByUuid(String uuid);
User findByUuid(String uuid); List<User> findByIdIn(List<Long> ids);
User findById(Long id); User findById(Long id);
} }
...@@ -6,8 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -6,8 +6,8 @@ import org.springframework.data.jpa.repository.JpaRepository;
/** /**
* Created by Miraculous on 15/10/29. * Created by Miraculous on 15/10/29.
*/ */
public interface IUuidPhoneMappingRepository extends JpaRepository<UuidPhoneMapping, Long>{ public interface IUuidPhoneMappingRepository extends JpaRepository<UuidPhoneMapping, Long> {
UuidPhoneMapping findByUuid(String uuid); UuidPhoneMapping findByUuid(String uuid);
} }
...@@ -8,7 +8,9 @@ import org.springframework.data.jpa.repository.JpaRepository; ...@@ -8,7 +8,9 @@ import org.springframework.data.jpa.repository.JpaRepository;
* Created by 11 on 2017/1/18. * Created by 11 on 2017/1/18.
*/ */
public interface IWeChatUserRepository extends JpaRepository<WechatUserInfo, Long> { public interface IWeChatUserRepository extends JpaRepository<WechatUserInfo, Long> {
WechatUserInfo findByOpenId(String openId); WechatUserInfo findByOpenId(String openId);
WechatUserInfo findByPhoneNo(String phoneNo);
WechatUserInfo findByUserId(Long userId); WechatUserInfo findByPhoneNo(String phoneNo);
WechatUserInfo findByUserId(Long userId);
} }
...@@ -5,5 +5,5 @@ package cn.quantgroup.xyqb.service.api; ...@@ -5,5 +5,5 @@ package cn.quantgroup.xyqb.service.api;
*/ */
public interface IUserApiService { public interface IUserApiService {
boolean userImportCheck(String phoneNo); boolean userImportCheck(String phoneNo);
} }
...@@ -14,26 +14,25 @@ import org.springframework.stereotype.Service; ...@@ -14,26 +14,25 @@ import org.springframework.stereotype.Service;
@Service @Service
public class UserApiServiceImpl implements IUserApiService { public class UserApiServiceImpl implements IUserApiService {
@Autowired @Autowired
private IModelService modelService; private IModelService modelService;
@Autowired @Autowired
private IUserService userService; private IUserService userService;
@Override
public boolean userImportCheck(String phoneNo) {
User user = userService.findByPhoneWithCache(phoneNo);
@Override if (user != null) {
public boolean userImportCheck(String phoneNo) { return false;
User user=userService.findByPhoneWithCache(phoneNo); }
if (user!=null){
return false;
}
BlacklistMatchResult blacklistMatchResult = modelService.getBlacklistMatchResult(phoneNo); BlacklistMatchResult blacklistMatchResult = modelService.getBlacklistMatchResult(phoneNo);
if (blacklistMatchResult == null) { if (blacklistMatchResult == null) {
return true; return true;
}
return !blacklistMatchResult.getFlag();
} }
return !blacklistMatchResult.getFlag();
}
} }
...@@ -6,9 +6,9 @@ package cn.quantgroup.xyqb.service.auth; ...@@ -6,9 +6,9 @@ package cn.quantgroup.xyqb.service.auth;
*/ */
public interface IAuthApiService { public interface IAuthApiService {
String login(String phone, Long loginFrom, String key); String login(String phone, Long loginFrom, String key);
String login(String phone, Long loginFrom, Long channelId, String key); String login(String phone, Long loginFrom, Long channelId, String key);
String login(String phone, Long loginFrom, Long channelId, Long createdFrom, String key); String login(String phone, Long loginFrom, Long channelId, Long createdFrom, String key);
} }
...@@ -9,10 +9,10 @@ import java.text.ParseException; ...@@ -9,10 +9,10 @@ import java.text.ParseException;
*/ */
public interface IIdCardService { public interface IIdCardService {
boolean isIdCardValid(String idCard) throws ParseException; boolean isIdCardValid(String idCard) throws ParseException;
IdCardInfo getIdCardInfo(String idCardStr) throws ParseException; IdCardInfo getIdCardInfo(String idCardStr) throws ParseException;
// 当身份证不合法,直接抛出异常。 // 当身份证不合法,直接抛出异常。
IdCardInfo getIdCardInfoWithExceptions(String idCardStr) throws ParseException; IdCardInfo getIdCardInfoWithExceptions(String idCardStr) throws ParseException;
} }
...@@ -23,54 +23,54 @@ import java.util.Map; ...@@ -23,54 +23,54 @@ import java.util.Map;
@Service @Service
public class AuthApiServiceImpl implements IAuthApiService { public class AuthApiServiceImpl implements IAuthApiService {
@Autowired @Autowired
private IHttpService httpService; private IHttpService httpService;
@Value("${xyqb.auth.url}") @Value("${xyqb.auth.url}")
private String xyqbAuthUrl; private String xyqbAuthUrl;
@Override @Override
public String login(String phone, Long loginFrom, String key) { public String login(String phone, Long loginFrom, String key) {
return this.getToken(phone, loginFrom, 1L, loginFrom, key); return this.getToken(phone, loginFrom, 1L, loginFrom, key);
} }
@Override @Override
public String login(String phone, Long loginFrom, Long channelId, String key) { public String login(String phone, Long loginFrom, Long channelId, String key) {
return this.getToken(phone, loginFrom, channelId, loginFrom, key); return this.getToken(phone, loginFrom, channelId, loginFrom, key);
} }
@Override @Override
public String login(String phone, Long loginFrom, Long channelId, Long createdFrom, String key) { public String login(String phone, Long loginFrom, Long channelId, Long createdFrom, String key) {
return this.getToken(phone, loginFrom, channelId, createdFrom, key); return this.getToken(phone, loginFrom, channelId, createdFrom, key);
} }
/** /**
* 用户免密登录/注册 * 用户免密登录/注册
* *
* @param phone * @param phone
* @return * @return
*/ */
private String getToken(String phone, Long loginFrom, Long channelId, Long createdFrom, String key) { private String getToken(String phone, Long loginFrom, Long channelId, Long createdFrom, String key) {
Map<String, String> parameters = ImmutableMap.<String, String>builder() Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("phoneNo", phone) .put("phoneNo", phone)
.put("registerFrom", loginFrom + "") .put("registerFrom", loginFrom + "")
.put("channelId", channelId + "") .put("channelId", channelId + "")
.put("createdFrom", createdFrom + "") .put("createdFrom", createdFrom + "")
.put("key", key) .put("key", key)
.build(); .build();
String response = httpService.post(xyqbAuthUrl + "/app/login", parameters); String response = httpService.post(xyqbAuthUrl + "/app/login", parameters);
//JsonResult result = GSON.fromJson(response, JsonResult.class); //JsonResult result = GSON.fromJson(response, JsonResult.class);
JsonResult result = JSONObject.parseObject(response, JsonResult.class); JsonResult result = JSONObject.parseObject(response, JsonResult.class);
if (result == null || !"0000".equals(result.getCode()) || !"0000".equals(result.getBusinessCode())) { if (result == null || !"0000".equals(result.getCode()) || !"0000".equals(result.getBusinessCode())) {
throw new ResponseException("用户免密登录返回结果错误"); throw new ResponseException("用户免密登录返回结果错误");
} }
String token = ((Map<String, String>) result.getData()).get("token"); String token = ((Map<String, String>) result.getData()).get("token");
if (StringUtils.isEmpty(token)) { if (StringUtils.isEmpty(token)) {
throw new ResponseException("用户免密登录失败"); throw new ResponseException("用户免密登录失败");
}
return token;
} }
return token;
}
} }
...@@ -20,254 +20,254 @@ import java.util.regex.Pattern; ...@@ -20,254 +20,254 @@ import java.util.regex.Pattern;
@Service @Service
public class IdCardServiceImpl implements IIdCardService { public class IdCardServiceImpl implements IIdCardService {
private String[] validCodes = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"}; private String[] validCodes = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"};
private Map<String, String> areaCodes; private Map<String, String> areaCodes;
private int[] wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; private int[] wi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
private Pattern datePattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))" + private Pattern datePattern = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))" +
"[\\-/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-/\\s]?" + "[\\-/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-/\\s]?" +
"((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-/\\s]?((((0?[13578])|(1[02]))[\\-/\\s]?" + "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-/\\s]?((((0?[13578])|(1[02]))[\\-/\\s]?" +
"((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))" + "((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))" +
"(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(:([0-5]?[0-9])))))?$"); "(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(:([0-5]?[0-9])))))?$");
@PostConstruct @PostConstruct
private void init() { private void init() {
areaCodes = new HashMap<>(); areaCodes = new HashMap<>();
areaCodes.put("11", "北京"); areaCodes.put("11", "北京");
areaCodes.put("12", "天津"); areaCodes.put("12", "天津");
areaCodes.put("13", "河北"); areaCodes.put("13", "河北");
areaCodes.put("14", "山西"); areaCodes.put("14", "山西");
areaCodes.put("15", "内蒙古"); areaCodes.put("15", "内蒙古");
areaCodes.put("21", "辽宁"); areaCodes.put("21", "辽宁");
areaCodes.put("22", "吉林"); areaCodes.put("22", "吉林");
areaCodes.put("23", "黑龙江"); areaCodes.put("23", "黑龙江");
areaCodes.put("31", "上海"); areaCodes.put("31", "上海");
areaCodes.put("32", "江苏"); areaCodes.put("32", "江苏");
areaCodes.put("33", "浙江"); areaCodes.put("33", "浙江");
areaCodes.put("34", "安徽"); areaCodes.put("34", "安徽");
areaCodes.put("35", "福建"); areaCodes.put("35", "福建");
areaCodes.put("36", "江西"); areaCodes.put("36", "江西");
areaCodes.put("37", "山东"); areaCodes.put("37", "山东");
areaCodes.put("41", "河南"); areaCodes.put("41", "河南");
areaCodes.put("42", "湖北"); areaCodes.put("42", "湖北");
areaCodes.put("43", "湖南"); areaCodes.put("43", "湖南");
areaCodes.put("44", "广东"); areaCodes.put("44", "广东");
areaCodes.put("45", "广西"); areaCodes.put("45", "广西");
areaCodes.put("46", "海南"); areaCodes.put("46", "海南");
areaCodes.put("50", "重庆"); areaCodes.put("50", "重庆");
areaCodes.put("51", "四川"); areaCodes.put("51", "四川");
areaCodes.put("52", "贵州"); areaCodes.put("52", "贵州");
areaCodes.put("53", "云南"); areaCodes.put("53", "云南");
areaCodes.put("54", "西藏"); areaCodes.put("54", "西藏");
areaCodes.put("61", "陕西"); areaCodes.put("61", "陕西");
areaCodes.put("62", "甘肃"); areaCodes.put("62", "甘肃");
areaCodes.put("63", "青海"); areaCodes.put("63", "青海");
areaCodes.put("64", "宁夏"); areaCodes.put("64", "宁夏");
areaCodes.put("65", "新疆"); areaCodes.put("65", "新疆");
areaCodes.put("71", "台湾"); areaCodes.put("71", "台湾");
areaCodes.put("81", "香港"); areaCodes.put("81", "香港");
areaCodes.put("82", "澳门"); areaCodes.put("82", "澳门");
areaCodes.put("91", "国外"); areaCodes.put("91", "国外");
} }
@Override
public boolean isIdCardValid(String idCardStr) throws ParseException {
if (idCardStr == null) {
return false;
}
String actualId;
if (idCardStr.length() == 18) {
actualId = idCardStr.substring(0, 17);
} else if (idCardStr.length() == 15) {
actualId = idCardStr.substring(0, 6) + "19" + idCardStr.substring(6, 15);
} else {
return false;
}
if (!StringUtils.isNumeric(actualId)) {
return false;
}
String yearStr = actualId.substring(6, 10); @Override
String monthStr = actualId.substring(10, 12); public boolean isIdCardValid(String idCardStr) throws ParseException {
String dayStr = actualId.substring(12, 14); if (idCardStr == null) {
int year = Integer.parseInt(yearStr); return false;
int month = Integer.parseInt(monthStr); }
int day = Integer.parseInt(dayStr); String actualId;
String dateStr = yearStr + "-" + monthStr + "-" + dayStr; if (idCardStr.length() == 18) {
Matcher matcher = datePattern.matcher(dateStr); actualId = idCardStr.substring(0, 17);
if (!matcher.matches()) { } else if (idCardStr.length() == 15) {
return false; actualId = idCardStr.substring(0, 6) + "19" + idCardStr.substring(6, 15);
} } else {
GregorianCalendar gc = new GregorianCalendar(); return false;
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); }
if (gc.get(Calendar.YEAR) - year > 150 || gc.getTime().getTime() - date.getTime() < 0) { if (!StringUtils.isNumeric(actualId)) {
return false; return false;
}
if (month < 1 || month > 12) {
return false;
}
if (day < 1 || day > 31) {
return false;
}
String areaCode = actualId.substring(0, 2);
if (!areaCodes.containsKey(areaCode)) {
return false;
}
// 校验码
int acurateCode = 0;
for (int i = 0; i < 17; ++i) {
acurateCode += ((actualId.charAt(i) - '0') * wi[i]);
}
actualId += validCodes[acurateCode % 11];
return idCardStr.length() != 18 || actualId.equalsIgnoreCase(idCardStr);
} }
@Override String yearStr = actualId.substring(6, 10);
public IdCardInfo getIdCardInfo(String idCardStr) throws ParseException { String monthStr = actualId.substring(10, 12);
IdCardInfo cardInfo = new IdCardInfo(); String dayStr = actualId.substring(12, 14);
cardInfo.setIsValid(false); int year = Integer.parseInt(yearStr);
if (idCardStr == null) { int month = Integer.parseInt(monthStr);
return cardInfo; int day = Integer.parseInt(dayStr);
} String dateStr = yearStr + "-" + monthStr + "-" + dayStr;
String actualId; Matcher matcher = datePattern.matcher(dateStr);
String lastChar; if (!matcher.matches()) {
if (idCardStr.length() == 18) { return false;
actualId = idCardStr.substring(0, 17); }
lastChar = idCardStr.substring(16, 17).toLowerCase(); GregorianCalendar gc = new GregorianCalendar();
} else if (idCardStr.length() == 15) { Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
actualId = idCardStr.substring(0, 6) + "19" + idCardStr.substring(6, 15); if (gc.get(Calendar.YEAR) - year > 150 || gc.getTime().getTime() - date.getTime() < 0) {
lastChar = idCardStr.substring(13, 14).toLowerCase(); return false;
} else { }
return cardInfo; if (month < 1 || month > 12) {
} return false;
if (!StringUtils.isNumeric(actualId)) { }
return cardInfo; if (day < 1 || day > 31) {
} return false;
String yearStr = actualId.substring(6, 10); }
String monthStr = actualId.substring(10, 12); String areaCode = actualId.substring(0, 2);
String dayStr = actualId.substring(12, 14); if (!areaCodes.containsKey(areaCode)) {
int year = Integer.parseInt(yearStr); return false;
int month = Integer.parseInt(monthStr); }
int day = Integer.parseInt(dayStr); // 校验码
String dateStr = yearStr + "-" + monthStr + "-" + dayStr; int acurateCode = 0;
Matcher matcher = datePattern.matcher(dateStr); for (int i = 0; i < 17; ++i) {
if (!matcher.matches()) { acurateCode += ((actualId.charAt(i) - '0') * wi[i]);
return cardInfo; }
} actualId += validCodes[acurateCode % 11];
GregorianCalendar gc = new GregorianCalendar(); return idCardStr.length() != 18 || actualId.equalsIgnoreCase(idCardStr);
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); }
if (gc.get(Calendar.YEAR) - year > 150 || gc.getTime().getTime() - date.getTime() < 0) {
return cardInfo;
}
if (month < 1 || month > 12) {
return cardInfo;
}
if (day < 1 || day > 31) {
return cardInfo;
}
String areaCode = actualId.substring(0, 2);
if (!areaCodes.containsKey(areaCode)) {
return cardInfo;
}
// 校验码 @Override
int checkCode = 0; public IdCardInfo getIdCardInfo(String idCardStr) throws ParseException {
for (int i = 0; i < 17; ++i) { IdCardInfo cardInfo = new IdCardInfo();
checkCode += ((actualId.charAt(i) - '0') * wi[i]); cardInfo.setIsValid(false);
} if (idCardStr == null) {
actualId += validCodes[checkCode % 11]; return cardInfo;
}
String actualId;
String lastChar;
if (idCardStr.length() == 18) {
actualId = idCardStr.substring(0, 17);
lastChar = idCardStr.substring(16, 17).toLowerCase();
} else if (idCardStr.length() == 15) {
actualId = idCardStr.substring(0, 6) + "19" + idCardStr.substring(6, 15);
lastChar = idCardStr.substring(13, 14).toLowerCase();
} else {
return cardInfo;
}
if (!StringUtils.isNumeric(actualId)) {
return cardInfo;
}
String yearStr = actualId.substring(6, 10);
String monthStr = actualId.substring(10, 12);
String dayStr = actualId.substring(12, 14);
int year = Integer.parseInt(yearStr);
int month = Integer.parseInt(monthStr);
int day = Integer.parseInt(dayStr);
String dateStr = yearStr + "-" + monthStr + "-" + dayStr;
Matcher matcher = datePattern.matcher(dateStr);
if (!matcher.matches()) {
return cardInfo;
}
GregorianCalendar gc = new GregorianCalendar();
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
if (gc.get(Calendar.YEAR) - year > 150 || gc.getTime().getTime() - date.getTime() < 0) {
return cardInfo;
}
if (month < 1 || month > 12) {
return cardInfo;
}
if (day < 1 || day > 31) {
return cardInfo;
}
String areaCode = actualId.substring(0, 2);
if (!areaCodes.containsKey(areaCode)) {
return cardInfo;
}
if (idCardStr.length() == 18) { // 校验码
if (!actualId.equalsIgnoreCase(idCardStr)) { int checkCode = 0;
return cardInfo; for (int i = 0; i < 17; ++i) {
} checkCode += ((actualId.charAt(i) - '0') * wi[i]);
} }
actualId += validCodes[checkCode % 11];
cardInfo.setIsValid(true); if (idCardStr.length() == 18) {
// 判断男女 if (!actualId.equalsIgnoreCase(idCardStr)) {
if (Integer.parseInt(lastChar) % 2 == 0) {
cardInfo.setGender(Gender.FEMALE);
} else {
cardInfo.setGender(Gender.MALE);
}
cardInfo.setIdNo(idCardStr);
cardInfo.setProvince(areaCodes.get(areaCode));
cardInfo.setBirthDate(date);
return cardInfo; return cardInfo;
}
}
cardInfo.setIsValid(true);
// 判断男女
if (Integer.parseInt(lastChar) % 2 == 0) {
cardInfo.setGender(Gender.FEMALE);
} else {
cardInfo.setGender(Gender.MALE);
} }
cardInfo.setIdNo(idCardStr);
cardInfo.setProvince(areaCodes.get(areaCode));
cardInfo.setBirthDate(date);
return cardInfo;
}
@Override @Override
public IdCardInfo getIdCardInfoWithExceptions(String idCardStr) throws ParseException { public IdCardInfo getIdCardInfoWithExceptions(String idCardStr) throws ParseException {
if (idCardStr == null) { if (idCardStr == null) {
throw new IdCardException("身份证号码不能为空"); throw new IdCardException("身份证号码不能为空");
} }
String actualId; String actualId;
String lastValue; String lastValue;
if (idCardStr.length() == 18) { if (idCardStr.length() == 18) {
actualId = idCardStr.substring(0, 17); actualId = idCardStr.substring(0, 17);
lastValue = idCardStr.substring(16, 17).toLowerCase(); lastValue = idCardStr.substring(16, 17).toLowerCase();
} else if (idCardStr.length() == 15) { } else if (idCardStr.length() == 15) {
actualId = idCardStr.substring(0, 6) + "19" + idCardStr.substring(6, 15); actualId = idCardStr.substring(0, 6) + "19" + idCardStr.substring(6, 15);
lastValue = idCardStr.substring(13, 14).toLowerCase(); lastValue = idCardStr.substring(13, 14).toLowerCase();
} else { } else {
throw new IdCardException("身份证号码必须为18位或15位"); throw new IdCardException("身份证号码必须为18位或15位");
} }
if (!StringUtils.isNumeric(actualId)) { if (!StringUtils.isNumeric(actualId)) {
throw new IdCardException("身份证格式不正确"); throw new IdCardException("身份证格式不正确");
} }
String yearStr = actualId.substring(6, 10); String yearStr = actualId.substring(6, 10);
String monthStr = actualId.substring(10, 12); String monthStr = actualId.substring(10, 12);
String dayStr = actualId.substring(12, 14); String dayStr = actualId.substring(12, 14);
int year = Integer.parseInt(yearStr); int year = Integer.parseInt(yearStr);
int month = Integer.parseInt(monthStr); int month = Integer.parseInt(monthStr);
int day = Integer.parseInt(dayStr); int day = Integer.parseInt(dayStr);
String dateStr = yearStr + "-" + monthStr + "-" + dayStr; String dateStr = yearStr + "-" + monthStr + "-" + dayStr;
Matcher matcher = datePattern.matcher(dateStr); Matcher matcher = datePattern.matcher(dateStr);
if (!matcher.matches()) { if (!matcher.matches()) {
throw new IdCardException("身份证出生日期不正确"); throw new IdCardException("身份证出生日期不正确");
} }
GregorianCalendar gc = new GregorianCalendar(); GregorianCalendar gc = new GregorianCalendar();
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr); Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
if (gc.get(Calendar.YEAR) - year > 150 || gc.getTime().getTime() - date.getTime() < 0) { if (gc.get(Calendar.YEAR) - year > 150 || gc.getTime().getTime() - date.getTime() < 0) {
throw new IdCardException("身份证出生年份不正确"); throw new IdCardException("身份证出生年份不正确");
} }
if (month < 1 || month > 12) { if (month < 1 || month > 12) {
throw new IdCardException("身份证出生月份不正确"); throw new IdCardException("身份证出生月份不正确");
} }
if (day < 1 || day > 31) { if (day < 1 || day > 31) {
throw new IdCardException("身份证出生日期不正确"); throw new IdCardException("身份证出生日期不正确");
} }
String areaCode = actualId.substring(0, 2); String areaCode = actualId.substring(0, 2);
if (!areaCodes.containsKey(areaCode)) { if (!areaCodes.containsKey(areaCode)) {
throw new IdCardException("身份证省份不正确"); throw new IdCardException("身份证省份不正确");
} }
// 校验码 // 校验码
int checkCode = 0; int checkCode = 0;
for (int i = 0; i < 17; ++i) { for (int i = 0; i < 17; ++i) {
checkCode += ((actualId.charAt(i) - '0') * wi[i]); checkCode += ((actualId.charAt(i) - '0') * wi[i]);
} }
actualId += validCodes[checkCode % 11]; actualId += validCodes[checkCode % 11];
if (idCardStr.length() == 18) { if (idCardStr.length() == 18) {
if (!actualId.equalsIgnoreCase(idCardStr)) { if (!actualId.equalsIgnoreCase(idCardStr)) {
throw new IdCardException("身份证校验不正确"); throw new IdCardException("身份证校验不正确");
} }
} }
IdCardInfo cardInfo = new IdCardInfo(); IdCardInfo cardInfo = new IdCardInfo();
cardInfo.setIsValid(true); cardInfo.setIsValid(true);
// 判断男女 // 判断男女
if (Integer.parseInt(lastValue) % 2 == 0) { if (Integer.parseInt(lastValue) % 2 == 0) {
cardInfo.setGender(Gender.FEMALE); cardInfo.setGender(Gender.FEMALE);
} else { } else {
cardInfo.setGender(Gender.MALE); cardInfo.setGender(Gender.MALE);
}
cardInfo.setIdNo(idCardStr);
cardInfo.setProvince(areaCodes.get(areaCode));
cardInfo.setBirthDate(date);
return cardInfo;
} }
cardInfo.setIdNo(idCardStr);
cardInfo.setProvince(areaCodes.get(areaCode));
cardInfo.setBirthDate(date);
return cardInfo;
}
} }
...@@ -8,51 +8,57 @@ import java.util.Map; ...@@ -8,51 +8,57 @@ import java.util.Map;
*/ */
public interface IHttpService { public interface IHttpService {
/** /**
* Http Get * Http Get
* @param uri *
* @return * @param uri
*/ * @return
String get(String uri); */
String get(String uri);
/**
* Http Get /**
* @param uri * Http Get
* @param parameters *
* @return * @param uri
*/ * @param parameters
String get(String uri, Map<String, String> parameters); * @return
*/
/** String get(String uri, Map<String, String> parameters);
* Http Get
* @param uri /**
* @param headers * Http Get
* @param parameters *
* @return * @param uri
*/ * @param headers
String get(String uri, Map<String, String> headers, Map<String, String> parameters); * @param parameters
* @return
/** */
* Http Post String get(String uri, Map<String, String> headers, Map<String, String> parameters);
* @param uri
* @return /**
*/ * Http Post
String post(String uri); *
* @param uri
/** * @return
* Http Post */
* @param uri String post(String uri);
* @param parameters
* @return /**
*/ * Http Post
String post(String uri, Map<String, String> parameters); *
* @param uri
/** * @param parameters
* Http Post * @return
* @param uri */
* @param headers String post(String uri, Map<String, String> parameters);
* @param parameters
* @return /**
*/ * Http Post
String post(String uri, Map<String, String> headers, Map<String, String> parameters); *
* @param uri
* @param headers
* @param parameters
* @return
*/
String post(String uri, Map<String, String> headers, Map<String, String> parameters);
} }
...@@ -59,207 +59,207 @@ import java.util.Set; ...@@ -59,207 +59,207 @@ import java.util.Set;
@Service @Service
public class HttpServiceImpl implements IHttpService { public class HttpServiceImpl implements IHttpService {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpServiceImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(HttpServiceImpl.class);
private static final int TIME_OUT = 60 * 1000; // 超时时间 private static final int TIME_OUT = 60 * 1000; // 超时时间
@Override @Override
public String get(String uri) { public String get(String uri) {
return get(uri, null, null); return get(uri, null, null);
} }
@Override @Override
public String get(String uri, Map<String, String> parameters) { public String get(String uri, Map<String, String> parameters) {
return get(uri, null, parameters); return get(uri, null, parameters);
} }
@Override @Override
public String get(String uri, Map<String, String> headers, Map<String, String> parameters) { public String get(String uri, Map<String, String> headers, Map<String, String> parameters) {
return doHttp(RequestBuilder.get(), uri, headers, parameters); return doHttp(RequestBuilder.get(), uri, headers, parameters);
} }
@Override @Override
public String post(String uri) { public String post(String uri) {
return post(uri, null, null); return post(uri, null, null);
} }
@Override @Override
public String post(String uri, Map<String, String> parameters) { public String post(String uri, Map<String, String> parameters) {
return post(uri, null, parameters); return post(uri, null, parameters);
}
@Override
public String post(String uri, Map<String, String> headers, Map<String, String> parameters) {
return doHttp(RequestBuilder.post(), uri, headers, parameters);
}
/**
* Send Http
*
* @param requestBuilder
* @param uri
* @param headers
* @param parameters
* @return
*/
private String doHttp(RequestBuilder requestBuilder, String uri, Map<String, String> headers, Map<String, String> parameters) {
if (StringUtils.isEmpty(uri)) {
LOGGER.info("uri cannot be empty, uri:{}", uri);
return null;
} }
@Override String method = requestBuilder.getMethod();
public String post(String uri, Map<String, String> headers, Map<String, String> parameters) { LOGGER.info("{}, uri:{}, headers:{}, parameters:{}", method, uri, headers, StringUtils.substring(Utils.safeMap2Str(parameters), 0, 200));
return doHttp(RequestBuilder.post(), uri, headers, parameters); HttpEntity httpEntity = null;
} CloseableHttpResponse httpResponse = null;
try {
/** /************** 设置URI **************/
* Send Http requestBuilder.setUri(uri);
*
* @param requestBuilder /************** 公共配置 **************/
* @param uri this.setConfig(requestBuilder);
* @param headers
* @param parameters /************** 设置Header **************/
* @return this.setHeader(requestBuilder, headers);
*/
private String doHttp(RequestBuilder requestBuilder, String uri, Map<String, String> headers, Map<String, String> parameters) { /************** 设置Parameter **************/
if (StringUtils.isEmpty(uri)) { this.setParameter(requestBuilder, parameters, method);
LOGGER.info("uri cannot be empty, uri:{}", uri);
return null; /************** 发送请求 **************/
httpResponse = httpClient().execute(requestBuilder.build());
httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity, Charsets.UTF_8);
LOGGER.info("{}, uri:{}, response:{}", method, uri, StringUtils.substring(response, 0, 200));
return response;
} catch (Exception e) {
LOGGER.info("{}, uri:{}, headers:{}, parameters:{}", method, uri, headers, StringUtils.substring(Utils.safeMap2Str(parameters), 0, 200), e);
return null;
} finally {
EntityUtils.consumeQuietly(httpEntity);
try {
if (httpResponse != null) {
httpResponse.close();
} }
} catch (Exception e) {
String method = requestBuilder.getMethod(); LOGGER.error("{}, httpResponse.close error", method, e);
LOGGER.info("{}, uri:{}, headers:{}, parameters:{}", method, uri, headers, StringUtils.substring(Utils.safeMap2Str(parameters), 0, 200)); }
HttpEntity httpEntity = null;
CloseableHttpResponse httpResponse = null;
try {
/************** 设置URI **************/
requestBuilder.setUri(uri);
/************** 公共配置 **************/
this.setConfig(requestBuilder);
/************** 设置Header **************/
this.setHeader(requestBuilder, headers);
/************** 设置Parameter **************/
this.setParameter(requestBuilder, parameters, method);
/************** 发送请求 **************/
httpResponse = httpClient().execute(requestBuilder.build());
httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity, Charsets.UTF_8);
LOGGER.info("{}, uri:{}, response:{}", method, uri, StringUtils.substring(response, 0, 200));
return response;
} catch (Exception e) {
LOGGER.info("{}, uri:{}, headers:{}, parameters:{}", method, uri, headers, StringUtils.substring(Utils.safeMap2Str(parameters), 0, 200), e);
return null;
} finally {
EntityUtils.consumeQuietly(httpEntity);
try {
if (httpResponse != null) {
httpResponse.close();
}
} catch (Exception e) {
LOGGER.error("{}, httpResponse.close error", method, e);
}
}
}
/**
* Create HttpClient
*
* @return
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public CloseableHttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// socket factory
ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
null, (x509Certificates, authType) -> true).build();
LayeredConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.register("https", sslSocketFactory).build();
// cookie specification
Registry<CookieSpecProvider> cookieSpecProviderRegistry = RegistryBuilder.<CookieSpecProvider>create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
.register("easy", httpContext -> new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
}).build();
// connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(10000);
connectionManager.setDefaultMaxPerRoute(1000);
// retry handler
HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(3, false);
// keep alive strategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
// httpclient
return HttpClients.custom()
.setConnectionManager(connectionManager)
.setRetryHandler(retryHandler)
.setKeepAliveStrategy(keepAliveStrategy)
.setDefaultCookieSpecRegistry(cookieSpecProviderRegistry).build();
} }
}
/**
* Set Parameter /**
* * Create HttpClient
* @param requestBuilder *
* @param parameters * @return
* @param method * @throws KeyStoreException
*/ * @throws NoSuchAlgorithmException
private void setParameter(RequestBuilder requestBuilder, Map<String, String> parameters, String method) { * @throws KeyManagementException
if (MapUtils.isNotEmpty(parameters)) { */
parameters = Maps.filterValues(parameters, Predicates.notNull()); public CloseableHttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// socket factory
Set<Map.Entry<String, String>> entrys = parameters.entrySet(); ConnectionSocketFactory plainSocketFactory = new PlainConnectionSocketFactory();
/************** Get 请求 **************/ SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { null, (x509Certificates, authType) -> true).build();
for (Map.Entry<String, String> entry : entrys) {
requestBuilder.addParameter(entry.getKey(), entry.getValue()); LayeredConnectionSocketFactory sslSocketFactory =
} new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
} Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
/************** Post 请求 **************/ .register("http", plainSocketFactory)
else { .register("https", sslSocketFactory).build();
List<NameValuePair> valuePairs = new ArrayList<>();
for (Map.Entry<String, String> entry : entrys) { // cookie specification
valuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); Registry<CookieSpecProvider> cookieSpecProviderRegistry = RegistryBuilder.<CookieSpecProvider>create()
} .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
requestBuilder.setEntity(new UrlEncodedFormEntity(valuePairs, Charsets.UTF_8)); .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
} .register("easy", httpContext -> new BrowserCompatSpec() {
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
}).build();
// connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(10000);
connectionManager.setDefaultMaxPerRoute(1000);
// retry handler
HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(3, false);
// keep alive strategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
// httpclient
return HttpClients.custom()
.setConnectionManager(connectionManager)
.setRetryHandler(retryHandler)
.setKeepAliveStrategy(keepAliveStrategy)
.setDefaultCookieSpecRegistry(cookieSpecProviderRegistry).build();
}
/**
* Set Parameter
*
* @param requestBuilder
* @param parameters
* @param method
*/
private void setParameter(RequestBuilder requestBuilder, Map<String, String> parameters, String method) {
if (MapUtils.isNotEmpty(parameters)) {
parameters = Maps.filterValues(parameters, Predicates.notNull());
Set<Map.Entry<String, String>> entrys = parameters.entrySet();
/************** Get 请求 **************/
if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
for (Map.Entry<String, String> entry : entrys) {
requestBuilder.addParameter(entry.getKey(), entry.getValue());
} }
} }
/************** Post 请求 **************/
/** else {
* Set Header List<NameValuePair> valuePairs = new ArrayList<>();
* for (Map.Entry<String, String> entry : entrys) {
* @param requestBuilder valuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
* @param headers
*/
public void setHeader(RequestBuilder requestBuilder, Map<String, String> headers) {
requestBuilder.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36")
.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
.setHeader("Connection", "keep-alive");
if (MapUtils.isNotEmpty(headers)) {
headers = Maps.filterValues(headers, Predicates.notNull());
Set<Map.Entry<String, String>> entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
} }
requestBuilder.setEntity(new UrlEncodedFormEntity(valuePairs, Charsets.UTF_8));
}
} }
}
/**
* Request config /**
* * Set Header
* @return *
*/ * @param requestBuilder
private void setConfig(RequestBuilder requestBuilder) { * @param headers
RequestConfig config = RequestConfig.custom() */
.setConnectTimeout(TIME_OUT) public void setHeader(RequestBuilder requestBuilder, Map<String, String> headers) {
.setSocketTimeout(TIME_OUT) requestBuilder.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36")
.setConnectionRequestTimeout(TIME_OUT) .setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
.build(); .setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
.setHeader("Connection", "keep-alive");
requestBuilder.setConfig(config);
if (MapUtils.isNotEmpty(headers)) {
headers = Maps.filterValues(headers, Predicates.notNull());
Set<Map.Entry<String, String>> entrys = headers.entrySet();
for (Map.Entry<String, String> entry : entrys) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
} }
}
/**
* Request config
*
* @return
*/
private void setConfig(RequestBuilder requestBuilder) {
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(TIME_OUT)
.setSocketTimeout(TIME_OUT)
.setConnectionRequestTimeout(TIME_OUT)
.build();
requestBuilder.setConfig(config);
}
} }
...@@ -12,30 +12,31 @@ import java.io.UnsupportedEncodingException; ...@@ -12,30 +12,31 @@ import java.io.UnsupportedEncodingException;
*/ */
public interface Jr58Service { public interface Jr58Service {
/** /**
* 用户注册 * 用户注册
* *
* @param param * @param param
* @return * @return
*/ */
String register(Jr58RegisterParam param); String register(Jr58RegisterParam param);
/** /**
* 避免填写资料 * 避免填写资料
*/ */
void getRidOfFillingProfile(User user,String phoneNo) throws UnsupportedEncodingException; void getRidOfFillingProfile(User user, String phoneNo) throws UnsupportedEncodingException;
/** /**
* 推送授权数据 * 推送授权数据
*/ */
void pushAuthorizationData(Jr58Authorization authorizationData); void pushAuthorizationData(Jr58Authorization authorizationData);
/** /**
* 推送授权开始的状态 * 推送授权开始的状态
* @param userId *
* @param account * @param userId
* @param authorizationType * @param account
*/ * @param authorizationType
void pushAuthorizationStatus(String userId,String account,String authorizationType); */
void pushAuthorizationStatus(String userId, String account, String authorizationType);
} }
...@@ -6,7 +6,6 @@ import cn.quantgroup.xyqb.entity.UserDetail; ...@@ -6,7 +6,6 @@ import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.entity.UserJr58; import cn.quantgroup.xyqb.entity.UserJr58;
import cn.quantgroup.xyqb.model.IdCardInfo; import cn.quantgroup.xyqb.model.IdCardInfo;
import cn.quantgroup.xyqb.model.IdType; import cn.quantgroup.xyqb.model.IdType;
import cn.quantgroup.xyqb.model.JsonResult;
import cn.quantgroup.xyqb.model.jr58.Jr58Authorization; import cn.quantgroup.xyqb.model.jr58.Jr58Authorization;
import cn.quantgroup.xyqb.model.jr58.Jr58RegisterParam; import cn.quantgroup.xyqb.model.jr58.Jr58RegisterParam;
import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult; import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult;
...@@ -18,15 +17,12 @@ import cn.quantgroup.xyqb.service.http.IHttpService; ...@@ -18,15 +17,12 @@ import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.jr58.Jr58Service; import cn.quantgroup.xyqb.service.jr58.Jr58Service;
import cn.quantgroup.xyqb.service.user.ILkbUserService; import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.util.GZipUtil; import cn.quantgroup.xyqb.util.GZipUtil;
import cn.quantgroup.xyqb.util.PasswordUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -45,248 +41,247 @@ import java.util.Map; ...@@ -45,248 +41,247 @@ import java.util.Map;
@Service @Service
public class Jr58ServiceImpl implements Jr58Service { public class Jr58ServiceImpl implements Jr58Service {
private static final Logger LOGGER = LoggerFactory.getLogger(Jr58ServiceImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(Jr58ServiceImpl.class);
@Autowired @Autowired
private ILkbUserService lkbUserService; private ILkbUserService lkbUserService;
@Autowired @Autowired
private IUserJr58Repository userJr58Repository; private IUserJr58Repository userJr58Repository;
@Autowired @Autowired
private IHttpService httpService; private IHttpService httpService;
@Value("${xyqb.api.url}") @Value("${xyqb.api.url}")
private String apiUrl; private String apiUrl;
@Value("${lkb.import.url}") @Value("${lkb.import.url}")
private String pushImportForJr58Url; private String pushImportForJr58Url;
@Autowired @Autowired
private IUserRepository userRepository; private IUserRepository userRepository;
@Autowired @Autowired
private IUserDetailRepository userDetailRepository; private IUserDetailRepository userDetailRepository;
@Autowired @Autowired
private IIdCardService idCardService; private IIdCardService idCardService;
@Override @Override
@Transactional(value = Transactional.TxType.REQUIRED) @Transactional(value = Transactional.TxType.REQUIRED)
public String register(Jr58RegisterParam param) { public String register(Jr58RegisterParam param) {
String uuid; String uuid;
User user = userRepository.findByPhoneNo(param.getPhone()); User user = userRepository.findByPhoneNo(param.getPhone());
/***************** 用户是否在新系统存在 ********************/ /***************** 用户是否在新系统存在 ********************/
if (user != null) { if (user != null) {
uuid = user.getUuid(); uuid = user.getUuid();
return uuid; return uuid;
} }
/***************** 向老系统注册用户 ********************/ /***************** 向老系统注册用户 ********************/
Jr58RegisterResult result = lkbUserService.registerJr58(param); Jr58RegisterResult result = lkbUserService.registerJr58(param);
if (result == null || !"0".equals(result.getErrorcode())) { if (result == null || !"0".equals(result.getErrorcode())) {
LOGGER.warn("向LKB注册58金融用户失败, param:{}", param); LOGGER.warn("向LKB注册58金融用户失败, param:{}", param);
return ""; return "";
} }
/***************** 用户已经在老系统存在 ********************/ /***************** 用户已经在老系统存在 ********************/
uuid = result.getCustomerid(); uuid = result.getCustomerid();
/*if (result.getHasUser()) { /*if (result.getHasUser()) {
LOGGER.info("该用户已经在LKB系统中存在, uuid:{}", uuid); LOGGER.info("该用户已经在LKB系统中存在, uuid:{}", uuid);
return uuid; return uuid;
}*/ }*/
/***************** 新用户 ********************/ /***************** 新用户 ********************/
LOGGER.info("Save User:{}", uuid); LOGGER.info("Save User:{}", uuid);
user = this.saveUser(param, uuid); user = this.saveUser(param, uuid);
if (user == null) { if (user == null) {
throw new RuntimeException("保存用户信息出错"); throw new RuntimeException("保存用户信息出错");
}
LOGGER.info("Save UserDetail:{}", user.getId());
this.saveUserDetail(param, user.getId());
LOGGER.info("Save UserJr58:{}", user.getId());
this.saveUserJr58(param, user.getId());
LOGGER.info("用户注册成功, registerFrom:{}, phoneNo:{}", Constants.Channel.JR58, param.getPhone());
return uuid;
} }
LOGGER.info("Save UserDetail:{}", user.getId());
this.saveUserDetail(param, user.getId());
@Override LOGGER.info("Save UserJr58:{}", user.getId());
public void getRidOfFillingProfile(User user,String phoneNo) throws UnsupportedEncodingException { this.saveUserJr58(param, user.getId());
if (user == null) {
LOGGER.info("58用户不存在");
return;
}
Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("userId", user.getId().toString())
.put("key", "abc1234")
.put("phoneNo", phoneNo)
.build();
LOGGER.info("调用58保存用户贷款信息接口开始");
httpService.get(apiUrl + "/ex/auth-58/info", parameters);
LOGGER.info("调用58保存用户贷款信息接口结束");
}
/** LOGGER.info("用户注册成功, registerFrom:{}, phoneNo:{}", Constants.Channel.JR58, param.getPhone());
* Save UserJr58 return uuid;
* }
* @param param
* @param userId
*/
private void saveUserJr58(Jr58RegisterParam param, Long userId) {
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
UserJr58 userJr58 = new UserJr58(); @Override
userJr58.setUserId(userId); public void getRidOfFillingProfile(User user, String phoneNo) throws UnsupportedEncodingException {
userJr58.setWbId(param.getWbId()); if (user == null) {
userJr58.setWbUserName(param.getWbUserName()); LOGGER.info("58用户不存在");
userJr58.setCustomerId(param.getCustomerId()); return;
userJr58.setName(param.getName());
userJr58.setIdcard(param.getIdcard());
userJr58.setEmail(StringUtils.substring(param.getEmail(), 0, 50));
userJr58.setPhone(param.getPhone());
userJr58.setInfo(param.getInfo());
userJr58.setRoleId(param.getRoleId());
userJr58.setFlag(param.getFlag());
userJr58.setCity(param.getCity());
userJr58.setAccessMode(param.getAccessMode());
userJr58.setAppId(param.getAppId());
userJr58.setCreatedAt(currentTime);
userJr58.setUpdatedAt(currentTime);
userJr58.setEdu(param.getEdu());
userJr58.setIncome(param.getIncome());
userJr58.setMarry(param.getMarry());
userJr58Repository.saveAndFlush(userJr58);
} }
Map<String, String> parameters = ImmutableMap.<String, String>builder()
/** .put("userId", user.getId().toString())
* Save UserDetail .put("key", "abc1234")
* .put("phoneNo", phoneNo)
* @param param .build();
* @param userId LOGGER.info("调用58保存用户贷款信息接口开始");
*/ httpService.get(apiUrl + "/ex/auth-58/info", parameters);
private void saveUserDetail(Jr58RegisterParam param, Long userId) { LOGGER.info("调用58保存用户贷款信息接口结束");
Timestamp currentTime = new Timestamp(System.currentTimeMillis()); }
IdCardInfo idCardInfo = param.getIdCardInfo();
UserDetail userDetail = new UserDetail(); /**
userDetail.setUserId(userId); * Save UserJr58
userDetail.setName(param.getName()); *
userDetail.setPhoneNo(param.getPhone()); * @param param
userDetail.setIdNo(param.getIdcard()); * @param userId
Timestamp time = new Timestamp(System.currentTimeMillis()); */
userDetail.setCreatedAt(time); private void saveUserJr58(Jr58RegisterParam param, Long userId) {
userDetail.setUpdatedAt(time); Timestamp currentTime = new Timestamp(System.currentTimeMillis());
userDetail.setIdType(IdType.ID_CARD);
try { UserJr58 userJr58 = new UserJr58();
userDetail.setGender(idCardService.getIdCardInfo(param.getIdcard()).getGender()); userJr58.setUserId(userId);
} catch (ParseException e) { userJr58.setWbId(param.getWbId());
LOGGER.error("根据身份证获取性别出错,错误信息:" + e); userJr58.setWbUserName(param.getWbUserName());
} userJr58.setCustomerId(param.getCustomerId());
userDetail.setEmail(StringUtils.substring(param.getEmail(), 0, 30)); userJr58.setName(param.getName());
userDetailRepository.saveAndFlush(userDetail); userJr58.setIdcard(param.getIdcard());
userJr58.setEmail(StringUtils.substring(param.getEmail(), 0, 50));
userJr58.setPhone(param.getPhone());
userJr58.setInfo(param.getInfo());
userJr58.setRoleId(param.getRoleId());
userJr58.setFlag(param.getFlag());
userJr58.setCity(param.getCity());
userJr58.setAccessMode(param.getAccessMode());
userJr58.setAppId(param.getAppId());
userJr58.setCreatedAt(currentTime);
userJr58.setUpdatedAt(currentTime);
userJr58.setEdu(param.getEdu());
userJr58.setIncome(param.getIncome());
userJr58.setMarry(param.getMarry());
userJr58Repository.saveAndFlush(userJr58);
}
/**
* Save UserDetail
*
* @param param
* @param userId
*/
private void saveUserDetail(Jr58RegisterParam param, Long userId) {
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
IdCardInfo idCardInfo = param.getIdCardInfo();
UserDetail userDetail = new UserDetail();
userDetail.setUserId(userId);
userDetail.setName(param.getName());
userDetail.setPhoneNo(param.getPhone());
userDetail.setIdNo(param.getIdcard());
Timestamp time = new Timestamp(System.currentTimeMillis());
userDetail.setCreatedAt(time);
userDetail.setUpdatedAt(time);
userDetail.setIdType(IdType.ID_CARD);
try {
userDetail.setGender(idCardService.getIdCardInfo(param.getIdcard()).getGender());
} catch (ParseException e) {
LOGGER.error("根据身份证获取性别出错,错误信息:" + e);
} }
userDetail.setEmail(StringUtils.substring(param.getEmail(), 0, 30));
/** userDetailRepository.saveAndFlush(userDetail);
* Save User }
*
* @param param /**
* @param uuid * Save User
*/ *
private User saveUser(Jr58RegisterParam param, String uuid) { * @param param
Timestamp currentTime = new Timestamp(System.currentTimeMillis()); * @param uuid
User user = new User(); */
user.setPhoneNo(param.getPhone()); private User saveUser(Jr58RegisterParam param, String uuid) {
user.setCreatedAt(currentTime); Timestamp currentTime = new Timestamp(System.currentTimeMillis());
user.setUpdatedAt(currentTime); User user = new User();
user.setEnable(true); user.setPhoneNo(param.getPhone());
user.setRegisteredFrom(Constants.Channel.JR58); user.setCreatedAt(currentTime);
user.setUuid(uuid); user.setUpdatedAt(currentTime);
user.setPassword(""); user.setEnable(true);
user = userRepository.save(user); user.setRegisteredFrom(Constants.Channel.JR58);
return userRepository.saveAndFlush(user); user.setUuid(uuid);
user.setPassword("");
user = userRepository.save(user);
return userRepository.saveAndFlush(user);
}
/**
* 推送授权数据
*/
@Async
public void pushAuthorizationData(Jr58Authorization authorizationData) {
LOGGER.info("运营商授权数据推送到lkb开始");
Map<String, String> parameters = null;
String url = "";
//量化派数据
if ("0".equals(authorizationData.getSourceFrom())) {
parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("loginName", authorizationData.getOperator_data().getOriginalData().getPhone())
.put("currentUser", authorizationData.getUserId())
.put("userSource", "YUNYINGSHANG")
.build();
url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
} else if ("1".equals(authorizationData.getSourceFrom())) {
//读秒数据
//String graspingJson = Constants.GSON.toJson(authorizationData.getOperator_data());
String graspingJson = JSONObject.toJSONString(authorizationData.getOperator_data());
byte[] graspingJsonBytes = GZipUtil.compressToByte(graspingJson);
String authorizationDataStr = Base64.getEncoder().encodeToString(graspingJsonBytes);
parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("data", authorizationDataStr)
.put("currentUser", authorizationData.getUserId())
.put("source", "58")
.build();
url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/receive.json";
} }
for (int i = 0; i < 4; i++) {
try {
String response = httpService.post(url, parameters);
/** if (response.contains(",\"status\":1,")) {
* 推送授权数据 LOGGER.info("运营商授权数据推送到lkb成功");
*/ break;
@Async } else {
public void pushAuthorizationData(Jr58Authorization authorizationData) { Thread.sleep(2000);
LOGGER.info("运营商授权数据推送到lkb开始"); LOGGER.error("运营商授权数据推送到lkb中失败 - {} ,userId ={}, response = {} url ={}", i + 1, authorizationData.getUserId(), response, url);
Map<String, String> parameters = null;
String url = "";
//量化派数据
if("0".equals(authorizationData.getSourceFrom())){
parameters = ImmutableMap.<String, String>builder()
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
.put("loginName", authorizationData.getOperator_data().getOriginalData().getPhone())
.put("currentUser", authorizationData.getUserId())
.put("userSource", "YUNYINGSHANG")
.build();
url= pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
}else if("1".equals(authorizationData.getSourceFrom())){
//读秒数据
//String graspingJson = Constants.GSON.toJson(authorizationData.getOperator_data());
String graspingJson = JSONObject.toJSONString(authorizationData.getOperator_data());
byte[] graspingJsonBytes = GZipUtil.compressToByte(graspingJson);
String authorizationDataStr = Base64.getEncoder().encodeToString(graspingJsonBytes);
parameters = ImmutableMap.<String, String>builder()
.put("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
.put("data", authorizationDataStr)
.put("currentUser", authorizationData.getUserId())
.put("source", "58")
.build();
url= pushImportForJr58Url + "/SpiderServer/api/dataTransfer/receive.json";
}
for (int i = 0; i <4 ; i++) {
try {
String response = httpService.post(url, parameters);
if(response.contains(",\"status\":1,")){
LOGGER.info("运营商授权数据推送到lkb成功");
break;
}else{
Thread.sleep(2000);
LOGGER.error("运营商授权数据推送到lkb中失败 - {} ,userId ={}, response = {} url ={}", i+1, authorizationData.getUserId(),response,url);
}
}catch (InterruptedException e) {
LOGGER.error("运营商授权数据推送到失败 url ={}", url);
}
} }
} catch (InterruptedException e) {
LOGGER.info("运营商授权数据推送到lkb结束"); LOGGER.error("运营商授权数据推送到失败 url ={}", url);
}
} }
@Async LOGGER.info("运营商授权数据推送到lkb结束");
@Override
public void pushAuthorizationStatus(String userId, String account, String authorizationType) { }
LOGGER.info("通知lkb授权成功- 开始");
Map<String, String> parameters = ImmutableMap.<String, String>builder() @Async
.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") @Override
.put("loginName", account) public void pushAuthorizationStatus(String userId, String account, String authorizationType) {
.put("currentUser",userId) LOGGER.info("通知lkb授权成功- 开始");
.put("userSource", "YUNYINGSHANG") Map<String, String> parameters = ImmutableMap.<String, String>builder()
.build(); .put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
String url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json"; .put("loginName", account)
for (int i = 0; i <4 ; i++) { .put("currentUser", userId)
try { .put("userSource", "YUNYINGSHANG")
String response = httpService.post(url, parameters); .build();
if(response.contains(",\"status\":1,")){ String url = pushImportForJr58Url + "/SpiderServer/api/dataTransfer/saveUserAuthInfo.json";
LOGGER.info("通知lkb授权成功"); for (int i = 0; i < 4; i++) {
break; try {
}else{ String response = httpService.post(url, parameters);
Thread.sleep(2000); if (response.contains(",\"status\":1,")) {
LOGGER.error("通知lkb授权失败 - {} ,userId ={}, response = {} url ={}", i+1, userId,response,url); LOGGER.info("通知lkb授权成功");
} break;
}catch (InterruptedException e) { } else {
LOGGER.error("通知lkb授权失败 url ={}", url); Thread.sleep(2000);
} LOGGER.error("通知lkb授权失败 - {} ,userId ={}, response = {} url ={}", i + 1, userId, response, url);
} }
LOGGER.info("通知lkb授权- 结束"); } catch (InterruptedException e) {
LOGGER.error("通知lkb授权失败 url ={}", url);
}
} }
LOGGER.info("通知lkb授权- 结束");
}
} }
...@@ -7,9 +7,9 @@ import cn.quantgroup.xyqb.entity.MerchantConfig; ...@@ -7,9 +7,9 @@ import cn.quantgroup.xyqb.entity.MerchantConfig;
* Created by Miraculous on 2017/1/3. * Created by Miraculous on 2017/1/3.
*/ */
public interface IMerchantService { public interface IMerchantService {
MerchantConfig findConfigByMerchantIdAndConfigName(Long merchantId, String configName); MerchantConfig findConfigByMerchantIdAndConfigName(Long merchantId, String configName);
Merchant findMerchantById(Long merchantId); Merchant findMerchantById(Long merchantId);
Merchant findMerchantByName(String name); Merchant findMerchantByName(String name);
} }
...@@ -19,45 +19,45 @@ import java.util.concurrent.ConcurrentHashMap; ...@@ -19,45 +19,45 @@ import java.util.concurrent.ConcurrentHashMap;
@Service @Service
public class MerchantServiceImpl implements IMerchantService { public class MerchantServiceImpl implements IMerchantService {
private static final ConcurrentHashMap<String, Merchant> MERCHANT_NAME_MAP = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, Merchant> MERCHANT_NAME_MAP = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Long, Merchant> MERCHANT_ID_MAP = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<Long, Merchant> MERCHANT_ID_MAP = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, MerchantConfig> MERCHANT_ID_CONFIG_MAP = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, MerchantConfig> MERCHANT_ID_CONFIG_MAP = new ConcurrentHashMap<>();
@Autowired @Autowired
private IMerchantRepository merchantRepository; private IMerchantRepository merchantRepository;
@Autowired @Autowired
private IMerchantConfigRepository merchantConfigRepository; private IMerchantConfigRepository merchantConfigRepository;
@PostConstruct @PostConstruct
private void init() { private void init() {
List<Merchant> merchantList = merchantRepository.findAll(); List<Merchant> merchantList = merchantRepository.findAll();
List<MerchantConfig> merchantConfigList = merchantConfigRepository.findAll(); List<MerchantConfig> merchantConfigList = merchantConfigRepository.findAll();
merchantList.forEach(m -> { merchantList.forEach(m -> {
MERCHANT_NAME_MAP.put(m.getName(), m); MERCHANT_NAME_MAP.put(m.getName(), m);
MERCHANT_ID_MAP.put(m.getId(), m); MERCHANT_ID_MAP.put(m.getId(), m);
}); });
merchantConfigList.forEach(m -> MERCHANT_ID_CONFIG_MAP.put(m.getMerchantId() + "_" + m.getConfigName(), m)); merchantConfigList.forEach(m -> MERCHANT_ID_CONFIG_MAP.put(m.getMerchantId() + "_" + m.getConfigName(), m));
} }
@Override @Override
public MerchantConfig findConfigByMerchantIdAndConfigName(Long merchantId, String configName) { public MerchantConfig findConfigByMerchantIdAndConfigName(Long merchantId, String configName) {
String key = merchantId + "_" + configName; String key = merchantId + "_" + configName;
return MERCHANT_ID_CONFIG_MAP.containsKey(key) ? MERCHANT_ID_CONFIG_MAP.get(key) : null; return MERCHANT_ID_CONFIG_MAP.containsKey(key) ? MERCHANT_ID_CONFIG_MAP.get(key) : null;
} }
@Override @Override
public Merchant findMerchantById(Long merchantId) { public Merchant findMerchantById(Long merchantId) {
return MERCHANT_ID_MAP.containsKey(merchantId) ? MERCHANT_ID_MAP.get(merchantId) : null; return MERCHANT_ID_MAP.containsKey(merchantId) ? MERCHANT_ID_MAP.get(merchantId) : null;
} }
@Override @Override
public Merchant findMerchantByName(String name) { public Merchant findMerchantByName(String name) {
if (StringUtils.isEmpty(name)) { if (StringUtils.isEmpty(name)) {
return null; return null;
}
return MERCHANT_NAME_MAP.containsKey(name) ? MERCHANT_NAME_MAP.get(name) : null;
} }
return MERCHANT_NAME_MAP.containsKey(name) ? MERCHANT_NAME_MAP.get(name) : null;
}
} }
...@@ -7,10 +7,11 @@ import cn.quantgroup.xyqb.model.model.BlacklistMatchResult; ...@@ -7,10 +7,11 @@ import cn.quantgroup.xyqb.model.model.BlacklistMatchResult;
*/ */
public interface IModelService { public interface IModelService {
/** /**
* 验证用户是否在黑名单里 * 验证用户是否在黑名单里
* @param phoneNo *
* @return * @param phoneNo
*/ * @return
BlacklistMatchResult getBlacklistMatchResult(String phoneNo); */
BlacklistMatchResult getBlacklistMatchResult(String phoneNo);
} }
package cn.quantgroup.xyqb.service.model.impl; package cn.quantgroup.xyqb.service.model.impl;
import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.model.model.BlacklistMatchResult; import cn.quantgroup.xyqb.model.model.BlacklistMatchResult;
import cn.quantgroup.xyqb.service.http.IHttpService; import cn.quantgroup.xyqb.service.http.IHttpService;
import cn.quantgroup.xyqb.service.model.IModelService; import cn.quantgroup.xyqb.service.model.IModelService;
...@@ -17,37 +16,34 @@ import org.springframework.stereotype.Service; ...@@ -17,37 +16,34 @@ import org.springframework.stereotype.Service;
@Service @Service
public class ModelServiceImpl implements IModelService { public class ModelServiceImpl implements IModelService {
@Value("${model.quantgroup.url}") private static final String BLACKLIST_URL_PATTERN =
private String modelUrlPrefix; "%s/Model/openapi/checkBlack.json?appId=0001&userId=0001_001&timeunit=%s&token=%s&phone=%s";
String TOKEN_PATTERN = "timeunit=%sappkey=wer123!@";
@Autowired @Value("${model.quantgroup.url}")
private IHttpService httpService; private String modelUrlPrefix;
@Autowired
String TOKEN_PATTERN = "timeunit=%sappkey=wer123!@"; private IHttpService httpService;
private static final String BLACKLIST_URL_PATTERN = @Override
"%s/Model/openapi/checkBlack.json?appId=0001&userId=0001_001&timeunit=%s&token=%s&phone=%s"; public BlacklistMatchResult getBlacklistMatchResult(String phoneNo) {
if (StringUtils.isEmpty(phoneNo)) {
@Override return null;
public BlacklistMatchResult getBlacklistMatchResult(String phoneNo) {
if (StringUtils.isEmpty(phoneNo)) {
return null;
}
String url = buildBlacklistMatchUrl(phoneNo);
String result = httpService.get(url);
try {
//BlacklistMatchResult blacklistMatchResult = Constants.GSON.fromJson(result, BlacklistMatchResult.class);
BlacklistMatchResult blacklistMatchResult = JSONObject.parseObject(result, BlacklistMatchResult.class);
return blacklistMatchResult;
} catch (Exception e) {
return null;
}
} }
String url = buildBlacklistMatchUrl(phoneNo);
private String buildBlacklistMatchUrl(String phoneNo) { String result = httpService.get(url);
Long timeUnit = System.currentTimeMillis(); try {
String token = PasswordUtil.MD5(String.format(TOKEN_PATTERN, String.valueOf(timeUnit))); //BlacklistMatchResult blacklistMatchResult = Constants.GSON.fromJson(result, BlacklistMatchResult.class);
String url = String.format(BLACKLIST_URL_PATTERN, modelUrlPrefix, timeUnit, token, phoneNo); BlacklistMatchResult blacklistMatchResult = JSONObject.parseObject(result, BlacklistMatchResult.class);
return url; return blacklistMatchResult;
} catch (Exception e) {
return null;
} }
}
private String buildBlacklistMatchUrl(String phoneNo) {
Long timeUnit = System.currentTimeMillis();
String token = PasswordUtil.MD5(String.format(TOKEN_PATTERN, String.valueOf(timeUnit)));
String url = String.format(BLACKLIST_URL_PATTERN, modelUrlPrefix, timeUnit, token, phoneNo);
return url;
}
} }
...@@ -7,5 +7,5 @@ import cn.quantgroup.xyqb.model.Tuple; ...@@ -7,5 +7,5 @@ import cn.quantgroup.xyqb.model.Tuple;
* Created by Miraculous on 2017/1/3. * Created by Miraculous on 2017/1/3.
*/ */
public interface IPageService { public interface IPageService {
Tuple<String, Boolean> nextPage(User user, String target, String currentPage); Tuple<String, Boolean> nextPage(User user, String target, String currentPage);
} }
package cn.quantgroup.xyqb.service.page.bean; package cn.quantgroup.xyqb.service.page.bean;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.Tuple;
/** /**
* Created by Miraculous on 2017/1/3. * Created by Miraculous on 2017/1/3.
*/ */
public abstract class PageType { public abstract class PageType {
protected String name; protected String name;
protected Boolean needShow; protected Boolean needShow;
public PageType(String name, Boolean needShow) { public PageType(String name, Boolean needShow) {
this.name = name; this.name = name;
this.needShow = needShow; this.needShow = needShow;
} }
public abstract boolean canPass(User user); public abstract boolean canPass(User user);
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public Boolean getNeedShow() { public Boolean getNeedShow() {
return needShow; return needShow;
} }
public void setNeedShow(Boolean needShow) { public void setNeedShow(Boolean needShow) {
this.needShow = needShow; this.needShow = needShow;
} }
} }
...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.page.impl; ...@@ -2,7 +2,6 @@ package cn.quantgroup.xyqb.service.page.impl;
import cn.quantgroup.xyqb.entity.*; import cn.quantgroup.xyqb.entity.*;
import cn.quantgroup.xyqb.model.Tuple; import cn.quantgroup.xyqb.model.Tuple;
import cn.quantgroup.xyqb.repository.IUserExtInfoRepository;
import cn.quantgroup.xyqb.service.page.IPageService; import cn.quantgroup.xyqb.service.page.IPageService;
import cn.quantgroup.xyqb.service.page.bean.PageType; import cn.quantgroup.xyqb.service.page.bean.PageType;
import cn.quantgroup.xyqb.service.user.IAddressService; import cn.quantgroup.xyqb.service.user.IAddressService;
...@@ -23,89 +22,89 @@ import java.util.Map; ...@@ -23,89 +22,89 @@ import java.util.Map;
@Service @Service
public class PageServiceImpl implements IPageService { public class PageServiceImpl implements IPageService {
private Map<String, PageType[]> routerDefinetion; private Map<String, PageType[]> routerDefinetion;
private PageType pageIdNo = new PageType("name", false) { @Autowired
@Override private IUserDetailService userDetailService;
public boolean canPass(User user) { private PageType pageIdNo = new PageType("name", false) {
UserDetail userDetail = userDetailService.findByUserId(user.getId()); @Override
return userDetail != null; public boolean canPass(User user) {
} UserDetail userDetail = userDetailService.findByUserId(user.getId());
}; return userDetail != null;
private PageType pageUserFinance = new PageType("info", false) { }
@Override };
public boolean canPass(User user) { @Autowired
UserExtInfo extInfo = userExtInfoService.findByUserId(user.getId()); private IUserExtInfoService userExtInfoService;
return null != extInfo; private PageType pageUserFinance = new PageType("info", false) {
} @Override
}; public boolean canPass(User user) {
private PageType pageAddress = new PageType("address", false) { UserExtInfo extInfo = userExtInfoService.findByUserId(user.getId());
@Override return null != extInfo;
public boolean canPass(User user) { }
Address address = addressService.findByUserId(user.getId()); };
return null != address; @Autowired
} private IAddressService addressService;
}; private PageType pageAddress = new PageType("address", false) {
private PageType pageContacts = new PageType("contacts", false) { @Override
@Override public boolean canPass(User user) {
public boolean canPass(User user) { Address address = addressService.findByUserId(user.getId());
List<Contact> contacts = contactService.findByUserId(user.getId()); return null != address;
return contacts != null && contacts.size() != 0; }
} };
}; @Autowired
@Autowired private IContactService contactService;
private IUserDetailService userDetailService; private PageType pageContacts = new PageType("contacts", false) {
@Autowired @Override
private IUserExtInfoService userExtInfoService; public boolean canPass(User user) {
@Autowired List<Contact> contacts = contactService.findByUserId(user.getId());
private IAddressService addressService; return contacts != null && contacts.size() != 0;
@Autowired }
private IContactService contactService; };
@PostConstruct @PostConstruct
private void init() { private void init() {
routerDefinetion = new HashMap<>(); routerDefinetion = new HashMap<>();
routerDefinetion.put("cashTarget1", new PageType[] { routerDefinetion.put("cashTarget1", new PageType[]{
pageIdNo, pageUserFinance pageIdNo, pageUserFinance
}); });
routerDefinetion.put("cashTarget2", new PageType[] { routerDefinetion.put("cashTarget2", new PageType[]{
pageIdNo, pageAddress pageIdNo, pageAddress
}); });
routerDefinetion.put("cashTarget3", new PageType[] { routerDefinetion.put("cashTarget3", new PageType[]{
pageIdNo, pageContacts pageIdNo, pageContacts
}); });
routerDefinetion.put("cashTarget4", new PageType[] { routerDefinetion.put("cashTarget4", new PageType[]{
pageIdNo pageIdNo
}); });
routerDefinetion.put("cashTarget5", new PageType[] { routerDefinetion.put("cashTarget5", new PageType[]{
}); });
} }
@Override @Override
public Tuple<String, Boolean> nextPage(User user, String target, String currentPage) { public Tuple<String, Boolean> nextPage(User user, String target, String currentPage) {
if (user == null ) { if (user == null) {
return new Tuple<>("", false); return new Tuple<>("", false);
} }
PageType[] processLists = routerDefinetion.containsKey(target) ? routerDefinetion.get(target): null; PageType[] processLists = routerDefinetion.containsKey(target) ? routerDefinetion.get(target) : null;
if (processLists == null) { if (processLists == null) {
return new Tuple<>("", false); return new Tuple<>("", false);
} }
if (processLists.length == 0) { if (processLists.length == 0) {
return new Tuple<>("", true); return new Tuple<>("", true);
} }
boolean isBeforeCurrentPage = true; boolean isBeforeCurrentPage = true;
for (PageType page : processLists) { for (PageType page : processLists) {
if (!page.canPass(user)) { if (!page.canPass(user)) {
return new Tuple<>(page.getName(), false); return new Tuple<>(page.getName(), false);
} }
if (!isBeforeCurrentPage && page.getNeedShow()) { if (!isBeforeCurrentPage && page.getNeedShow()) {
return new Tuple<>(page.getName(), false); return new Tuple<>(page.getName(), false);
} }
if (page.getName().equals(currentPage)) { if (page.getName().equals(currentPage)) {
isBeforeCurrentPage = false; isBeforeCurrentPage = false;
} }
}
return new Tuple<>("", true);
} }
return new Tuple<>("", true);
}
} }
...@@ -10,11 +10,13 @@ import cn.quantgroup.sms.SmsSender; ...@@ -10,11 +10,13 @@ import cn.quantgroup.sms.SmsSender;
*/ */
public interface ISmsService { public interface ISmsService {
SmsSender getSmsSender(); SmsSender getSmsSender();
void sendAfterRegister(String phoneNo); void sendAfterRegister(String phoneNo);
boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode); void sendAfterRegister(String phoneNo,String contentId);
boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode); boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode);
boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode);
} }
package cn.quantgroup.xyqb.service.sms.impl; package cn.quantgroup.xyqb.service.sms.impl;
import cn.quantgroup.sms.MsgParams; import cn.quantgroup.sms.MsgParams;
import cn.quantgroup.sms.SendAndForgetMsg;
import cn.quantgroup.sms.SmsSender; import cn.quantgroup.sms.SmsSender;
import cn.quantgroup.xyqb.Constants; import cn.quantgroup.xyqb.Constants;
import cn.quantgroup.xyqb.service.sms.ISmsService; import cn.quantgroup.xyqb.service.sms.ISmsService;
...@@ -23,95 +22,106 @@ import java.util.Collections; ...@@ -23,95 +22,106 @@ import java.util.Collections;
@Service @Service
public class SmsServiceImpl implements ISmsService { public class SmsServiceImpl implements ISmsService {
private static final Logger LOGGER = LoggerFactory.getLogger(SmsServiceImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(SmsServiceImpl.class);
private static final int SMS_VERIFICATION_MAXLEN = 6; private static final int SMS_VERIFICATION_MAXLEN = 6;
private static final String SMS_VERIFY_PREFIX = "sms:verify:"; private static final String SMS_VERIFY_PREFIX = "sms:verify:";
private static final SmsSender smsSender = new SmsSender();
@Value("${sms.is.debug}")
private boolean isDebug;
@Autowired
@Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> stringRedisTemplate;
@Value("${sms.is.debug}") @Override
private boolean isDebug; public SmsSender getSmsSender() {
if (null == smsSender) {
@Autowired return smsSender;
@Qualifier("stringRedisTemplate") }
private RedisTemplate<String, String> stringRedisTemplate; return this.smsSender;
}
private static final SmsSender smsSender = new SmsSender();
@Override @Override
public SmsSender getSmsSender() { public void sendAfterRegister(String phoneNo) {
if (null == smsSender) { try {
return smsSender; MsgParams msgParams = new MsgParams(Collections.singletonList(2), phoneNo, "1", "24", Collections.emptyList());
} smsSender.sendMsg(msgParams);
return this.smsSender; //smsSender.sendAndForget(new SendAndForgetMsg(Collections.emptyList(), "24", "1", phoneNo));
LOGGER.info("注册完成,发送短信, phoneNo:{}", phoneNo);
} catch (Exception e) {
e.printStackTrace();
} }
}
@Override @Override
public void sendAfterRegister(String phoneNo) { public void sendAfterRegister(String phoneNo, String contentId) {
try { try {
MsgParams msgParams = new MsgParams(Collections.singletonList(2), phoneNo, "1", "24", Collections.emptyList()); if(StringUtils.isBlank(contentId)){
smsSender.sendMsg(msgParams); contentId = "24";
//smsSender.sendAndForget(new SendAndForgetMsg(Collections.emptyList(), "24", "1", phoneNo)); }
LOGGER.info("注册完成,发送短信, phoneNo:{}", phoneNo); MsgParams msgParams = new MsgParams(Collections.singletonList(2), phoneNo, "1", contentId, Collections.emptyList());
} catch (Exception e) { smsSender.sendMsg(msgParams);
e.printStackTrace(); LOGGER.info("注册完成,发送短信, phoneNo:{}", phoneNo);
} } catch (Exception e) {
e.printStackTrace();
} }
}
/** /**
* 检查验证码是否正确 * 检查验证码是否正确
* *
* @param phoneNo * @param phoneNo
* @param smsVerificationCode * @param smsVerificationCode
* @return * @return
*/ */
@Override @Override
public boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode) { public boolean validRegisterOrResetPasswdVerificationCode(String phoneNo, String smsVerificationCode) {
if (StringUtils.isEmpty(smsVerificationCode) || smsVerificationCode.length() != SMS_VERIFICATION_MAXLEN) { if (StringUtils.isEmpty(smsVerificationCode) || smsVerificationCode.length() != SMS_VERIFICATION_MAXLEN) {
return false; return false;
}
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isEmpty(randomCode)){
return false;
}
String[] arr = randomCode.split(":");
String unqiueId = arr[0];
String code = arr[1];
return confirmSms(smsVerificationCode, unqiueId, code);
} }
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isEmpty(randomCode)) {
return false;
}
String[] arr = randomCode.split(":");
String unqiueId = arr[0];
String code = arr[1];
return confirmSms(smsVerificationCode, unqiueId, code);
}
@Override @Override
public boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode){ public boolean validateFastLoginVerificationCode(String phoneNo, String verificationCode) {
String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo; String key = Constants.REDIS_PREFIX_VERIFICATION_CODE + phoneNo;
String randomCode = stringRedisTemplate.opsForValue().get(key); String randomCode = stringRedisTemplate.opsForValue().get(key);
if(StringUtils.isBlank(randomCode)){ if (StringUtils.isBlank(randomCode)) {
return false; return false;
} }
String[] arr = randomCode.split(":"); String[] arr = randomCode.split(":");
if(arr.length != 2){ if (arr.length != 2) {
return false; return false;
}
String uniqueId = arr[0];
String code = arr[1];
return confirmSms(verificationCode, uniqueId, code);
} }
String uniqueId = arr[0];
String code = arr[1];
return confirmSms(verificationCode, uniqueId, code);
}
private boolean confirmSms(String smsVerificationCode, String unqiueId, String code) { private boolean confirmSms(String smsVerificationCode, String unqiueId, String code) {
try { try {
MsgParams message = new MsgParams(Collections.singletonList(2), unqiueId); MsgParams message = new MsgParams(Collections.singletonList(2), unqiueId);
//MsgParams messageVoice = new MsgParams(Collections.singletonList(4), unqiueId); //MsgParams messageVoice = new MsgParams(Collections.singletonList(4), unqiueId);
getSmsSender().confirmMsg(message); getSmsSender().confirmMsg(message);
//getSmsSender().confirmMsg(messageVoice); //getSmsSender().confirmMsg(messageVoice);
//smsSender.confirmSmsResult("1", unqiueId); //smsSender.confirmSmsResult("1", unqiueId);
LOGGER.info("confirmMsg send success, uniqueId={}", unqiueId); LOGGER.info("confirmMsg send success, uniqueId={}", unqiueId);
} catch (Exception e) { } catch (Exception e) {
LOGGER.info("短信验证像短信中心确认失效"); LOGGER.info("短信验证像短信中心确认失效");
} }
if (StringUtils.equals(code, smsVerificationCode)) { if (StringUtils.equals(code, smsVerificationCode)) {
return true; return true;
}
return false;
} }
return false;
}
} }
...@@ -7,8 +7,9 @@ import cn.quantgroup.xyqb.entity.Address; ...@@ -7,8 +7,9 @@ import cn.quantgroup.xyqb.entity.Address;
*/ */
public interface IAddressService { public interface IAddressService {
Address findByUserId(Long userId); Address findByUserId(Long userId);
Address save(Address addressObj); Address save(Address addressObj);
Address saveAddress(Address address);
Address saveAddress(Address address);
} }
...@@ -8,7 +8,7 @@ import java.util.List; ...@@ -8,7 +8,7 @@ import java.util.List;
* Created by Miraculous on 2017/1/3. * Created by Miraculous on 2017/1/3.
*/ */
public interface IContactService { public interface IContactService {
List<Contact> findByUserId(Long userId); List<Contact> findByUserId(Long userId);
List<Contact> save(List<Contact> contacts); List<Contact> save(List<Contact> contacts);
} }
...@@ -9,29 +9,29 @@ import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult; ...@@ -9,29 +9,29 @@ import cn.quantgroup.xyqb.model.jr58.Jr58RegisterResult;
*/ */
public interface ILkbUserService { public interface ILkbUserService {
/** /**
* App用户注册 * App用户注册
* *
* @param phoneNo * @param phoneNo
* @param password * @param password
* @return * @return
*/ */
String registerApp(String phoneNo, String password); String registerApp(String phoneNo, String password);
/** /**
* 58金融用户注册 * 58金融用户注册
* *
* @param param * @param param
* @return * @return
*/ */
Jr58RegisterResult registerJr58(Jr58RegisterParam param); Jr58RegisterResult registerJr58(Jr58RegisterParam param);
/** /**
* 同步用户信息 * 同步用户信息
* *
* @param uuid * @param uuid
* @param name * @param name
* @param idNo * @param idNo
*/ */
void userUpdate(String uuid, String name, String idNo); void userUpdate(String uuid, String name, String idNo);
} }
...@@ -7,7 +7,7 @@ import cn.quantgroup.xyqb.entity.UserExtInfo; ...@@ -7,7 +7,7 @@ import cn.quantgroup.xyqb.entity.UserExtInfo;
*/ */
public interface IUserExtInfoService { public interface IUserExtInfoService {
UserExtInfo findByUserId(Long userId); UserExtInfo findByUserId(Long userId);
UserExtInfo save(UserExtInfo info); UserExtInfo save(UserExtInfo info);
} }
package cn.quantgroup.xyqb.service.user; package cn.quantgroup.xyqb.service.user;
import cn.quantgroup.xyqb.entity.User; import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.entity.WechatUserInfo;
import java.util.List;
import java.util.Map;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
public interface IUserService { public interface IUserService {
User findByPhoneWithCache(String phone); User findByPhoneWithCache(String phone);
User findByUuidWithCache(String uuid);
User findByUuidWithCache(String uuid); boolean register(String phoneNo, String password, Long registerFrom, String userIp, Long channelId);
boolean register(String phoneNo, String password, Long registerFrom, String userIp, Long channelId); User registerAndReturn(String phoneNo, String password, Long registerFrom);
User registerAndReturn(String phoneNo, String password, Long registerFrom); boolean exist(String phoneNo);
boolean exist(String phoneNo); boolean resetPassword(String phoneNo, String password);
boolean resetPassword(String phoneNo, String password); User findByPhoneInDb(String phone);
User findByPhoneInDb(String phone); User findByUuidInDb(String uuid);
User findByUuidInDb(String uuid); Map<Long, String> findPhoneByIdsInDb(List<Long> userIds);
User saveUser(User user); User saveUser(User user);
User findById(Long userId); User findById(Long userId);
} }
...@@ -7,6 +7,6 @@ import cn.quantgroup.xyqb.entity.UuidPhoneMapping; ...@@ -7,6 +7,6 @@ import cn.quantgroup.xyqb.entity.UuidPhoneMapping;
*/ */
public interface IUuidPhoneMappingService { public interface IUuidPhoneMappingService {
UuidPhoneMapping findByUuid(String uuid); UuidPhoneMapping findByUuid(String uuid);
} }
...@@ -14,24 +14,24 @@ import org.springframework.stereotype.Service; ...@@ -14,24 +14,24 @@ import org.springframework.stereotype.Service;
@Service @Service
public class AddressServiceImpl implements IAddressService { public class AddressServiceImpl implements IAddressService {
@Autowired @Autowired
private IAddressRepository addressRepository; private IAddressRepository addressRepository;
@Override @Override
@Cacheable(value = "addresscache", key = "'address' + #userId", unless = "#result == null", cacheManager = "cacheManager") @Cacheable(value = "addresscache", key = "'address' + #userId", unless = "#result == null", cacheManager = "cacheManager")
public Address findByUserId(Long userId) { public Address findByUserId(Long userId) {
return addressRepository.findByUserId(userId); return addressRepository.findByUserId(userId);
} }
@Override @Override
@CacheEvict(value = "addresscache", key = "'address' + #addressObj.userId", cacheManager = "cacheManager") @CacheEvict(value = "addresscache", key = "'address' + #addressObj.userId", cacheManager = "cacheManager")
public Address save(Address addressObj) { public Address save(Address addressObj) {
return addressRepository.save(addressObj); return addressRepository.save(addressObj);
} }
@Override @Override
public Address saveAddress(Address address) { public Address saveAddress(Address address) {
return addressRepository.save(address); return addressRepository.save(address);
} }
} }
...@@ -16,20 +16,20 @@ import java.util.List; ...@@ -16,20 +16,20 @@ import java.util.List;
@Service @Service
public class ContactServiceImpl implements IContactService { public class ContactServiceImpl implements IContactService {
@Autowired @Autowired
private IContactRepository contactRepository; private IContactRepository contactRepository;
@Override @Override
@Cacheable(value = "contact", key = "'contact' + #userId", unless = "#result == null or #result.size() == 0", cacheManager = "cacheManager") @Cacheable(value = "contact", key = "'contact' + #userId", unless = "#result == null or #result.size() == 0", cacheManager = "cacheManager")
public List<Contact> findByUserId(Long userId) { public List<Contact> findByUserId(Long userId) {
return contactRepository.findByUserId(userId); return contactRepository.findByUserId(userId);
} }
@Override @Override
@CacheEvict(value = "contact", key = "'contact' + #contacts.get(0).userId", cacheManager = "cacheManager") @CacheEvict(value = "contact", key = "'contact' + #contacts.get(0).userId", cacheManager = "cacheManager")
public List<Contact> save(List<Contact> contacts) { public List<Contact> save(List<Contact> contacts) {
return contactRepository.save(contacts); return contactRepository.save(contacts);
} }
} }
...@@ -26,79 +26,79 @@ import java.util.Map; ...@@ -26,79 +26,79 @@ import java.util.Map;
@Service @Service
public class LkbUserviceImpl implements ILkbUserService { public class LkbUserviceImpl implements ILkbUserService {
private static final Logger LOGGER = LoggerFactory.getLogger(LkbUserviceImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(LkbUserviceImpl.class);
private static final String TOKEN_PATTERN = "timeunit=%sappkey=lkb010203#$%%";
@Autowired
private IHttpService httpService;
@Value("${lkb.client.url}")
private String clientUrl;
@Value("${lkb.client.user.register.app}")
private String registerApp;
@Value("${lkb.client.user.register.58jr}")
private String register58jr;
@Value("${lkb.client.user.update}")
private String userUpdate;
@Override
public String registerApp(String phoneNo, String password) {
String timeunit = System.currentTimeMillis() + "";
String token = PasswordUtil.MD5(String.format(TOKEN_PATTERN, timeunit));
Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("appId", Constants.Channel.LKB_CODE)
.put("timeunit", timeunit)
.put("token", token)
.put("userName", phoneNo)
.put("password", password)
.build();
String response = httpService.get(clientUrl + registerApp, parameters);
//Map<String, String> result = GSON.fromJson(response, Map.class);
Map<String, String> result = JSONObject.parseObject(response, Map.class);
if (result == null || "0".equals(result.get("flag"))) {
LOGGER.warn("向LKB注册用户失败, phoneNo:{}, password:{}", phoneNo, password);
return "";
}
//String uid = java.util.UUID.randomUUID().toString().replace("-","");
return result.get("uid");
}
@Override private static final String TOKEN_PATTERN = "timeunit=%sappkey=lkb010203#$%%";
public Jr58RegisterResult registerJr58(Jr58RegisterParam param) {
Map<String, String> parameters = ImmutableMap.<String, String>builder() @Autowired
.put("wbId", param.getWbId()) private IHttpService httpService;
.put("customerId", param.getCustomerId())
.put("name", param.getName()) @Value("${lkb.client.url}")
.put("idcard", param.getIdcard()) private String clientUrl;
.put("email", StringUtils.substring(param.getEmail(), 0, 30))
.put("phone", param.getPhone()) @Value("${lkb.client.user.register.app}")
.build(); private String registerApp;
String response = httpService.get(clientUrl + register58jr, parameters);
//return GSON.fromJson(response, Jr58RegisterResult.class);
return JSONObject.parseObject(response, Jr58RegisterResult.class);
}
@Override @Value("${lkb.client.user.register.58jr}")
@Async private String register58jr;
public void userUpdate(String uuid, String name, String idNo) {
Map<String, String> parameters = ImmutableMap.<String, String>builder() @Value("${lkb.client.user.update}")
.put("userId", uuid) private String userUpdate;
.put("realName", name)
.put("idcard", idNo) @Override
.build(); public String registerApp(String phoneNo, String password) {
String timeunit = System.currentTimeMillis() + "";
String response = httpService.get(clientUrl + userUpdate, parameters); String token = PasswordUtil.MD5(String.format(TOKEN_PATTERN, timeunit));
//Map<String, String> result = GSON.fromJson(response, Map.class);
Map<String, String> result = JSONObject.parseObject(response, Map.class); Map<String, String> parameters = ImmutableMap.<String, String>builder()
if (result == null || "false".equals(result.get("flag"))) { .put("appId", Constants.Channel.LKB_CODE)
LOGGER.warn("向LKB-Client同步用户信息失败, result: {}", result); .put("timeunit", timeunit)
} .put("token", token)
.put("userName", phoneNo)
.put("password", password)
.build();
String response = httpService.get(clientUrl + registerApp, parameters);
//Map<String, String> result = GSON.fromJson(response, Map.class);
Map<String, String> result = JSONObject.parseObject(response, Map.class);
if (result == null || "0".equals(result.get("flag"))) {
LOGGER.warn("向LKB注册用户失败, phoneNo:{}, password:{}", phoneNo, password);
return "";
}
//String uid = java.util.UUID.randomUUID().toString().replace("-","");
return result.get("uid");
}
@Override
public Jr58RegisterResult registerJr58(Jr58RegisterParam param) {
Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("wbId", param.getWbId())
.put("customerId", param.getCustomerId())
.put("name", param.getName())
.put("idcard", param.getIdcard())
.put("email", StringUtils.substring(param.getEmail(), 0, 30))
.put("phone", param.getPhone())
.build();
String response = httpService.get(clientUrl + register58jr, parameters);
//return GSON.fromJson(response, Jr58RegisterResult.class);
return JSONObject.parseObject(response, Jr58RegisterResult.class);
}
@Override
@Async
public void userUpdate(String uuid, String name, String idNo) {
Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("userId", uuid)
.put("realName", name)
.put("idcard", idNo)
.build();
String response = httpService.get(clientUrl + userUpdate, parameters);
//Map<String, String> result = GSON.fromJson(response, Map.class);
Map<String, String> result = JSONObject.parseObject(response, Map.class);
if (result == null || "false".equals(result.get("flag"))) {
LOGGER.warn("向LKB-Client同步用户信息失败, result: {}", result);
} }
}
} }
...@@ -56,7 +56,6 @@ public class UserDetailServiceImpl implements IUserDetailService { ...@@ -56,7 +56,6 @@ public class UserDetailServiceImpl implements IUserDetailService {
@Override @Override
public List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo) { public List<UserDetailVO> searchUserDetailList(String name, String phoneNo, String idNo) {
// return
List<UserDetail> details = userDetailRepository.findAll(getSpecification(name, phoneNo, idNo)); List<UserDetail> details = userDetailRepository.findAll(getSpecification(name, phoneNo, idNo));
Map<Long, User> userMap = Maps.newHashMap(); Map<Long, User> userMap = Maps.newHashMap();
if (!CollectionUtils.isEmpty(details)) { if (!CollectionUtils.isEmpty(details)) {
......
...@@ -15,20 +15,20 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -15,20 +15,20 @@ import org.springframework.transaction.annotation.Transactional;
@Service @Service
public class UserExtInfoServiceImpl implements IUserExtInfoService { public class UserExtInfoServiceImpl implements IUserExtInfoService {
@Autowired @Autowired
private IUserExtInfoRepository userExtInfoRepository; private IUserExtInfoRepository userExtInfoRepository;
@Override @Override
@Cacheable(value = "userextinfocache", key = "'extinfo' + #userId", unless = "#result == null", cacheManager = "cacheManager") @Cacheable(value = "userextinfocache", key = "'extinfo' + #userId", unless = "#result == null", cacheManager = "cacheManager")
public UserExtInfo findByUserId(Long userId) { public UserExtInfo findByUserId(Long userId) {
return userExtInfoRepository.findByUserId(userId); return userExtInfoRepository.findByUserId(userId);
} }
@Override @Override
@Transactional @Transactional
@CacheEvict(value = "userextinfocache", key = "'extinfo' + #info.userId", cacheManager = "cacheManager") @CacheEvict(value = "userextinfocache", key = "'extinfo' + #info.userId", cacheManager = "cacheManager")
public UserExtInfo save(UserExtInfo info) { public UserExtInfo save(UserExtInfo info) {
return userExtInfoRepository.save(info); return userExtInfoRepository.save(info);
} }
} }
...@@ -7,21 +7,27 @@ import cn.quantgroup.xyqb.service.sms.ISmsService; ...@@ -7,21 +7,27 @@ import cn.quantgroup.xyqb.service.sms.ISmsService;
import cn.quantgroup.xyqb.service.user.ILkbUserService; import cn.quantgroup.xyqb.service.user.ILkbUserService;
import cn.quantgroup.xyqb.service.user.IUserService; import cn.quantgroup.xyqb.service.user.IUserService;
import cn.quantgroup.xyqb.util.PasswordUtil; import cn.quantgroup.xyqb.util.PasswordUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Created by Miraculous on 15/7/5. * Created by Miraculous on 15/7/5.
*/ */
@Service @Service
@Slf4j
public class UserServiceImpl implements IUserService { public class UserServiceImpl implements IUserService {
@Autowired @Autowired
...@@ -41,6 +47,31 @@ public class UserServiceImpl implements IUserService { ...@@ -41,6 +47,31 @@ public class UserServiceImpl implements IUserService {
return userRepository.findByPhoneNo(phone); return userRepository.findByPhoneNo(phone);
} }
@Override
public Map<Long, String> findPhoneByIdsInDb(List<Long> userIds) {
if (CollectionUtils.isEmpty(userIds)) {
return Maps.newHashMap();
}
Map<Long, String> userIdAndPhoneMap = Maps.newHashMap();
int pageSize = 1000;
int idSize = userIds.size();
for (int i = 0; i < idSize; i += pageSize) {
List<Long> subList = userIds.subList(i, Math.min(idSize, i + pageSize));
List<User> users = userRepository.findByIdIn(subList);
users.stream().forEach(user -> {
userIdAndPhoneMap.put(user.getId(), user.getPhoneNo());
});
if (i + pageSize < idSize) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
log.error("线程sleep失败", e);
}
}
}
return userIdAndPhoneMap;
}
@Override @Override
public User findByUuidInDb(String uuid) { public User findByUuidInDb(String uuid) {
return userRepository.findByUuid(uuid); return userRepository.findByUuid(uuid);
......
...@@ -12,14 +12,13 @@ import org.springframework.stereotype.Service; ...@@ -12,14 +12,13 @@ import org.springframework.stereotype.Service;
@Service @Service
public class UuidPhoneMappingServiceImpl implements IUuidPhoneMappingService { public class UuidPhoneMappingServiceImpl implements IUuidPhoneMappingService {
@Autowired @Autowired
private IUuidPhoneMappingRepository uuidPhoneMappingRepository; private IUuidPhoneMappingRepository uuidPhoneMappingRepository;
@Override
public UuidPhoneMapping findByUuid(String uuid) {
return uuidPhoneMappingRepository.findByUuid(uuid);
}
@Override
public UuidPhoneMapping findByUuid(String uuid) {
return uuidPhoneMappingRepository.findByUuid(uuid);
}
} }
package cn.quantgroup.xyqb.service.user.vo; package cn.quantgroup.xyqb.service.user.vo;
import cn.quantgroup.motan.retbean.XUserDetail;
import cn.quantgroup.xyqb.entity.UserDetail; import cn.quantgroup.xyqb.entity.UserDetail;
import cn.quantgroup.xyqb.model.Gender; import cn.quantgroup.xyqb.model.Gender;
import cn.quantgroup.xyqb.model.IdType; import cn.quantgroup.xyqb.model.IdType;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.sql.Timestamp;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
public class UserDetailVO { public class UserDetailVO {
...@@ -56,4 +59,32 @@ public class UserDetailVO { ...@@ -56,4 +59,32 @@ public class UserDetailVO {
} }
return userDetailVO; return userDetailVO;
} }
public XUserDetail toXUserDetail() {
XUserDetail xUserDetail = new XUserDetail();
xUserDetail.setId(this.getId());
xUserDetail.setUserId(this.getUserId());
xUserDetail.setPhoneNo(this.getPhoneNo());
xUserDetail.setName(this.getName());
xUserDetail.setIdNo(this.getIdNo());
if (this.getIdType() != null) {
xUserDetail.setIdType(cn.quantgroup.motan.enums.IdType.valueOf(this.getIdType().name()));
}
if (this.getGender() != null) {
xUserDetail.setGender(cn.quantgroup.motan.enums.Gender.valueOf(this.getGender().name()));
}
xUserDetail.setEmail(this.getEmail());
xUserDetail.setQq(this.getQq());
xUserDetail.setId(this.getId());
if (this.getCreatedAt() != null) {
xUserDetail.setCreatedAt(new Timestamp(this.getCreatedAt()));
}
if (this.getUpdatedAt() != null) {
xUserDetail.setUpdatedAt(new Timestamp(this.getUpdatedAt()));
}
xUserDetail.setIsAuthenticated(this.getIsAuthenticated());
xUserDetail.setEnable(this.getEnable());
return xUserDetail;
}
} }
...@@ -7,14 +7,15 @@ import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse; ...@@ -7,14 +7,15 @@ import cn.quantgroup.xyqb.model.webchat.AccessTokenResponse;
* Created by Miraculous on 2017/1/19. * Created by Miraculous on 2017/1/19.
*/ */
public interface IWechatService { public interface IWechatService {
AccessTokenResponse getToken(String code); AccessTokenResponse getToken(String code);
WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId);
WechatUserInfo findWechatUserInfoFromDb(String openId); WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId);
WechatUserInfo findWechatUserInfoByPhoneNo(String phoneNo); WechatUserInfo findWechatUserInfoFromDb(String openId);
WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo); WechatUserInfo findWechatUserInfoByPhoneNo(String phoneNo);
WechatUserInfo queryOpenIdByUserId(Long userId); WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo);
WechatUserInfo queryOpenIdByUserId(Long userId);
} }
...@@ -22,124 +22,120 @@ import java.util.concurrent.TimeUnit; ...@@ -22,124 +22,120 @@ import java.util.concurrent.TimeUnit;
*/ */
@Service @Service
public class WechatServiceImpl implements IWechatService { public class WechatServiceImpl implements IWechatService {
@Autowired private static final String WECHAT_TOKEN_KEY_PREFIX = "wechat:token:";
private IHttpService httpService; @Autowired
private IHttpService httpService;
@Autowired @Autowired
@Qualifier("stringRedisTemplate") @Qualifier("stringRedisTemplate")
private RedisTemplate<String, String> redisTemplate; private RedisTemplate<String, String> redisTemplate;
@SafeValue("wechat.appid")
@SafeValue("wechat.appid") private String appId;
private String appId; @SafeValue("wechat.secret")
@SafeValue("wechat.secret") private String secret;
private String secret; @Autowired
private IWeChatUserRepository weChatUserRepository;
@Autowired private String accessTokenUrl;
private IWeChatUserRepository weChatUserRepository; private String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";
private String accessTokenUrl; @PostConstruct
private String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s"; private void init() {
private static final String WECHAT_TOKEN_KEY_PREFIX = "wechat:token:"; accessTokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&grant_type=authorization_code&code=", appId, secret) + "%s";
@PostConstruct refreshTokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=", appId) + "%s";
private void init() { }
accessTokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&grant_type=authorization_code&code=", appId, secret) + "%s";
@Override
refreshTokenUrl = String.format("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=", appId) + "%s"; public AccessTokenResponse getToken(String code) {
if (StringUtils.isEmpty(code)) {
return null;
} }
String key = WECHAT_TOKEN_KEY_PREFIX + code;
@Override
public AccessTokenResponse getToken(String code) { String resultStr = redisTemplate.opsForValue().get(key);
if (StringUtils.isEmpty(code)) { if (StringUtils.isEmpty(resultStr)) {
return null; String response = getTokenFromWechatServer(code);
} if (StringUtils.isEmpty(response)) {
String key = WECHAT_TOKEN_KEY_PREFIX + code; return null;
}
String resultStr = redisTemplate.opsForValue().get(key); try {
if (StringUtils.isEmpty(resultStr)) { AccessTokenResponse accessTokenResponse = JSONObject.parseObject(response,
String response = getTokenFromWechatServer(code); AccessTokenResponse.class);
if (StringUtils.isEmpty(response)) { if (accessTokenResponse == null) {
return null; return null;
}
try {
AccessTokenResponse accessTokenResponse = JSONObject.parseObject(response,
AccessTokenResponse.class);
if (accessTokenResponse == null) {
return null;
}
accessTokenResponse.setInitialTime(System.currentTimeMillis() - 10000);
redisTemplate.opsForValue().set(key, JSONObject.toJSONString(accessTokenResponse), accessTokenResponse.getExpiresIn() + 1000, TimeUnit.SECONDS);
return accessTokenResponse;
} catch (Exception ex) {
return null;
}
} else {
try {
AccessTokenResponse response = JSONObject.parseObject(resultStr, AccessTokenResponse.class);
// 刷新
if (response.getInitialTime() + response.getExpiresIn()*1000 > System.currentTimeMillis()) {
String refreshTokenStr = refreshToken(response.getRefreshToken());
response = JSONObject.parseObject(refreshTokenStr, AccessTokenResponse.class);
if (response == null) {
return null;
}
response.setInitialTime(System.currentTimeMillis() - 10000);
}
redisTemplate.opsForValue().set(key, JSONObject.toJSONString(response), response.getExpiresIn() + 1000, TimeUnit.SECONDS);
return response;
} catch (Exception ex) {
return null;
}
} }
} accessTokenResponse.setInitialTime(System.currentTimeMillis() - 10000);
redisTemplate.opsForValue().set(key, JSONObject.toJSONString(accessTokenResponse), accessTokenResponse.getExpiresIn() + 1000, TimeUnit.SECONDS);
@Override return accessTokenResponse;
public WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId) { } catch (Exception ex) {
if (StringUtils.isEmpty(token) || StringUtils.isEmpty(openId)) { return null;
}
} else {
try {
AccessTokenResponse response = JSONObject.parseObject(resultStr, AccessTokenResponse.class);
// 刷新
if (response.getInitialTime() + response.getExpiresIn() * 1000 > System.currentTimeMillis()) {
String refreshTokenStr = refreshToken(response.getRefreshToken());
response = JSONObject.parseObject(refreshTokenStr, AccessTokenResponse.class);
if (response == null) {
return null; return null;
}
response.setInitialTime(System.currentTimeMillis() - 10000);
} }
String accessUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"; redisTemplate.opsForValue().set(key, JSONObject.toJSONString(response), response.getExpiresIn() + 1000, TimeUnit.SECONDS);
String url = String.format(accessUserInfoUrl, token, openId); return response;
String result = httpService.get(url); } catch (Exception ex) {
return JSONObject.parseObject(result, WechatUserInfo.class); return null;
}
} }
}
@Override @Override
public WechatUserInfo findWechatUserInfoFromDb(String openId) { public WechatUserInfo getWechatUserInfoFromWechatServer(String token, String openId) {
return weChatUserRepository.findByOpenId(openId); if (StringUtils.isEmpty(token) || StringUtils.isEmpty(openId)) {
return null;
} }
String accessUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";
@Override String url = String.format(accessUserInfoUrl, token, openId);
@Transactional String result = httpService.get(url);
public WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo) { return JSONObject.parseObject(result, WechatUserInfo.class);
if(null == userInfo.getPhoneNo()) { }
userInfo.setPhoneNo("");
} @Override
return weChatUserRepository.save(userInfo); public WechatUserInfo findWechatUserInfoFromDb(String openId) {
return weChatUserRepository.findByOpenId(openId);
}
@Override
@Transactional
public WechatUserInfo saveWechatUserInfo(WechatUserInfo userInfo) {
if (null == userInfo.getPhoneNo()) {
userInfo.setPhoneNo("");
} }
return weChatUserRepository.save(userInfo);
}
@Override @Override
public WechatUserInfo findWechatUserInfoByPhoneNo(String phoneNo) { public WechatUserInfo findWechatUserInfoByPhoneNo(String phoneNo) {
return weChatUserRepository.findByPhoneNo(phoneNo); return weChatUserRepository.findByPhoneNo(phoneNo);
} }
private String getTokenFromWechatServer(String code) { private String getTokenFromWechatServer(String code) {
if (StringUtils.isEmpty(code)) { if (StringUtils.isEmpty(code)) {
return null; return null;
}
String finalAccessTokenUrl = String.format(accessTokenUrl, code);
return httpService.get(finalAccessTokenUrl);
} }
String finalAccessTokenUrl = String.format(accessTokenUrl, code);
return httpService.get(finalAccessTokenUrl);
}
private String refreshToken(String refreshToken) { private String refreshToken(String refreshToken) {
if (StringUtils.isEmpty(refreshToken)) { if (StringUtils.isEmpty(refreshToken)) {
return null; return null;
}
return httpService.get(String.format(refreshTokenUrl, refreshToken));
} }
return httpService.get(String.format(refreshTokenUrl, refreshToken));
}
@Override @Override
public WechatUserInfo queryOpenIdByUserId(Long userId) { public WechatUserInfo queryOpenIdByUserId(Long userId) {
return weChatUserRepository.findByUserId(userId); return weChatUserRepository.findByUserId(userId);
} }
} }
...@@ -18,41 +18,67 @@ import javax.servlet.http.HttpServletRequest; ...@@ -18,41 +18,67 @@ import javax.servlet.http.HttpServletRequest;
*/ */
public class XyqbSessionContextHolder { public class XyqbSessionContextHolder {
private static final ThreadLocal<SessionStruct> threadSession = new ThreadLocal<>(); private static final ThreadLocal<SessionStruct> threadSession = new ThreadLocal<>();
public static RedisTemplate<String, String> redisTemplate = null; private static final Logger LOGGER = LoggerFactory.getLogger(XyqbSessionContextHolder.class);
private static final Logger LOGGER = LoggerFactory.getLogger(XyqbSessionContextHolder.class); public static RedisTemplate<String, String> redisTemplate = null;
public static SessionStruct getXSession() { public static SessionStruct getXSession() {
if (threadSession.get() != null) { if (threadSession.get() != null) {
return threadSession.get(); return threadSession.get();
} }
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token"); String token = request.getHeader("x-auth-token");
if (token == null || token.length() != 36) { if (token == null || token.length() != 36) {
return null; return null;
} }
String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token); String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token);
if (StringUtils.isEmpty(result)) { if (StringUtils.isEmpty(result)) {
return null; return null;
} }
try { try {
SessionValue values = JSON.parseObject(result, SessionValue.class); SessionValue values = JSON.parseObject(result, SessionValue.class);
if (values == null) { if (values == null) {
return null; return null;
} }
SessionStruct sessionStruct = new SessionStruct(); SessionStruct sessionStruct = new SessionStruct();
sessionStruct.setSid(token); sessionStruct.setSid(token);
sessionStruct.setValues(values); sessionStruct.setValues(values);
threadSession.set(sessionStruct); threadSession.set(sessionStruct);
return sessionStruct; return sessionStruct;
} catch (Exception ex) { } catch (Exception ex) {
LOGGER.error("序列化session出错", ex); LOGGER.error("序列化session出错", ex);
return null; return null;
}
} }
}
public static void releaseSession() { public static SessionStruct getXSessionFromRedis(){
threadSession.remove(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String token = request.getHeader("x-auth-token");
if (token == null || token.length() != 36) {
return null;
} }
String result = redisTemplate.opsForValue().get(Constants.Session.USER_SESSION_CACHE + token);
if (StringUtils.isEmpty(result)) {
return null;
}
try {
SessionValue values = JSON.parseObject(result, SessionValue.class);
if (values == null) {
return null;
}
SessionStruct sessionStruct = new SessionStruct();
sessionStruct.setSid(token);
sessionStruct.setValues(values);
return sessionStruct;
}catch (Exception ex){
LOGGER.error("序列化session出错", ex);
return null;
}
}
public static void releaseSession() {
threadSession.remove();
}
} }
...@@ -28,267 +28,267 @@ import java.util.Locale; ...@@ -28,267 +28,267 @@ import java.util.Locale;
*/ */
public abstract class AbstractManageableCaptchaService extends AbstractCaptchaService implements AbstractManageableCaptchaServiceMBean, CaptchaService { public abstract class AbstractManageableCaptchaService extends AbstractCaptchaService implements AbstractManageableCaptchaServiceMBean, CaptchaService {
private int minGuarantedStorageDelayInSeconds; private int minGuarantedStorageDelayInSeconds;
private int captchaStoreMaxSize; private int captchaStoreMaxSize;
private int captchaStoreSizeBeforeGarbageCollection; private int captchaStoreSizeBeforeGarbageCollection;
private int numberOfGeneratedCaptchas; private int numberOfGeneratedCaptchas;
private int numberOfCorrectResponse; private int numberOfCorrectResponse;
private int numberOfUncorrectResponse; private int numberOfUncorrectResponse;
private int numberOfGarbageCollectedCaptcha; private int numberOfGarbageCollectedCaptcha;
private FastHashMap times; private FastHashMap times;
private long oldestCaptcha; private long oldestCaptcha;
protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize) { protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize) {
super(captchaStore, captchaEngine); super(captchaStore, captchaEngine);
this.numberOfGeneratedCaptchas = 0; this.numberOfGeneratedCaptchas = 0;
this.numberOfCorrectResponse = 0; this.numberOfCorrectResponse = 0;
this.numberOfUncorrectResponse = 0; this.numberOfUncorrectResponse = 0;
this.numberOfGarbageCollectedCaptcha = 0; this.numberOfGarbageCollectedCaptcha = 0;
this.oldestCaptcha = 0L; this.oldestCaptcha = 0L;
this.setCaptchaStoreMaxSize(maxCaptchaStoreSize); this.setCaptchaStoreMaxSize(maxCaptchaStoreSize);
this.setMinGuarantedStorageDelayInSeconds(minGuarantedStorageDelayInSeconds); this.setMinGuarantedStorageDelayInSeconds(minGuarantedStorageDelayInSeconds);
this.setCaptchaStoreSizeBeforeGarbageCollection((int)Math.round(0.8D * (double)maxCaptchaStoreSize)); this.setCaptchaStoreSizeBeforeGarbageCollection((int) Math.round(0.8D * (double) maxCaptchaStoreSize));
this.times = new FastHashMap(); this.times = new FastHashMap();
} }
protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) { protected AbstractManageableCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
this(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize); this(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize);
if(maxCaptchaStoreSize < captchaStoreLoadBeforeGarbageCollection) { if (maxCaptchaStoreSize < captchaStoreLoadBeforeGarbageCollection) {
throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)"); throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)");
} else { } else {
this.setCaptchaStoreSizeBeforeGarbageCollection(captchaStoreLoadBeforeGarbageCollection); this.setCaptchaStoreSizeBeforeGarbageCollection(captchaStoreLoadBeforeGarbageCollection);
} }
} }
public String getCaptchaEngineClass() { public String getCaptchaEngineClass() {
return this.engine.getClass().getName(); return this.engine.getClass().getName();
} }
public void setCaptchaEngineClass(String theClassName) throws IllegalArgumentException { public void setCaptchaEngineClass(String theClassName) throws IllegalArgumentException {
try { try {
Object e = Class.forName(theClassName).newInstance(); Object e = Class.forName(theClassName).newInstance();
if(e instanceof CaptchaEngine) { if (e instanceof CaptchaEngine) {
this.engine = (CaptchaEngine)e; this.engine = (CaptchaEngine) e;
} else { } else {
throw new IllegalArgumentException("Class is not instance of CaptchaEngine! " + theClassName); throw new IllegalArgumentException("Class is not instance of CaptchaEngine! " + theClassName);
} }
} catch (InstantiationException | IllegalAccessException | RuntimeException | ClassNotFoundException var) { } catch (InstantiationException | IllegalAccessException | RuntimeException | ClassNotFoundException var) {
throw new IllegalArgumentException(var.getMessage()); throw new IllegalArgumentException(var.getMessage());
} }
} }
public CaptchaEngine getEngine() { public CaptchaEngine getEngine() {
return this.engine; return this.engine;
} }
public void setCaptchaEngine(CaptchaEngine engine) { public void setCaptchaEngine(CaptchaEngine engine) {
this.engine = engine; this.engine = engine;
} }
public int getMinGuarantedStorageDelayInSeconds() { public int getMinGuarantedStorageDelayInSeconds() {
return this.minGuarantedStorageDelayInSeconds; return this.minGuarantedStorageDelayInSeconds;
} }
public void setMinGuarantedStorageDelayInSeconds(int theMinGuarantedStorageDelayInSeconds) { public void setMinGuarantedStorageDelayInSeconds(int theMinGuarantedStorageDelayInSeconds) {
this.minGuarantedStorageDelayInSeconds = theMinGuarantedStorageDelayInSeconds; this.minGuarantedStorageDelayInSeconds = theMinGuarantedStorageDelayInSeconds;
} }
public long getNumberOfGeneratedCaptchas() { public long getNumberOfGeneratedCaptchas() {
return (long)this.numberOfGeneratedCaptchas; return (long) this.numberOfGeneratedCaptchas;
} }
public long getNumberOfCorrectResponses() { public void setNumberOfGeneratedCaptchas(int numberOfGeneratedCaptchas) {
return (long)this.numberOfCorrectResponse; this.numberOfGeneratedCaptchas = numberOfGeneratedCaptchas;
} }
public long getNumberOfUncorrectResponses() { public long getNumberOfCorrectResponses() {
return (long)this.numberOfUncorrectResponse; return (long) this.numberOfCorrectResponse;
} }
public int getCaptchaStoreSize() { public long getNumberOfUncorrectResponses() {
return (long) this.numberOfUncorrectResponse;
}
public int getCaptchaStoreSize() {
// return this.store.getSize(); // return this.store.getSize();
return this.times.size(); return this.times.size();
} }
public int getNumberOfGarbageCollectableCaptchas() { public int getNumberOfGarbageCollectableCaptchas() {
return this.getGarbageCollectableCaptchaIds(System.currentTimeMillis()).size(); return this.getGarbageCollectableCaptchaIds(System.currentTimeMillis()).size();
} }
public long getNumberOfGarbageCollectedCaptcha() { public long getNumberOfGarbageCollectedCaptcha() {
return (long)this.numberOfGarbageCollectedCaptcha; return (long) this.numberOfGarbageCollectedCaptcha;
} }
public int getCaptchaStoreSizeBeforeGarbageCollection() { public void setNumberOfGarbageCollectedCaptcha(int numberOfGarbageCollectedCaptcha) {
return this.captchaStoreSizeBeforeGarbageCollection; this.numberOfGarbageCollectedCaptcha = numberOfGarbageCollectedCaptcha;
} }
public void setCaptchaStoreSizeBeforeGarbageCollection(int captchaStoreSizeBeforeGarbageCollection) { public int getCaptchaStoreSizeBeforeGarbageCollection() {
if(this.captchaStoreMaxSize < captchaStoreSizeBeforeGarbageCollection) { return this.captchaStoreSizeBeforeGarbageCollection;
throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)"); }
} else {
this.captchaStoreSizeBeforeGarbageCollection = captchaStoreSizeBeforeGarbageCollection; public void setCaptchaStoreSizeBeforeGarbageCollection(int captchaStoreSizeBeforeGarbageCollection) {
} if (this.captchaStoreMaxSize < captchaStoreSizeBeforeGarbageCollection) {
} throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)");
} else {
public void setCaptchaStoreMaxSize(int size) { this.captchaStoreSizeBeforeGarbageCollection = captchaStoreSizeBeforeGarbageCollection;
if(size < this.captchaStoreSizeBeforeGarbageCollection) { }
throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)"); }
} else {
this.captchaStoreMaxSize = size; public int getCaptchaStoreMaxSize() {
} return this.captchaStoreMaxSize;
} }
public int getCaptchaStoreMaxSize() { public void setCaptchaStoreMaxSize(int size) {
return this.captchaStoreMaxSize; if (size < this.captchaStoreSizeBeforeGarbageCollection) {
} throw new IllegalArgumentException("the max store size can\'t be less than garbage collection size. if you want to disable garbage collection (this is not recommended) you may set them equals (max=garbage)");
} else {
public void garbageCollectCaptchaStore() { this.captchaStoreMaxSize = size;
long now = System.currentTimeMillis(); }
// id 垃圾回收 }
Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now);
// 存储器垃圾回收 public void garbageCollectCaptchaStore() {
this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator()); long now = System.currentTimeMillis();
} // id 垃圾回收
Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now);
protected void garbageCollectCaptchaStore(Iterator garbageCollectableCaptchaIds) { // 存储器垃圾回收
long now = System.currentTimeMillis(); this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator());
long limit = now - (long)(1000 * this.minGuarantedStorageDelayInSeconds); }
while(garbageCollectableCaptchaIds.hasNext()) { protected void garbageCollectCaptchaStore(Iterator garbageCollectableCaptchaIds) {
String id = garbageCollectableCaptchaIds.next().toString(); long now = System.currentTimeMillis();
if((Long) this.times.get(id) < limit) { long limit = now - (long) (1000 * this.minGuarantedStorageDelayInSeconds);
// 清理计数器
this.times.remove(id); while (garbageCollectableCaptchaIds.hasNext()) {
// 对于 redis 存储, 使用其自动失效机制, 不手动清理 String id = garbageCollectableCaptchaIds.next().toString();
if(this.store.getClass() != RedisCaptchaStore.class){ if ((Long) this.times.get(id) < limit) {
this.store.removeCaptcha(id); // 清理计数器
} this.times.remove(id);
++this.numberOfGarbageCollectedCaptcha; // 对于 redis 存储, 使用其自动失效机制, 不手动清理
} if (this.store.getClass() != RedisCaptchaStore.class) {
this.store.removeCaptcha(id);
} }
++this.numberOfGarbageCollectedCaptcha;
} }
}
private Collection getGarbageCollectableCaptchaIds(long now) {
HashSet garbageCollectableCaptchas = new HashSet(); }
long limit = now - (long)(1000 * this.getMinGuarantedStorageDelayInSeconds());
if(limit > this.oldestCaptcha) { private Collection getGarbageCollectableCaptchaIds(long now) {
for (Object o : this.times.keySet()) { HashSet garbageCollectableCaptchas = new HashSet();
String id = (String) o; long limit = now - (long) (1000 * this.getMinGuarantedStorageDelayInSeconds());
long captchaDate = (Long) this.times.get(id); if (limit > this.oldestCaptcha) {
this.oldestCaptcha = Math.min(captchaDate, this.oldestCaptcha == 0L ? captchaDate : this.oldestCaptcha); for (Object o : this.times.keySet()) {
if (captchaDate < limit) { String id = (String) o;
garbageCollectableCaptchas.add(id); long captchaDate = (Long) this.times.get(id);
} this.oldestCaptcha = Math.min(captchaDate, this.oldestCaptcha == 0L ? captchaDate : this.oldestCaptcha);
} if (captchaDate < limit) {
} garbageCollectableCaptchas.add(id);
return garbageCollectableCaptchas;
}
public void emptyCaptchaStore() {
this.store.empty();
this.times = new FastHashMap();
}
protected Captcha generateAndStoreCaptcha(Locale locale, String ID) {
if(this.isCaptchaStoreFull()) {
logger.info("生成图形验证码时检测到, 容量已满, 执行垃圾回收");
long now = System.currentTimeMillis();
Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now);
if(garbageCollectableCaptchaIds.size() > 0) {
this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator());
return this.generateAndStoreCaptcha(locale, ID);
} else {
logger.error("Captcha Store 已满, 但无可回收验证码, 请检查验证码超时配置和验证码临界值!");
throw new CaptchaServiceException("Store is full, try to increase CaptchaStore Size orto decrease time out, or to decrease CaptchaStoreSizeBeforeGrbageCollection");
}
} else {
if(this.isCaptchaStoreQuotaReached()) {
logger.info("生成图形验证码时检测到, 容量已达配额, 执行垃圾回收");
this.garbageCollectCaptchaStore();
}
return this.generateCountTimeStampAndStoreCaptcha(ID, locale);
}
}
private Captcha generateCountTimeStampAndStoreCaptcha(String ID, Locale locale) {
++this.numberOfGeneratedCaptchas;
Long now = System.currentTimeMillis();
this.times.put(ID, now);
return super.generateAndStoreCaptcha(locale, ID);
}
protected boolean isCaptchaStoreFull() {
return this.getCaptchaStoreMaxSize() != 0 && this.getCaptchaStoreSize() >= this.getCaptchaStoreMaxSize();
}
protected boolean isCaptchaStoreQuotaReached() {
return this.getCaptchaStoreSize() >= this.getCaptchaStoreSizeBeforeGarbageCollection();
}
public Boolean validateResponseForID(String ID, Object response) throws CaptchaServiceException {
Boolean valid = super.validateResponseForID(ID, response);
this.times.remove(ID);
if(valid) {
++this.numberOfCorrectResponse;
} else {
++this.numberOfUncorrectResponse;
} }
}
return valid;
} }
public void setNumberOfGeneratedCaptchas(int numberOfGeneratedCaptchas) { return garbageCollectableCaptchas;
this.numberOfGeneratedCaptchas = numberOfGeneratedCaptchas; }
}
public int getNumberOfCorrectResponse() { public void emptyCaptchaStore() {
return numberOfCorrectResponse; this.store.empty();
} this.times = new FastHashMap();
}
public void setNumberOfCorrectResponse(int numberOfCorrectResponse) { protected Captcha generateAndStoreCaptcha(Locale locale, String ID) {
this.numberOfCorrectResponse = numberOfCorrectResponse; if (this.isCaptchaStoreFull()) {
} logger.info("生成图形验证码时检测到, 容量已满, 执行垃圾回收");
long now = System.currentTimeMillis();
public int getNumberOfUncorrectResponse() { Collection garbageCollectableCaptchaIds = this.getGarbageCollectableCaptchaIds(now);
return numberOfUncorrectResponse; if (garbageCollectableCaptchaIds.size() > 0) {
} this.garbageCollectCaptchaStore(garbageCollectableCaptchaIds.iterator());
return this.generateAndStoreCaptcha(locale, ID);
public void setNumberOfUncorrectResponse(int numberOfUncorrectResponse) { } else {
this.numberOfUncorrectResponse = numberOfUncorrectResponse; logger.error("Captcha Store 已满, 但无可回收验证码, 请检查验证码超时配置和验证码临界值!");
} throw new CaptchaServiceException("Store is full, try to increase CaptchaStore Size orto decrease time out, or to decrease CaptchaStoreSizeBeforeGrbageCollection");
}
public void setNumberOfGarbageCollectedCaptcha(int numberOfGarbageCollectedCaptcha) { } else {
this.numberOfGarbageCollectedCaptcha = numberOfGarbageCollectedCaptcha; if (this.isCaptchaStoreQuotaReached()) {
} logger.info("生成图形验证码时检测到, 容量已达配额, 执行垃圾回收");
this.garbageCollectCaptchaStore();
public void addNumberOfGarbageCollectedCaptcha(int num) { }
this.numberOfGarbageCollectedCaptcha += num;
} return this.generateCountTimeStampAndStoreCaptcha(ID, locale);
}
public void addNumberOfUncorrectResponse(int num) { }
this.numberOfUncorrectResponse += num;
} private Captcha generateCountTimeStampAndStoreCaptcha(String ID, Locale locale) {
++this.numberOfGeneratedCaptchas;
public void addNumberOfCorrectResponse(int num){ Long now = System.currentTimeMillis();
this.numberOfCorrectResponse += num; this.times.put(ID, now);
} return super.generateAndStoreCaptcha(locale, ID);
}
public FastHashMap getTimes() {
return times; protected boolean isCaptchaStoreFull() {
} return this.getCaptchaStoreMaxSize() != 0 && this.getCaptchaStoreSize() >= this.getCaptchaStoreMaxSize();
}
public void setTimes(FastHashMap times) {
this.times = times; protected boolean isCaptchaStoreQuotaReached() {
} return this.getCaptchaStoreSize() >= this.getCaptchaStoreSizeBeforeGarbageCollection();
}
public long getOldestCaptcha() {
return oldestCaptcha; public Boolean validateResponseForID(String ID, Object response) throws CaptchaServiceException {
} Boolean valid = super.validateResponseForID(ID, response);
this.times.remove(ID);
public void setOldestCaptcha(long oldestCaptcha) { if (valid) {
this.oldestCaptcha = oldestCaptcha; ++this.numberOfCorrectResponse;
} } else {
++this.numberOfUncorrectResponse;
}
return valid;
}
public int getNumberOfCorrectResponse() {
return numberOfCorrectResponse;
}
public void setNumberOfCorrectResponse(int numberOfCorrectResponse) {
this.numberOfCorrectResponse = numberOfCorrectResponse;
}
public int getNumberOfUncorrectResponse() {
return numberOfUncorrectResponse;
}
public void setNumberOfUncorrectResponse(int numberOfUncorrectResponse) {
this.numberOfUncorrectResponse = numberOfUncorrectResponse;
}
public void addNumberOfGarbageCollectedCaptcha(int num) {
this.numberOfGarbageCollectedCaptcha += num;
}
public void addNumberOfUncorrectResponse(int num) {
this.numberOfUncorrectResponse += num;
}
public void addNumberOfCorrectResponse(int num) {
this.numberOfCorrectResponse += num;
}
public FastHashMap getTimes() {
return times;
}
public void setTimes(FastHashMap times) {
this.times = times;
}
public long getOldestCaptcha() {
return oldestCaptcha;
}
public void setOldestCaptcha(long oldestCaptcha) {
this.oldestCaptcha = oldestCaptcha;
}
} }
...@@ -21,26 +21,26 @@ import java.util.Locale; ...@@ -21,26 +21,26 @@ import java.util.Locale;
* 修改备注: * 修改备注:
*/ */
public abstract class AbstractManageableImageCaptchaService extends AbstractManageableCaptchaService implements ImageCaptchaService { public abstract class AbstractManageableImageCaptchaService extends AbstractManageableCaptchaService implements ImageCaptchaService {
protected AbstractManageableImageCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) { protected AbstractManageableImageCaptchaService(CaptchaStore captchaStore, CaptchaEngine captchaEngine, int minGuarantedStorageDelayInSeconds, int maxCaptchaStoreSize, int captchaStoreLoadBeforeGarbageCollection) {
super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection); super(captchaStore, captchaEngine, minGuarantedStorageDelayInSeconds, maxCaptchaStoreSize, captchaStoreLoadBeforeGarbageCollection);
} }
public BufferedImage getImageChallengeForID(String ID) throws CaptchaServiceException { public BufferedImage getImageChallengeForID(String ID) throws CaptchaServiceException {
return (BufferedImage)this.getChallengeForID(ID); return (BufferedImage) this.getChallengeForID(ID);
} }
public BufferedImage getImageChallengeForID(String ID, Locale locale) throws CaptchaServiceException { public BufferedImage getImageChallengeForID(String ID, Locale locale) throws CaptchaServiceException {
return (BufferedImage)this.getChallengeForID(ID, locale); return (BufferedImage) this.getChallengeForID(ID, locale);
} }
protected Object getChallengeClone(Captcha captcha) { protected Object getChallengeClone(Captcha captcha) {
BufferedImage challenge = (BufferedImage)captcha.getChallenge(); BufferedImage challenge = (BufferedImage) captcha.getChallenge();
BufferedImage clone = new BufferedImage(challenge.getWidth(), challenge.getHeight(), challenge.getType()); BufferedImage clone = new BufferedImage(challenge.getWidth(), challenge.getHeight(), challenge.getType());
clone.getGraphics().drawImage(challenge, 0, 0, clone.getWidth(), clone.getHeight(), null); clone.getGraphics().drawImage(challenge, 0, 0, clone.getWidth(), clone.getHeight(), null);
clone.getGraphics().dispose(); clone.getGraphics().dispose();
return clone; return clone;
} }
public abstract long getCustomStoreSize(); public abstract long getCustomStoreSize();
} }
\ No newline at end of file
...@@ -23,22 +23,22 @@ import java.util.Locale; ...@@ -23,22 +23,22 @@ import java.util.Locale;
*/ */
public class CustomGimpyFactory extends GimpyFactory { public class CustomGimpyFactory extends GimpyFactory {
public CustomGimpyFactory(WordGenerator generator, WordToImage word2image) { public CustomGimpyFactory(WordGenerator generator, WordToImage word2image) {
super(generator, word2image); super(generator, word2image);
} }
@Override
public ImageCaptcha getImageCaptcha(Locale locale) {
Integer wordLength = this.getRandomLength();
String word = this.getWordGenerator().getWord(wordLength, locale);
BufferedImage image;
try { @Override
image = this.getWordToImage().getImage(word); public ImageCaptcha getImageCaptcha(Locale locale) {
} catch (Throwable var6) { Integer wordLength = this.getRandomLength();
throw new CaptchaException(var6); String word = this.getWordGenerator().getWord(wordLength, locale);
} BufferedImage image;
return new SimpleCaptcha(CaptchaQuestionHelper.getQuestion(locale, BUNDLE_QUESTION_KEY), image, word); try {
image = this.getWordToImage().getImage(word);
} catch (Throwable var6) {
throw new CaptchaException(var6);
} }
return new SimpleCaptcha(CaptchaQuestionHelper.getQuestion(locale, BUNDLE_QUESTION_KEY), image, word);
}
} }
...@@ -18,30 +18,30 @@ import java.awt.image.BufferedImage; ...@@ -18,30 +18,30 @@ import java.awt.image.BufferedImage;
*/ */
public class SimpleCaptcha extends ImageCaptcha { public class SimpleCaptcha extends ImageCaptcha {
private String response; private String response;
public SimpleCaptcha(String question, String response) { public SimpleCaptcha(String question, String response) {
this(question, null, response); this(question, null, response);
} }
public SimpleCaptcha(String question, BufferedImage challenge, String response) { public SimpleCaptcha(String question, BufferedImage challenge, String response) {
super(question, challenge); super(question, challenge);
this.response = response; this.response = response;
} }
public final Boolean validateResponse(Object response) { public final Boolean validateResponse(Object response) {
return null != response && response instanceof String ? this.validateResponse((String) response) : Boolean.FALSE; return null != response && response instanceof String ? this.validateResponse((String) response) : Boolean.FALSE;
} }
private Boolean validateResponse(String response) { private Boolean validateResponse(String response) {
return StringUtils.equals(this.response, response); return StringUtils.equals(this.response, response);
} }
public String getResponse() { public String getResponse() {
return response; return response;
} }
public void setResponse(String response) { public void setResponse(String response) {
this.response = response; this.response = response;
} }
} }
...@@ -13,111 +13,111 @@ import org.springframework.stereotype.Component; ...@@ -13,111 +13,111 @@ import org.springframework.stereotype.Component;
@Component @Component
public class ApplicationContextHolder implements ApplicationContextAware { public class ApplicationContextHolder implements ApplicationContextAware {
@Autowired /**
public ApplicationContextHolder(ApplicationContext applicationContext) { * Spring应用上下文环境
this.applicationContext = applicationContext; */
} private static ApplicationContext applicationContext;
/** @Autowired
* Spring应用上下文环境 public ApplicationContextHolder(ApplicationContext applicationContext) {
*/ this.applicationContext = applicationContext;
private static ApplicationContext applicationContext; }
/** /**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境. * 获取一个ApplicationContext.
* *
* @param applicationContext Spring ApplicationContext上下文 * @return ApplicationContext
*/ */
public void setApplicationContext(ApplicationContext applicationContext) { public static ApplicationContext getApplicationContext() {
ApplicationContextHolder.applicationContext = applicationContext; return applicationContext;
} }
/** /**
* 获取一个ApplicationContext. * 实现ApplicationContextAware接口的回调方法,设置上下文环境.
* *
* @return ApplicationContext * @param applicationContext Spring ApplicationContext上下文
*/ */
public static ApplicationContext getApplicationContext() { public void setApplicationContext(ApplicationContext applicationContext) {
return applicationContext; ApplicationContextHolder.applicationContext = applicationContext;
} }
/** /**
* 根据名称获取一个对象. * 根据名称获取一个对象.
* *
* @param name bean名称 * @param name bean名称
* @return Object 指定的bean * @return Object 指定的bean
* @throws BeansException 如果找不到bean * @throws BeansException 如果找不到bean
*/ */
public static <T> T getBean(String name) throws BeansException { public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name); return (T) applicationContext.getBean(name);
} }
/** /**
* 获取名称为name的bean,自动转为所需类型. * 获取名称为name的bean,自动转为所需类型.
* *
* @param <T> 需求的bean类型 * @param <T> 需求的bean类型
* @param name bean名称 * @param name bean名称
* @param requiredType 需求的bean类型 * @param requiredType 需求的bean类型
* @return 指定类型的bean * @return 指定类型的bean
* @throws BeansException 如果找不到匹配的类型,或是类型不能被转换,或是bean实例化失败 * @throws BeansException 如果找不到匹配的类型,或是类型不能被转换,或是bean实例化失败
*/ */
public static <T> T getBean(String name, Class<T> requiredType) throws BeansException { public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType); return applicationContext.getBean(name, requiredType);
} }
/** /**
* 获取类型为requiredType的对象. * 获取类型为requiredType的对象.
* *
* @param <T> 需求的bean类型 * @param <T> 需求的bean类型
* @param requiredType 需求的bean类型 * @param requiredType 需求的bean类型
* @return 指定类型的bean * @return 指定类型的bean
* @throws BeansException 如果找不到匹配的类型 * @throws BeansException 如果找不到匹配的类型
*/ */
public static <T> T getBean(Class<T> requiredType) throws BeansException { public static <T> T getBean(Class<T> requiredType) throws BeansException {
return applicationContext.getBean(requiredType); return applicationContext.getBean(requiredType);
} }
/** /**
* 检测一个bean是否已经被定义. * 检测一个bean是否已经被定义.
* *
* @param name bean名称 * @param name bean名称
* @return boolean 如果bean已经被定义,则返回true,否则返回false * @return boolean 如果bean已经被定义,则返回true,否则返回false
*/ */
public static boolean containsBean(String name) { public static boolean containsBean(String name) {
return applicationContext.containsBean(name); return applicationContext.containsBean(name);
} }
/** /**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype. * 判断以给定名字注册的bean定义是一个singleton还是一个prototype.
* *
* @param name bean名称 * @param name bean名称
* @return boolean 如果是singleton则返回true * @return boolean 如果是singleton则返回true
* @throws NoSuchBeanDefinitionException 如果bean名称不存在 * @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/ */
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name); return applicationContext.isSingleton(name);
} }
/** /**
* 获取给定名字的bean的类型. * 获取给定名字的bean的类型.
* *
* @param name bean名称 * @param name bean名称
* @return Class bean类型 * @return Class bean类型
* @throws NoSuchBeanDefinitionException 如果bean名称不存在 * @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/ */
public static Class getType(String name) throws NoSuchBeanDefinitionException { public static Class getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name); return applicationContext.getType(name);
} }
/** /**
* 取出指定bean的别名列表. * 取出指定bean的别名列表.
* *
* @param name bean名称 * @param name bean名称
* @return 如果有别名,返回别名,否则返回空数组. * @return 如果有别名,返回别名,否则返回空数组.
* @throws NoSuchBeanDefinitionException 如果bean名称不存在 * @throws NoSuchBeanDefinitionException 如果bean名称不存在
*/ */
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name); return applicationContext.getAliases(name);
} }
} }
\ No newline at end of file
...@@ -9,9 +9,9 @@ import java.util.regex.Pattern; ...@@ -9,9 +9,9 @@ import java.util.regex.Pattern;
*/ */
public class EmojiUtil { public class EmojiUtil {
private static final Pattern EMOJI = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]"); private static final Pattern EMOJI = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]");
public static String filter(String str) { public static String filter(String str) {
return str == null || str.trim().isEmpty() ? str : EMOJI.matcher(str).replaceAll(""); return str == null || str.trim().isEmpty() ? str : EMOJI.matcher(str).replaceAll("");
} }
} }
...@@ -11,109 +11,119 @@ import java.util.zip.GZIPOutputStream; ...@@ -11,109 +11,119 @@ import java.util.zip.GZIPOutputStream;
*/ */
public class GZipUtil { public class GZipUtil {
private static String encode = "utf-8";//"ISO-8859-1" private static String encode = "utf-8";//"ISO-8859-1"
public String getEncode() { /**
return encode; * 字符串压缩为字节数组
*/
public static byte[] compressToByte(String str) {
if (str == null || str.length() == 0) {
return null;
} }
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encode));
gzip.close();
/** 设置 编码,默认编码:UTF-8 */ } catch (IOException e) {
public void setEncode(String encode) { e.printStackTrace();
this.encode = encode;
}
/** 字符串压缩为字节数组 */ }
public static byte[] compressToByte(String str) { return out.toByteArray();
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encode));
gzip.close();
} catch (IOException e) { }
e.printStackTrace();
} /**
return out.toByteArray(); * 字符串压缩为字节数组
*/
public static byte[] compressToByte(String str, String encoding) {
if (str == null || str.length() == 0) {
return null;
} }
/** 字符串压缩为字节数组 */ ByteArrayOutputStream out = new ByteArrayOutputStream();
public static byte[] compressToByte(String str, String encoding) { GZIPOutputStream gzip;
if (str == null || str.length() == 0) { try {
return null; gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
} } catch (IOException e) {
e.printStackTrace();
ByteArrayOutputStream out = new ByteArrayOutputStream(); }
GZIPOutputStream gzip; return out.toByteArray();
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
} catch (IOException e) { }
e.printStackTrace();
} /**
return out.toByteArray(); * 字节数组解压缩后返回字符串
*/
public static String uncompressToString(byte[] b) {
if (b == null || b.length == 0) {
return null;
} }
/** 字节数组解压缩后返回字符串 */ ByteArrayOutputStream out = new ByteArrayOutputStream();
public static String uncompressToString(byte[] b) { ByteArrayInputStream in = new ByteArrayInputStream(b);
if (b == null || b.length == 0) { try {
return null; GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
} }
ByteArrayOutputStream out = new ByteArrayOutputStream(); } catch (IOException e) {
ByteArrayInputStream in = new ByteArrayInputStream(b); e.printStackTrace();
try {
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
} }
return out.toString();
} catch (IOException e) { }
e.printStackTrace();
} /**
return out.toString(); * 字节数组解压缩后返回字符串
*/
public static String uncompressToString(byte[] b, String encoding) {
if (b == null || b.length == 0) {
return null;
} }
/** 字节数组解压缩后返回字符串 */ ByteArrayOutputStream out = new ByteArrayOutputStream();
public static String uncompressToString(byte[] b, String encoding) { ByteArrayInputStream in = new ByteArrayInputStream(b);
if (b == null || b.length == 0) { try {
return null; GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
} }
ByteArrayOutputStream out = new ByteArrayOutputStream(); return out.toString(encoding);
ByteArrayInputStream in = new ByteArrayInputStream(b); } catch (IOException e) {
try { e.printStackTrace();
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
} }
return null;
return out.toString(encoding); }
} catch (IOException e) {
e.printStackTrace();
} public String getEncode() {
return null; return encode;
}
} /**
* 设置 编码,默认编码:UTF-8
*/
public void setEncode(String encode) {
this.encode = encode;
}
} }
...@@ -12,30 +12,30 @@ import javax.servlet.http.HttpServletRequest; ...@@ -12,30 +12,30 @@ import javax.servlet.http.HttpServletRequest;
*/ */
public class IPUtil { public class IPUtil {
/** /**
* 通过指定请求获得对应的远程ip地址 * 通过指定请求获得对应的远程ip地址
* *
* @param request * @param request
* @return * @return
*/ */
public static String getRemoteIP(HttpServletRequest request) { public static String getRemoteIP(HttpServletRequest request) {
String ip = request.getHeader("x-real-ip"); String ip = request.getHeader("x-real-ip");
if (StringUtils.isEmpty(ip)) { if (StringUtils.isEmpty(ip)) {
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
//过滤反向代理的ip
String[] stemps = ip.split(",");
if (stemps != null && stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
ip = ip.trim(); //过滤反向代理的ip
if (ip.length() > 23) { String[] stemps = ip.split(",");
ip = ip.substring(0, 23); if (stemps != null && stemps.length >= 1) {
} //得到第一个IP,即客户端真实IP
ip = stemps[0];
}
return ip; ip = ip.trim();
if (ip.length() > 23) {
ip = ip.substring(0, 23);
} }
return ip;
}
} }
...@@ -10,60 +10,62 @@ import java.util.zip.GZIPInputStream; ...@@ -10,60 +10,62 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
public class JR58GzipUtil { public class JR58GzipUtil {
public static String bytesTogzip(byte[] bytes, String encode) { public static String bytesTogzip(byte[] bytes, String encode) {
if(bytes==null || bytes.length==0){ if (bytes == null || bytes.length == 0) {
return null; return null;
} }
ByteArrayInputStream byteArrayIn=null;
GZIPInputStream in = null;
ByteArrayOutputStream byteArrayout = new ByteArrayOutputStream(); ByteArrayInputStream byteArrayIn = null;
PrintStream out= new PrintStream(byteArrayout); GZIPInputStream in = null;
try {
byteArrayIn= new ByteArrayInputStream(bytes);
in = new GZIPInputStream(byteArrayIn);
byte[] b = new byte[1024];
int readlen = 0;;
while((readlen=in.read(b))!=-1){
out.write(b, 0, readlen);
}
out.flush();
} catch (IOException e) { ByteArrayOutputStream byteArrayout = new ByteArrayOutputStream();
e.printStackTrace(); PrintStream out = new PrintStream(byteArrayout);
} finally{ try {
try { byteArrayIn = new ByteArrayInputStream(bytes);
byteArrayIn.close(); in = new GZIPInputStream(byteArrayIn);
in.close(); byte[] b = new byte[1024];
} catch (IOException e) { int readlen = 0;
e.printStackTrace(); ;
} while ((readlen = in.read(b)) != -1) {
} out.write(b, 0, readlen);
System.out.println("解密后的数据:"); }
return new String(byteArrayout.toByteArray(),Charset.forName(encode)); out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
byteArrayIn.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
public static byte[] gzipTobytes(String str, String encode) { System.out.println("解密后的数据:");
if(str==null || str.length()==0){ return new String(byteArrayout.toByteArray(), Charset.forName(encode));
return null;
} }
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip= new GZIPOutputStream(out);
gzip.write(str.getBytes(encode));
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return out.toByteArray();
public static byte[] gzipTobytes(String str, String encode) {
if (str == null || str.length() == 0) {
return null;
} }
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encode));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return out.toByteArray();
}
} }
...@@ -7,28 +7,28 @@ import java.security.MessageDigest; ...@@ -7,28 +7,28 @@ import java.security.MessageDigest;
*/ */
public class PasswordUtil { public class PasswordUtil {
private static final char[] HEX_DIGITS = { private static final char[] HEX_DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
}; };
public final static String MD5(String s) { public final static String MD5(String s) {
try { try {
byte[] strTemp = s.getBytes("utf-8"); byte[] strTemp = s.getBytes("utf-8");
MessageDigest mdTemp = MessageDigest.getInstance("MD5"); MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp); mdTemp.update(strTemp);
byte[] md = mdTemp.digest(); byte[] md = mdTemp.digest();
int j = md.length; int j = md.length;
char[] str = new char[j << 1]; char[] str = new char[j << 1];
int k = 0; int k = 0;
for (int i = 0; i < j; i++) { for (int i = 0; i < j; i++) {
byte byte0 = md[i]; byte byte0 = md[i];
str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf]; str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
str[k++] = HEX_DIGITS[byte0 & 0xf]; str[k++] = HEX_DIGITS[byte0 & 0xf];
} }
return new String(str); return new String(str);
} catch (Exception e) { } catch (Exception e) {
return null; return null;
}
} }
}
} }
package cn.quantgroup.xyqb.util; package cn.quantgroup.xyqb.util;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Map; import java.util.Map;
/** /**
...@@ -10,23 +7,23 @@ import java.util.Map; ...@@ -10,23 +7,23 @@ import java.util.Map;
*/ */
public class Utils { public class Utils {
public static String safeMap2Str(Map<String, String> info) { public static String safeMap2Str(Map<String, String> info) {
if (null == info) { if (null == info) {
return null; return null;
}
StringBuilder builder = new StringBuilder();
builder.append("{");
info.forEach((key, value) -> {
if ("password".equals(key)) {
return;
}
builder.append(key);
builder.append("=");
builder.append(value);
builder.append(",");
});
builder.append("}");
return builder.toString();
} }
StringBuilder builder = new StringBuilder();
builder.append("{");
info.forEach((key, value) -> {
if ("password".equals(key)) {
return;
}
builder.append(key);
builder.append("=");
builder.append(value);
builder.append(",");
});
builder.append("}");
return builder.toString();
}
} }
...@@ -11,42 +11,42 @@ import java.util.regex.Pattern; ...@@ -11,42 +11,42 @@ import java.util.regex.Pattern;
*/ */
public class ValidationUtil { public class ValidationUtil {
private static String regExp = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$"; private static String regExp = "^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
private static String chineseExp = "^[\u4e00-\u9fa5]+(\\.|·)?[\u4e00-\u9fa5]+$"; private static String chineseExp = "^[\u4e00-\u9fa5]+(\\.|·)?[\u4e00-\u9fa5]+$";
private static Pattern phonePattern = Pattern.compile(regExp); private static Pattern phonePattern = Pattern.compile(regExp);
private static Pattern chinesePattern = Pattern.compile(chineseExp); private static Pattern chinesePattern = Pattern.compile(chineseExp);
public static boolean validatePhoneNo(String phoneNo) { public static boolean validatePhoneNo(String phoneNo) {
boolean lengthValid = StringUtils.isNotEmpty(phoneNo) && phoneNo.length() == 11 && StringUtils.isNumeric(phoneNo); boolean lengthValid = StringUtils.isNotEmpty(phoneNo) && phoneNo.length() == 11 && StringUtils.isNumeric(phoneNo);
if (!lengthValid) { if (!lengthValid) {
return false; return false;
} }
Matcher matcher = phonePattern.matcher(phoneNo); Matcher matcher = phonePattern.matcher(phoneNo);
return matcher.find(); return matcher.find();
} }
public static boolean validateChinese(String chinese) { public static boolean validateChinese(String chinese) {
if (StringUtils.isEmpty(chinese)) { if (StringUtils.isEmpty(chinese)) {
return false; return false;
}
Matcher matcher = chinesePattern.matcher(chinese);
return matcher.find();
} }
Matcher matcher = chinesePattern.matcher(chinese);
return matcher.find();
}
public static boolean validateChannelId(Long channelId) { public static boolean validateChannelId(Long channelId) {
return channelId == 0L ? false : true; return channelId == 0L ? false : true;
} }
public static boolean isNull(Object object) { public static boolean isNull(Object object) {
if (object == null) { if (object == null) {
return true; return true;
}
return false;
} }
return false;
}
} }
...@@ -20,131 +20,131 @@ import java.io.StringWriter; ...@@ -20,131 +20,131 @@ import java.io.StringWriter;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public class XmlUtil { public class XmlUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(XmlUtil.class); private static final Logger LOGGER = LoggerFactory.getLogger(XmlUtil.class);
/** /**
* Disable new * Disable new
*/ */
private XmlUtil() { private XmlUtil() {
} }
/** /**
* XML => Object * XML => Object
* *
* @param xml * @param xml
* @param clazz * @param clazz
* @param <T> * @param <T>
* @return * @return
*/ */
public static <T> T obj(String xml, Class<T> clazz) { public static <T> T obj(String xml, Class<T> clazz) {
if (StringUtils.isEmpty(xml)) { if (StringUtils.isEmpty(xml)) {
return null; return null;
} }
Reader reader = null; Reader reader = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xml);
return (T) unmarshaller.unmarshal(reader);
} catch (Exception e) {
LOGGER.error("Parse XML to Object error\nXML:{}\nClass<T>:{}", xml, clazz.getName(), e);
return null;
} finally {
if (reader != null) {
try { try {
JAXBContext context = JAXBContext.newInstance(clazz); reader.close();
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xml);
return (T) unmarshaller.unmarshal(reader);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Parse XML to Object error\nXML:{}\nClass<T>:{}", xml, clazz.getName(), e); LOGGER.error("Close Reader error", e);
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
LOGGER.error("Close Reader error", e);
}
}
} }
}
} }
}
/** /**
* Object => XML * Object => XML
* *
* @param obj * @param obj
* @param clazz * @param clazz
* @param <T> * @param <T>
* @return * @return
*/ */
public static <T> String xml(Object obj, Class<T> clazz) { public static <T> String xml(Object obj, Class<T> clazz) {
return doXml(obj, clazz, "UTF-8", false); return doXml(obj, clazz, "UTF-8", false);
} }
/** /**
* Object => XML * Object => XML
* *
* @param obj * @param obj
* @param clazz * @param clazz
* @param charset * @param charset
* @param <T> * @param <T>
* @return * @return
*/ */
public static <T> String xml(Object obj, Class<T> clazz, String charset) { public static <T> String xml(Object obj, Class<T> clazz, String charset) {
return doXml(obj, clazz, charset, false); return doXml(obj, clazz, charset, false);
} }
/** /**
* Object => XML pretty * Object => XML pretty
* *
* @param obj * @param obj
* @param clazz * @param clazz
* @param <T> * @param <T>
* @return * @return
*/ */
public static <T> String xmlPretty(Object obj, Class<T> clazz) { public static <T> String xmlPretty(Object obj, Class<T> clazz) {
return doXml(obj, clazz, "UTF-8", true); return doXml(obj, clazz, "UTF-8", true);
} }
/** /**
* Object => XML pretty * Object => XML pretty
* *
* @param obj * @param obj
* @param clazz * @param clazz
* @param charset * @param charset
* @param <T> * @param <T>
* @return * @return
*/ */
public static <T> String xmlPretty(Object obj, Class<T> clazz, String charset) { public static <T> String xmlPretty(Object obj, Class<T> clazz, String charset) {
return doXml(obj, clazz, charset, true); return doXml(obj, clazz, charset, true);
} }
/** /**
* Object => XML * Object => XML
* *
* @param obj * @param obj
* @param clazz * @param clazz
* @param pretty * @param pretty
* @param <T> * @param <T>
* @return * @return
*/ */
private static <T> String doXml(Object obj, Class<T> clazz, String charset, boolean pretty) { private static <T> String doXml(Object obj, Class<T> clazz, String charset, boolean pretty) {
if (obj == null || clazz == null) { if (obj == null || clazz == null) {
return null; return null;
} }
StringWriter writer = null; StringWriter writer = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, pretty);
writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
} catch (Exception e) {
LOGGER.error("Parse Object to XML error\nXML:{}\nClass<T>:{}", obj.getClass().getName(), clazz.getName(), e);
return null;
} finally {
if (writer != null) {
try { try {
JAXBContext context = JAXBContext.newInstance(clazz); writer.close();
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, pretty);
writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("Parse Object to XML error\nXML:{}\nClass<T>:{}", obj.getClass().getName(), clazz.getName(), e); LOGGER.error("Close Writer error", e);
return null;
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
LOGGER.error("Close Writer error", e);
}
}
} }
}
} }
}
} }
server.port=8080 server.port=8080
security.sessions=if_required security.sessions=if_required
spring.aop.proxy-target-class=true spring.aop.proxy-target-class=true
configserver.disable=1 configserver.disable=1
configserver.system=xyqb-user configserver.system=xyqb-user
xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8 xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.163:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8
xyqb.data.mysql.password=qatest xyqb.data.mysql.password=qatest
...@@ -15,7 +15,7 @@ xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If- ...@@ -15,7 +15,7 @@ xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-
xyqb.data.redis.defaultExpiration=3600 xyqb.data.redis.defaultExpiration=3600
# redis # redis
xyqb.redis.master.host=192.168.4.13 xyqb.redis.master.host=192.168.4.163
xyqb.redis.master.port=6379 xyqb.redis.master.port=6379
xyqb.redis.master.name= xyqb.redis.master.name=
xyqb.redis.sentinel1.host= xyqb.redis.sentinel1.host=
...@@ -29,7 +29,7 @@ xyqb.redis.sentinel3.port=0 ...@@ -29,7 +29,7 @@ xyqb.redis.sentinel3.port=0
sms.is.debug=1 sms.is.debug=1
# LKB client # LKB client
lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi lkb.client.url=http://192.168.192.163:8082/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json lkb.client.user.update=/new/register/updateUser.json
...@@ -42,9 +42,9 @@ lkb.url=http://192.168.192.251:8081/LKB ...@@ -42,9 +42,9 @@ lkb.url=http://192.168.192.251:8081/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb # xyqb
xyqb.url=http://192.168.192.206:8999 xyqb.url=http://192.168.192.163:8999
xyqb.api.url=http://192.168.192.206:9004 xyqb.api.url=http://192.168.192.163:9004
# JR58 # JR58
jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q== jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q==
...@@ -69,4 +69,19 @@ usersys.url=http://localhost:9001 ...@@ -69,4 +69,19 @@ usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.100.36:7043 xyqb-user.ui=http://192.168.100.36:7043
wechat.appid=wxcdf6077af8127559 wechat.appid=wxcdf6077af8127559
wechat.secret=16eaec16084d0d9c52d4114f359cc72c wechat.secret=16eaec16084d0d9c52d4114f359cc72c
\ No newline at end of file
#motan protocol
protocol.name=motan
protocol.contentLength=1048576
protocol.isDefault=true
#motan registry center
registry.protocol=zookeeper
registry.address=192.168.4.163:2181
motan.port=8086
motan.user.group=userGroup
motan.user.module=user-motan-rpc
motan.application=xyqbUserMotan
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
\ No newline at end of file
server.port=9001 server.port=9001
security.sessions=if_required security.sessions=if_required
server.session-timeout=5184000 server.session-timeout=5184000
spring.aop.proxy-target-class=true spring.aop.proxy-target-class=true
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
<logger name="ch.qos.logback" level="warn"/> <logger name="ch.qos.logback" level="warn"/>
<root level="info"> <root level="info">
<appender-ref ref="FILE" /> <appender-ref ref="FILE"/>
</root> </root>
</configuration> </configuration>
\ No newline at end of file
configserver.disable=0 configserver.disable=0
configserver.system=xyqb-user configserver.system=xyqb-user
xyqb.data.mysql.max-pool-size=1000 xyqb.data.mysql.max-pool-size=1000
# CORS # CORS
xyqb.filter.allowedOrigin=* xyqb.filter.allowedOrigin=*
xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization
xyqb.data.redis.defaultExpiration=3600 xyqb.data.redis.defaultExpiration=3600
# redis # redis
xyqb.redis.master.host=172.16.1.179 xyqb.redis.master.host=172.16.1.179
xyqb.redis.master.port=6373 xyqb.redis.master.port=6373
...@@ -19,34 +15,38 @@ xyqb.redis.sentinel2.host=172.16.1.180 ...@@ -19,34 +15,38 @@ xyqb.redis.sentinel2.host=172.16.1.180
xyqb.redis.sentinel2.port=26373 xyqb.redis.sentinel2.port=26373
xyqb.redis.sentinel3.host=172.16.1.181 xyqb.redis.sentinel3.host=172.16.1.181
xyqb.redis.sentinel3.port=26373 xyqb.redis.sentinel3.port=26373
# 短信平台配置 # 短信平台配置
sms.is.debug=0 sms.is.debug=0
# LKB client # LKB client
lkb.client.url=http://openapi.quantgroup.cn/LKBClient/openapi lkb.client.url=http://openapi.quantgroup.cn/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json lkb.client.user.update=/new/register/updateUser.json
# LKB import # LKB import
lkb.import.url=http://spider.quantgroup.cn lkb.import.url=http://spider.quantgroup.cn
# LKB # LKB
lkb.url=http://58.xyqb.com/LKB lkb.url=http://58.xyqb.com/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb # xyqb
xyqb.url=http://m.xyqb.com xyqb.url=http://m.xyqb.com
xyqb.api.url=http://api.xyqb.com xyqb.api.url=http://api.xyqb.com
# JR58 # JR58
jr58.notify.userinfo=http://dk.58.com/customer/quantgroup_user_info jr58.notify.userinfo=http://dk.58.com/customer/quantgroup_user_info
#sdk #sdk
model.quantgroup.url=http://model.quantgroup.cn model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://auth.xyqb.com xyqb.auth.url=http://auth.xyqb.com
xyqb-user.ui=http://passport.xyqb.com
xyqb-user.ui=http://passport.xyqb.com #motan protocol
\ No newline at end of file protocol.name=motan
protocol.contentLength=1048576
protocol.isDefault=true
#motan registry center
registry.protocol=zookeeper
registry.address=172.16.1.63:2181,172.16.1.64:2181,172.16.1.65:2181
motan.port=8082
motan.user.group=userGroup
motan.user.module=user-motan-rpc
motan.application=xyqbUserMotan
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
\ No newline at end of file
server.port=9001 server.port=9001
security.sessions=if_required security.sessions=if_required
spring.aop.proxy-target-class=true spring.aop.proxy-target-class=true
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
<logger name="ch.qos.logback" level="warn"/> <logger name="ch.qos.logback" level="warn"/>
<root level="info"> <root level="info">
<appender-ref ref="FILE" /> <appender-ref ref="FILE"/>
</root> </root>
</configuration> </configuration>
\ No newline at end of file
configserver.disable=1 configserver.disable=1
configserver.system=xyqb-user configserver.system=xyqb-user
xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8 xyqb.data.mysql.jdbc-url=jdbc:mysql://192.168.4.104:3306/xyqb_user?useUnicode=true&characterEncoding=UTF8
xyqb.data.mysql.password=qatest xyqb.data.mysql.password=qatest
xyqb.data.mysql.user=qa xyqb.data.mysql.user=qa
xyqb.data.mysql.max-pool-size=20 xyqb.data.mysql.max-pool-size=20
# CORS # CORS
xyqb.filter.allowedOrigin=* xyqb.filter.allowedOrigin=*
xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization xyqb.filter.allowedHeaders=Origin, No-Cache, x-auth-token, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type,Authorization
xyqb.data.redis.defaultExpiration=3600 xyqb.data.redis.defaultExpiration=3600
# redis # redis
xyqb.redis.master.host=192.168.4.103 xyqb.redis.master.host=192.168.4.103
xyqb.redis.master.port=6379 xyqb.redis.master.port=6379
...@@ -24,49 +18,37 @@ xyqb.redis.sentinel2.host= ...@@ -24,49 +18,37 @@ xyqb.redis.sentinel2.host=
xyqb.redis.sentinel2.port=0 xyqb.redis.sentinel2.port=0
xyqb.redis.sentinel3.host= xyqb.redis.sentinel3.host=
xyqb.redis.sentinel3.port=0 xyqb.redis.sentinel3.port=0
# 短信平台配置 # 短信平台配置
sms.is.debug=1 sms.is.debug=1
# LKB client # LKB client
lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi lkb.client.url=http://192.168.192.251:8082/LKBClient/openapi
lkb.client.user.register.app=/new/register/registerApp.json lkb.client.user.register.app=/new/register/registerApp.json
lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json lkb.client.user.register.58jr=/new/register/jr58/saveUserInfo.json
lkb.client.user.update=/new/register/updateUser.json lkb.client.user.update=/new/register/updateUser.json
# LKB import # LKB import
lkb.import.url=http://spider.quantgroup.cn lkb.import.url=http://spider.quantgroup.cn
# LKB # LKB
lkb.url=http://192.168.192.251:8081/LKB lkb.url=http://192.168.192.251:8081/LKB
lkb.entrypoint.jr58=/jr58/arc_all.html lkb.entrypoint.jr58=/jr58/arc_all.html
# xyqb # xyqb
xyqb.url=http://192.168.192.206:8999 xyqb.url=http://192.168.192.206:8999
xyqb.api.url=http://192.168.192.206:9004 xyqb.api.url=http://192.168.192.206:9004
# JR58 # JR58
jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q== jr58.sign.key=MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKG/Y0J/c+JguU6cPdFHRC9eHrkgaZ9bpYpeQVujBpL+OkA8pAQTZ1XhoLZu/IH4Rv2kx85e8WVF7FxIFkgqJobjvai2XsD7QRYHGb6EEsqjROPndxnlpLeXmyp+WvbPhtRMoLyP3bZncaR1xsPkmW4ajXSUCa4+qlEfrEMskG79AgMBAAECgYAYmA5StSh8unJSxqULpkdy4F/RjGEjDv9by7sqYN6GCUv4KoBR8lVbFKSoOLYCWSsKND0BXyRbXsdyvK9Op8IVsKIbUnpen5V2cgNrVhlomy7E7RFSdoyFcRuWzck0NGtjJLPzi4qztiKprFH8yMf3tfD8aEKMo7pFpqetGfkezQJBANZTUTiGePRsiO7igin92jf9pWeSiI9OecQ/9hxwIlXXxQAwMUcvvyjoKfp6TRs3HlYugoiP/5VwTWRM/iTbf18CQQDBMtpKI5NtgrpfqbN2czP35S7VOnYO0QofEEuLj3oVCo2CxXfz0cViY/ng3BFk/oTykbMmS/TxCD5VHi17QRsjAkEAv9/3ZtN8ldZVAQhn35AUPOwnmIHnH+TxvnBEtVDubEuvYmvCsihcyxKOAmBbh3HhBua8leXUusS/hHwpSnX3oQJAc4eLTYZUpMnl1UrPjGd7jiO4i72310hduxGtezlDEc4LrUWUY3Lvi9SpGjO/GxuwOLWz4ZTOVkxNqeyv2eKm7QJAQHvgO0ciDFuFuhahFli7ktyZcn5CV8PPkQrbMXUFrMbX3AP61HPyH9EGCqBvsdyRYqPxFseDFY3yYveOWMPq0Q==
jr58.notify.userinfo=http://xfd.test.58v5.cn/customer/quantgroup_user_info jr58.notify.userinfo=http://xfd.test.58v5.cn/customer/quantgroup_user_info
# 图形验证码 # 图形验证码
# 是否启用超级验证码 "__SUPERQG__", 用于测试环境自动化测试, 线上环境可忽略此参数 # 是否启用超级验证码 "__SUPERQG__", 用于测试环境自动化测试, 线上环境可忽略此参数
xyqb.auth.captcha.super.enable=1 xyqb.auth.captcha.super.enable=1
#首参数校验 #首参数校验
xyqb.fplock.limit.byhour=3 xyqb.fplock.limit.byhour=3
xyqb.fplock.limit.byday=5 xyqb.fplock.limit.byday=5
#sdk #sdk
model.quantgroup.url=http://model.quantgroup.cn model.quantgroup.url=http://model.quantgroup.cn
xyqb.auth.url=http://192.168.192.206:9001 xyqb.auth.url=http://192.168.192.206:9001
usersys.url=http://localhost:9001 usersys.url=http://localhost:9001
xyqb-user.ui=http://192.168.12.40:8080 xyqb-user.ui=http://192.168.12.40:8080
wechat.appid=wxcdf6077af8127559 wechat.appid=wxcdf6077af8127559
wechat.secret=16eaec16084d0d9c52d4114f359cc72c wechat.secret=16eaec16084d0d9c52d4114f359cc72c
\ No newline at end of file
#xyqb-user-域名
xyqb.user.domain=passport.xyqb.com
\ No newline at end of file
...@@ -8,50 +8,48 @@ import org.junit.Assert; ...@@ -8,50 +8,48 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.validation.constraints.AssertTrue;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Bootstrap.class) @SpringApplicationConfiguration(classes = Bootstrap.class)
@WebAppConfiguration @WebAppConfiguration
public class DemoApplicationTests { public class DemoApplicationTests {
@Autowired @Autowired
private UserController userController; private UserController userController;
@Autowired @Autowired
private SmsController smsController; private SmsController smsController;
private String smsRegCode = ""; private String smsRegCode = "";
@Test @Test
public void sendRegCode() { public void sendRegCode() {
JsonResult jsonResult = smsController.sendRegistCode("18611428880", null); JsonResult jsonResult = smsController.sendRegistCode("18611428880", null);
System.out.print(jsonResult.getMsg()); System.out.print(jsonResult.getMsg());
Assert.assertEquals(jsonResult.getCode(), "0000"); Assert.assertEquals(jsonResult.getCode(), "0000");
Assert.assertEquals(jsonResult.getBusinessCode(), "0000"); Assert.assertEquals(jsonResult.getBusinessCode(), "0000");
} }
@Test @Test
public void registerFast() { public void registerFast() {
JsonResult jsonResult = userController.registerFast("18611428880", "000000", null, null, ""); JsonResult jsonResult = userController.registerFast("18611428880", "000000", null, null, "");
Assert.assertEquals(jsonResult.getCode(), "0000"); Assert.assertEquals(jsonResult.getCode(), "0000");
} }
@Test @Test
public void sendLoginCode() { public void sendLoginCode() {
JsonResult jsonResult = smsController.sendLoginCode("18611428880", null); JsonResult jsonResult = smsController.sendLoginCode("18611428880", null);
Assert.assertEquals(jsonResult.getCode(), "0000"); Assert.assertEquals(jsonResult.getCode(), "0000");
} }
@Test @Test
public void loginFast() { public void loginFast() {
} }
} }
...@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.Bootstrap; ...@@ -4,8 +4,6 @@ import cn.quantgroup.xyqb.Bootstrap;
import cn.quantgroup.xyqb.controller.internal.user.UserController; import cn.quantgroup.xyqb.controller.internal.user.UserController;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
...@@ -20,23 +18,14 @@ import org.springframework.test.context.web.WebAppConfiguration; ...@@ -20,23 +18,14 @@ import org.springframework.test.context.web.WebAppConfiguration;
@WebAppConfiguration @WebAppConfiguration
public class TestUserLogin { public class TestUserLogin {
private static final Logger LOGGER = LoggerFactory.getLogger(TestUserLogin.class); private MockHttpServletRequest request;
@Autowired
private UserController userController;
private MockHttpServletRequest request; @Test
public void testUserLogin() {
@Autowired //访问xyqb-user拿到登录token
private UserController userController;
@Test
public void testLogAppender(){
LOGGER.info("test customer logger appender:[{}]",74646);
System.out.println("%%%%%%");
}
@Test
public void testUserLogin(){
//访问xyqb-user拿到登录token
/*Long channelId = 1L; /*Long channelId = 1L;
String appChannel = "3"; String appChannel = "3";
Long createFrom = 152L; Long createFrom = 152L;
...@@ -67,6 +56,6 @@ public class TestUserLogin { ...@@ -67,6 +56,6 @@ public class TestUserLogin {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
}*/ }*/
} }
} }
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