Commit 52bb15fa authored by alex yao's avatar alex yao

init

parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.com.gsst</groupId>
<artifactId>auth</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>cn.com.yict.framemax</groupId>
<artifactId>framemax-core</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>cn.com.yict.framemax</groupId>
<artifactId>framemax-data-hibernate</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>cn.com.yict.framemax</groupId>
<artifactId>framemax-common</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>cn.com.yict.framemax</groupId>
<artifactId>framemax-security</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>cn.com.yict.framemax</groupId>
<artifactId>framemax-frame</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>cn.com.yict.framemax</groupId>
<artifactId>framemax-webservice</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-cas</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.10</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.0</version>
</dependency>
<!-- jedis依赖 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.baidubce</groupId>
<artifactId>bce-java-sdk</artifactId>
<version>0.10.328</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-customsearch</artifactId>
<version>v1-rev20240821-2.0.0</version>
</dependency>
</dependencies>
<build>
<finalName>gsst-auth</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.sql</include>
</includes>
</resource>
<resource>
<directory>src/main/resources/</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<!-- 绑定source插件到Maven的生命周期,并在生命周期后执行绑定的source的goal -->
<executions>
<execution>
<!-- 绑定source插件到Maven的生命周期 -->
<phase>package</phase>
<!--在生命周期后执行绑定的source插件的goals -->
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>aliyun</id>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
<repository>
<id>yict</id>
<name>Nexus ISD</name>
<url>http://nexus3.gsstcloud.com:8090/nexus/content/groups/public</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>releases</id>
<name>Releases</name>
<url>http://nexus3.gsstcloud.com:8090/nexus/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<name>Snapshots</name>
<url>http://nexus3.gsstcloud.com:8090/nexus/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
\ No newline at end of file
package cn.com.gsst.auth.common.constant;
/**
* @author Focan.Zhong
*/
public interface CommonConstant {
/**
* 是否删除 Y-是 N-否
*/
interface IsDeleted {
String Y = "Y";
String N = "N";
}
/**
* 使用中 使用中,0:默认,非使用中|1:使用中
*/
interface IsUsed {
/**
* 使用中
*/
Integer Y = 0;
/**
* 未使用
*/
Integer N = 1;
}
/**
*
*/
interface YOrN {
String Y = "Y";
String N = "N";
}
/**
*
*/
interface SYSTEM_FIELD {
String SYSTEM = "SYSTEM";
}
int ZERO = 0;
}
package cn.com.gsst.auth.common.constant;
/**
* @author Roger Wu
*/
public interface FmxParamConfigConstant {
//token过期时间配置
String TOKEN_EXPIRED_HOURS = "login.tokenExpiredHours";
interface Prefix {
/**
* 营销工具中台
*/
public static final String DG_TOOLS = "dg.tools.project";
}
/**
* 营销中台
*/
interface Dgtools {
/**
* 项目key
*/
public static final String PROJECT_KEY ="dg.tools.project.key";
/**
* 项目密钥
*/
public static final String PROJECT_SECRET ="dg.tools.project.secret";
/**
* 加密私钥
*/
public static final String PRIVATE_KEY ="dg.tools.project.private.key";
/**
* 加密偏移量
*/
public static final String VI ="dg.tools.project.vi";
}
/**
* String TOKEN_EXPIRED_HOURS = "login.tokenExpiredHours";
* <p>
* <p>
* /**
* 小程序设计轮播图、文字轮播配置
*/
interface Design {
String PREFIX = "mp.design.config.list";
//跑马灯
String MARQUEE = "marquee";
//轮播图
String SLIDE_SHOW = "slideshow";
//content-detail
String CONTENT_DETAIL = "content-detail";
//jumpType
String JUMP_TYPE = "jumpType";
//jumpQuery
String JUMP_QUERY = "jumpQuery";
//contentId
String CONTENT_ID = "contentId";
}
}
package cn.com.gsst.auth.common.constant;
/**
* 第三方登录渠道
**/
public enum Member3ptLoginChannel {
/**
* 微信小程序
*/
wx_mini,
/**
* 公众号
*/
wx_pub,
/**
* 手机验证码
*/
app_verification_code,
/**
* 密码登录
*/
app_password,
ibt,
;
}
package cn.com.gsst.auth.common.constant;
/**
*
*/
public interface RedisKeyConstant {
public class Code{
/**
* 验证码授权码
*/
public final static String AUTH_CODE = "auth_code:";
}
}
\ No newline at end of file
package cn.com.gsst.auth.common.dto;
import cn.com.gsst.auth.support.sms.constant.SmsConstant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
/**
* @author Focan.Zhong
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class SmsDto implements Serializable {
private SmsConstant.Channel channel;
/**
* 手机号
*/
private String mobilePhone;
/**
* 手机验证码
*/
private String smsCode;
//验证码请求体
/**
* verifyCodeType String 是 短信验证码类型(必传)
* * 1.发送快捷登录或注册短信,
* * 2.发送语音短信,
* * 4.重置密码发送短信,
* * 5.风控发送短信
* verifyImgType String 是 图形、滑块验证类型(必传) 2.图形验证码,3.滑块验证
* verifyImgCode String 否 图形验证码(verifyImgType=2时必填)
* uniqueFlag String 是 滑块唯一标识(verifyImgType=3时必填)
* xPercent String 是 滑块横坐标所占比例 (verifyImgType=3时必填) @mock=1
*/
private String verifyCodeType;
private String verifyImgType;
private String verifyImgCode;
private String uniqueFlag;
private String xPercent;
/**
* 滑块开关
*/
private String captchaSwitch;
/**
* 滑块大图
*/
private String oriCopyImages;
/**
* 滑块图
*/
private String slideImages;
public SmsConstant.Channel getChannel() {
return channel;
}
public void setChannel(SmsConstant.Channel channel) {
this.channel = channel;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getSmsCode() {
return smsCode;
}
public void setSmsCode(String smsCode) {
this.smsCode = smsCode;
}
public String getVerifyCodeType() {
return verifyCodeType;
}
public void setVerifyCodeType(String verifyCodeType) {
this.verifyCodeType = verifyCodeType;
}
public String getVerifyImgType() {
return verifyImgType;
}
public void setVerifyImgType(String verifyImgType) {
this.verifyImgType = verifyImgType;
}
public String getVerifyImgCode() {
return verifyImgCode;
}
public void setVerifyImgCode(String verifyImgCode) {
this.verifyImgCode = verifyImgCode;
}
public String getUniqueFlag() {
return uniqueFlag;
}
public void setUniqueFlag(String uniqueFlag) {
this.uniqueFlag = uniqueFlag;
}
public String getxPercent() {
return xPercent;
}
public void setxPercent(String xPercent) {
this.xPercent = xPercent;
}
public String getCaptchaSwitch() {
return captchaSwitch;
}
public void setCaptchaSwitch(String captchaSwitch) {
this.captchaSwitch = captchaSwitch;
}
public String getOriCopyImages() {
return oriCopyImages;
}
public void setOriCopyImages(String oriCopyImages) {
this.oriCopyImages = oriCopyImages;
}
public String getSlideImages() {
return slideImages;
}
public void setSlideImages(String slideImages) {
this.slideImages = slideImages;
}
}
package cn.com.gsst.auth.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
/**
* @author alex.yao
* @date 2024/12/24
*/
@Permission(Access.Anonymous)
public interface GoogleConfigRest extends BaseRest {
/**
* 获取谷歌client_id
*/
String getClientId();
}
package cn.com.gsst.auth.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
@Permission(Access.Anonymous)
public interface JudgeCodeRest extends BaseRest {
/**
* 校验验证码是否正确
*
* @param account,code
* @throws Exception
*/
boolean judgeCode(@RequestParam String account, @RequestParam String code) throws Exception;
/**
* 校验验证码是否正确,正确的话就返回授权码,可以给别的业务操作
*
* @param account,code
* @throws Exception
*/
String judgeCodeReturnAuthCode(@RequestParam String account, @RequestParam String code) throws Exception;
}
package cn.com.gsst.auth.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
@Permission(Access.Anonymous)
public interface SendEmailRest extends BaseRest {
/**
* 发送邮件 验证码发送
* @param emailAddress
* @throws Exception
* */
void sendEmailCode(@RequestParam String emailAddress) throws Exception;
}
package cn.com.gsst.auth.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author jennie.chen
* @date 2024/7/22
**/
@Permission(Access.Anonymous)
public interface SmsRest extends BaseRest{
/**
* 短信下发(获取验证码)
*
* @param phone
* @throws Exception
*/
void smsDelivered(@RequestParam String phone) throws Exception;
}
package cn.com.gsst.auth.common.rest.impl;
import cn.com.gsst.auth.common.rest.GoogleConfigRest;
import cn.com.yict.framemax.core.config.Config;
import org.springframework.stereotype.Component;
/**
* @author alex.yao
* @date 2024/12/24
*/
@Component
public class GoogleConfigRestImpl implements GoogleConfigRest {
private final String CLIENT_ID = Config.get("google.client.id");
@Override
public String getClientId() {
return CLIENT_ID;
}
}
package cn.com.gsst.auth.common.rest.impl;
import cn.com.gsst.auth.common.rest.JudgeCodeRest;
import cn.com.gsst.auth.common.utils.Assert;
import cn.com.gsst.auth.common.service.JudgeCodeService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class JudgeCodeRestImpl implements JudgeCodeRest {
@Resource
private JudgeCodeService judgeCodeService;
@Override
public boolean judgeCode(String account, String code) throws Exception {
Assert.notBlank(account);
Assert.notBlank(code);
return judgeCodeService.judgeCode(account, code);
}
@Override
public String judgeCodeReturnAuthCode(String account, String code) throws Exception {
Assert.notBlank(account);
Assert.notBlank(code);
return judgeCodeService.judgeCodeReturnAuthCode(account, code);
}
}
package cn.com.gsst.auth.common.rest.impl;
import cn.com.gsst.auth.common.rest.SendEmailRest;
import cn.com.gsst.auth.common.service.SendEmailService;
import cn.com.gsst.auth.common.utils.Assert;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class SendEmailRestImpl implements SendEmailRest {
@Resource
private SendEmailService sendEmailService;
@Override
public void sendEmailCode(String emailAddress) throws Exception {
Assert.notBlank(emailAddress);
sendEmailService.sendEmailCode(emailAddress);
}
}
package cn.com.gsst.auth.common.rest.impl;
import cn.com.gsst.auth.common.rest.SmsRest;
import cn.com.gsst.auth.common.service.SmsService;
import cn.com.gsst.auth.common.utils.Assert;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.regex.Pattern;
@Component
public class SmsRestImpl implements SmsRest {
@Resource
private SmsService smsService;
/**
* 短信下发(百度SMS)
*
* @param phone
* @throws Exception
*/
@Override
public void smsDelivered(String phone) throws Exception {
Assert.notBlank(phone);
//校验手机号格式(其中包含大陆和港澳台的校验)
//正则表达式使用了多个正则模式,每个模式使用|分隔,表示多个模式中的任何一个匹配即可。这样,它可以用于校验多种手机号的格式
boolean matches = Pattern.matches(
"(?:0|86|\\+86)?1[3-9]\\d{9}|" + //移动电话MOBILE
"(?:0|852|\\+852)?\\d{8}|" + //MOBILE_HK
"(?:0|886|\\+886)?(?:|-)09\\d{8}|" + //MOBILE_TW
"(?:0|853|\\+853)?(?:|-)6\\d{7}", phone); //MOBILE_MO
Assert.isTrue(matches);
smsService.smsDelivered(phone);
}
}
package cn.com.gsst.auth.common.service;
public interface JudgeCodeService {
/**
* 校验验证码是否正确
*
* @param account,code
* @throws Exception
*/
boolean judgeCode(String account, String code) throws Exception;
/**
* 校验验证码是否正确,正确的话就返回授权码,可以给别的业务操作
*
* @param account,code
* @throws Exception
*/
String judgeCodeReturnAuthCode(String account, String code) throws Exception;
}
package cn.com.gsst.auth.common.service;
public interface SendEmailService {
/**
* 发送邮箱 验证码发送
*
* */
void sendEmailCode(String emailAddress) throws Exception;
}
package cn.com.gsst.auth.common.service;
public interface SmsService {
/**
* 短信下发(获取验证码)
*
* @param phone
* @throws Exception
*/
void smsDelivered(String phone) throws Exception;
}
package cn.com.gsst.auth.common.service.impl;
import cn.com.gsst.auth.common.constant.RedisKeyConstant;
import cn.com.gsst.auth.common.service.JudgeCodeService;
import cn.com.gsst.auth.common.service.RedisService;
import cn.com.gsst.auth.common.utils.UUIDTool;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.regex.Pattern;
@Component
public class JudgeCodeServiceImpl implements JudgeCodeService {
@Resource
private RedisService redisService;
@Override
public boolean judgeCode(String account, String code) throws Exception {
//验证次数
String accountKey = "JUDGE_CODE_COUNT:" + account;
//校验校验验证码:从redis获取发送的验证码
String mobileCode = (String) redisService.get(account);
if (StringUtils.isEmpty(mobileCode)) {
throw new I18nMessageException("exception/verification.code.has.expired.please.obtain.it.again");
}
// 防止撞库攻击
if (!redisService.hasKey(accountKey)) {
redisService.set(accountKey, 1, 60);
}
//如果没有验证过
int verifyCount = Integer.parseInt(String.valueOf(redisService.get(accountKey)));
if (verifyCount > 5) {
throw new I18nMessageException("exception/maximum.number.of.verifications.has.been.reached");
}
//验证次数自增
verifyCount++;
redisService.set(accountKey, verifyCount, redisService.getExpire(accountKey));
//验证逻辑
boolean isValid = mobileCode.equals(code);
//如果成功,删除验证码和验证码次数
if (isValid) {
redisService.del(account);
redisService.del(accountKey);
return true;
}
return false;
}
@Override
public String judgeCodeReturnAuthCode(String account, String code) throws Exception {
//验证验证码是否正确
if (!judgeCode(account, code)) {
return StringUtils.EMPTY;
}
//验证次数
String authCode = UUIDTool.getUUID();
//校验手机号格式
boolean matches = Pattern.matches(
"(?:0|86|\\+86)?1[3-9]\\d{9}|" +
"(?:0|852|\\+852)?\\d{8}|" +
"(?:0|886|\\+886)?(?:|-)09\\d{8}|" +
"(?:0|853|\\+853)?(?:|-)6\\d{7}", account);
if(matches){ //是手机号
redisService.set(RedisKeyConstant.Code.AUTH_CODE + account, authCode, 60 * 5);
}else{
redisService.set(RedisKeyConstant.Code.AUTH_CODE + account, authCode, 60 * 15);
}
return authCode;
}
}
package cn.com.gsst.auth.common.service.impl;
import cn.com.gsst.auth.common.service.RedisService;
import cn.com.gsst.auth.common.service.SendEmailService;
import cn.com.gsst.auth.common.utils.Assert;
import cn.com.gsst.auth.common.utils.DateUtils;
import cn.com.gsst.auth.common.utils.RandomCodeUtils;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import cn.com.yict.framemax.frame.entity.EmailSenderEntity;
import cn.com.yict.framemax.frame.service.EmailSenderService;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
@Service
public class SendEmailServiceImpl implements SendEmailService {
@Resource
private EmailSenderService emailSenderService;
@Resource
private FmxParamConfigService fmxParamConfigService;
@Resource
private RedisService redisService;
@Override
public void sendEmailCode(String emailAddress) throws Exception {
Assert.notBlank(emailAddress);
EmailSenderEntity entity = new EmailSenderEntity();
String code = RandomCodeUtils.generateNumber(6);
String projectName = fmxParamConfigService.getParam("project.name");
String body = fmxParamConfigService.getParam("login.email.send.body");
body = body.replaceAll("\\$\\{projectName}", projectName)
.replaceAll("\\$\\{emailAddress}", emailAddress)
.replaceAll("\\$\\{authCode}", code)
.replaceAll("\\$\\{CurrDate}", DateUtils.getCurrDate());
entity.setBody(body);
entity.setSubject("用户邮箱校验");
List<String> list = new LinkedList<>();
list.add(emailAddress);
entity.setTo(list); //接收者
try {
// 如果成功发送,则把验证码存入redis当中,并设置15分钟的过期时间
emailSenderService.sendMail(entity, null);
redisService.set(emailAddress, code, 900);
} catch (Exception e) {
throw new I18nMessageException("exception/verification.code.sending.failed.please.try.again");
}
}
}
package cn.com.gsst.auth.common.service.impl;
import cn.com.gsst.auth.common.dto.SmsDto;
import cn.com.gsst.auth.common.service.SmsService;
import cn.com.gsst.auth.common.service.RedisService;
import cn.com.gsst.auth.support.sms.channel.baidu.BaiDuThirdPlatformService;
import cn.com.yict.framemax.core.i18n.I18nMessageException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Random;
@Service
public class SmsServiceImpl implements SmsService {
@Resource
private BaiDuThirdPlatformService baiDuThirdPlatformService;
@Resource
private RedisService redisService;
@Override
public void smsDelivered(String phone) throws Exception {
SmsDto smsDto = new SmsDto();
Random random = new Random();
// 随机生成六位数的随机数字
int randomNum = 100000 + random.nextInt(900000); // 生成[10000, 99999]范围内的随机数
String code = Integer.toString(randomNum);
smsDto.setMobilePhone(phone);
smsDto.setSmsCode(code);
boolean isSend = baiDuThirdPlatformService.doSend(smsDto);
if (isSend) {
// 如果成功发送,则把验证码存入redis当中,并设置五分钟的过期时间
redisService.set(phone, code, 300);
} else {
throw new I18nMessageException("exception/verification.code.sending.failed.please.try.again");
}
}
}
package cn.com.gsst.auth.common.utils;
public class Assert extends org.springframework.util.Assert {
public static void notBlank(String text) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException("缺少必要参数");
}
}
public static void notBlank(String text, String message) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException("缺少必要参数-[" + message + "]");
}
}
public static void notNull(Object text, String message) {
if (text == null) {
throw new IllegalArgumentException("缺少必要参数-[" + message + "]");
}
}
}
package cn.com.gsst.auth.common.utils;
import cn.com.gsst.auth.support.security.oauth.constants.OauthConstants;
import cn.com.gsst.auth.support.security.oauth.entity.UserBaseEntity;
import cn.com.gsst.auth.user.entity.MemberInfoEntity;
import cn.com.yict.framemax.core.context.Context;
import cn.com.yict.framemax.data.model.UserBaseModel;
import cn.com.yict.framemax.security.oauth.exception.TokenExpiredException;
import org.springframework.beans.BeanUtils;
/**
* @author Focan Zhong
* @create 2021/8/6
*/
public class BlContext {
/**
* 获取上下文用户
*
* @return
*/
public static UserBaseEntity getCurrentUser() {
UserBaseModel userBaseModel = Context.get().getCurrentUser();
if (userBaseModel == null) {
throw new TokenExpiredException();
}
return distinguishUserType(userBaseModel);
}
/**
* 获取上下文用户 无异常
*
* @return
*/
public static UserBaseEntity getCurrentUserNotException() {
UserBaseModel userBaseModel = Context.get().getCurrentUser();
if (userBaseModel == null) {
return null;
}
return distinguishUserType(userBaseModel);
}
/**
* 区分用户类型
*
* @param userBaseModel
* @return
*/
private static UserBaseEntity distinguishUserType(UserBaseModel userBaseModel) {
UserBaseEntity userBaseEntity = new UserBaseEntity();
BeanUtils.copyProperties(userBaseModel, userBaseEntity);
if (Context.get().getCurrentUser() instanceof MemberInfoEntity) {
userBaseEntity.setType(OauthConstants.OauthEnum.MEMBER_DOMAIN.name());
}
return userBaseEntity;
}
/**
* 获取当前系统语言[小写]
*/
public static String getCurrentLocaleLanguageToLowerCase() {
return Context.get().getMessageSource().getCurrentLocale().toLanguageTag().toLowerCase();
}
}
This diff is collapsed.
package cn.com.gsst.auth.common.utils;
import cn.com.yict.framemax.core.utils.BeanUtils;
import cn.com.yict.framemax.core.utils.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONPath;
import org.apache.log4j.Logger;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* 系统Json 工具类
* <p>
*
* @see JSON
*/
public final class JsonUtils {
private static Logger log = Logger.getLogger(JsonUtils.class);
private JsonUtils() {
}
/**
* 转换Java Bean 为 json
*/
public static String serialize(Object o) {
if(o ==null){
return null;
}
return JSON.serialize(o);
}
/**
* 转换Java Bean 为 json 附加了个时间格式参数
*
* @param o
* @param dateFormat
* @return
*//*
public static String serialize(Object o, String dateFormat) {
if(StringUtils.isEmpty(dateFormat)) {
return JSON.serialize(o);
}
return com.alibaba.fastjson.JSON.toJSONStringWithDateFormat(o, dateFormat);
}*/
/**
* json 转 javabean
*
* @param json
* @return
*/
public static <T> T deSerialize(String json, Class<T> clazz) {
try {
return JSON.deSerialize(clazz, json);
} catch (Exception e) {
log.error(e);
return null;
}
}
/**
* json 转 javabean
*
* @param json
* @return
*/
public static <T> T deSerialize(String json, Type type) {
try {
return JSON.deSerialize(type, json);
} catch (Exception e) {
log.error(e);
return null;
}
}
/**
* 转换Java Bean 为 HashMap
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> beanToMap(Object o) {
try {
String json = serialize(o);
return JSON.deSerialize(Map.class, json);
} catch (Exception e) {
log.error(e);
return null;
}
}
/**
* 转换Json String 为 HashMap
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> jsonToMap(String json,
boolean collToString) {
try {
Map<String, Object> map = JSON.deSerialize(Map.class, json);
if (collToString) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Collection
|| entry.getValue() instanceof Map) {
entry.setValue(serialize(entry.getValue()));
}
}
}
return map;
} catch (Exception e) {
log.error(e);
return null;
}
}
/**
* List 转换成json
*
* @param list
* @return
*/
public static String listToJson(List<?> list) {
return JSON.serialize(list);
}
public static <T> List<T> parseArray(String json, String jsonPath, Class<T> clazz) {
Object read = JSONPath.read(json, jsonPath);
if (read instanceof ArrayList) {
return (List<T>) read;
}
return JSONArray.parseArray(read.toString(), clazz);
}
public static <T> T convert(Object object, Type type) {
if (object instanceof String) {
try {
return deSerialize(object.toString(), type);
} catch (Exception e) {
}
}
if (BeanUtils.isSimpleValueType(object.getClass())) {
return (T) object;
}
String serialize = serialize(object);
return deSerialize(serialize, type);
}
}
package cn.com.gsst.auth.common.utils;
import java.util.Random;
public class RandomCodeUtils {
public static final String ALLCHAR = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
public static final String ALLNUM = "0123456789";
/**
* 返回一个定长的随机字符串(只包含大小写字母、数字)
*
* @param length 随机字符串长度
* @return 随机字符串
*/
public static String generateString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的数字串
*
* @param length 随机字符串长度
* @return 随机数字串
*/
public static String generateNumber(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLNUM.charAt(random.nextInt(ALLNUM.length())));
}
return sb.toString();
}
}
\ No newline at end of file
package cn.com.gsst.auth.common.utils;
import java.util.Random;
/**
* @version:
* @function: 产生随机数字、随机字母、随机数字+字母。
*/
public class RandomUtil {
/**
* 随机产生几位数字:例:maxLength=3,则结果可能是 012
*/
public static final int produceNumber(int maxLength) {
Random random = new Random();
return random.nextInt(maxLength);
}
/**
* 随机产生区间数字:例:minNumber=1,maxNumber=2,则结果可能是 1、2,包括首尾。
*/
public static int produceRegionNumber(int minNumber, int maxNumber) {
return minNumber + produceNumber(maxNumber);
}
/**
* 随机产生几位字符串:例:maxLength=3,则结果可能是 aAz
*
* @param maxLength 传入数必须是正数。
*/
public static String produceString(int maxLength) {
String source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return doProduce(maxLength, source);
}
/**
* 随机产生随机数字+字母:例:maxLength=3,则结果可能是 1Az
*
* @param maxLength 传入数必须是正数。
*/
public static String produceStringAndNumber(int maxLength) {
String source = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
return doProduce(maxLength, source);
}
/**
* 自定义随机产生结果
*/
public static String produceResultByCustom(String customString, int maxLength) {
return doProduce(maxLength, customString);
}
/**
* 生产结果
*/
private static String doProduce(int maxLength, String source) {
StringBuffer sb = new StringBuffer(100);
for (int i = 0; i < maxLength; i++) {
final int number = produceNumber(source.length());
sb.append(source.charAt(number));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(RandomUtil.produceNumber(3));
System.out.println(RandomUtil.produceRegionNumber(1, 2));
System.out.println(RandomUtil.produceString(3));
System.out.println(RandomUtil.produceStringAndNumber(32));
System.out.println(RandomUtil.produceResultByCustom("demo.", 8));
}
}
\ No newline at end of file
This diff is collapsed.
package cn.com.gsst.auth.common.utils;
import java.util.UUID;
/**
* uuid工具类
*
* @author Sean.Chan
*
*/
public class UUIDTool {
/**
* 返回uuid 去掉"-"符号
* @return
*/
public static String getUUID() {
return UUID.randomUUID().toString().replace("-", "");
}
}
package cn.com.gsst.auth.common.utils.http;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* httpclient 4.5.x
*/
public class HttpClientFactory {
private static final Logger logger = LoggerFactory.getLogger(HttpClientFactory.class);
private static final String[] SUPPORTED_PROTOCOLS = new String[]{"TLSv1"};
public static CloseableHttpClient createHttpClient() {
return createHttpClient(100, 10, 5000, 2);
}
/**
* @param maxTotal maxTotal
* @param maxPerRoute maxPerRoute
* @param timeout timeout
* @param retryExecutionCount retryExecutionCount
* @return CloseableHttpClient
*/
public static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int timeout, int retryExecutionCount) {
try {
// SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(null, new TrustStrategy() {
// // 信任所有证书
// public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// return true;
// }
// }).build();
// SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// // 信任所有
// public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// return true;
// }
// }).build();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
//NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何
//有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig);
return HttpClientBuilder.create()
.setConnectionManager(poolingHttpClientConnectionManager)
.setSSLSocketFactory(sslsf)
.setSSLHostnameVerifier(new HostnameVerifier() {
// 所有hostName验证返回true 不安全
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
.build();
} catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e ) {
logger.error("", e);
}
return null;
}
/**
* Key store 类型HttpClient
*
* @param keystore keystore
* @param keyPassword keyPassword
* @param timeout timeout
* @param retryExecutionCount retryExecutionCount
* @return CloseableHttpClient
*/
public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore, String keyPassword, int timeout, int retryExecutionCount) {
return createKeyMaterialHttpClient(keystore, keyPassword, SUPPORTED_PROTOCOLS, timeout, retryExecutionCount);
}
/**
* Key store 类型HttpClient
*
* @param keystore keystore
* @param keyPassword keyPassword
* @param supportedProtocols supportedProtocols
* @param timeout timeout
* @param retryExecutionCount retryExecutionCount
* @return CloseableHttpClient
*/
public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore, String keyPassword, String[] supportedProtocols, int timeout, int retryExecutionCount) {
try {
SSLContext sslContext = SSLContexts.custom().useSSL().loadKeyMaterial(keystore, keyPassword.toCharArray()).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, supportedProtocols,
null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
return HttpClientBuilder.create()
.setDefaultSocketConfig(socketConfig)
.setSSLSocketFactory(sf)
.setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
.build();
} catch (KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException e) {
logger.error("", e);
}
return null;
}
/**
* HttpClient 超时重试
*
* @author LiYi
*/
private static class HttpRequestRetryHandlerImpl implements HttpRequestRetryHandler {
private int retryExecutionCount;
public HttpRequestRetryHandlerImpl(int retryExecutionCount) {
this.retryExecutionCount = retryExecutionCount;
}
@Override
public boolean retryRequest(
IOException exception,
int executionCount,
HttpContext context) {
if (executionCount > retryExecutionCount) {
return false;
}
if (exception instanceof InterruptedIOException) {
return false;
}
if (exception instanceof UnknownHostException) {
return false;
}
if (exception instanceof SSLException) {
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
}
;
}
package cn.com.gsst.auth.common.utils.http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
/**
* http请求工具类
*/
public class HttpUtils {
final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
public static String postForm(String url, Map<String, String> parameters) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;//输出流
String params = "";// 编码之后的参数
try {
// 编码请求参数
for (Map.Entry<String, String> entry : parameters.entrySet()) {
params = params + entry.getKey() + "=" + entry.getValue() + "&";
}
params = params.substring(0, params.length() - 1);
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
httpConn.setRequestProperty("Accept-Charset", "UTF-8");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpConn.setRequestProperty("Authorization", "Basic MzYgOiBTdXBlcmxpbmsx");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
System.out.println("requers parms::" + params);
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line + "\r\n";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
public static String postForm(String url, Map<String, String> parameters, Map<String, String> headers) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;//输出流
String params = "";// 编码之后的参数
try {
// 编码请求参数
for (Map.Entry<String, String> entry : parameters.entrySet()) {
params = params + entry.getKey() + "=" + entry.getValue() + "&";
}
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
httpConn.setRequestProperty("Accept-Charset", "UTF-8");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpConn.setRequestProperty(entry.getKey(), entry.getValue());
}
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
System.out.println("requers parms::" + params);
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line + "\r\n";
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return result;
}
public static String postMethod(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送 POST 请求出现异常!" + e.getMessage(), e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
logger.error("发送 POST 请求出现异常!" + ex.getMessage(), ex);
// ex.printStackTrace();
}
}
return result;
}
public static String postJson(String url, String params, Map<String, String> headers) {
URL uUrl = null;
HttpURLConnection conn = null;
BufferedWriter out = null;
BufferedReader in = null;
try {
//创建和初始化连接
uUrl = new URL(url);
conn = (HttpURLConnection) uUrl.openConnection();
conn.setRequestProperty("content-type", "application/json;charset=UTF-8");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
//指定请求header参数
if (headers != null && headers.size() > 0) {
Set<String> headerSet = headers.keySet();
for (String key : headerSet) {
conn.setRequestProperty(key, headers.get(key));
}
}
out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
out.write(params);
out.flush();
//接收返回结果
StringBuilder result = new StringBuilder();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
if (in != null) {
String line = "";
while ((line = in.readLine()) != null) {
result.append(line);
}
}
return result.toString();
} catch (Exception e) {
logger.error("发送 POST 请求出现异常!" + e.getMessage(), e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
logger.error("发送 POST 请求出现异常!" + ex.getMessage(), ex);
// ex.printStackTrace();
}
}
return null;
}
}
package cn.com.gsst.auth.common.utils.http;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public class JsonResponseHandler {
private static final Logger logger = LoggerFactory.getLogger(JsonResponseHandler.class);
public static <T> ResponseHandler<T> createResponseHandler(final Class<T> clazz) {
return new JsonResponseHandlerImpl<T>(null, clazz);
}
public static class JsonResponseHandlerImpl<T> extends LocalResponseHandler implements ResponseHandler<T> {
private Class<T> clazz;
public JsonResponseHandlerImpl(String uriId, Class<T> clazz) {
this.uriId = uriId;
this.clazz = clazz;
}
@Override
public T handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity, "utf-8");
if (str.length() < 300) {
logger.info("URI[{}] elapsed time:{} ms RESPONSE DATA:{}", super.uriId, System.currentTimeMillis() - super.startTime, str);
}else{
logger.info("URI[{}] elapsed time:{} ms RESPONSE DATA:{}", super.uriId, System.currentTimeMillis() - super.startTime, "返回结果过长,忽略输出");
}
if (isJson(str)) {
return JSON.parseObject(str, clazz);
} else{
return null;
}
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
/**
* f**k json parse
* @param str
* @return
*/
private boolean isJson(String str){
try{
JSON.parseObject(str,clazz);
}catch (Exception e){
return false;
}
return true;
}
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#package name
gsst-auth.basePackage=cn.com.gsst.auth
This diff is collapsed.
This diff is collapsed.
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