Commit b70abedb by Simon Cheng

Merge branch 'dev'

创建车险基础架构,铭感信息加解密,芝麻车险统一连接方式
parents 199a899c e3df6806
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/> <attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
......
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry excluding="**/bower_components/*|**/node_modules/*|**/*.min.js" kind="src" path="src/main/webapp"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/main/resources/application-dev.properties=UTF-8
encoding//src/main/resources/application-local.properties=UTF-8
encoding//src/main/resources/application-prod.properties=UTF-8
encoding//src/main/resources/application-stage.properties=UTF-8
encoding//src/main/resources/application.properties=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8
encoding/pom.xml=UTF-8
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.processAnnotations=enabled
org.eclipse.jdt.core.compiler.source=1.8
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="synch">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/.apt_generated"/>
<dependent-module archiveName="ajb-car-vo-0.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/ajb-car-vo/ajb-car-vo">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="ajb-car-entity-0.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/ajb-car-entity/ajb-car-entity">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="ajb-car-jpa-0.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/ajb-car-jpa/ajb-car-jpa">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/ajb-car-api/target/classes"/>
<property name="context-root" value="synch"/>
</wb-module>
</project-modules>
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="ajb-api">
<wb-resource deploy-path="/" source-path="/target/m2e-wtp/web-resources"/>
<wb-resource deploy-path="/" source-path="/src/main/webapp" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/.apt_generated"/>
<dependent-module archiveName="ajb-car-vo-0.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/ajb-car-vo/ajb-car-vo">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="ajb-car-entity-0.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/ajb-car-entity/ajb-car-entity">
<dependency-type>uses</dependency-type>
</dependent-module>
<dependent-module archiveName="ajb-car-jpa-0.0.1-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/ajb-car-jpa/ajb-car-jpa">
<dependency-type>uses</dependency-type>
</dependent-module>
<property name="java-output-path" value="/ajb-api/target/classes"/>
<property name="context-root" value="ajb-api"/>
</wb-module>
</project-modules>
org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
eclipse.preferences.version=1
org.springframework.ide.eclipse.core.builders.enable.aopreferencemodelbuilder=true
org.springframework.ide.eclipse.core.builders.enable.beanmetadatabuilder=true
org.springframework.ide.eclipse.core.enable.project.preferences=false
org.springframework.ide.eclipse.core.validator.enable.org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.enable.org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.enable.org.springframework.ide.eclipse.boot.bootvalidator=true
org.springframework.ide.eclipse.core.validator.enable.org.springframework.ide.eclipse.core.springvalidator=false
org.springframework.ide.eclipse.core.validator.enable.org.springframework.ide.eclipse.data.core.datavalidator=true
org.springframework.ide.eclipse.core.validator.enable.org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.autowire.autowire-org.springframework.ide.eclipse.beans.core.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanAlias-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanClass-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanConstructorArgument-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanDefinition-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanDefinitionHolder-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanFactory-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanInitDestroyMethod-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanProperty-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanReference-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.methodOverride-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.parsingProblems-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.requiredProperty-org.springframework.ide.eclipse.beans.core.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.toolAnnotation-org.springframework.ide.eclipse.beans.core.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.AvoidDriverManagerDataSource-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.ImportElementsAtTopRulee-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.ParentBeanSpecifiesAbstractClassRule-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.RefElementRule-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.TooManyBeansInFileRule-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.UnnecessaryValueElementRule-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.com.springsource.sts.bestpractices.UseBeanInheritance-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.bestpractices.legacyxmlusage.jndiobjectfactory-org.springframework.ide.eclipse.bestpractices.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.boot.missingConfigurationProcessor-org.springframework.ide.eclipse.boot.bootvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.core.springClasspath-org.springframework.ide.eclipse.core.springvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.data.core.invalidDerivedQuery-org.springframework.ide.eclipse.data.core.datavalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.data.core.invalidParameterType-org.springframework.ide.eclipse.data.core.datavalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.action-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.actionstate-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.attribute-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.attributemapper-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.beanaction-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.evaluationaction-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.evaluationresult-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.exceptionhandler-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.import-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.inputattribute-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.mapping-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.outputattribute-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.set-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.state-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.subflowstate-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.transition-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.variable-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.webflowstate-org.springframework.ide.eclipse.webflow.core.validator=true
...@@ -8,7 +8,10 @@ ...@@ -8,7 +8,10 @@
<artifactId>ajb-car</artifactId> <artifactId>ajb-car</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<groupId>ajb-car-app</groupId>
<artifactId>ajb-car-api</artifactId> <artifactId>ajb-car-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ajb-car-api</name> <name>ajb-car-api</name>
<packaging>war</packaging> <packaging>war</packaging>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
...@@ -19,25 +22,25 @@ ...@@ -19,25 +22,25 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-car-vo</artifactId> <artifactId>ajb-car-vo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>ajb-car</groupId>
<artifactId>ajb-common-utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-car-entity</artifactId> <artifactId>ajb-car-entity</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-car-utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>ajb-car-app</groupId>
<artifactId>ajb-car-jpa</artifactId> <artifactId>ajb-car-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
...@@ -110,23 +113,11 @@ ...@@ -110,23 +113,11 @@
<groupId>org.springframework.mobile</groupId> <groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId> <artifactId>spring-mobile-device</artifactId>
</dependency> </dependency>
<!-- <dependency>
<dependency> <groupId>io.jsonwebtoken</groupId>
<groupId>org.jeecg</groupId> <artifactId>jjwt</artifactId>
<artifactId>easypoi-base</artifactId> <version>0.6.0</version>
<version>2.3.1</version> </dependency>
</dependency>
<dependency>
<groupId>org.jeecg</groupId>
<artifactId>easypoi-web</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.jeecg</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>2.3.1</version>
</dependency>
-->
</dependencies> </dependencies>
<!-- 打包spring boot应用 --> <!-- 打包spring boot应用 -->
<build> <build>
...@@ -142,4 +133,5 @@ ...@@ -142,4 +133,5 @@
</plugins> </plugins>
<finalName>carapi</finalName> <finalName>carapi</finalName>
</build> </build>
</project> </project>
package com.ajb.car.apimessage;
public class originmessage {
}
package com.ajb.global.authorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ajb.global.authorize.service.AuthorizeService;
import com.ajb.global.authorize.vo.CheckTokenRequestVO;
import com.ajb.car.vo.common.JsonResult;
import com.ajb.global.authorize.vo.CheckTokenResponseVO;
import com.ajb.global.authorize.vo.ObtainTokenRequestVO;
import com.ajb.global.authorize.vo.ObtainTokenResponseVO;
@RestController
@RequestMapping("/authorize")
public class AuthorizeController {
@Autowired
private AuthorizeService authorizeService;
@RequestMapping("/obtainToken")
public Object obtainToken(@RequestBody ObtainTokenRequestVO requestVO){
JsonResult result = new JsonResult();
ObtainTokenResponseVO responseVO = authorizeService.obtainToken(requestVO);
result.setData(responseVO);
return result;
}
@RequestMapping("/checkToken")
public Object checkToken(@RequestBody CheckTokenRequestVO requestVO){
JsonResult result = new JsonResult();
CheckTokenResponseVO responseVO = authorizeService.checkToken(requestVO);
result.setData(responseVO);
return result;
}
}
package com.ajb.global.authorize.service;
import com.ajb.global.authorize.vo.CheckTokenRequestVO;
import com.ajb.global.authorize.vo.CheckTokenResponseVO;
import com.ajb.global.authorize.vo.ObtainTokenRequestVO;
import com.ajb.global.authorize.vo.ObtainTokenResponseVO;
public interface AuthorizeService {
public ObtainTokenResponseVO obtainToken(ObtainTokenRequestVO requestVO);
public CheckTokenResponseVO checkToken(CheckTokenRequestVO requestVO);
}
package com.ajb.global.authorize.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ajb.global.authorize.service.AuthorizeService;
import com.ajb.global.authorize.util.AudienceSetting;
import com.ajb.global.authorize.util.JwtTokenUtil;
import com.ajb.global.authorize.vo.CheckTokenRequestVO;
import com.ajb.car.vo.common.CommonResult;
import com.ajb.common.utils.string.CommonUtil;
import com.ajb.global.enums.ParamVerifyEnum;
import com.ajb.global.enums.ResultEnum;
import com.ajb.global.authorize.vo.CheckTokenResponseVO;
import com.ajb.global.authorize.vo.ObtainTokenRequestVO;
import com.ajb.global.authorize.vo.ObtainTokenResponseVO;
@Service("authorizeService")
public class AuthorizeServiceImpl implements AuthorizeService {
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private AudienceSetting audienceSetting;
@Override
public ObtainTokenResponseVO obtainToken(ObtainTokenRequestVO requestVO) {
boolean success = true;
String message = ResultEnum.QUERY_SUCCESS.getMessage();
ObtainTokenResponseVO responseVO = new ObtainTokenResponseVO();
if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getTicket())){
responseVO.setCommonResult(new CommonResult(false,ParamVerifyEnum.PARAM_NOT_NULL.getMessage()));
return responseVO;
}
String token = jwtTokenUtil.generateToken(requestVO.getTicket());
responseVO.setToken(token);
responseVO.setCommonResult(new CommonResult(success,message));
return responseVO;
}
@Override
public CheckTokenResponseVO checkToken(CheckTokenRequestVO requestVO) {
boolean success = true;
String message = "校验通过";
CheckTokenResponseVO responseVO = new CheckTokenResponseVO();
if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getToken())){
responseVO.setCommonResult(new CommonResult(false,ParamVerifyEnum.PARAM_NOT_NULL.getMessage()));
return responseVO;
}
String token = requestVO.getToken();
if(token.startsWith(audienceSetting.issuer)){
token = token.substring(audienceSetting.issuer.length()+1);
}
boolean isTokenValid = jwtTokenUtil.validateToken(token);
boolean isTokenExpired = jwtTokenUtil.isTokenExpired(token);
if(isTokenExpired){
success = false;
message = "token已失效!";
}else if(isTokenValid){
String ticket = requestVO.getTicket();
if(!CommonUtil.isNullOrBlank(ticket)){
boolean valid = jwtTokenUtil.validateToken(token, ticket);
if(!valid){
success = false;
message = "由token解析出的ticket和传入的ticket不一致!";
}
}
}else{
success = false;
message = "token格式不合法!";
}
responseVO.setCommonResult(new CommonResult(success,message));
return responseVO;
}
}
package com.ajb.global.authorize.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* jwt安全验证设置 head tag,seal封条,过期时间,发行,bypass
* @author Simon Cheng
*/
@Service
public class AudienceSetting {
@Value("${jwt.header}")
public String header;
@Value("${jwt.seal}")
public String seal;
@Value("${jwt.expiration}")
public Long expiration;
@Value("${jwt.issuer}")
public String issuer;
@Value("${jwt.bypass}")
public String bypass;
}
package com.ajb.global.authorize.util;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
/**
* jwt 工具类
* @author
*/
@Service
public class JwtTokenUtil {
private static final String CLAIM_KEY_SUBJECT = "sub";
// private static final String CLAIM_KEY_ISSURE = "iss";
// private static final String CLAIM_KEY_AUDIENCE = "aud";
private static final String CLAIM_KEY_CREATED = "created";
// private static final String CLAIM_KEY_BIRTHDAY = "birthDay";
// private static final String CLAIM_KEY_ADDRESS = "address";
@Autowired
private AudienceSetting audienceSetting;
/**
* 从token中获取subject
* @param token
* @return
*/
public String getSubjectFromToken(String token) {
String subject = null;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
subject = claims.getSubject();
}
}
return subject;
}
/**
* 获取创建时间
* @param token
* @return
*/
public Date getCreatedDateFromToken(String token) {
Date created = null ;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
}
}
return created;
}
/**
* 获取过期时间
* @param token
* @return
*/
public Date getExpirationDateFromToken(String token){
Date expiration = null;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
expiration = claims.getExpiration();
}
}
return expiration;
}
/**
* check token是否过期
* @param token
* @return
*/
public Boolean isTokenExpired(String token) {
boolean result = false;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("EXPIRED".equals(resultCode)){
result = true;
}else if("SUCCESS".equals(resultCode)){
Date expiration = getExpirationDateFromToken(token);
if(expiration != null){
result = expiration.before(new Date());
}
}
return result;
}
/**
* 检查是否可以被刷新
* @param token
* @param lastPasswordReset
* @return
*/
public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
//如果过期则不可以刷新
if(isTokenExpired(token)){
return false;
}
Date created = getCreatedDateFromToken(token);
if(created == null){
return false;
}
//如果token是在上次密码重置前生成则不可以刷新
if(lastPasswordReset != null && created.before(lastPasswordReset)){
return false;
}
return true;
}
/**
* 刷新token
* @param token
* @return
*/
public String refreshToken(String token) {
String refreshedToken = null ;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims);
}
}
return refreshedToken;
}
/**
* 根据ticket验证token有效
* @param ticket
* @param user
* @return
*/
public Boolean validateToken(String token, String ticket) {
boolean result = false;
final String subject = getSubjectFromToken(token);
if(subject == null){
return false;
}
if(!isTokenExpired(token)){
if(ticket != null && subject.equals(ticket)){
result = true;
}
}
return result;
}
/**
* 判断token是否有效(主要是格式是否有效)
* @param token
* @return
*/
public Boolean validateToken(String token) {
boolean result = true;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("INVALID".equals(resultCode)){
result = false;
}
return result;
}
/**
* 生成过期时间
* @return
*/
private Date generateExpirationDate() {
Date expirationDate = new Date(System.currentTimeMillis() + audienceSetting.expiration * 1000);
return expirationDate;
}
/**
* 根据ticket生成token
* @param ticket
* @return
*/
public String generateToken(String ticket){
String token = null;
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_SUBJECT, ticket);
claims.put(CLAIM_KEY_CREATED, new Date());
token = generateToken(claims);
token = audienceSetting.issuer + " " + token;
return token;
}
/**
* 根据Map 生成token串
* @param Map<String, Object>claims
* @return
*/
private String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, audienceSetting.seal)
.compact();
}
/**
* 根据token获取Claims,申明内容
* @param token
* @return
*/
private Map<String,Object> getClaimsFromToken(String token){
Map<String,Object> map = new HashMap<String,Object>();
String resultCode = "SUCCESS";
Claims claims = null;
try {
JwtParser jwtParser = Jwts.parser().setSigningKey(audienceSetting.seal);
Jws<Claims> jwsClaims = jwtParser.parseClaimsJws(token);
claims = jwsClaims.getBody();
}catch(ExpiredJwtException e){
resultCode = "EXPIRED";
}catch(UnsupportedJwtException|MalformedJwtException|SignatureException|IllegalArgumentException e){
resultCode = "INVALID";
}catch(Exception e){
resultCode = "INVALID";
}
map.put("resultCode", resultCode);
map.put("claims", claims);
return map;
}
}
package com.ajb.global.authorize.vo;
public class CheckTokenRequestVO {
private String token;
private String ticket;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
}
package com.ajb.global.authorize.vo;
import com.ajb.car.vo.common.CommonResult;
public class CheckTokenResponseVO {
private CommonResult commonResult;
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
}
package com.ajb.global.authorize.vo;
public class ObtainTokenRequestVO {
private String ticket;
private String ipAddress;
private String loginId;
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
}
package com.ajb.global.authorize.vo;
import com.ajb.car.vo.common.CommonResult;
public class ObtainTokenResponseVO {
private String token;
private CommonResult commonResult;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
}
package com.ajb.global.config;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
/***
* alibaba druid datasource configuration
*
* @author fan
*
*/
@Configuration
public class DruidConfiguration {
/***
* ConditionalOnMissingBean 当不存在时 返回Bean的实例
* 通过ConfigurationProperties自动注入配置
* @return
*/
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
}
package com.ajb.global.config;
/**
* Register security zuihuibi filter
*/
import javax.servlet.Filter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ajb.global.filter.HttpZuihuibiAuthorizeFilter;
@Configuration
public class HttpZuihuibiAuthorizeConfig {
@Bean
public Filter AuthFilter() {
return new HttpZuihuibiAuthorizeFilter();
}
}
package com.ajb.global.config;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import com.ajb.Application;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
\ No newline at end of file
package com.ajb.global.config;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
/**
* 通过上下文过去注入的bean instance
* @author Simon Cheng
*
*/
@Configuration
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return SpringContextUtil.applicationContext;
}
public static <T> T getBean(Class<T> t) {
return SpringContextUtil.applicationContext.getBean(t);
}
// 通过name获取Bean.
public static <T> T getBean(String name) {
T bean = (T) SpringContextUtil.applicationContext.getBean(name);
return bean;
}
}
package com.ajb.global.config;
import javax.servlet.Filter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class SpringMvcConfig {
/**
* 解决同源策略问题的filter
* @return
*/
@Bean
public Filter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
package com.ajb.global.config;
import java.util.Date;
import com.ajb.car.entity.apimessage.AgTransVehicleMsgOrigin;
import com.ajb.car.metadata.service.SystemConfigService;
import com.ajb.car.quotation.service.AgTransVehicleMsgOriginService;
import com.ajb.car.vo.zhima.TokenZhiMa;
import com.ajb.common.utils.http.HttpHelpZhiMa;
import com.ajb.common.utils.string.CommonUtil;
import com.alibaba.fastjson.JSON;
/**
* 获取芝麻车险访问连接
* @author Simon Cheng
*
*/
public class ZhimaConnection {
private static String auth2ParamProduction = "";
private static String hostURL = "";
private static String tokenMethod = "";
private static String token = "";
private static ZhimaConnection zhimaConnection = null;
public static synchronized ZhimaConnection getInstance(){
if (zhimaConnection == null)
{
SystemConfigService systemConfigService = (SystemConfigService)SpringContextUtil.getBean("systemConfigService");
zhimaConnection = new ZhimaConnection();
auth2ParamProduction = systemConfigService.getSingleConfigValue("LinkerSoftAPITokenAuth2Param");
hostURL = systemConfigService.getSingleConfigValue("LinkerSoftAPIHostURL");
tokenMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPITokenMethod");
}
return zhimaConnection;
}
public static String getAuth2ParamProduction() {
getInstance();
return auth2ParamProduction;
}
public static String getHostURL() {
getInstance();
return hostURL;
}
public static String getTokenMethod() {
getInstance();
return tokenMethod;
}
/**
* 获取芝麻API接口的token
* @param urlQuery
* @param queryParams
* @return
*/
private static TokenZhiMa getToken(String urlQuery,String queryParams)
{
TokenZhiMa returnToken = (TokenZhiMa)HttpHelpZhiMa.getToken(urlQuery,queryParams);
return returnToken;
}
public static String getToken()
{
getInstance();
if (CommonUtil.isNullOrBlank(token))
{
TokenZhiMa returnToken = (TokenZhiMa)getToken(hostURL + tokenMethod, auth2ParamProduction);
token = returnToken.getDatas().getTokenInfo().getToken();
}
return token;
}
public static String refreshToken()
{
getInstance();
TokenZhiMa returnToken = (TokenZhiMa)getToken(hostURL + tokenMethod, auth2ParamProduction);
token = returnToken.getDatas().getTokenInfo().getToken();
return token;
}
public static <T> T postUrlMap2JavaBean(String urlQuery,String queryParams, Class<T> beanClass)
{
T t = postUrlMap2JavaBean(urlQuery, queryParams, getToken(), beanClass);
return t;
}
public static <T> T postUrlMap2JavaBean(String urlQuery,String queryParams, String token,Class<T> beanClass)
{
T t = HttpHelpZhiMa.postUrlMap2JavaBean(urlQuery,queryParams,token,beanClass);
//写原始消息入表
AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
agtransvehiclemsgorigin = initOriginMessage(ZhimaConnection.getHostURL(),urlQuery,queryParams,"Post",JSON.toJSONString(t));
AgTransVehicleMsgOriginService carZhiMaService = (AgTransVehicleMsgOriginService)SpringContextUtil.getBean("agTransVehicleMsgOriginService");
carZhiMaService.save(agtransvehiclemsgorigin);
return t;
}
public static <T> T getUrlMap2JavaBean(String urlQuery, Class<T> beanClass)
{
T t = getUrlMap2JavaBean(urlQuery,getToken(),beanClass);
return t;
}
public static <T> T getUrlMap2JavaBean(String urlQuery, String token,Class<T> beanClass)
{
T t = HttpHelpZhiMa.getUrlMap2JavaBean(urlQuery,token,beanClass);
//写原始消息入表
AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
agtransvehiclemsgorigin = initOriginMessage(ZhimaConnection.getHostURL(),urlQuery,"","Get",JSON.toJSONString(t));
AgTransVehicleMsgOriginService carZhiMaService = (AgTransVehicleMsgOriginService)SpringContextUtil.getBean("agTransVehicleMsgOriginService");
carZhiMaService.save(agtransvehiclemsgorigin);
return t;
}
/**
* 记录请求log,初始化日志项
* @param requestHost
* @param requestMethod
* @param requestParams
* @param requestType
* @param responseMessage
* @return
*/
private static AgTransVehicleMsgOrigin initOriginMessage(final String requestHost,final String requestMethod,final String requestParams,final String requestType,final String responseMessage)
{
AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
agtransvehiclemsgorigin.setQuoteProviderId(2L);
agtransvehiclemsgorigin.setQuoteProviderType("V");
agtransvehiclemsgorigin.setQuoteProvider("芝麻");
agtransvehiclemsgorigin.setRequestHost(requestHost);
agtransvehiclemsgorigin.setRequestParams(requestParams);
agtransvehiclemsgorigin.setRequestMethod(requestMethod);
agtransvehiclemsgorigin.setRequestType(requestType);
agtransvehiclemsgorigin.setRequestDate(new Date());
agtransvehiclemsgorigin.setUserId(36);
agtransvehiclemsgorigin.setUserName("simon");
agtransvehiclemsgorigin.setResponseMessage(responseMessage);
return agtransvehiclemsgorigin;
}
}
package com.ajb.global.enums;
public enum ParamVerifyEnum {
/**
* 参数不能为空
*/
PARAM_NOT_NULL(1,"参数不能为空!"),
/**
* 参数不正确
*/
PARAM_ERROR(2,"参数不正确!"),
/**
* 常用联系人类型不能为空
*/
CONTACTTYPE_NOT_NULL(11,"常用联系人类型不能为空!"),
/**
* 常用联系人姓名不能为空
*/
CONTACTNAME_NOT_NULL(12,"常用联系人姓名不能为空!"),
/**
* 与投保人关系不能为空
*/
RELATIONID_NOT_NULL(13,"与投保人关系不能为空!"),
/**
* 身份证件类型不能为空
*/
IDTYPEID_NOT_NULL(14,"身份证件类型不能为空!"),
/**
* 身份证件号码不能为空
*/
IDNO_NOT_NULL(15,"身份证件号码不能为空!"),
/**
* 性别不能为空
*/
GENDER_NOT_NULL(16,"性别不能为空!"),
/**
* 手机号码不能为空
*/
MOBILENO_NOT_NULL(17,"手机号码不能为空!"),
/**
* 生日不能为空
*/
BIRTHDATE_NOT_NULL(18,"生日不能为空!"),
/**
* 投保人ID不能为空
*/
CUSTOMERID_NOT_NULL(19,"投保人ID不能为空!")
;
private int code;
private String message;
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
private ParamVerifyEnum(int code, String message) {
this.code = code;
this.message = message;
}
}
package com.ajb.global.enums;
public enum ResultEnum {
/**
* 查询成功
*/
QUERY_SUCCESS(1,"查询成功!"),
/**
* 查询失败
*/
QUERY_FAIL(2,"查询失败!"),
/**
* 保存成功
*/
SAVE_SUCCESS(3,"保存成功!"),
/**
* 被保人信息已更新
*/
USER_IS_EXIST(4,"被保人信息已更新"),
/**
* 删除成功
*/
DELETE_SUCCESS(5,"删除成功")
;
private int code;
private String message;
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
private ResultEnum(int code,String message) {
this.code = code;
this.message = message;
}
}
package com.ajb.global.exception;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ajb.car.vo.common.JsonResult;
import com.ajb.common.utils.string.CommonUtil;
/***
* 统一异常处理
* @author fan
*
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
*
* @param req
* @param ex
* @return
* @throws Exception
*/
@ExceptionHandler(value=Exception.class)
public JsonResult handler(HttpServletRequest req,Exception ex) throws Exception{
logger.error("request url is:"+req.getRequestURL()+" \n "+CommonUtil.parseExceptionStack(ex));//ex.getMessage()
JsonResult result=new JsonResult();
result.setSuccess(false);
result.setMessage("system error"+ex.getMessage());
//TODO log
return result;
}
}
package com.ajb.global.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import com.ajb.global.authorize.util.AudienceSetting;
import com.ajb.global.authorize.util.JwtTokenUtil;
import com.ajb.common.utils.string.CommonUtil;
/**
* jwt过滤器
* @author
* zuihuibi intercept all request from client, check whether token is there,verify the token is valid.
*/
public class HttpZuihuibiAuthorizeFilter implements Filter{
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private AudienceSetting audienceSetting;
private static final String BY_PASS_ALL = "TEST";
@Override
public void destroy() {}
/**
* 过滤器,对客户请求过滤,验证
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException{
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
String requestUri = httpRequest.getRequestURI();
boolean isDoFilter = false;
//这里通过判断请求的方法,判断此次是否是预检请求,如果是,立即返回一个204状态吗,标示,允许跨域;预检后,正式请求,这个方法参数就是我们设置的post了
if ("OPTIONS".equals(httpRequest.getMethod())){
//HttpStatus.SC_NO_CONTENT = 204
httpResponse.setStatus(HttpStatus.SC_NO_CONTENT);
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");//当判定为预检请求后,设定允许请求的方法
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Token, X-Authorization"); //当判定为预检请求后,设定允许请求的头部类型
httpResponse.addHeader("Access-Control-Max-Age", "1");
chain.doFilter(request, response);
return;
}
String byPass = audienceSetting.bypass;
if(!CommonUtil.isNullOrBlank(byPass)){
if(byPass.contains(BY_PASS_ALL)){//bypass配置为TEST时所有方法都放过
isDoFilter = true;
}else{
if(byPass.contains(requestUri)){//完整路径匹配
isDoFilter = true;
}else{//按照“,”拆分后逐个模糊匹配
String[] arr = byPass.split(",");
for(String item : arr){
if(item.startsWith("*") && item.endsWith("*")){//以*开头且以*结尾
if(requestUri.contains(item.replace("*", ""))){
isDoFilter = true;
break;
}
}else if(item.startsWith("*")){//仅以*开头
if(requestUri.endsWith(item.replace("*", ""))){
isDoFilter = true;
break;
}
}else if(item.endsWith("*")){//仅以*结尾
if(requestUri.startsWith(item.replace("*", ""))){
isDoFilter = true;
break;
}
}
}//for arr
}//!byPass.contains(requestUri)
}//not BY_PASS_ALL
}//byPass != null
if (isDoFilter){
chain.doFilter(request, response);
return;
}
//其他的URL请求,先获取head中的token,进行验证即可
int issuerLength = audienceSetting.issuer.length();
String token = httpRequest.getHeader(audienceSetting.header);
if(!CommonUtil.isNullOrBlank(token) && token.length() > issuerLength){
String headStr = token.substring(0, issuerLength).toLowerCase();
if (headStr.compareTo(audienceSetting.issuer) == 0){
token = token.substring(issuerLength, token.length());
//token格式合法并且没有失效
if (jwtTokenUtil.validateToken(token) && !jwtTokenUtil.isTokenExpired(token)){
chain.doFilter(request, response);
return;
}
}
}
//验证失败,返回错误提示
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
String responseJson = "{"
+"\n \"success\": false,"
+"\n \"errorCode\": \"T001\","
+"\n \"message\": \"Invalid token!\""
+"\n}";
httpResponse.getWriter().write(responseJson);
return;
}
@Override
public void init(FilterConfig arg0) throws ServletException {}
}
package com.ajb.car; package com.ajb.web;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
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 com.ajb.car.schedule.ScheduledTaskService; import com.ajb.car.vo.common.CommonResult;
import com.ajb.car.vo.common.CommonResult; import com.ajb.car.vo.zhima.quotation.QuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.QuotationRequestVO; import com.ajb.car.vo.zhima.quotation.QuotationResponse;
import com.ajb.car.vo.zhima.quotation.QuotationResponse; import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.web.zhima.ZhimaDataSyncService;
@RestController @RestController
public class CarController { public class DataController {
@Autowired
private ScheduledTaskService taskService; @Autowired
private ZhimaDataSyncService taskService;
@RequestMapping("/quotations")
public Object synch(@RequestBody QuotationRequestVO loginRequestVO) throws Exception{ /**
QuotationResponse quotationResponse = new QuotationResponse(); * 同步芝麻车险报价数据
* @param loginRequestVO
try * @return
{ * @throws Exception
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd"); */
Date begin = fmt.parse(loginRequestVO.getBegindate()); @RequestMapping("/syncquotations")
public Object synch(@RequestBody QuotationRequestVO loginRequestVO) throws Exception{
Date end = fmt.parse(loginRequestVO.getEnddate()); QuotationResponse quotationResponse = new QuotationResponse();
quotationResponse = taskService.synchQuotaion(begin,end); try
}catch (Exception ex){ {
quotationResponse.setCommonResult(new CommonResult(false, "Error! begindate and enddate format yyyy-MM-dd!ex:{\"begindate\":\"2018-06-10\",\"enddate\":\"2018-06-10\"}")); DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
}finally{ Date begin = fmt.parse(loginRequestVO.getBegindate());
}
quotationResponse.setCommonResult(new CommonResult(true, "Success!")); Date end = fmt.parse(loginRequestVO.getEnddate());
return quotationResponse;
} quotationResponse = taskService.synchQuotaion(begin,end);
} }catch (Exception ex){
\ No newline at end of file quotationResponse.setCommonResult(new CommonResult(false, "Error! begindate and enddate format yyyy-MM-dd!ex:{\"begindate\":\"2018-06-10\",\"enddate\":\"2018-06-10\"}"));
quotationResponse.setErrorCode("S01");
quotationResponse.setErrorMessage("系统出现问题,我们正在加紧解决!");
}finally{
}
quotationResponse.setCommonResult(new CommonResult(true, "Success!"));
return quotationResponse;
}
/**
* 批处理表中的一列,多列
* @param userdataRequestVO
* @return
* @throws Exception
*/
@RequestMapping("/encryptbatch")
public Object query(@RequestBody UserdataRequestVO userdataRequestVO) throws Exception{
return null;
}
}
package com.ajb.web;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* 车险相关系统数据
* @author Simon Cheng
*
*/
@RestController
public class MetaDataController {
/**
* 输出省份,省份简称列表
* @return
* @throws Exception
*/
@RequestMapping(value="/listprovince",method = RequestMethod.GET)
public Object queryProvince() throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
//TODO
return null;
}
/**
* 关键字查询品牌,大众,别克,宝马,奔驰
* @param keyword
* @return
* @throws Exception
*/
@RequestMapping(value="/queryallbrand",method = RequestMethod.GET)
public Object queryAllBrand() throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
//TODO
return null;
}
/**
* 关键字查询品牌,大众,别克,宝马,奔驰
* @param keyword
* @return
* @throws Exception
*/
@RequestMapping(value="/querybrand/{keyword}",method = RequestMethod.GET)
public Object queryBrand(@PathVariable String keyword) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
//TODO
return null;
}
/**
* 查询型号详细信息,指导价格
* @param modelnumber
* @return
* @throws Exception
*/
@RequestMapping(value="/querybrandmodel/{modelnumber}",method = RequestMethod.GET)
public Object queryBrandModel(@PathVariable String modelnumber) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
//TODO
return null;
}
}
\ No newline at end of file
package com.ajb.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.quotation.QuotationRequestVO;
import com.ajb.common.utils.encryption.MaskUtils;
import com.ajb.web.quotation.AgPoQuotationWebService;
/**
* 车险报价
* @author Simon Cheng
*
*/
@RestController
public class OrderController {
@Autowired
private AgPoQuotationWebService agPoOrderWebService;
/**
* 支付报价
* 参数:
* 返回:
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/paymentorder")
public Object paymentOrder(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 查询订单
* 参数:
* 返回:
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/queryorder")
public Object queryOrder(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 取消订单
* 参数:
* 返回:
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/cancelorder")
public Object cancelOrder(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
}
\ No newline at end of file
package com.ajb.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.quotation.QuotationRequestVO;
import com.ajb.common.utils.encryption.MaskUtils;
import com.ajb.global.config.ZhimaConnection;
import com.ajb.web.quotation.AgPoQuotationWebService;
/**
* 车险报价
* @author Simon Cheng
*
*/
@RestController
public class QuotationController {
@Autowired
private AgPoQuotationWebService agPoQuotationWebService;
/**
* 查询用户报价详细信息(某一个保险公司的)
* 保费,保障详情,服务和礼包,车辆信息
* @param quotationId
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/quotation/{quotationId}", method=RequestMethod.GET)
public AgPoQuotationRequestVO queryAgPoQuotation(@PathVariable String quotationId, Model model) throws Exception{
AgPoQuotationRequestVO quotationResponse= agPoQuotationWebService.queryAgPoQuotation(Long.valueOf(quotationId));
quotationResponse.setCustomerMobileMask(MaskUtils.maskCellphone(quotationResponse.getCustomerMobile()));
model.addAttribute("quotation", quotationResponse);
return quotationResponse;
}
/**
* 车牌号,车架号,发动机号,车主,身份证号,
* 报价查询,能查到去年的历史,返回上年的投保范围方案
* 没有的话,就获取车险投保方案(见车险投保推荐方案)
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/lastyearquotation")
public Object lastYearQuotation(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 车险投保推荐方案,自选,推荐,基础型三种
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/recommendcoverages")
public Object recommendCoverages(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 提交用户报价信息
* 参数:用户在一种推荐方案的基础上修改
* 返回:根据用户选择的保障范围,查询各家保险公司的报价返回
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/postquotation")
public Object postQuotation(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 修改用户报价信息
* 参数:用户在一种推荐方案的基础上修改
* 返回:根据用户选择的保障范围,查询各家保险公司的报价返回
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/modifyquotation")
public Object modifyQuotation(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 确认用户报价信息,阅读保险条款并同意
* 参数:阅读保险条款并同意
* 返回:
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/confirmquotation")
public Object confirmQuotation(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 确认用户报价信息后,提交收件地址
* 参数:
* 返回:
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/postrecieveaddress")
public Object postRecieveAddress(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
/**
* 确认用户报价信息后,提交发票信息
* 参数:阅读保险条款并同意
* 返回:
* @param requestVO
* @return
* @throws Exception
*/
@RequestMapping("/postinvoiceinfo")
public Object postInvoiceInfo(@RequestBody QuotationRequestVO requestVO) throws Exception{
//ProvinceResponse quotationResponse = new ProvinceResponse();
return null;
}
}
\ No newline at end of file
package com.ajb.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ajb.car.vo.common.DESCommon;
import com.ajb.car.vo.common.JsonResult;
import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO;
import com.ajb.common.utils.encryption.DESUtils;
import com.ajb.common.utils.encryption.JPACryptoConverter;
import com.ajb.web.user.UserdataWebService;
@RestController
public class UserDataController {
@Autowired
private UserdataWebService userdataWebService;
@RequestMapping("/userdataQuery")
public Object query(@RequestBody UserdataRequestVO userdataRequestVO) throws Exception{
JsonResult result = new JsonResult();
UserdataResponseVO userdataResponseVO = userdataWebService.queryUserdata(userdataRequestVO);
result.setData(userdataResponseVO);
return result;
}
@RequestMapping("/userdataSave")
public Object save(@RequestBody UserdataRequestVO userdataRequestVO) throws Exception{
JsonResult result = new JsonResult();
UserdataResponseVO userdataResponseVO = userdataWebService.saveUserdata(userdataRequestVO);
result.setData(userdataResponseVO);
return result;
}
@RequestMapping("/userdataUpdate")
public Object update(@RequestBody UserdataRequestVO userdataRequestVO) throws Exception{
JsonResult result = new JsonResult();
UserdataResponseVO userdataResponseVO = userdataWebService.updateUserdata(userdataRequestVO);
result.setData(userdataResponseVO);
return result;
}
@RequestMapping("/userdataEncrypt")
public Object encrypt(@RequestBody DESCommon requestVO) throws Exception{
JsonResult result = new JsonResult();
DESUtils des;
String resultString = "";
try {
JPACryptoConverter jpaCryptoConverter = new JPACryptoConverter();
resultString = jpaCryptoConverter.convertToDatabaseColumn(requestVO.getContent());
requestVO.setEncrypted(resultString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setData(requestVO);
return result;
}
@RequestMapping("/userdataDecrypt")
public Object Decrypt(@RequestBody DESCommon requestVO) throws Exception{
JsonResult result = new JsonResult();
DESUtils des;
String content = "";
try {
JPACryptoConverter jpaCryptoConverter = new JPACryptoConverter();
content = jpaCryptoConverter.convertToEntityAttribute(requestVO.getEncrypted());
requestVO.setContent(content);;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result.setData(requestVO);
return result;
}
}
\ No newline at end of file
package com.ajb.web.metadata;
import java.util.List;
import com.ajb.car.vo.zhima.meta.VehicleModels;
public interface MetaDataService {
public List<String> searchmodel1(String keyword);
public List<VehicleModels> searchmodel2(String modelNumber);
}
package com.ajb.web.metadata.impl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ajb.car.entity.meta.Userdata;
import com.ajb.car.metadata.service.UserdataService;
import com.ajb.car.vo.common.CommonResult;
import com.ajb.car.vo.zhima.user.UserdataDeleteRequestVO;
import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO;
import com.ajb.common.utils.encryption.MaskUtils;
import com.ajb.web.user.UserdataWebService;
/**
* 基础资料表的处理
* 这里是演示铭感字段的存储和读取方式
* @author Simon Cheng
*
*/
@Service("userdataWebService")
public class UserdataWebServiceImpl implements UserdataWebService {
@Autowired
private UserdataService userdataService;
@Transactional
@Override
public UserdataResponseVO saveUserdata(UserdataRequestVO userdataRequestVO) throws Exception {
UserdataResponseVO result = new UserdataResponseVO();
//TODO validate the user inputs
Userdata tempEntity = new Userdata();
//TODO validate the user inputs
BeanUtils.copyProperties(userdataRequestVO,tempEntity);
//data persistence
tempEntity = userdataService.save(tempEntity);
//return success info
Boolean success = true;
String message = "save success!";
BeanUtils.copyProperties(tempEntity,userdataRequestVO);
result.setCommonResult(new CommonResult(success,message));
result.setRequestVO(userdataRequestVO);
return result;
}
@Transactional
@Override
public UserdataResponseVO updateUserdata(UserdataRequestVO userdataRequestVO) {
// TODO Auto-generated method stub
Boolean success = true;
String message = "save success!";
UserdataResponseVO result = new UserdataResponseVO();
result.setCommonResult(new CommonResult(success,message));
return result;
}
@Transactional
@Override
public UserdataResponseVO queryUserdata(UserdataRequestVO userdataRequestVO) {
Boolean success = true;
String message = "save success!";
Userdata tempEntity = new Userdata();
BeanUtils.copyProperties(userdataRequestVO,tempEntity);
//data persistence
tempEntity = userdataService.findById(userdataRequestVO.getId());
UserdataResponseVO result = new UserdataResponseVO();
BeanUtils.copyProperties(tempEntity,userdataRequestVO);
//当输出到前端时, view object对象,铭感字段需要打上mask
userdataRequestVO.setIdnumbermask(MaskUtils.maskIDCardNo(userdataRequestVO.getIdnumber()));
userdataRequestVO.setTelephonemask(MaskUtils.maskCellphone(userdataRequestVO.getTelephone()));
result.setRequestVO(userdataRequestVO);
result.setCommonResult(new CommonResult(success,message));
return result;
}
}
\ No newline at end of file
package com.ajb.car.quotation; package com.ajb.web.quotation;
import java.util.Date; import java.util.Date;
import com.ajb.car.entity.quotation.AgPoQuotation; import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.vo.zhima.quotation.ConfirmInfo; import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.Priceinfo; import com.ajb.car.vo.zhima.quotation.ConfirmInfo;
import com.ajb.car.vo.zhima.quotation.Priceinfo;
public interface AgPoQuotationWebService {
public interface AgPoQuotationWebService {
public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo);
public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId);
public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation);
public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo);
public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo);
public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation);
public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo);
} }
\ No newline at end of file
package com.ajb.web.user;
import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO;
public interface UserdataWebService {
public UserdataResponseVO saveUserdata(UserdataRequestVO userdataRequestVO) throws Exception;
public UserdataResponseVO updateUserdata(UserdataRequestVO userdataRequestVO);
public UserdataResponseVO queryUserdata(UserdataRequestVO userdataRequestVO);
//public boolean delteUserdata(UserdataDeleteRequestVO userdataDeleteRequestVO);
}
\ No newline at end of file
package com.ajb.web.zhima;
import java.util.Date;
import com.ajb.car.vo.zhima.quotation.QuotationResponse;
public interface ZhimaDataSyncService {
public QuotationResponse synchQuotaion(Date begin,Date end) throws InterruptedException;
}
package com.ajb.web.zhima.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.metadata.service.SystemConfigService;
import com.ajb.car.quotation.service.AgPoQuotationService;
import com.ajb.car.vo.zhima.policy.PolicyInfo;
import com.ajb.car.vo.zhima.policy.PolicyResponse;
import com.ajb.car.vo.zhima.quotation.QuotationDetail;
import com.ajb.car.vo.zhima.quotation.QuotationResponse;
import com.ajb.common.utils.string.CommonUtil;
import com.ajb.global.config.ZhimaConnection;
import com.ajb.web.quotation.AgPoQuotationWebService;
import com.ajb.web.zhima.ZhimaDataSyncService;
/**
* 同步芝麻车险报价数据
* @author Simon Cheng
*
*/
@Service("zhimaDataSyncService")
public class ZhimaDataSyncServiceImpl implements ZhimaDataSyncService{
@Autowired
private SystemConfigService systemConfigService;
@Autowired
AgPoQuotationWebService agPoQuotationWebService;
@Autowired
AgPoQuotationService agPoQuotationService;
//报价列表查询
private static String queryQuotationURLScopeParam = "";
private static String queryQuotationMethod = "";
//获取报价单详情
private static String queryQuotationDetailMethod = "";
/**
* 同步报价数据
* @param begin
* @param end
* @return
* @throws InterruptedException
*/
@Override
public QuotationResponse synchQuotaion(Date begin,Date end) throws InterruptedException {
queryQuotationMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationMethod");
queryQuotationURLScopeParam = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationURLScopeParam");
queryQuotationDetailMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationDetailMethod");
String startTime = CommonUtil.dateParseString(begin,"yyyy-MM-dd");
String endTime = CommonUtil.dateParseString(end,"yyyy-MM-dd");
return syncPolicyList(startTime,endTime);
}
/**
* 同步芝麻报价数据
* @param startTime
* @param endTime
* @param token
* @return
*/
private QuotationResponse syncPolicyList(String startTime,String endTime)
{
QuotationResponse quotationResponse;
quotationResponse = new QuotationResponse();
QuotationResponse quotationResponsePage = new QuotationResponse();
Integer start = 0;
Integer total = 0;
Integer size = 15;
//询价单列表,按状态,1,2,3
PolicyResponse policyList = null;
policyList = queryListOnePage(startTime,endTime,start);
total = Integer.parseInt(policyList.getDatas().getPolicyPage().getTotal());
System.out.println("Total:" + total);
quotationResponse.setTotal(total);
while(start < total)
{
quotationResponsePage = new QuotationResponse();
//分页,开始行,页行数queryQuotationURLParam
System.out.println("start:" + start);
policyList = queryListOnePage(startTime,endTime,start);
quotationResponsePage = displayList(policyList.getDatas().getPolicyPage().getRows());
quotationResponse.setTotalPremium(quotationResponse.getTotalPremium().add(quotationResponsePage.getTotalPremium()));
quotationResponse.setBzPremium(quotationResponse.getBzPremium().add(quotationResponsePage.getBzPremium()));
quotationResponse.setTcPremium(quotationResponse.getTcPremium().add(quotationResponsePage.getTcPremium()));
quotationResponse.setTsltax(quotationResponse.getTsltax().add(quotationResponsePage.getTsltax()));
quotationResponse.setAllCharge(quotationResponse.getAllCharge().add(quotationResponsePage.getAllCharge()));
if (start > 0 && (start + size > total))
{
break;
}else
{
start = start + size;
}
}
return quotationResponse;
}
/**
* 同步一页数据
* @param startTime
* @param endTime
* @param start
* @param token
* @return
*/
private PolicyResponse queryListOnePage(String startTime,String endTime,Integer start)
{
String queryQuotationMethodStep = String.format(queryQuotationMethod, start.toString(),"15");
queryQuotationURLScopeParam = String.format(queryQuotationURLScopeParam, startTime,endTime);
PolicyResponse policyList = ZhimaConnection.postUrlMap2JavaBean(ZhimaConnection.getHostURL() + queryQuotationMethodStep, queryQuotationURLScopeParam, PolicyResponse.class);
return policyList;
}
/**
* 同步一页报价详情
* @param list
* @param token
* @return
*/
private QuotationResponse displayList(List<PolicyInfo> list)
{
QuotationResponse quotationResponse = new QuotationResponse();
String policyCode = null;
Date quotationDate = null;
BigDecimal totalPremium = new BigDecimal(0);
BigDecimal bzPremium = new BigDecimal(0);
BigDecimal tcPremium = new BigDecimal(0);
BigDecimal vsltax = new BigDecimal(0);
BigDecimal allCharge = new BigDecimal(0);
for(int i = 0; i < list.size();i++)
{
policyCode = list.get(i).getPolicycode();
quotationDate = list.get(i).getCreateDate();
System.out.print(""+ list.get(i).getCarNumber());
totalPremium = totalPremium.add(BigDecimal.valueOf(list.get(i).getTotalPremium()));
bzPremium = bzPremium.add(BigDecimal.valueOf(list.get(i).getBzPremium()));
tcPremium = tcPremium.add(BigDecimal.valueOf(list.get(i).getTcPremium()));
vsltax = vsltax.add(BigDecimal.valueOf(list.get(i).getVsltax()));
allCharge = allCharge.add(BigDecimal.valueOf(list.get(i).getAllCharge()));
System.out.print("getTotalPremium," + list.get(i).getTotalPremium());
System.out.print("getBzPremium," + list.get(i).getBzPremium());
System.out.print("getTcPremium," + list.get(i).getTcPremium());
System.out.print("getVsltax," + list.get(i).getVsltax());
System.out.println("getAllCharge," + list.get(i).getAllCharge());
//检查是否已经存在
AgPoQuotation one = agPoQuotationService.findByQuoteNo(policyCode);
if (one==null)
{
String queryQuotationDetailMethodNew = String.format(queryQuotationDetailMethod, policyCode);
//QuotationDetail postConfirm = getComfirmationDetail(ZhimaConnection.getHostURL() + queryQuotationDetailMethodNew,null,token);
QuotationDetail postConfirm = ZhimaConnection.getUrlMap2JavaBean(ZhimaConnection.getHostURL() + queryQuotationDetailMethodNew,QuotationDetail.class);
//写车辆信息,报价信息,coverages入表
//agPoQuotationWebService.saveAgPoQuotation(postConfirm.getDatas().getPriceinfo());
agPoQuotationWebService.saveAgPoQuotationAndConfirm(quotationDate,postConfirm.getDatas().getPriceinfo(),postConfirm.getDatas().getConfirmInfo());
//写确认信息入表confirmInfo
//agPoQuotationWebService.saveAgPoQuotationConfirm(postConfirm.getDatas().getConfirmInfo());
/*System.out.print("" + postConfirm.getDatas().getPriceinfo().getVehInfo().getRegistrationNumber());
System.out.print("getTotalPremium," + postConfirm.getDatas().getPriceinfo().getTotalPremium());
System.out.print("getBzPremium," + postConfirm.getDatas().getPriceinfo().getBzPremium());
System.out.print("getTcPremium," + postConfirm.getDatas().getPriceinfo().getTcPremium());
System.out.print("getAllCharge," + postConfirm.getDatas().getPriceinfo().getAllCharge());
System.out.println("getVsltax," + postConfirm.getDatas().getPriceinfo().getVsltax());
System.out.print("getAllCharge," + postConfirm.getDatas().getPriceinfo().getAllCharge());
System.out.print("," + dateToString(list.get(i).getCreateDate()));
System.out.println("");*/
}
}
quotationResponse.setTotalPremium(totalPremium);
quotationResponse.setBzPremium(bzPremium);
quotationResponse.setTcPremium(tcPremium);
quotationResponse.setTsltax(vsltax);
quotationResponse.setAllCharge(allCharge);
return quotationResponse;
}
}
\ No newline at end of file
#tomcat 端口号 #tomcat 端口号
server.port=8080 server.port=8081
server.context-path=/synch server.context-path=/carapi
# \u9875\u9762\u9ED8\u8BA4\u524D\u7F00\u76EE\u5F55 # \u9875\u9762\u9ED8\u8BA4\u524D\u7F00\u76EE\u5F55
spring.mvc.view.prefix=/ spring.mvc.view.prefix=/
# \u54CD\u5E94\u9875\u9762\u9ED8\u8BA4\u540E\u7F00 # \u54CD\u5E94\u9875\u9762\u9ED8\u8BA4\u540E\u7F00
...@@ -72,5 +72,5 @@ jwt.issuer:zuihuibi ...@@ -72,5 +72,5 @@ jwt.issuer:zuihuibi
jwt.bypass:TEST jwt.bypass:TEST
#jwt.bypass:/user/loginDemo,/auth/token,/login,/register #jwt.bypass:/user/loginDemo,/auth/token,/login,/register
jpa.sensitivekey:12345678
encryption.key=12345678
\ No newline at end of file
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_121"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
...@@ -17,5 +17,12 @@ ...@@ -17,5 +17,12 @@
<attribute name="org.eclipse.jst.component.nondependency" value=""/> <attribute name="org.eclipse.jst.component.nondependency" value=""/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/ajb-car-utils"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>
</classpath> </classpath>
...@@ -16,17 +16,17 @@ ...@@ -16,17 +16,17 @@
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name> <name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name> <name>org.eclipse.wst.validation.validationbuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
......
...@@ -7,7 +7,10 @@ ...@@ -7,7 +7,10 @@
<artifactId>ajb-car</artifactId> <artifactId>ajb-car</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<groupId>ajb-car-app</groupId>
<artifactId>ajb-car-entity</artifactId> <artifactId>ajb-car-entity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ajb-car-entity</name> <name>ajb-car-entity</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
...@@ -22,4 +25,5 @@ ...@@ -22,4 +25,5 @@
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
package com.ajb.car.entity.meta;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="userdata")
public class Userdata implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/** ?? 主键,???? ag_md_code_type.id */
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@Column(name="username")
private String username;
@Column(name="pasword")
private String pasword;
@Column(name="encryptedpassword")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
private String encryptedpassword;
@Column(name="telephone")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
private String telephone;
@Column(name="idnumber")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
private String idnumber;
public String getUsername(){
return this.username;
}
public void setUsername(String username){
this.username = username;
}
public String getPasword(){
return this.pasword;
}
public void setPasword(String pasword){
this.pasword = pasword;
}
public String getEncryptedpassword(){
return this.encryptedpassword;
}
public void setEncryptedpassword(String encryptedpassword){
this.encryptedpassword = encryptedpassword;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getIdnumber() {
return idnumber;
}
public void setIdnumber(String idnumber) {
this.idnumber = idnumber;
}
}
\ No newline at end of file
...@@ -2,12 +2,15 @@ package com.ajb.car.entity.quotation; ...@@ -2,12 +2,15 @@ package com.ajb.car.entity.quotation;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
import javax.persistence.Id; import javax.persistence.Id;
import javax.persistence.Table; import javax.persistence.Table;
import org.hibernate.annotations.ColumnTransformer;
/** /**
报价单表 报价单表
*/ */
...@@ -150,7 +153,7 @@ private static final long serialVersionUID = 1L; ...@@ -150,7 +153,7 @@ private static final long serialVersionUID = 1L;
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id") @Column(name="id")
public Long getId(){ public Long getId(){
return this.id; return this.id;
} }
...@@ -249,6 +252,7 @@ private static final long serialVersionUID = 1L; ...@@ -249,6 +252,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 客户手机,???? ag_po_quotation.customer_mobile */ /** ?? 客户手机,???? ag_po_quotation.customer_mobile */
@Column(name="customer_mobile") @Column(name="customer_mobile")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getCustomerMobile(){ public String getCustomerMobile(){
return this.customerMobile; return this.customerMobile;
} }
......
...@@ -2,6 +2,7 @@ package com.ajb.car.entity.quotation; ...@@ -2,6 +2,7 @@ package com.ajb.car.entity.quotation;
import java.util.Date; import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
...@@ -148,6 +149,7 @@ private static final long serialVersionUID = 1L; ...@@ -148,6 +149,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 投保人证件号,???? ag_po_quotation_confirm.applicant_certcode */ /** ?? 投保人证件号,???? ag_po_quotation_confirm.applicant_certcode */
@Column(name="applicant_certcode") @Column(name="applicant_certcode")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getApplicantCertcode(){ public String getApplicantCertcode(){
return this.applicantCertcode; return this.applicantCertcode;
} }
...@@ -157,6 +159,7 @@ private static final long serialVersionUID = 1L; ...@@ -157,6 +159,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 投保人,???? ag_po_quotation_confirm.applicant_tel */ /** ?? 投保人,???? ag_po_quotation_confirm.applicant_tel */
@Column(name="applicant_tel") @Column(name="applicant_tel")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getApplicantTel(){ public String getApplicantTel(){
return this.applicantTel; return this.applicantTel;
} }
...@@ -184,6 +187,7 @@ private static final long serialVersionUID = 1L; ...@@ -184,6 +187,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 被保人证件号,???? ag_po_quotation_confirm.insured_certcode */ /** ?? 被保人证件号,???? ag_po_quotation_confirm.insured_certcode */
@Column(name="insured_certcode") @Column(name="insured_certcode")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getInsuredCertcode(){ public String getInsuredCertcode(){
return this.insuredCertcode; return this.insuredCertcode;
} }
...@@ -211,6 +215,7 @@ private static final long serialVersionUID = 1L; ...@@ -211,6 +215,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 权益人证件号,???? ag_po_quotation_confirm.claimant_certcode */ /** ?? 权益人证件号,???? ag_po_quotation_confirm.claimant_certcode */
@Column(name="claimant_certcode") @Column(name="claimant_certcode")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getClaimantCertcode(){ public String getClaimantCertcode(){
return this.claimantCertcode; return this.claimantCertcode;
} }
...@@ -256,6 +261,7 @@ private static final long serialVersionUID = 1L; ...@@ -256,6 +261,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 银行账户,???? ag_po_quotation_confirm.invoice_bankcard_id */ /** ?? 银行账户,???? ag_po_quotation_confirm.invoice_bankcard_id */
@Column(name="invoice_bankcard_id") @Column(name="invoice_bankcard_id")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getInvoiceBankcardId(){ public String getInvoiceBankcardId(){
return this.invoiceBankcardId; return this.invoiceBankcardId;
} }
...@@ -274,6 +280,7 @@ private static final long serialVersionUID = 1L; ...@@ -274,6 +280,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 登记电话,???? ag_po_quotation_confirm.invoice_tel */ /** ?? 登记电话,???? ag_po_quotation_confirm.invoice_tel */
@Column(name="invoice_tel") @Column(name="invoice_tel")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getInvoiceTel(){ public String getInvoiceTel(){
return this.invoiceTel; return this.invoiceTel;
} }
...@@ -292,6 +299,7 @@ private static final long serialVersionUID = 1L; ...@@ -292,6 +299,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 收件人电话,???? ag_po_quotation_confirm.receiver_tel */ /** ?? 收件人电话,???? ag_po_quotation_confirm.receiver_tel */
@Column(name="receiver_tel") @Column(name="receiver_tel")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getReceiverTel(){ public String getReceiverTel(){
return this.receiverTel; return this.receiverTel;
} }
......
...@@ -3,6 +3,7 @@ package com.ajb.car.entity.quotation; ...@@ -3,6 +3,7 @@ package com.ajb.car.entity.quotation;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
...@@ -137,6 +138,7 @@ private static final long serialVersionUID = 1L; ...@@ -137,6 +138,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 电话,???? ag_po_quotation_tax.telephone */ /** ?? 电话,???? ag_po_quotation_tax.telephone */
@Column(name="telephone") @Column(name="telephone")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getTelephone(){ public String getTelephone(){
return this.telephone; return this.telephone;
} }
...@@ -187,6 +189,7 @@ private static final long serialVersionUID = 1L; ...@@ -187,6 +189,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 证件号码,???? ag_po_quotation_tax.cert_code */ /** ?? 证件号码,???? ag_po_quotation_tax.cert_code */
@Column(name="cert_code") @Column(name="cert_code")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getCertCode(){ public String getCertCode(){
return this.certCode; return this.certCode;
} }
......
...@@ -2,6 +2,7 @@ package com.ajb.car.entity.quotation; ...@@ -2,6 +2,7 @@ package com.ajb.car.entity.quotation;
import java.util.Date; import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
...@@ -309,6 +310,7 @@ private static final long serialVersionUID = 1L; ...@@ -309,6 +310,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 发动机号,???? ag_po_quotation_vehicle.engine_no */ /** ?? 发动机号,???? ag_po_quotation_vehicle.engine_no */
@Column(name="engine_no") @Column(name="engine_no")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getEngineNo(){ public String getEngineNo(){
return this.engineNo; return this.engineNo;
} }
...@@ -318,6 +320,7 @@ private static final long serialVersionUID = 1L; ...@@ -318,6 +320,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? VIN编号,???? ag_po_quotation_vehicle.vin_no */ /** ?? VIN编号,???? ag_po_quotation_vehicle.vin_no */
@Column(name="vin_no") @Column(name="vin_no")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getVinNo(){ public String getVinNo(){
return this.vinNo; return this.vinNo;
} }
...@@ -327,6 +330,7 @@ private static final long serialVersionUID = 1L; ...@@ -327,6 +330,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 车架号,???? ag_po_quotation_vehicle.frame_number */ /** ?? 车架号,???? ag_po_quotation_vehicle.frame_number */
@Column(name="frame_number") @Column(name="frame_number")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getFrameNumber(){ public String getFrameNumber(){
return this.frameNumber; return this.frameNumber;
} }
...@@ -516,6 +520,7 @@ private static final long serialVersionUID = 1L; ...@@ -516,6 +520,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 证件号,???? ag_po_quotation_vehicle.owner_certi_code */ /** ?? 证件号,???? ag_po_quotation_vehicle.owner_certi_code */
@Column(name="owner_certi_code") @Column(name="owner_certi_code")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getOwnerCertiCode(){ public String getOwnerCertiCode(){
return this.ownerCertiCode; return this.ownerCertiCode;
} }
...@@ -640,6 +645,7 @@ private static final long serialVersionUID = 1L; ...@@ -640,6 +645,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 平台型号编码,???? ag_po_quotation_vehicle.platform_model_code */ /** ?? 平台型号编码,???? ag_po_quotation_vehicle.platform_model_code */
@Column(name="platform_model_code") @Column(name="platform_model_code")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getPlatformModelCode(){ public String getPlatformModelCode(){
return this.platformModelCode; return this.platformModelCode;
} }
......
...@@ -2,6 +2,7 @@ package com.ajb.car.entity.quotation; ...@@ -2,6 +2,7 @@ package com.ajb.car.entity.quotation;
import java.util.Date; import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.GenerationType;
...@@ -159,6 +160,7 @@ private static final long serialVersionUID = 1L; ...@@ -159,6 +160,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 证件编号,???? ag_po_quotation_vehicle_relation.id_no */ /** ?? 证件编号,???? ag_po_quotation_vehicle_relation.id_no */
@Column(name="id_no") @Column(name="id_no")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getIdNo(){ public String getIdNo(){
return this.idNo; return this.idNo;
} }
...@@ -168,6 +170,7 @@ private static final long serialVersionUID = 1L; ...@@ -168,6 +170,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 移动电话,???? ag_po_quotation_vehicle_relation.mobile_phone */ /** ?? 移动电话,???? ag_po_quotation_vehicle_relation.mobile_phone */
@Column(name="mobile_phone") @Column(name="mobile_phone")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getMobilePhone(){ public String getMobilePhone(){
return this.mobilePhone; return this.mobilePhone;
} }
...@@ -240,6 +243,7 @@ private static final long serialVersionUID = 1L; ...@@ -240,6 +243,7 @@ private static final long serialVersionUID = 1L;
} }
/** ?? 固定电话,???? ag_po_quotation_vehicle_relation.telephone */ /** ?? 固定电话,???? ag_po_quotation_vehicle_relation.telephone */
@Column(name="telephone") @Column(name="telephone")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getTelephone(){ public String getTelephone(){
return this.telephone; return this.telephone;
} }
...@@ -278,6 +282,7 @@ private static final long serialVersionUID = 1L; ...@@ -278,6 +282,7 @@ private static final long serialVersionUID = 1L;
this.versionNo = versionNo; this.versionNo = versionNo;
} }
@Column(name="email") @Column(name="email")
@Convert(converter = com.ajb.common.utils.encryption.JPACryptoConverter.class)
public String getEmail(){ public String getEmail(){
return this.email; return this.email;
} }
......
...@@ -12,9 +12,20 @@ ...@@ -12,9 +12,20 @@
<attribute name="org.eclipse.jst.component.nondependency" value=""/> <attribute name="org.eclipse.jst.component.nondependency" value=""/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"> <classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes> <attributes>
<attribute name="owner.project.facets" value="java"/> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path=".apt_generated">
<attributes>
<attribute name="optional" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>
......
eclipse.preferences.version=1 eclipse.preferences.version=1
encoding//src/main/java=UTF-8 encoding//src/main/java=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8 encoding/<project>=UTF-8
encoding/pom.xml=UTF-8 encoding/pom.xml=UTF-8
eclipse.preferences.version=1 eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.6 org.eclipse.jdt.core.compiler.processAnnotations=enabled
org.eclipse.jdt.core.compiler.source=1.8
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0"> <?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="ajb-car-jpa"> <wb-module deploy-name="ajb-car-jpa">
<wb-resource deploy-path="/" source-path="/src/main/java"/> <wb-resource deploy-path="/" source-path="/src/main/java"/>
<wb-resource deploy-path="/" source-path="/.apt_generated"/>
</wb-module> </wb-module>
</project-modules> </project-modules>
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
<faceted-project> <faceted-project>
<installed facet="cloudfoundry.standalone.app" version="1.0"/> <installed facet="cloudfoundry.standalone.app" version="1.0"/>
<installed facet="jst.utility" version="1.0"/> <installed facet="jst.utility" version="1.0"/>
<installed facet="java" version="1.6"/> <installed facet="java" version="1.8"/>
</faceted-project> </faceted-project>
disabled=06target
eclipse.preferences.version=1 eclipse.preferences.version=1
line.separator=\r\n
eclipse.preferences.version=1
userprojectsettings=false
...@@ -7,7 +7,10 @@ ...@@ -7,7 +7,10 @@
<artifactId>ajb-car</artifactId> <artifactId>ajb-car</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<artifactId>ajb-car-jpa</artifactId> <artifactId>ajb-car-jpa</artifactId>
<groupId>ajb-car-app</groupId>
<version>0.0.1-SNAPSHOT</version>
<name>ajb-car-jpa</name> <name>ajb-car-jpa</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
...@@ -15,18 +18,18 @@ ...@@ -15,18 +18,18 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-car-vo</artifactId> <artifactId>ajb-car-vo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-car-entity</artifactId> <artifactId>ajb-car-entity</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-common-utils</artifactId> <artifactId>ajb-car-utils</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
...@@ -163,4 +166,25 @@ ...@@ -163,4 +166,25 @@
<version>3.9</version> <version>3.9</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<!-- Compiler 插件, 设定JDK版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>
package com.ajb.car.metadata.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.ajb.car.entity.meta.Userdata;
@Repository
public interface UserdataRepository extends JpaRepository<Userdata, Long>,JpaSpecificationExecutor<Userdata> {
/***
* mock find 10
*/
@Query(value="select * from ${context.tableName} t limit 10 ", nativeQuery=true)
List<Userdata> findAll();
}
\ No newline at end of file
package com.ajb.car.metadata.service;
import java.util.List;
import org.springframework.data.domain.Sort;
import com.ajb.car.entity.meta.Userdata;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface UserdataService {
Userdata save(Userdata userdata);
Boolean delete (Long id);
Userdata update(Userdata userdata);
Userdata findById(Long id);
Page<Userdata> findByObjPageable(Userdata userdata,Pageable pageable);
List<Userdata> findByObjSortable(Userdata userdata,Sort sort);
}
\ No newline at end of file
package com.ajb.car.metadata.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.ajb.car.entity.meta.Userdata;
import com.ajb.car.metadata.repositories.UserdataRepository;
import com.ajb.car.metadata.service.UserdataService;
@Service("userdataService")
public class UserdataServiceImpl implements UserdataService{
@Autowired
private UserdataRepository userdataRepo;
public Userdata save(Userdata obj){
return userdataRepo.save(obj);
}
public Boolean delete(Long id) {
try {
userdataRepo .delete(id);
} catch (Exception e) {
return false;
}
return true;
}
public Userdata update(Userdata obj) {
return userdataRepo.saveAndFlush(obj);
}
public Userdata findById(Long id){
return userdataRepo.findOne(id);
}
public Page<Userdata> findByObjPageable(Userdata obj,Pageable pageable){
ExampleMatcher matcher = ExampleMatcher.matching();
Example<Userdata> ex = Example.of(obj, matcher);
return userdataRepo.findAll(ex,pageable);
}
public List<Userdata> findByObjSortable(Userdata obj,Sort sort){
ExampleMatcher matcher = ExampleMatcher.matching();
Example<Userdata> ex = Example.of(obj, matcher);
return userdataRepo.findAll(ex,sort);
}
}
\ No newline at end of file
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_121"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
...@@ -14,6 +14,13 @@ ...@@ -14,6 +14,13 @@
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"> <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.nondependency" value=""/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="target/classes"/> <classpathentry kind="output" path="target/classes"/>
......
...@@ -6,18 +6,37 @@ ...@@ -6,18 +6,37 @@
</projects> </projects>
<buildSpec> <buildSpec>
<buildCommand> <buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name> <name>org.eclipse.jdt.core.javabuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures> </natures>
</projectDescription> </projectDescription>
eclipse.preferences.version=1 eclipse.preferences.version=1
encoding//src/main/java=UTF-8 encoding//src/main/java=UTF-8
encoding//src/main/java/com/ajb/common/utils/string/StringUtil.java=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8 encoding/<project>=UTF-8
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="ajb-car-utils">
<wb-resource deploy-path="/" source-path="/src/main/java"/>
</wb-module>
</project-modules>
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<faceted-project> <faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="cloudfoundry.standalone.app" version="1.0"/>
<installed facet="java" version="1.8"/> <installed facet="java" version="1.8"/>
<installed facet="jst.web" version="3.1"/> <installed facet="jst.utility" version="1.0"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project> </faceted-project>
disabled=06target
eclipse.preferences.version=1
...@@ -16,10 +16,21 @@ ...@@ -16,10 +16,21 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>ajb-car</groupId> <groupId>ajb-car-app</groupId>
<artifactId>ajb-car-vo</artifactId> <artifactId>ajb-car-vo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- SpringBoot Web 依赖 --> <!-- SpringBoot Web 依赖 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -73,4 +84,20 @@ ...@@ -73,4 +84,20 @@
<version>3.9</version> <version>3.9</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<plugins>
<!-- Compiler 插件, 设定JDK版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
<groupId>ajb-car-app</groupId>
<version>0.0.1-SNAPSHOT</version>
</project> </project>
package com.ajb.common.utils.cache; package com.ajb.common.utils.cache;
import net.sf.ehcache.Cache; import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager; import net.sf.ehcache.CacheManager;
public class SystemCacheManager { public class SystemCacheManager {
public static final CacheManager manager = CacheManager.create(); public static final CacheManager manager = CacheManager.create();
public SystemCacheManager() { public SystemCacheManager() {
} }
public static Cache getCache(String cacheName) { public static Cache getCache(String cacheName) {
if (!manager.cacheExists(cacheName)) { if (!manager.cacheExists(cacheName)) {
manager.addCache(cacheName); manager.addCache(cacheName);
} }
return manager.getCache(cacheName); return manager.getCache(cacheName);
} }
} }
package com.ajb.common.utils.encryption;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* 加密/解密工具
* @author ershuai
* @date 2017年4月18日 上午11:27:36
*/
public class DESUtils {
private final byte[] DESIV = new byte[] { 0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef };// 向量
private AlgorithmParameterSpec iv = null;// 加密算法的参数接口
private Key key = null;
private String charset = "utf-8";
/**
* 初始化
* @param deSkey 密钥
* @return
* @throws Exception
*/
public DESUtils(String deSkey, String charset) throws Exception {
if (charset!=null && !charset.isEmpty())
{
this.charset = charset;
}
DESKeySpec keySpec = new DESKeySpec(deSkey.getBytes(this.charset));// 设置密钥参数
iv = new IvParameterSpec(DESIV);// 设置向量
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
key = keyFactory.generateSecret(keySpec);// 得到密钥对象
}
/**
* 加密
* @author ershuai
* @date 2017年4月19日 上午9:40:53
* @param data
* @return
* @throws Exception
*/
public String encode(String data) throws Exception {
Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(pasByte);
}
/**
* 解密
* @author ershuai
* @date 2017年4月19日 上午9:41:01
* @param data
* @return
* @throws Exception
*/
public String decode(String data) throws Exception {
Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, key, iv);
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
return new String(pasByte, "UTF-8");
}
public static void main(String[] args) {
try {
String test = "ershuai";
String key = "12345678";// 自定义密钥
DESUtils des = new DESUtils(key, "utf-8");
System.out.println("加密前的字符:" + test);
System.out.println("加密后的字符:" + des.encode(test));
System.out.println("解密后的字符:" + des.decode(des.encode(test)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.ajb.common.utils.encryption;
import java.util.Properties;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import org.apache.commons.lang3.StringUtils;
@Converter
public class JPACryptoConverter implements AttributeConverter<String, String> {
private static final String secret_property_key = "encryption.key";
private static final Properties properties = new Properties();
private static String sensitivekey = null;
static {
try {
properties.load(JPACryptoConverter.class.getClassLoader()
.getResourceAsStream("persistence.properties"));
} catch (Exception e) {
properties.put(secret_property_key, "12345678");
}
sensitivekey = (String)properties.get(secret_property_key);
}
@Override
public String convertToDatabaseColumn(String sensitive) {
DESUtils des;
String result = "";
try {
des = new DESUtils(sensitivekey, "utf-8");
if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive))
{
result = des.encode(sensitive);
}
return result;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Override
public String convertToEntityAttribute(String sensitive) {
DESUtils des;
String result = "";
try {
des = new DESUtils(sensitivekey, "utf-8");
if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive))
{
result = des.decode(sensitive);
}
return result;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
package com.ajb.common.utils.encryption;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* jwt安全验证设置 head tag,seal封条,过期时间,发行,bypass
* @author Simon Cheng
*/
@Service
public class JPASensitiveSetting {
@Value("${jpa.sensitivekey}")
public String sensitivekey;
}
package com.ajb.common.utils.encryption; package com.ajb.common.utils.encryption;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
public class MD5Util { public class MD5Util {
private static final String HEX_CHARS = "0123456789abcdef"; private static final String HEX_CHARS = "0123456789abcdef";
/** 日志 */ /** 日志 */
private static Log logger = LogFactory.getLog(MD5Util.class); private static Log logger = LogFactory.getLog(MD5Util.class);
private MD5Util() {} private MD5Util() {}
/** /**
* 返回 MessageDigest MD5 * 返回 MessageDigest MD5
*/ */
private static MessageDigest getDigest() { private static MessageDigest getDigest() {
try { try {
return MessageDigest.getInstance("MD5"); return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* 返回 MessageDigest MD5 * 返回 MessageDigest MD5
*/ */
private static MessageDigest getDigestBySha() { private static MessageDigest getDigestBySha() {
try { try {
return MessageDigest.getInstance("SHA-256"); return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* MD5加密,并返回作为一个十六进制字节 * MD5加密,并返回作为一个十六进制字节
*/ */
public static byte[] md5(byte[] data) { public static byte[] md5(byte[] data) {
return getDigest().digest(data); return getDigest().digest(data);
} }
/** /**
* SHA-256加密,并返回作为一个十六进制字节 * SHA-256加密,并返回作为一个十六进制字节
*/ */
public static byte[] sha256(byte[] data) { public static byte[] sha256(byte[] data) {
return getDigestBySha().digest(data); return getDigestBySha().digest(data);
} }
/** /**
* MD5加密,并返回作为一个十六进制字节 * MD5加密,并返回作为一个十六进制字节
* <code>byte[]</code>. * <code>byte[]</code>.
* *
* @param data * @param data
* Data to digest * Data to digest
* @return MD5 digest * @return MD5 digest
*/ */
public static byte[] md5(String data) { public static byte[] md5(String data) {
byte[] bytes = null; byte[] bytes = null;
try { try {
bytes = md5(data.getBytes("UTF-8")); bytes = md5(data.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e); logger.error("MD5加密出错。",e);
} }
return bytes; return bytes;
} }
/** /**
* MD5加密,并返回一个32字符的十六进制值 * MD5加密,并返回一个32字符的十六进制值
*/ */
public static String md5Hex(byte[] data) { public static String md5Hex(byte[] data) {
return toHexString(md5(data)); return toHexString(md5(data));
} }
/** /**
* MD5加密,并返回一个32字符的十六进制值 * MD5加密,并返回一个32字符的十六进制值
*/ */
public static String md5Hex(String data) { public static String md5Hex(String data) {
return toHexString(md5(data)); return toHexString(md5(data));
} }
/** /**
* SHA256加密 * SHA256加密
*/ */
public static String sha256Hex(String data) { public static String sha256Hex(String data) {
try { try {
return toHexString(sha256(data.getBytes("UTF-8"))); return toHexString(sha256(data.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e); logger.error("MD5加密出错。",e);
return null; return null;
} }
} }
private static String toHexString(byte[] b) { private static String toHexString(byte[] b) {
StringBuffer stringbuffer = new StringBuffer(); StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < b.length; i++) { for (int i = 0; i < b.length; i++) {
stringbuffer.append(HEX_CHARS.charAt(b[i] >>> 4 & 0x0F)); stringbuffer.append(HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
stringbuffer.append(HEX_CHARS.charAt(b[i] & 0x0F)); stringbuffer.append(HEX_CHARS.charAt(b[i] & 0x0F));
} }
return stringbuffer.toString(); return stringbuffer.toString();
} }
} }
package com.ajb.common.utils.encryption;
import org.apache.commons.lang3.StringUtils;
/**
*
*/
public class MaskUtils {
public static String maskCellphone(String cellphoneNo) {
if ((cellphoneNo == null) || (cellphoneNo.trim().length() != 11)) {
return cellphoneNo;
}
return cellphoneNo.substring(0, 3) + "****" + cellphoneNo.substring(cellphoneNo.length() - 4);
}
public static String maskEmail(String email) {
if (StringUtils.isBlank(email)) {
return "";
}
int index = StringUtils.indexOf(email, "@");
if (index <= 1)
return email;
else
return StringUtils.rightPad(StringUtils.left(email, 1), index, "*")
.concat(StringUtils.mid(email, index, StringUtils.length(email)));
}
private static String maskCardNo(String cardNo) {
if ((cardNo == null) || (cardNo.trim().length() <= 8)) {
return cardNo;
}
cardNo = cardNo.trim();
int length = cardNo.length();
String firstFourNo = cardNo.substring(0, 4);
String lastFourNo = cardNo.substring(length - 4);
String mask = "";
for (int i = 0; i < length - 8; i++) {
mask = mask + "*";
}
return firstFourNo + mask + lastFourNo;
}
public static String maskIDCardNo(String idCardNo) {
return maskCardNo(idCardNo);
}
public static String maskBankCardNo(String bankCardNo) {
return maskCardNo(bankCardNo);
}
}
package com.ajb.common.utils.http; package com.ajb.common.utils.http;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import com.ajb.car.vo.zhima.TokenZhiMa; import com.ajb.car.vo.zhima.TokenZhiMa;
import com.ajb.common.utils.string.StringUtil; import com.ajb.common.utils.string.StringUtil;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import okhttp3.MediaType; import okhttp3.MediaType;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.Request; import okhttp3.Request;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import okhttp3.Response; import okhttp3.Response;
public class HttpHelpZhiMa { public class HttpHelpZhiMa {
/** /**
* *
* @param urlQuery * @param urlQuery
* @param queryParams * @param queryParams
* @param requestPath * @param requestPath
* @param token * @param token
* @param beanClass * @param beanClass
* @return * @return
*/ */
public static Object postUrlMap2JavaBean(String urlQuery,String queryParams, String token) public static Object postUrlMap2JavaBean(String urlQuery,String queryParams, String token)
{ {
Object object = null; Object object = null;
String returnQueryList = null; String returnQueryList = null;
returnQueryList = doPost(urlQuery,queryParams,token); returnQueryList = doPost(urlQuery,queryParams,token);
System.out.println("response:" + returnQueryList); System.out.println("response:" + returnQueryList);
object = JSON.parseObject(returnQueryList); object = JSON.parseObject(returnQueryList);
return object; return object;
} }
public static <T> T postUrlMap2JavaBean(String urlQuery,String queryParams, String token,Class<T> beanClass) public static <T> T postUrlMap2JavaBean(String urlQuery,String queryParams, String token,Class<T> beanClass)
{ {
T t = null; T t = null;
String returnQueryList = null; String returnQueryList = null;
returnQueryList = doPost(urlQuery,queryParams,token); returnQueryList = doPost(urlQuery,queryParams,token);
//System.out.println("response:" + returnQueryList); //System.out.println("response:" + returnQueryList);
t = JSON.parseObject(returnQueryList, beanClass); t = JSON.parseObject(returnQueryList, beanClass);
return t; return t;
} }
public static <T> T getUrlMap2JavaBean(String urlQuery, String token,Class<T> beanClass) public static <T> T getUrlMap2JavaBean(String urlQuery, String token,Class<T> beanClass)
{ {
T t = null; T t = null;
String returnQueryList = null; String returnQueryList = null;
returnQueryList = doGet(urlQuery, token); returnQueryList = doGet(urlQuery, token);
//System.out.println("response:" + returnQueryList); //System.out.println("response:" + returnQueryList);
t = JSON.parseObject(returnQueryList, beanClass); t = JSON.parseObject(returnQueryList, beanClass);
return t; return t;
} }
/** /**
* 获取token * 获取token
* @param url * @param url
* @param requestBody * @param requestBody
* @param tokenPathParam * @param tokenPathParam
* @param token * @param token
* @return * @return
*/ */
public static TokenZhiMa getToken(String url, String requestBody) public static TokenZhiMa getToken(String url, String requestBody)
{ {
TokenZhiMa token = null; TokenZhiMa token = null;
String reToken = null; String reToken = null;
reToken = doPost(url,requestBody,null); reToken = doPost(url,requestBody,null);
token = JSON.parseObject(reToken, TokenZhiMa.class); token = JSON.parseObject(reToken, TokenZhiMa.class);
return token; return token;
} }
public static String doGet(String url, String token) public static String doGet(String url, String token)
{ {
String returnValue = null; String returnValue = null;
RequestBody body = null;
OkHttpClient client = new OkHttpClient();
OkHttpClient client = new OkHttpClient();
Request request = null;
Request request = null; if (token == null || token == "")
if (token == null || token == "") {
{ request = new Request.Builder()
request = new Request.Builder() .url(url)
.url(url) .get()
.get() .addHeader("Content-Type", "application/json")
.addHeader("Content-Type", "application/json") .addHeader("Cache-Control", "no-cache")
.addHeader("Cache-Control", "no-cache") .build();
.build();
}else
}else {
{ request = new Request.Builder()
request = new Request.Builder() .url(url)
.url(url) .get()
.get() .addHeader("Content-Type", "application/json")
.addHeader("Content-Type", "application/json") .addHeader("Cache-Control", "no-cache")
.addHeader("Cache-Control", "no-cache") .addHeader("token", token)
.addHeader("token", token) .build();
.build(); }
} try
try {
{ Response response = client.newCall(request).execute();
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
InputStream inputStream = response.body().byteStream(); try {
try { String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
returnValue = responseXml;
returnValue = responseXml; } catch (Exception e) {
} catch (Exception e) { // TODO Auto-generated catch block
// TODO Auto-generated catch block e.printStackTrace();
e.printStackTrace(); }
} } catch (IOException e) {
} catch (IOException e) { // TODO Auto-generated catch block
// TODO Auto-generated catch block e.printStackTrace();
e.printStackTrace(); }
}
return returnValue; return returnValue;
} }
public static String doPost(String url, String requestBody,String token) public static String doPost(String url, String requestBody,String token)
{ {
String returnValue = null; String returnValue = null;
RequestBody body = null; RequestBody body = null;
OkHttpClient client = new OkHttpClient(); OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json"); MediaType mediaType = MediaType.parse("application/json");
body = RequestBody.create(mediaType, requestBody); body = RequestBody.create(mediaType, requestBody);
Request request = null; Request request = null;
if (token == null || token == "") if (token == null || token == "")
{ {
request = new Request.Builder() request = new Request.Builder()
.url(url) .url(url)
.post(body) .post(body)
.addHeader("Content-Type", "application/json") .addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache") .addHeader("Cache-Control", "no-cache")
.build(); .build();
}else }else
{ {
request = new Request.Builder() request = new Request.Builder()
.url(url) .url(url)
.post(body) .post(body)
.addHeader("Content-Type", "application/json") .addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache") .addHeader("Cache-Control", "no-cache")
.addHeader("token", token) .addHeader("token", token)
.build(); .build();
} }
try { try {
Response response = client.newCall(request).execute(); Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream(); InputStream inputStream = response.body().byteStream();
try { try {
String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8"); String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
returnValue = responseXml; returnValue = responseXml;
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return returnValue; return returnValue;
} }
} }
package com.ajb.common.utils.string;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Data {
private String ip;
private String country;
private String area;
private String region;
private String city;
private String county;
private String isp;
private String countryId;
private String areaId;
private String regionId;
private String cityId;
private String countyId;
private String ispId;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getIsp() {
return isp;
}
public void setIsp(String isp) {
this.isp = isp;
}
@JsonProperty("country_id")
public String getCountryId() {
return countryId;
}
@JsonProperty(value="country_id")
public void setCountryId(String countryId) {
this.countryId = countryId;
}
@JsonProperty("area_id")
public String getAreaId() {
return areaId;
}
@JsonProperty(value="area_id")
public void setAreaId(String areaId) {
this.areaId = areaId;
}
@JsonProperty("region_id")
public String getRegionId() {
return regionId;
}
@JsonProperty(value="region_id")
public void setRegionId(String regionId) {
this.regionId = regionId;
}
@JsonProperty("city_id")
public String getCityId() {
return cityId;
}
@JsonProperty(value="city_id")
public void setCityId(String cityId) {
this.cityId = cityId;
}
@JsonProperty("county_id")
public String getCountyId() {
return countyId;
}
@JsonProperty(value="county_id")
public void setCountyId(String countyId) {
this.countyId = countyId;
}
@JsonProperty("isp_id")
public String getIspId() {
return ispId;
}
@JsonProperty(value="isp_id")
public void setIspId(String ispId) {
this.ispId = ispId;
}
}
package com.ajb.common.utils.string;
public class IpToAddress {
private String code;
private Data data;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
package com.ajb.common.utils.string; package com.ajb.common.utils.string;
import java.io.IOException; import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil { public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper(); //转换器 private static ObjectMapper mapper = new ObjectMapper(); //转换器
public static String objToJson(Object obj){ public static String objToJson(Object obj){
mapper.setSerializationInclusion(Include.NON_NULL); mapper.setSerializationInclusion(Include.NON_NULL);
String json = null; String json = null;
try { try {
json = mapper.writeValueAsString(obj); json = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
e.printStackTrace(); e.printStackTrace();
} }
return json; return json;
} }
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
public static Object jsonToObj(String json,Class cl){ public static Object jsonToObj(String json,Class cl){
if(json == null || "".equals(json.trim())){ if(json == null || "".equals(json.trim())){
return null; return null;
} }
Object obj = null; Object obj = null;
try { try {
obj = mapper.readValue(json, cl); obj = mapper.readValue(json, cl);
} catch (JsonParseException e) { } catch (JsonParseException e) {
e.printStackTrace(); e.printStackTrace();
} catch (JsonMappingException e) { } catch (JsonMappingException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e){ } catch (Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return obj; return obj;
} }
public static String format(String jsonStr) { public static String format(String jsonStr) {
int level = 0; int level = 0;
StringBuffer jsonForMatStr = new StringBuffer(); StringBuffer jsonForMatStr = new StringBuffer();
for(int i=0;i<jsonStr.length();i++){ for(int i=0;i<jsonStr.length();i++){
char c = jsonStr.charAt(i); char c = jsonStr.charAt(i);
if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){ if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(getLevelStr(level));
} }
switch (c) { switch (c) {
case '{': case '{':
case '[': case '[':
jsonForMatStr.append(c+"\n"); jsonForMatStr.append(c+"\n");
level++; level++;
break; break;
case ',': case ',':
jsonForMatStr.append(c+"\n"); jsonForMatStr.append(c+"\n");
break; break;
case '}': case '}':
case ']': case ']':
jsonForMatStr.append("\n"); jsonForMatStr.append("\n");
level--; level--;
jsonForMatStr.append(getLevelStr(level)); jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c); jsonForMatStr.append(c);
break; break;
default: default:
jsonForMatStr.append(c); jsonForMatStr.append(c);
break; break;
} }
} }
return jsonForMatStr.toString(); return jsonForMatStr.toString();
} }
private static String getLevelStr(int level){ private static String getLevelStr(int level){
StringBuffer levelStr = new StringBuffer(); StringBuffer levelStr = new StringBuffer();
for(int levelI = 0;levelI<level ; levelI++){ for(int levelI = 0;levelI<level ; levelI++){
levelStr.append("\t"); levelStr.append("\t");
} }
return levelStr.toString(); return levelStr.toString();
} }
} }
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jre1.8.0_121"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
......
...@@ -16,12 +16,12 @@ ...@@ -16,12 +16,12 @@
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name> <name>org.eclipse.wst.validation.validationbuilder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand> <buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name> <name>org.eclipse.m2e.core.maven2Builder</name>
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
......
eclipse.preferences.version=1 eclipse.preferences.version=1
encoding//src/main/java=UTF-8 encoding//src/main/java=UTF-8
encoding//src/main/java/com/ajb/car/vo/common/JsonResult.java=UTF-8 encoding//src/main/java/com/ajb/car/vo/common/JsonResult.java=UTF-8
encoding//src/test/java=UTF-8
encoding/<project>=UTF-8 encoding/<project>=UTF-8
disabled=06target
eclipse.preferences.version=1
...@@ -20,17 +20,23 @@ ...@@ -20,17 +20,23 @@
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.47</version> <version>1.2.47</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.7.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<plugins>
<!-- Compiler 插件, 设定JDK版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</build>
<version>0.0.1-SNAPSHOT</version>
<groupId>ajb-car-app</groupId>
</project> </project>
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