Commit 744bf4ee by Simon Cheng

重构芝麻访问连接,统一记录访问调用msg

parent d35e0281
......@@ -113,23 +113,11 @@
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.jeecg</groupId>
<artifactId>easypoi-base</artifactId>
<version>2.3.1</version>
</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>
-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
</dependencies>
<!-- 打包spring boot应用 -->
<build>
......
package com.ajb.car;
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.zhima.user.UserdataRequestVO;
@RestController
public class DataController {
/**
* 批处理表中的一列,多列
* @param userdataRequestVO
* @return
* @throws Exception
*/
@RequestMapping("/batch")
public Object query(@RequestBody UserdataRequestVO userdataRequestVO) throws Exception{
return null;
}
}
package com.ajb.car.apimessage;
public class originmessage {
}
package com.ajb.car.quotation;
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.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.common.utils.encryption.MaskUtils;
@RestController
public class QuotationController {
@Autowired
private AgPoQuotationWebService agPoQuotationWebService;
@RequestMapping(value="/quotations/{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;
}
}
\ No newline at end of file
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;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
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.schedule.ScheduledTaskService;
import com.ajb.car.vo.common.CommonResult;
import com.ajb.car.vo.zhima.quotation.QuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.QuotationResponse;
@RestController
public class CarController {
@Autowired
private ScheduledTaskService taskService;
@RequestMapping("/quotations")
public Object synch(@RequestBody QuotationRequestVO loginRequestVO) throws Exception{
QuotationResponse quotationResponse = new QuotationResponse();
try
{
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
Date begin = fmt.parse(loginRequestVO.getBegindate());
Date end = fmt.parse(loginRequestVO.getEnddate());
quotationResponse = taskService.synchQuotaion(begin,end);
}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\"}"));
}finally{
}
quotationResponse.setCommonResult(new CommonResult(true, "Success!"));
return quotationResponse;
}
}
\ No newline at end of file
package com.ajb.web;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
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.CommonResult;
import com.ajb.car.vo.zhima.quotation.QuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.QuotationResponse;
import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.global.config.ZhimaConnection;
import com.ajb.web.zhima.ZhimaDataSyncService;
@RestController
public class DataController {
@Autowired
private ZhimaDataSyncService taskService;
/**
* 同步芝麻车险报价数据
* @param loginRequestVO
* @return
* @throws Exception
*/
@RequestMapping("/syncquotations")
public Object synch(@RequestBody QuotationRequestVO loginRequestVO) throws Exception{
QuotationResponse quotationResponse = new QuotationResponse();
try
{
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
Date begin = fmt.parse(loginRequestVO.getBegindate());
Date end = fmt.parse(loginRequestVO.getEnddate());
quotationResponse = taskService.synchQuotaion(begin,end);
}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\"}"));
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.car;
package com.ajb.web;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -6,16 +6,15 @@ 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.user.UserdataWebService;
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.web.user.UserdataWebService;
@RestController
@RequestMapping("/userdata")
public class UserdataController {
public class UserDataController {
@Autowired
private UserdataWebService userdataWebService;
......
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.car.user.impl;
package com.ajb.web.metadata.impl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -8,13 +7,12 @@ import org.springframework.transaction.annotation.Transactional;
import com.ajb.car.entity.meta.Userdata;
import com.ajb.car.metadata.service.UserdataService;
import com.ajb.car.user.UserdataWebService;
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;
@Service("userdataWebService")
public class UserdataWebServiceImpl implements UserdataWebService {
......
package com.ajb.car.quotation;
import java.util.Date;
import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.ConfirmInfo;
import com.ajb.car.vo.zhima.quotation.Priceinfo;
public interface AgPoQuotationWebService {
public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId);
public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo);
public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation);
public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo);
package com.ajb.web.quotation;
import java.util.Date;
import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.ConfirmInfo;
import com.ajb.car.vo.zhima.quotation.Priceinfo;
public interface AgPoQuotationWebService {
public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId);
public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo);
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.car.user;
package com.ajb.web.user;
import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO;
......
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
......@@ -56,7 +56,7 @@ spring.jpa.properties.hibernate.format_sql=false
spring.jpa.properties.hibernate.use_sql_comments=false
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.ddl-auto = none
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
......
package com.ajb.common.utils.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
public class SystemCacheManager {
public static final CacheManager manager = CacheManager.create();
public SystemCacheManager() {
}
public static Cache getCache(String cacheName) {
if (!manager.cacheExists(cacheName)) {
manager.addCache(cacheName);
}
return manager.getCache(cacheName);
}
}
package com.ajb.common.utils.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
public class SystemCacheManager {
public static final CacheManager manager = CacheManager.create();
public SystemCacheManager() {
}
public static Cache getCache(String cacheName) {
if (!manager.cacheExists(cacheName)) {
manager.addCache(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.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 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;
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;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MD5Util {
private static final String HEX_CHARS = "0123456789abcdef";
/** 日志 */
private static Log logger = LogFactory.getLog(MD5Util.class);
private MD5Util() {}
/**
* 返回 MessageDigest MD5
*/
private static MessageDigest getDigest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* 返回 MessageDigest MD5
*/
private static MessageDigest getDigestBySha() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* MD5加密,并返回作为一个十六进制字节
*/
public static byte[] md5(byte[] data) {
return getDigest().digest(data);
}
/**
* SHA-256加密,并返回作为一个十六进制字节
*/
public static byte[] sha256(byte[] data) {
return getDigestBySha().digest(data);
}
/**
* MD5加密,并返回作为一个十六进制字节
* <code>byte[]</code>.
*
* @param data
* Data to digest
* @return MD5 digest
*/
public static byte[] md5(String data) {
byte[] bytes = null;
try {
bytes = md5(data.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
}
return bytes;
}
/**
* MD5加密,并返回一个32字符的十六进制值
*/
public static String md5Hex(byte[] data) {
return toHexString(md5(data));
}
/**
* MD5加密,并返回一个32字符的十六进制值
*/
public static String md5Hex(String data) {
return toHexString(md5(data));
}
/**
* SHA256加密
*/
public static String sha256Hex(String data) {
try {
return toHexString(sha256(data.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
return null;
}
}
private static String toHexString(byte[] b) {
StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < b.length; i++) {
stringbuffer.append(HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
stringbuffer.append(HEX_CHARS.charAt(b[i] & 0x0F));
}
return stringbuffer.toString();
}
}
package com.ajb.common.utils.encryption;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MD5Util {
private static final String HEX_CHARS = "0123456789abcdef";
/** 日志 */
private static Log logger = LogFactory.getLog(MD5Util.class);
private MD5Util() {}
/**
* 返回 MessageDigest MD5
*/
private static MessageDigest getDigest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* 返回 MessageDigest MD5
*/
private static MessageDigest getDigestBySha() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* MD5加密,并返回作为一个十六进制字节
*/
public static byte[] md5(byte[] data) {
return getDigest().digest(data);
}
/**
* SHA-256加密,并返回作为一个十六进制字节
*/
public static byte[] sha256(byte[] data) {
return getDigestBySha().digest(data);
}
/**
* MD5加密,并返回作为一个十六进制字节
* <code>byte[]</code>.
*
* @param data
* Data to digest
* @return MD5 digest
*/
public static byte[] md5(String data) {
byte[] bytes = null;
try {
bytes = md5(data.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
}
return bytes;
}
/**
* MD5加密,并返回一个32字符的十六进制值
*/
public static String md5Hex(byte[] data) {
return toHexString(md5(data));
}
/**
* MD5加密,并返回一个32字符的十六进制值
*/
public static String md5Hex(String data) {
return toHexString(md5(data));
}
/**
* SHA256加密
*/
public static String sha256Hex(String data) {
try {
return toHexString(sha256(data.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
return null;
}
}
private static String toHexString(byte[] b) {
StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < b.length; i++) {
stringbuffer.append(HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
stringbuffer.append(HEX_CHARS.charAt(b[i] & 0x0F));
}
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.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;
import java.io.IOException;
import java.io.InputStream;
import com.ajb.car.vo.zhima.TokenZhiMa;
import com.ajb.common.utils.string.StringUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpHelpZhiMa {
/**
*
* @param urlQuery
* @param queryParams
* @param requestPath
* @param token
* @param beanClass
* @return
*/
public static Object postUrlMap2JavaBean(String urlQuery,String queryParams, String token)
{
Object object = null;
String returnQueryList = null;
returnQueryList = doPost(urlQuery,queryParams,token);
System.out.println("response:" + returnQueryList);
object = JSON.parseObject(returnQueryList);
return object;
}
public static <T> T postUrlMap2JavaBean(String urlQuery,String queryParams, String token,Class<T> beanClass)
{
T t = null;
String returnQueryList = null;
returnQueryList = doPost(urlQuery,queryParams,token);
//System.out.println("response:" + returnQueryList);
t = JSON.parseObject(returnQueryList, beanClass);
return t;
}
public static <T> T getUrlMap2JavaBean(String urlQuery, String token,Class<T> beanClass)
{
T t = null;
String returnQueryList = null;
returnQueryList = doGet(urlQuery, token);
//System.out.println("response:" + returnQueryList);
t = JSON.parseObject(returnQueryList, beanClass);
return t;
}
/**
* 获取token
* @param url
* @param requestBody
* @param tokenPathParam
* @param token
* @return
*/
public static TokenZhiMa getToken(String url, String requestBody)
{
TokenZhiMa token = null;
String reToken = null;
reToken = doPost(url,requestBody,null);
token = JSON.parseObject(reToken, TokenZhiMa.class);
return token;
}
public static String doGet(String url, String token)
{
String returnValue = null;
RequestBody body = null;
OkHttpClient client = new OkHttpClient();
Request request = null;
if (token == null || token == "")
{
request = new Request.Builder()
.url(url)
.get()
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.build();
}else
{
request = new Request.Builder()
.url(url)
.get()
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.addHeader("token", token)
.build();
}
try
{
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
try {
String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
returnValue = responseXml;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnValue;
}
public static String doPost(String url, String requestBody,String token)
{
String returnValue = null;
RequestBody body = null;
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
body = RequestBody.create(mediaType, requestBody);
Request request = null;
if (token == null || token == "")
{
request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.build();
}else
{
request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.addHeader("token", token)
.build();
}
try {
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
try {
String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
returnValue = responseXml;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnValue;
}
}
package com.ajb.common.utils.http;
import java.io.IOException;
import java.io.InputStream;
import com.ajb.car.vo.zhima.TokenZhiMa;
import com.ajb.common.utils.string.StringUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpHelpZhiMa {
/**
*
* @param urlQuery
* @param queryParams
* @param requestPath
* @param token
* @param beanClass
* @return
*/
public static Object postUrlMap2JavaBean(String urlQuery,String queryParams, String token)
{
Object object = null;
String returnQueryList = null;
returnQueryList = doPost(urlQuery,queryParams,token);
System.out.println("response:" + returnQueryList);
object = JSON.parseObject(returnQueryList);
return object;
}
public static <T> T postUrlMap2JavaBean(String urlQuery,String queryParams, String token,Class<T> beanClass)
{
T t = null;
String returnQueryList = null;
returnQueryList = doPost(urlQuery,queryParams,token);
//System.out.println("response:" + returnQueryList);
t = JSON.parseObject(returnQueryList, beanClass);
return t;
}
public static <T> T getUrlMap2JavaBean(String urlQuery, String token,Class<T> beanClass)
{
T t = null;
String returnQueryList = null;
returnQueryList = doGet(urlQuery, token);
//System.out.println("response:" + returnQueryList);
t = JSON.parseObject(returnQueryList, beanClass);
return t;
}
/**
* 获取token
* @param url
* @param requestBody
* @param tokenPathParam
* @param token
* @return
*/
public static TokenZhiMa getToken(String url, String requestBody)
{
TokenZhiMa token = null;
String reToken = null;
reToken = doPost(url,requestBody,null);
token = JSON.parseObject(reToken, TokenZhiMa.class);
return token;
}
public static String doGet(String url, String token)
{
String returnValue = null;
OkHttpClient client = new OkHttpClient();
Request request = null;
if (token == null || token == "")
{
request = new Request.Builder()
.url(url)
.get()
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.build();
}else
{
request = new Request.Builder()
.url(url)
.get()
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.addHeader("token", token)
.build();
}
try
{
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
try {
String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
returnValue = responseXml;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnValue;
}
public static String doPost(String url, String requestBody,String token)
{
String returnValue = null;
RequestBody body = null;
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
body = RequestBody.create(mediaType, requestBody);
Request request = null;
if (token == null || token == "")
{
request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.build();
}else
{
request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Cache-Control", "no-cache")
.addHeader("token", token)
.build();
}
try {
Response response = client.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
try {
String responseXml = StringUtil.getInputStreamContent(inputStream,"UTF-8");
returnValue = responseXml;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper(); //转换器
public static String objToJson(Object obj){
mapper.setSerializationInclusion(Include.NON_NULL);
String json = null;
try {
json = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object jsonToObj(String json,Class cl){
if(json == null || "".equals(json.trim())){
return null;
}
Object obj = null;
try {
obj = mapper.readValue(json, cl);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return obj;
}
public static String format(String jsonStr) {
int level = 0;
StringBuffer jsonForMatStr = new StringBuffer();
for(int i=0;i<jsonStr.length();i++){
char c = jsonStr.charAt(i);
if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
jsonForMatStr.append(getLevelStr(level));
}
switch (c) {
case '{':
case '[':
jsonForMatStr.append(c+"\n");
level++;
break;
case ',':
jsonForMatStr.append(c+"\n");
break;
case '}':
case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);
break;
default:
jsonForMatStr.append(c);
break;
}
}
return jsonForMatStr.toString();
}
private static String getLevelStr(int level){
StringBuffer levelStr = new StringBuffer();
for(int levelI = 0;levelI<level ; levelI++){
levelStr.append("\t");
}
return levelStr.toString();
}
}
package com.ajb.common.utils.string;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper(); //转换器
public static String objToJson(Object obj){
mapper.setSerializationInclusion(Include.NON_NULL);
String json = null;
try {
json = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object jsonToObj(String json,Class cl){
if(json == null || "".equals(json.trim())){
return null;
}
Object obj = null;
try {
obj = mapper.readValue(json, cl);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return obj;
}
public static String format(String jsonStr) {
int level = 0;
StringBuffer jsonForMatStr = new StringBuffer();
for(int i=0;i<jsonStr.length();i++){
char c = jsonStr.charAt(i);
if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
jsonForMatStr.append(getLevelStr(level));
}
switch (c) {
case '{':
case '[':
jsonForMatStr.append(c+"\n");
level++;
break;
case ',':
jsonForMatStr.append(c+"\n");
break;
case '}':
case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);
break;
default:
jsonForMatStr.append(c);
break;
}
}
return jsonForMatStr.toString();
}
private static String getLevelStr(int level){
StringBuffer levelStr = new StringBuffer();
for(int levelI = 0;levelI<level ; levelI++){
levelStr.append("\t");
}
return levelStr.toString();
}
}
package com.ajb.car.vo.quotation;
public class QuotationRequestVO implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 车架号
*/
private String frameNumber;
/**
* 发动机号
*/
private String engineNumber;
/**
* 注册日期
*/
private String firstRegistrationDate;
/**
* 品牌型号
*/
private String brandModel;
/**
* 车主姓名
*/
private String customerName;
/**
* 身份证号
*/
private String customerCert;
/**
* 手机号
*/
private String customerMobile;
public String getCustomerMobile() {
return customerMobile;
}
public void setCustomerMobile(String customerMobile) {
this.customerMobile = customerMobile;
}
public String getCustomerCert() {
return customerCert;
}
public void setCustomerCert(String customerCert) {
this.customerCert = customerCert;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getBrandModel() {
return brandModel;
}
public void setBrandModel(String brandModel) {
this.brandModel = brandModel;
}
public String getFirstRegistrationDate() {
return firstRegistrationDate;
}
public void setFirstRegistrationDate(String firstRegistrationDate) {
this.firstRegistrationDate = firstRegistrationDate;
}
public String getEngineNumber() {
return engineNumber;
}
public void setEngineNumber(String engineNumber) {
this.engineNumber = engineNumber;
}
public String getFrameNumber() {
return frameNumber;
}
public void setFrameNumber(String frameNumber) {
this.frameNumber = frameNumber;
}
}
package com.ajb.car.vo.zhima.meta;
/**
* Auto-generated: 2018-08-08 10:22:33
*
* @author bejson.com (i@bejson.com)
* @website http://www.bejson.com/java2pojo/
*/
public class VehicleModels {
private String modelNumber;
private String standardName;
private String vehicleCode;
private String price;
private String remark;
private String brandName;
private String vehicleAlias;
private String seat;
private String marketDate;
private String englineDesc;
private String vehicleHyName;
public String getModelNumber() {
return modelNumber;
}
public void setModelNumber(String modelNumber) {
this.modelNumber = modelNumber;
}
public String getStandardName() {
return standardName;
}
public void setStandardName(String standardName) {
this.standardName = standardName;
}
public String getVehicleCode() {
return vehicleCode;
}
public void setVehicleCode(String vehicleCode) {
this.vehicleCode = vehicleCode;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getVehicleAlias() {
return vehicleAlias;
}
public void setVehicleAlias(String vehicleAlias) {
this.vehicleAlias = vehicleAlias;
}
public String getSeat() {
return seat;
}
public void setSeat(String seat) {
this.seat = seat;
}
public String getMarketDate() {
return marketDate;
}
public void setMarketDate(String marketDate) {
this.marketDate = marketDate;
}
public String getEnglineDesc() {
return englineDesc;
}
public void setEnglineDesc(String englineDesc) {
this.englineDesc = englineDesc;
}
public String getVehicleHyName() {
return vehicleHyName;
}
public void setVehicleHyName(String vehicleHyName) {
this.vehicleHyName = vehicleHyName;
}
}
\ No newline at end of file
......@@ -5,6 +5,9 @@ import java.math.BigDecimal;
import com.ajb.car.vo.common.CommonResult;
public class QuotationResponse {
private String errorCode;//错误代码,E01-入参校验不通过,E02-重复投保,S01-保存失败
private String errorMessage;//错误信息
private Integer total = 0;
private BigDecimal totalPremium = new BigDecimal(0);
private BigDecimal bzPremium = new BigDecimal(0);
......@@ -69,4 +72,20 @@ public class QuotationResponse {
this.bzPremium = bzPremium;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
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