Commit 744bf4ee by Simon Cheng

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

parent d35e0281
...@@ -113,23 +113,11 @@ ...@@ -113,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>
......
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.car.schedule;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
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.apimessage.AgTransVehicleMsgOrigin;
import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.metadata.service.SystemConfigService;
import com.ajb.car.quotation.AgPoQuotationWebService;
import com.ajb.car.quotation.service.AgPoQuotationService;
import com.ajb.car.quotation.service.AgTransVehicleMsgOriginService;
import com.ajb.car.vo.zhima.TokenZhiMa;
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.http.HttpHelpZhiMa;
import com.alibaba.fastjson.JSON;
/**
* 定时任务
* @service和@Component有一个即可,否则自动任务不会被启动
* @EnableScheduling 是必须
*/
@Service("ScheduledTaskService")
//@EnableScheduling
public class ScheduledTaskService {
@Autowired
private SystemConfigService systemConfigService;
@Autowired
AgPoQuotationWebService agPoQuotationWebService;
@Autowired
AgPoQuotationService agPoQuotationService;
//Map<String , String> map = new HashMap<String , String>();
private static String hostURL = "";// "https://baoxian.linkersoft.com/tbjap/";
//获取token
//private static String auth2ParamTest = "{\r\n\t\"unitid\": \"LKTEST\",\r\n\t\"pwd\": \"password\",\r\n\t\"secretid\": \"1aaca8b5fb364267a9d3b56474157cf6\"\r\n}\r\n";
private static String auth2ParamProduction1 = "";// "{\r\n\t\"unitid\": \"SHYD\",\r\n\t\"pwd\": \"shyd1234\",\r\n\t\"secretid\": \"ad9a64fb913f4affa8064f2ae51e3b91\"\r\n}\r\n";
private static String tokenMethod = "";//"api/login";
//private static String tokenXPath = "$.datas.session.token";
//按品牌查型号
//private static String queryUrlModelParam = "{\"keyword\":\"%s\"}";
//private static String queryUrlModelMethod = "api/searchmodel1";
//private static String queryUrlModelXPath = "$.datas.modelNumbers";
//按型号查详细信息
//private static String queryUrlModel2Param = "{\"modelNumber\":\"%s\"}";
//private static String queryUrlModel2Method = "api/searchmodel2";
//private static String queryUrlModel2XPath = "$.datas.vehiclemodels[*]";
//报价查询
//private static String queryUrlCarPriceParam = "{\"carNumber\": \"%s\", \"carOwner\": \"%s\", \"plateType\": \"02\",\"bizAttribute\": \"101\"}";
//private static String queryUrlCarPriceMethod = "api/carpricebynumber";
//private static String queryUrlCarPriceXPath = "$.datas.priceinfo";
//private static String queryUrlGiftParam = "{\"policycode\":\"%s\"}";
//private static String queryURLGift = "api/loadgift";
//报价单加载
//private static String queryUrlConfirmInfoParam = "{\"policycode\":\"%s\"}";
//private static String queryUrlConfirmInfoMethod = "api/loadconfirminfo";
//private static String queryUrlConfirmInfoXPath = "$.datas.confirminfo";
//报价确认
//private static String queryUrlConfirmInfoPostMethod = "api/confirmprice";
//报价列表查询
//private static String queryQuotationURLParam = "{\"status\":\"%s\"}";
private static String queryQuotationURLScopeParam = "";//"{\"begindate\":\"%s\",\"enddate\":\"%s\"}";
private static String queryQuotationMethod = "";// "api/policylist?start=%s&count=%s";
//private static String queryQuotationXPath = "$.datas.pages.rows[*]";
//获取报价单详情
private static String queryQuotationDetailMethod = "";//"api/getconfirmpolicydetail?policycode=%s";
@Autowired
private AgTransVehicleMsgOriginService carZhiMaService;
//@Scheduled(cron = "0/2 * * * * *")
public QuotationResponse synchQuotaion(Date begin,Date end) throws InterruptedException {
auth2ParamProduction1 = systemConfigService.getSingleConfigValue("LinkerSoftAPITokenAuth2Param");
hostURL = systemConfigService.getSingleConfigValue("LinkerSoftAPIHostURL");
tokenMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPITokenMethod");
queryQuotationMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationMethod");
queryQuotationURLScopeParam = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationURLScopeParam");
queryQuotationDetailMethod = systemConfigService.getSingleConfigValue("LinkerSoftAPIQueryQuotationDetailMethod");
TokenZhiMa tokenEntity = getToken(hostURL + tokenMethod,auth2ParamProduction1);
//写原始消息入表
AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
agtransvehiclemsgorigin = initOriginMessage(hostURL,tokenMethod,auth2ParamProduction1,"Post",JSON.toJSONString(tokenEntity));
carZhiMaService.save(agtransvehiclemsgorigin);
String token = tokenEntity.getDatas().getTokenInfo().getToken();
System.out.println("token:" + token);
String startTime = dateToString(begin);
String endTime = dateToString(end);
return testPolicyList(startTime,endTime,token);
}
public static String dateToString(Date time){
SimpleDateFormat formatter;
formatter = new SimpleDateFormat ("yyyy-MM-dd");
String ctime = formatter.format(time);
return ctime;
}
private QuotationResponse testPolicyList(String startTime,String endTime,String token)
{
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 = queryList(startTime,endTime,start,token);
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 = queryList(startTime,endTime,start,token);
quotationResponsePage = displayList(policyList.getDatas().getPolicyPage().getRows(),token);
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;
}
private PolicyResponse queryList(String startTime,String endTime,Integer start,String token)
{
String queryQuotationMethodStep = String.format(queryQuotationMethod, start.toString(),"15");
queryQuotationURLScopeParam = String.format(queryQuotationURLScopeParam, startTime,endTime);
PolicyResponse policyList = postQuotationList(hostURL + queryQuotationMethodStep,queryQuotationURLScopeParam,token);
//写原始消息入表
AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
agtransvehiclemsgorigin = initOriginMessage(hostURL,queryQuotationMethodStep,queryQuotationURLScopeParam,"Post",JSON.toJSONString(policyList));
carZhiMaService.save(agtransvehiclemsgorigin);
return policyList;
}
private QuotationResponse displayList(List<PolicyInfo> list,String token)
{
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(hostURL + queryQuotationDetailMethodNew,null,token);
//写车辆信息,报价信息,coverages入表
//agPoQuotationWebService.saveAgPoQuotation(postConfirm.getDatas().getPriceinfo());
agPoQuotationWebService.saveAgPoQuotationAndConfirm(quotationDate,postConfirm.getDatas().getPriceinfo(),postConfirm.getDatas().getConfirmInfo());
//写确认信息入表confirmInfo
//agPoQuotationWebService.saveAgPoQuotationConfirm(postConfirm.getDatas().getConfirmInfo());
//写原始消息入表
AgTransVehicleMsgOrigin agtransvehiclemsgorigin = new AgTransVehicleMsgOrigin();
agtransvehiclemsgorigin = initOriginMessage(hostURL,queryQuotationDetailMethodNew,"","Post",JSON.toJSONString(postConfirm));
carZhiMaService.save(agtransvehiclemsgorigin);
/*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;
}
public PolicyResponse postQuotationList(String urlQuery,String queryURLParams, String token)
{
PolicyResponse list = null;
list = HttpHelpZhiMa.postUrlMap2JavaBean(urlQuery,queryURLParams,token,PolicyResponse.class);
return list;
}
public static QuotationDetail getComfirmationDetail(String urlQuery,String queryParams, String token)
{
QuotationDetail confirm = null;
confirm = HttpHelpZhiMa.getUrlMap2JavaBean(urlQuery,token,QuotationDetail.class);
return confirm;
}
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;
}
public static TokenZhiMa getToken(String urlQuery,String queryParams)
{
TokenZhiMa returnToken = (TokenZhiMa)HttpHelpZhiMa.getToken(urlQuery,queryParams);
return returnToken;
}
}
\ 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; 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.global.config.ZhimaConnection;
import com.ajb.web.zhima.ZhimaDataSyncService;
@RestController
public class CarController { @RestController
@Autowired public class DataController {
private ScheduledTaskService taskService;
@Autowired
@RequestMapping("/quotations") private ZhimaDataSyncService taskService;
public Object synch(@RequestBody QuotationRequestVO loginRequestVO) throws Exception{
QuotationResponse quotationResponse = new QuotationResponse(); /**
* 同步芝麻车险报价数据
try * @param loginRequestVO
{ * @return
DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd"); * @throws Exception
Date begin = fmt.parse(loginRequestVO.getBegindate()); */
@RequestMapping("/syncquotations")
Date end = fmt.parse(loginRequestVO.getEnddate()); public Object synch(@RequestBody QuotationRequestVO loginRequestVO) throws Exception{
QuotationResponse quotationResponse = new QuotationResponse();
quotationResponse = taskService.synchQuotaion(begin,end);
}catch (Exception ex){ try
quotationResponse.setCommonResult(new CommonResult(false, "Error! begindate and enddate format yyyy-MM-dd!ex:{\"begindate\":\"2018-06-10\",\"enddate\":\"2018-06-10\"}")); {
}finally{ DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
} Date begin = fmt.parse(loginRequestVO.getBegindate());
quotationResponse.setCommonResult(new CommonResult(true, "Success!"));
return quotationResponse; Date end = fmt.parse(loginRequestVO.getEnddate());
}
} quotationResponse = taskService.synchQuotaion(begin,end);
\ No newline at end of file }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; import org.springframework.beans.factory.annotation.Autowired;
...@@ -6,16 +6,15 @@ import org.springframework.web.bind.annotation.RequestBody; ...@@ -6,16 +6,15 @@ 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.user.UserdataWebService;
import com.ajb.car.vo.common.DESCommon; import com.ajb.car.vo.common.DESCommon;
import com.ajb.car.vo.common.JsonResult; import com.ajb.car.vo.common.JsonResult;
import com.ajb.car.vo.zhima.user.UserdataRequestVO; import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO; import com.ajb.car.vo.zhima.user.UserdataResponseVO;
import com.ajb.common.utils.encryption.DESUtils; import com.ajb.common.utils.encryption.DESUtils;
import com.ajb.web.user.UserdataWebService;
@RestController @RestController
@RequestMapping("/userdata") public class UserDataController {
public class UserdataController {
@Autowired @Autowired
private UserdataWebService userdataWebService; 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.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -8,13 +7,12 @@ import org.springframework.transaction.annotation.Transactional; ...@@ -8,13 +7,12 @@ import org.springframework.transaction.annotation.Transactional;
import com.ajb.car.entity.meta.Userdata; import com.ajb.car.entity.meta.Userdata;
import com.ajb.car.metadata.service.UserdataService; 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.common.CommonResult;
import com.ajb.car.vo.zhima.user.UserdataDeleteRequestVO; import com.ajb.car.vo.zhima.user.UserdataDeleteRequestVO;
import com.ajb.car.vo.zhima.user.UserdataRequestVO; import com.ajb.car.vo.zhima.user.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO; import com.ajb.car.vo.zhima.user.UserdataResponseVO;
import com.ajb.common.utils.encryption.MaskUtils; import com.ajb.common.utils.encryption.MaskUtils;
import com.ajb.web.user.UserdataWebService;
@Service("userdataWebService") @Service("userdataWebService")
public class UserdataWebServiceImpl implements UserdataWebService { public class UserdataWebServiceImpl implements UserdataWebService {
......
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.quotation.AgPoQuotationRequestVO; import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.zhima.quotation.ConfirmInfo; import com.ajb.car.vo.zhima.quotation.ConfirmInfo;
import com.ajb.car.vo.zhima.quotation.Priceinfo; import com.ajb.car.vo.zhima.quotation.Priceinfo;
public interface AgPoQuotationWebService { public interface AgPoQuotationWebService {
public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId); public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId);
public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo); public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo);
public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation); public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation);
public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo); public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo);
} }
\ No newline at end of file
package com.ajb.car.quotation.impl; package com.ajb.web.quotation.impl;
import java.math.BigDecimal; import java.math.BigDecimal;
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.entity.quotation.AgPoQuotationCover; import com.ajb.car.entity.quotation.AgPoQuotationCover;
import com.ajb.car.vo.zhima.quotation.BzCoverages; import com.ajb.car.vo.zhima.quotation.BzCoverages;
import com.ajb.car.vo.zhima.quotation.Priceinfo; import com.ajb.car.vo.zhima.quotation.Priceinfo;
public class AgPoQuotationConverter { public class AgPoQuotationConverter {
public static AgPoQuotation initAgPoQuotationData(Priceinfo priceinfo,Long quoteVehicleId) public static AgPoQuotation initAgPoQuotationData(Priceinfo priceinfo,Long quoteVehicleId)
{ {
AgPoQuotation agPoQuotation = new AgPoQuotation(); AgPoQuotation agPoQuotation = new AgPoQuotation();
agPoQuotation.setPlateNo(priceinfo.getCarNumber()); agPoQuotation.setPlateNo(priceinfo.getCarNumber());
agPoQuotation.setQuoteNo(priceinfo.getPolicycode()); agPoQuotation.setQuoteNo(priceinfo.getPolicycode());
agPoQuotation.setQuoteVehicleId(quoteVehicleId); agPoQuotation.setQuoteVehicleId(quoteVehicleId);
if (priceinfo.getVehInfo().getIsNewCar()=="1") if (priceinfo.getVehInfo().getIsNewCar()=="1")
{ {
agPoQuotation.setIsRenewal(1); agPoQuotation.setIsRenewal(1);
}else }else
{ {
agPoQuotation.setIsRenewal(2); agPoQuotation.setIsRenewal(2);
} }
if (priceinfo.getHasbz()=="yes" && priceinfo.getHastc()=="yes") if (priceinfo.getHasbz()=="yes" && priceinfo.getHastc()=="yes")
{ {
agPoQuotation.setQuoteType(2); agPoQuotation.setQuoteType(2);
}else if (priceinfo.getHasbz()=="yes" && priceinfo.getHastc()!="yes") }else if (priceinfo.getHasbz()=="yes" && priceinfo.getHastc()!="yes")
{ {
agPoQuotation.setQuoteType(0); agPoQuotation.setQuoteType(0);
}else if (priceinfo.getHasbz()!="yes" && priceinfo.getHastc()=="yes") }else if (priceinfo.getHasbz()!="yes" && priceinfo.getHastc()=="yes")
{ {
agPoQuotation.setQuoteType(1); agPoQuotation.setQuoteType(1);
} }
agPoQuotation.setQuoteStatus(Integer.parseInt(priceinfo.getStatus())); agPoQuotation.setQuoteStatus(Integer.parseInt(priceinfo.getStatus()));
agPoQuotation.setQuoteProviderType("V"); agPoQuotation.setQuoteProviderType("V");
agPoQuotation.setQuoteProviderId(2L); agPoQuotation.setQuoteProviderId(2L);
agPoQuotation.setCustomerId(-1L); agPoQuotation.setCustomerId(-1L);
agPoQuotation.setCustomerMobile(priceinfo.getApplicant().getTel()); agPoQuotation.setCustomerMobile(priceinfo.getApplicant().getTel());
agPoQuotation.setCustomerName(priceinfo.getApplicant().getName()); agPoQuotation.setCustomerName(priceinfo.getApplicant().getName());
agPoQuotation.setCurrency("RMB"); agPoQuotation.setCurrency("RMB");
agPoQuotation.setTotalPremium(BigDecimal.valueOf(priceinfo.getTotalPremium())); agPoQuotation.setTotalPremium(BigDecimal.valueOf(priceinfo.getTotalPremium()));
agPoQuotation.setTotalCharge(BigDecimal.valueOf(priceinfo.getAllCharge())); agPoQuotation.setTotalCharge(BigDecimal.valueOf(priceinfo.getAllCharge()));
agPoQuotation.setCompulsoryStatus(priceinfo.getTcCoverageStatus()); agPoQuotation.setCompulsoryStatus(priceinfo.getTcCoverageStatus());
agPoQuotation.setCompulsoryMessage(priceinfo.getTcCoverageMsg()); agPoQuotation.setCompulsoryMessage(priceinfo.getTcCoverageMsg());
agPoQuotation.setCompulsoryPremium(BigDecimal.valueOf(priceinfo.getTcPremium())); agPoQuotation.setCompulsoryPremium(BigDecimal.valueOf(priceinfo.getTcPremium()));
agPoQuotation.setCompulsoryCharge(BigDecimal.valueOf(priceinfo.getTcCharge())); agPoQuotation.setCompulsoryCharge(BigDecimal.valueOf(priceinfo.getTcCharge()));
agPoQuotation.setCompulsoryStart(priceinfo.getTcStartTime()); agPoQuotation.setCompulsoryStart(priceinfo.getTcStartTime());
agPoQuotation.setVehicleTax(BigDecimal.valueOf(priceinfo.getVsltax())); agPoQuotation.setVehicleTax(BigDecimal.valueOf(priceinfo.getVsltax()));
java.util.Calendar Cal=java.util.Calendar.getInstance(); java.util.Calendar Cal=java.util.Calendar.getInstance();
Date dateOper = priceinfo.getTcStartTime(); Date dateOper = priceinfo.getTcStartTime();
Cal.setTime(dateOper); Cal.setTime(dateOper);
Cal.add(java.util.Calendar.YEAR,1); Cal.add(java.util.Calendar.YEAR,1);
dateOper = Cal.getTime(); dateOper = Cal.getTime();
agPoQuotation.setCompulsoryEnd(dateOper); agPoQuotation.setCompulsoryEnd(dateOper);
agPoQuotation.setCompulsoryCharge(BigDecimal.valueOf(priceinfo.getTcCharge())); agPoQuotation.setCompulsoryCharge(BigDecimal.valueOf(priceinfo.getTcCharge()));
agPoQuotation.setBusinessInsuranceStatus(priceinfo.getBzCoverageStatus()); agPoQuotation.setBusinessInsuranceStatus(priceinfo.getBzCoverageStatus());
agPoQuotation.setBusinessInsuranceMessage(priceinfo.getBzCoverageMsg()); agPoQuotation.setBusinessInsuranceMessage(priceinfo.getBzCoverageMsg());
agPoQuotation.setBusinessInsurancePremium(BigDecimal.valueOf(priceinfo.getBzPremium())); agPoQuotation.setBusinessInsurancePremium(BigDecimal.valueOf(priceinfo.getBzPremium()));
agPoQuotation.setBusinessInsuranceFloatingRate(BigDecimal.valueOf(Double.valueOf(priceinfo.getBzFloatRatio()))); agPoQuotation.setBusinessInsuranceFloatingRate(BigDecimal.valueOf(Double.valueOf(priceinfo.getBzFloatRatio())));
agPoQuotation.setBusinessInsuranceCharge(BigDecimal.valueOf(priceinfo.getBzCharge())); agPoQuotation.setBusinessInsuranceCharge(BigDecimal.valueOf(priceinfo.getBzCharge()));
agPoQuotation.setBusinessInsuranceStart(priceinfo.getBzStartTime()); agPoQuotation.setBusinessInsuranceStart(priceinfo.getBzStartTime());
dateOper = priceinfo.getBzStartTime(); dateOper = priceinfo.getBzStartTime();
Cal.setTime(dateOper); Cal.setTime(dateOper);
Cal.add(java.util.Calendar.YEAR,1); Cal.add(java.util.Calendar.YEAR,1);
dateOper = Cal.getTime(); dateOper = Cal.getTime();
agPoQuotation.setBusinessInsuranceEnd(dateOper); agPoQuotation.setBusinessInsuranceEnd(dateOper);
agPoQuotation.setBusinessInsuranceCharge(BigDecimal.valueOf(priceinfo.getBzCharge())); agPoQuotation.setBusinessInsuranceCharge(BigDecimal.valueOf(priceinfo.getBzCharge()));
//agPoQuotation.setDepartmentBelong(priceinfo.get); //agPoQuotation.setDepartmentBelong(priceinfo.get);
//agPoQuotation.setDepartmentBelonger(priceinfo.); //agPoQuotation.setDepartmentBelonger(priceinfo.);
//agPoQuotation.setOperator(priceinfo.get); //agPoQuotation.setOperator(priceinfo.get);
//agPoQuotation.setChannelCode(priceinfo.); //agPoQuotation.setChannelCode(priceinfo.);
//agPoQuotation.setGroupNumber(priceinfo.); //agPoQuotation.setGroupNumber(priceinfo.);
//agPoQuotation.setIssueAssociation(); //agPoQuotation.setIssueAssociation();
agPoQuotation.setCreatedAt(new Date()); agPoQuotation.setCreatedAt(new Date());
agPoQuotation.setCreatedBy(-1L); agPoQuotation.setCreatedBy(-1L);
return agPoQuotation; return agPoQuotation;
} }
public static AgPoQuotationCover initThirdPartyLiabilityExemptDeductibleSpecialClauseData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId) public static AgPoQuotationCover initThirdPartyLiabilityExemptDeductibleSpecialClauseData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId)
{ {
AgPoQuotationCover agPoQuotationCover = null; AgPoQuotationCover agPoQuotationCover = null;
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
return agPoQuotationCover; return agPoQuotationCover;
} }
public static AgPoQuotationCover initDamageLossCoverageData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId) public static AgPoQuotationCover initDamageLossCoverageData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId)
{ {
AgPoQuotationCover agPoQuotationCover = null; AgPoQuotationCover agPoQuotationCover = null;
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
return agPoQuotationCover; return agPoQuotationCover;
} }
public static AgPoQuotationCover initCarBodyPaintCoverageData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId) public static AgPoQuotationCover initCarBodyPaintCoverageData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId)
{ {
AgPoQuotationCover agPoQuotationCover = null; AgPoQuotationCover agPoQuotationCover = null;
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
return agPoQuotationCover; return agPoQuotationCover;
} }
public static AgPoQuotationCover initDamageLossExemptDeductibleSpecialClauseData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId) public static AgPoQuotationCover initDamageLossExemptDeductibleSpecialClauseData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId)
{ {
AgPoQuotationCover agPoQuotationCover = null; AgPoQuotationCover agPoQuotationCover = null;
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
return agPoQuotationCover; return agPoQuotationCover;
} }
public static AgPoQuotationCover initCarBodyPaintExemptDeductibleSpecialClauseData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId) public static AgPoQuotationCover initCarBodyPaintExemptDeductibleSpecialClauseData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId)
{ {
AgPoQuotationCover agPoQuotationCover = null; AgPoQuotationCover agPoQuotationCover = null;
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
return agPoQuotationCover; return agPoQuotationCover;
} }
public static AgPoQuotationCover initThirdPartyLiabilityCoverageData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId) public static AgPoQuotationCover initThirdPartyLiabilityCoverageData(BzCoverages bzCoverages,Long quotationId,Long quotationVehicleId)
{ {
AgPoQuotationCover agPoQuotationCover = null; AgPoQuotationCover agPoQuotationCover = null;
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
return agPoQuotationCover; return agPoQuotationCover;
} }
} }
package com.ajb.car.quotation.impl; package com.ajb.web.quotation.impl;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import com.ajb.car.entity.quotation.AgPoQuotation; import com.ajb.car.entity.quotation.AgPoQuotation;
import com.ajb.car.entity.quotation.AgPoQuotationConfirm; import com.ajb.car.entity.quotation.AgPoQuotationConfirm;
import com.ajb.car.entity.quotation.AgPoQuotationCover; import com.ajb.car.entity.quotation.AgPoQuotationCover;
import com.ajb.car.entity.quotation.AgPoQuotationTax; import com.ajb.car.entity.quotation.AgPoQuotationTax;
import com.ajb.car.entity.quotation.AgPoQuotationVehicle; import com.ajb.car.entity.quotation.AgPoQuotationVehicle;
import com.ajb.car.entity.quotation.AgPoQuotationVehicleRelation; import com.ajb.car.entity.quotation.AgPoQuotationVehicleRelation;
import com.ajb.car.quotation.AgPoQuotationWebService; import com.ajb.car.quotation.service.AgPoQuotationService;
import com.ajb.car.quotation.service.AgPoQuotationService; import com.ajb.car.quotation.service.AgPoQuotationTaxService;
import com.ajb.car.quotation.service.AgPoQuotationTaxService; import com.ajb.car.quotation.service.AgPoQuotationConfirmService;
import com.ajb.car.quotation.service.AgPoQuotationConfirmService; import com.ajb.car.quotation.service.AgPoQuotationVehicleService;
import com.ajb.car.quotation.service.AgPoQuotationVehicleService; import com.ajb.car.quotation.service.AgPoQuotationCoverService;
import com.ajb.car.quotation.service.AgPoQuotationCoverService; import com.ajb.car.quotation.service.AgPoQuotationVehicleRelationService;
import com.ajb.car.quotation.service.AgPoQuotationVehicleRelationService; import com.ajb.car.vo.quotation.AgPoQuotationRequestVO;
import com.ajb.car.vo.quotation.AgPoQuotationRequestVO; import com.ajb.car.vo.zhima.quotation.Applicant;
import com.ajb.car.vo.zhima.quotation.Applicant; import com.ajb.car.vo.zhima.quotation.Claimant;
import com.ajb.car.vo.zhima.quotation.BzCoverages; import com.ajb.car.vo.zhima.quotation.ConfirmInfo;
import com.ajb.car.vo.zhima.quotation.CarBodyPaintCoverage;
import com.ajb.car.vo.zhima.quotation.CarBodyPaintExemptDeductibleSpecialClause; import com.ajb.car.vo.zhima.quotation.Priceinfo;
import com.ajb.car.vo.zhima.quotation.Claimant; import com.ajb.car.vo.zhima.quotation.TcCoverages;
import com.ajb.car.vo.zhima.quotation.ConfirmInfo;
import com.ajb.car.vo.zhima.quotation.DamageLossCoverage; import com.ajb.car.vo.zhima.quotation.VehInfo;
import com.ajb.car.vo.zhima.quotation.DamageLossExemptDeductibleSpecialClause; import com.ajb.car.vo.zhima.quotation.VsltaxInfo;
import com.ajb.car.vo.zhima.quotation.Priceinfo; import com.ajb.web.quotation.AgPoQuotationWebService;
import com.ajb.car.vo.zhima.quotation.TcCoverages;
import com.ajb.car.vo.zhima.quotation.ThirdPartyLiabilityCoverage; @Service("agPoQuotationWebService")
import com.ajb.car.vo.zhima.quotation.ThirdPartyLiabilityExemptDeductibleSpecialClause; public class AgPoQuotationWebServiceImpl implements AgPoQuotationWebService {
import com.ajb.car.vo.zhima.quotation.VehInfo;
import com.ajb.car.vo.zhima.quotation.VsltaxInfo; @Autowired
private AgPoQuotationService agPoQuotationService;
@Service("agPoQuotationWebService")
public class AgPoQuotationWebServiceImpl implements AgPoQuotationWebService { @Autowired
private AgPoQuotationVehicleService agPoQuotationVehicleService;
@Autowired
private AgPoQuotationService agPoQuotationService; @Autowired
AgPoQuotationConfirmService agPoQuotationConfirmService;
@Autowired
private AgPoQuotationVehicleService agPoQuotationVehicleService; @Autowired
AgPoQuotationTaxService agPoQuotationTaxService;
@Autowired
AgPoQuotationConfirmService agPoQuotationConfirmService; @Autowired
AgPoQuotationCoverService agPoQuotationCoverService;
@Autowired
AgPoQuotationTaxService agPoQuotationTaxService; @Autowired
AgPoQuotationVehicleRelationService agPoQuotationVehicleRelationService;
@Autowired
AgPoQuotationCoverService agPoQuotationCoverService; @Transactional
@Override
@Autowired public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo) {
AgPoQuotationVehicleRelationService agPoQuotationVehicleRelationService; //车辆,保险范围,申请人,受益人
AgPoQuotation quotation = saveAgPoQuotationNoTrans(quotationDate,priceinfo);
@Transactional
@Override //保存确认单
public void saveAgPoQuotationAndConfirm(Date quotationDate,Priceinfo priceinfo,ConfirmInfo confirmInfo) { saveAgPoQuotationConfirmNoTrans(confirmInfo,quotation);
//车辆,保险范围,申请人,受益人
AgPoQuotation quotation = saveAgPoQuotationNoTrans(quotationDate,priceinfo); //保存确认单
saveAgPoQuotationVehicleTaxNoTrans(priceinfo.getVsltaxInfo(),priceinfo.getVsltax(),quotation);
//保存确认单 }
saveAgPoQuotationConfirmNoTrans(confirmInfo,quotation);
@Transactional
//保存确认单 @Override
saveAgPoQuotationVehicleTaxNoTrans(priceinfo.getVsltaxInfo(),priceinfo.getVsltax(),quotation); public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo) {
} return saveAgPoQuotationNoTrans(quotationDate,priceinfo);
}
@Transactional
@Override private AgPoQuotation saveAgPoQuotationNoTrans(Date quotationDate,Priceinfo priceinfo) {
public AgPoQuotation saveAgPoQuotation(Date quotationDate,Priceinfo priceinfo) { Long quotationVehicleId = 0L;
return saveAgPoQuotationNoTrans(quotationDate,priceinfo); //保存车辆信息
} //TODO如果存在直接取回,先check exist
AgPoQuotationVehicle agPoQuotationVehicle = new AgPoQuotationVehicle();
private AgPoQuotation saveAgPoQuotationNoTrans(Date quotationDate,Priceinfo priceinfo) { agPoQuotationVehicle = initAgPoQuotationVehicleData(priceinfo.getVehInfo());
Long quotationVehicleId = 0L; agPoQuotationVehicle = agPoQuotationVehicleService.save(agPoQuotationVehicle);
//保存车辆信息 quotationVehicleId = agPoQuotationVehicle.getId();
//TODO如果存在直接取回,先check exist //保存quotation
AgPoQuotationVehicle agPoQuotationVehicle = new AgPoQuotationVehicle(); AgPoQuotation agPoQuotation = new AgPoQuotation();
agPoQuotationVehicle = initAgPoQuotationVehicleData(priceinfo.getVehInfo()); agPoQuotation = AgPoQuotationConverter.initAgPoQuotationData(priceinfo,quotationVehicleId);
agPoQuotationVehicle = agPoQuotationVehicleService.save(agPoQuotationVehicle); agPoQuotation = agPoQuotationService.save(agPoQuotation);
quotationVehicleId = agPoQuotationVehicle.getId(); agPoQuotation.setQuoteVersion(quotationDate);
//保存quotation
AgPoQuotation agPoQuotation = new AgPoQuotation(); Long quotationId = agPoQuotation.getId();
agPoQuotation = AgPoQuotationConverter.initAgPoQuotationData(priceinfo,quotationVehicleId);
agPoQuotation = agPoQuotationService.save(agPoQuotation); //保存商业险
agPoQuotation.setQuoteVersion(quotationDate); //保存交强险
saveAgPoQuotationCoveragesData(priceinfo,quotationId,quotationVehicleId);
Long quotationId = agPoQuotation.getId();
//申请人
//保存商业险 AgPoQuotationVehicleRelation agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation();
//保存交强险 agPoQuotationVehicleRelation = initAgPoQuotationVehicleRelationApplicantData(priceinfo.getApplicant(),quotationId);
saveAgPoQuotationCoveragesData(priceinfo,quotationId,quotationVehicleId);
agPoQuotationVehicleRelationService.save(agPoQuotationVehicleRelation);
//申请人 //收益人
AgPoQuotationVehicleRelation agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation(); agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation();
agPoQuotationVehicleRelation = initAgPoQuotationVehicleRelationApplicantData(priceinfo.getApplicant(),quotationId); agPoQuotationVehicleRelation = initAgPoQuotationVehicleRelationClaimantData(priceinfo.getClaimant(),quotationId);
agPoQuotationVehicleRelationService.save(agPoQuotationVehicleRelation); agPoQuotationVehicleRelationService.save(agPoQuotationVehicleRelation);
//收益人
agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation(); return agPoQuotation;
agPoQuotationVehicleRelation = initAgPoQuotationVehicleRelationClaimantData(priceinfo.getClaimant(),quotationId); }
private AgPoQuotationVehicleRelation initAgPoQuotationVehicleRelationApplicantData(Applicant applicant,Long quotationId)
agPoQuotationVehicleRelationService.save(agPoQuotationVehicleRelation); {
AgPoQuotationVehicleRelation agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation();
return agPoQuotation; agPoQuotationVehicleRelation.setQuotationId(quotationId);
} agPoQuotationVehicleRelation.setName(applicant.getName());
private AgPoQuotationVehicleRelation initAgPoQuotationVehicleRelationApplicantData(Applicant applicant,Long quotationId) agPoQuotationVehicleRelation.setIdNo(applicant.getCertCode());
{ agPoQuotationVehicleRelation.setIdType(1L);
AgPoQuotationVehicleRelation agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation(); agPoQuotationVehicleRelation.setIdTypeName(applicant.getCertType());
agPoQuotationVehicleRelation.setQuotationId(quotationId); agPoQuotationVehicleRelation.setAddress(applicant.getAddress());
agPoQuotationVehicleRelation.setName(applicant.getName()); agPoQuotationVehicleRelation.setTelephone(applicant.getTel());
agPoQuotationVehicleRelation.setIdNo(applicant.getCertCode()); agPoQuotationVehicleRelation.setNationality(applicant.getNatureType());
agPoQuotationVehicleRelation.setIdType(1L); agPoQuotationVehicleRelation.setVehicleRelationId(1L);
agPoQuotationVehicleRelation.setIdTypeName(applicant.getCertType()); agPoQuotationVehicleRelation.setCreatedAt(new Date());
agPoQuotationVehicleRelation.setAddress(applicant.getAddress()); agPoQuotationVehicleRelation.setCreatedBy(-1L);
agPoQuotationVehicleRelation.setTelephone(applicant.getTel()); agPoQuotationVehicleRelation.setCustomerId(-1L);
agPoQuotationVehicleRelation.setNationality(applicant.getNatureType()); return agPoQuotationVehicleRelation;
agPoQuotationVehicleRelation.setVehicleRelationId(1L); }
agPoQuotationVehicleRelation.setCreatedAt(new Date()); private AgPoQuotationVehicleRelation initAgPoQuotationVehicleRelationClaimantData(Claimant claimant,Long quotationId)
agPoQuotationVehicleRelation.setCreatedBy(-1L); {
agPoQuotationVehicleRelation.setCustomerId(-1L); AgPoQuotationVehicleRelation agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation();
return agPoQuotationVehicleRelation; agPoQuotationVehicleRelation.setQuotationId(quotationId);
} agPoQuotationVehicleRelation.setName(claimant.getName());
private AgPoQuotationVehicleRelation initAgPoQuotationVehicleRelationClaimantData(Claimant claimant,Long quotationId) agPoQuotationVehicleRelation.setIdNo(claimant.getCertCode());
{ agPoQuotationVehicleRelation.setIdType(1L);
AgPoQuotationVehicleRelation agPoQuotationVehicleRelation = new AgPoQuotationVehicleRelation(); agPoQuotationVehicleRelation.setIdTypeName(claimant.getCertType());
agPoQuotationVehicleRelation.setQuotationId(quotationId); agPoQuotationVehicleRelation.setAddress(claimant.getAddress());
agPoQuotationVehicleRelation.setName(claimant.getName()); agPoQuotationVehicleRelation.setTelephone(claimant.getTel());
agPoQuotationVehicleRelation.setIdNo(claimant.getCertCode()); agPoQuotationVehicleRelation.setNationality(claimant.getNatureType());
agPoQuotationVehicleRelation.setIdType(1L); agPoQuotationVehicleRelation.setVehicleRelationId(5L);
agPoQuotationVehicleRelation.setIdTypeName(claimant.getCertType()); agPoQuotationVehicleRelation.setCreatedAt(new Date());
agPoQuotationVehicleRelation.setAddress(claimant.getAddress()); agPoQuotationVehicleRelation.setCreatedBy(-1L);
agPoQuotationVehicleRelation.setTelephone(claimant.getTel()); agPoQuotationVehicleRelation.setCustomerId(-1L);
agPoQuotationVehicleRelation.setNationality(claimant.getNatureType()); return agPoQuotationVehicleRelation;
agPoQuotationVehicleRelation.setVehicleRelationId(5L); }
agPoQuotationVehicleRelation.setCreatedAt(new Date()); private void saveAgPoQuotationCoveragesData(Priceinfo priceinfo,Long quotationId,Long quotationVehicleId)
agPoQuotationVehicleRelation.setCreatedBy(-1L); {
agPoQuotationVehicleRelation.setCustomerId(-1L); AgPoQuotationCover agPoQuotationCover = null;
return agPoQuotationVehicleRelation; //商业险--车损
} if (priceinfo.getBzCoverages().getDamageLossCoverage()!=null)
private void saveAgPoQuotationCoveragesData(Priceinfo priceinfo,Long quotationId,Long quotationVehicleId) {
{ agPoQuotationCover = new AgPoQuotationCover();
AgPoQuotationCover agPoQuotationCover = null; agPoQuotationCover.setCount(priceinfo.getBzCoverages().getDamageLossCoverage().getCount());
//商业险--车损 agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getDamageLossCoverage().getSumInsured());
if (priceinfo.getBzCoverages().getDamageLossCoverage()!=null) agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getDamageLossCoverage().getKind());
{ //agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getDamageLossCoverage().get);
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossCoverage().getFloatingRate()));
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getDamageLossCoverage().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossCoverage().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getDamageLossCoverage().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossCoverage().getStandardPremium()));
agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getDamageLossCoverage().getKind()); //agPoQuotationCover.setTax(priceinfo.getBzCoverages().getDamageLossCoverage().get);
//agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getDamageLossCoverage().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossCoverage().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossCoverage().getPolicyPremium())); agPoQuotationCover.setVehicleClauseId(1L);
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossCoverage().getStandardPremium())); agPoQuotationCover.setClauseCategory("M");
//agPoQuotationCover.setTax(priceinfo.getBzCoverages().getDamageLossCoverage().get); agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getDamageLossCoverage().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("机动车损失保险");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setVehicleClauseId(1L); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setClauseCategory("M");
agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getDamageLossCoverage().getKind()); System.out.println("机动车损失保险getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover.setClauseDescription("机动车损失保险");
agPoQuotationCover.setCreatedAt(new Date()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setCreatedBy(-1L); }
System.out.println("机动车损失保险getPremium," + agPoQuotationCover.getPremium()); //交强险
if (priceinfo.getTcCoverages()!=null)
agPoQuotationCoverService.save(agPoQuotationCover); {
} agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover = initAgPoQuotationTcCoveragesData(priceinfo.getTcCoverages(),quotationId,quotationVehicleId);
//交强险 agPoQuotationCover.setCreatedAt(new Date());
if (priceinfo.getTcCoverages()!=null) agPoQuotationCover.setCreatedBy(-1L);
{
agPoQuotationCover = new AgPoQuotationCover(); System.out.println("交强险getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover = initAgPoQuotationTcCoveragesData(priceinfo.getTcCoverages(),quotationId,quotationVehicleId);
agPoQuotationCover.setCreatedAt(new Date()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setCreatedBy(-1L); }
System.out.println("交强险getPremium," + agPoQuotationCover.getPremium()); //商业险--车身划痕损失险
if (priceinfo.getBzCoverages().getCarBodyPaintCoverage()!=null)
agPoQuotationCoverService.save(agPoQuotationCover); {
} agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getCount());
//商业险--车身划痕损失险 agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getSumInsured());
if (priceinfo.getBzCoverages().getCarBodyPaintCoverage()!=null) agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getKind());
{ //agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getCarBodyPaintCoverage().get);
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getFloatingRate()));
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getStandardPremium()));
agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getKind()); //agPoQuotationCover.setTax(priceinfo.getBzCoverages().getCarBodyPaintCoverage().get);
//agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getCarBodyPaintCoverage().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getPolicyPremium())); agPoQuotationCover.setVehicleClauseId(7L);
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getStandardPremium())); agPoQuotationCover.setClauseCategory("M");
//agPoQuotationCover.setTax(priceinfo.getBzCoverages().getCarBodyPaintCoverage().get); agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("车身划痕损失险");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setVehicleClauseId(7L); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setClauseCategory("M"); System.out.println("车身划痕损失险getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getCarBodyPaintCoverage().getKind()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setClauseDescription("车身划痕损失险"); }
agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setCreatedBy(-1L); //商业险--车漆面三则免赔
System.out.println("车身划痕损失险getPremium," + agPoQuotationCover.getPremium()); if (priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause()!=null)
agPoQuotationCoverService.save(agPoQuotationCover); {
} agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getCount());
//商业险--车漆面三则免赔 agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getSumInsured());
if (priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause()!=null) agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getKind());
{ //agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getCarBodyPaintCoverage().get);
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getFloatingRate()));
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getStandardPremium()));
agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getKind()); //agPoQuotationCover.setTax(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().get);
//agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getCarBodyPaintCoverage().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getPolicyPremium())); agPoQuotationCover.setVehicleClauseId(7L);
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getStandardPremium())); agPoQuotationCover.setClauseCategory("A");
//agPoQuotationCover.setTax(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().get); agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("车身划痕损失险免赔");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setVehicleClauseId(7L); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setClauseCategory("A"); System.out.println("车身划痕损失险免赔getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getCarBodyPaintExemptDeductibleSpecialClause().getKind()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setClauseDescription("车身划痕损失险免赔"); }
agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setCreatedBy(-1L); //商业险--不计免赔率险
System.out.println("车身划痕损失险免赔getPremium," + agPoQuotationCover.getPremium()); if (priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause()!=null)
agPoQuotationCoverService.save(agPoQuotationCover); {
} agPoQuotationCover = new AgPoQuotationCover();
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getCount());
//商业险--不计免赔率险 agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getSumInsured());
if (priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause()!=null) agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getKind());
{ //agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().get);
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getFloatingRate()));
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getStandardPremium()));
agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getKind()); //agPoQuotationCover.setTax(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().get);
//agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getPolicyPremium())); agPoQuotationCover.setVehicleClauseId(6L);
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getStandardPremium())); agPoQuotationCover.setClauseCategory("M");
//agPoQuotationCover.setTax(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().get); agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("机动车损失不计免赔保险");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setVehicleClauseId(6L); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setClauseCategory("M"); System.out.println("机动车损失不计免赔保险getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getDamageLossExemptDeductibleSpecialClause().getKind()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setClauseDescription("机动车损失不计免赔保险"); }
agPoQuotationCover.setCreatedAt(new Date()); //商业险--第三者责任险
agPoQuotationCover.setCreatedBy(-1L); if (priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage()!=null)
System.out.println("机动车损失不计免赔保险getPremium," + agPoQuotationCover.getPremium()); {
agPoQuotationCoverService.save(agPoQuotationCover); agPoQuotationCover = new AgPoQuotationCover();
} agPoQuotationCover.setCount(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getCount());
//商业险--第三者责任险 agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getSumInsured());
if (priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage()!=null) agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getKind());
{ //agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().get);
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getFloatingRate()));
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getStandardPremium()));
agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getKind()); //agPoQuotationCover.setTax(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().get);
//agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getPolicyPremium())); agPoQuotationCover.setClauseCategory("M");
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getStandardPremium())); agPoQuotationCover.setVehicleClauseId(2L);
//agPoQuotationCover.setTax(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().get); agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("机动车第三者责任保险");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setClauseCategory("M"); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setVehicleClauseId(2L); System.out.println("机动车第三者责任保险getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getThirdPartyLiabilityCoverage().getKind()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setClauseDescription("机动车第三者责任保险"); }
agPoQuotationCover.setCreatedAt(new Date()); //商业险--第三者责任险免赔
agPoQuotationCover.setCreatedBy(-1L); if (priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause()!=null)
System.out.println("机动车第三者责任保险getPremium," + agPoQuotationCover.getPremium()); {
agPoQuotationCoverService.save(agPoQuotationCover); agPoQuotationCover = new AgPoQuotationCover();
} agPoQuotationCover.setCount(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getCount());
//商业险--第三者责任险免赔 agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getSumInsured());
if (priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause()!=null) agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getKind());
{ //agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().get);
agPoQuotationCover = new AgPoQuotationCover(); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getFloatingRate()));
agPoQuotationCover.setCount(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getStandardPremium()));
agPoQuotationCover.setCoverName(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getKind()); //agPoQuotationCover.setTax(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().get);
//agPoQuotationCover.setDiscountRate(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getPolicyPremium())); agPoQuotationCover.setVehicleClauseId(2L);
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getStandardPremium())); agPoQuotationCover.setClauseCategory("A");
//agPoQuotationCover.setTax(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().get); agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("机动车第三者责任不计免赔率险");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setVehicleClauseId(2L); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setClauseCategory("A"); System.out.println("机动车第三者责任不计免赔率险getPremium," + agPoQuotationCover.getPremium());
agPoQuotationCover.setClauseCode(priceinfo.getBzCoverages().getThirdPartyLiabilityExemptDeductibleSpecialClause().getKind()); agPoQuotationCoverService.save(agPoQuotationCover);
agPoQuotationCover.setClauseDescription("机动车第三者责任不计免赔率险"); }
agPoQuotationCover.setCreatedAt(new Date()); }
agPoQuotationCover.setCreatedBy(-1L);
System.out.println("机动车第三者责任不计免赔率险getPremium," + agPoQuotationCover.getPremium()); private AgPoQuotationCover initAgPoQuotationTcCoveragesData(TcCoverages tcCoverages,Long quotationId,Long quotationVehicleId)
agPoQuotationCoverService.save(agPoQuotationCover); {
} AgPoQuotationCover agPoQuotationCover = new AgPoQuotationCover();
} BeanUtils.copyProperties(tcCoverages.getTRAFFICCOMPULSORYPRODUCT(),agPoQuotationCover);
agPoQuotationCover.setCount(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getCount());
private AgPoQuotationCover initAgPoQuotationTcCoveragesData(TcCoverages tcCoverages,Long quotationId,Long quotationVehicleId) agPoQuotationCover.setCoverAmount(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getSumInsured());
{ agPoQuotationCover.setCoverName(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getKind());
AgPoQuotationCover agPoQuotationCover = new AgPoQuotationCover(); //agPoQuotationCover.setDiscountRate(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().get);
BeanUtils.copyProperties(tcCoverages.getTRAFFICCOMPULSORYPRODUCT(),agPoQuotationCover); agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getFloatingRate()));
agPoQuotationCover.setCount(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getCount()); agPoQuotationCover.setPremium(BigDecimal.valueOf(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getPolicyPremium()));
agPoQuotationCover.setCoverAmount(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getSumInsured()); agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getStandardPremium()));
agPoQuotationCover.setCoverName(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getKind()); //agPoQuotationCover.setTax(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().get);
//agPoQuotationCover.setDiscountRate(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().get); agPoQuotationCover.setQuotationId(quotationId);
agPoQuotationCover.setFloatingRate(BigDecimal.valueOf(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getFloatingRate())); agPoQuotationCover.setQuotationVehicleId(quotationVehicleId);
agPoQuotationCover.setPremium(BigDecimal.valueOf(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getPolicyPremium())); agPoQuotationCover.setVehicleClauseId(18L);
agPoQuotationCover.setStandardPremium(BigDecimal.valueOf(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getStandardPremium())); agPoQuotationCover.setClauseCategory("A");
//agPoQuotationCover.setTax(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().get); agPoQuotationCover.setClauseCode(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getKind());
agPoQuotationCover.setQuotationId(quotationId); agPoQuotationCover.setClauseDescription("机动车第三者责任不计免赔率险");
agPoQuotationCover.setQuotationVehicleId(quotationVehicleId); agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setVehicleClauseId(18L); agPoQuotationCover.setCreatedBy(-1L);
agPoQuotationCover.setClauseCategory("A");
agPoQuotationCover.setClauseCode(tcCoverages.getTRAFFICCOMPULSORYPRODUCT().getKind()); return agPoQuotationCover;
agPoQuotationCover.setClauseDescription("机动车第三者责任不计免赔率险"); }
agPoQuotationCover.setCreatedAt(new Date());
agPoQuotationCover.setCreatedBy(-1L); private AgPoQuotationVehicle initAgPoQuotationVehicleData(VehInfo vehInfo)
{
return agPoQuotationCover; AgPoQuotationVehicle agPoQuotationVehicle = new AgPoQuotationVehicle();
} BeanUtils.copyProperties(vehInfo, agPoQuotationVehicle);
private AgPoQuotationVehicle initAgPoQuotationVehicleData(VehInfo vehInfo) agPoQuotationVehicle.setIsNewCar(vehInfo.getIsNewCar());
{
AgPoQuotationVehicle agPoQuotationVehicle = new AgPoQuotationVehicle(); //agPoQuotationVehicle.vehInfo.getNewCarFlag();
BeanUtils.copyProperties(vehInfo, agPoQuotationVehicle); //agPoQuotationVehicle.vehInfo.getInsuranceFlag();
agPoQuotationVehicle.setVehicleBrand(vehInfo.getModelNumber());
agPoQuotationVehicle.setIsNewCar(vehInfo.getIsNewCar()); agPoQuotationVehicle.setVehicleCode(vehInfo.getModelSerialCode());
//车架号非空
//agPoQuotationVehicle.vehInfo.getNewCarFlag(); agPoQuotationVehicle.setFrameNumber(vehInfo.getFrameNumber());
//agPoQuotationVehicle.vehInfo.getInsuranceFlag(); agPoQuotationVehicle.setLicenseType(vehInfo.getPlateType());
agPoQuotationVehicle.setVehicleBrand(vehInfo.getModelNumber()); //引擎号非空
agPoQuotationVehicle.setVehicleCode(vehInfo.getModelSerialCode()); agPoQuotationVehicle.setEngineNo(vehInfo.getEngineNumber());
//车架号非空 //初登日期非空
agPoQuotationVehicle.setFrameNumber(vehInfo.getFrameNumber()); agPoQuotationVehicle.setFirstRegistrationDate(vehInfo.getFirstRegistrationDate());
agPoQuotationVehicle.setLicenseType(vehInfo.getPlateType()); //车牌号非空
//引擎号非空 agPoQuotationVehicle.setPlateNo(vehInfo.getRegistrationNumber());
agPoQuotationVehicle.setEngineNo(vehInfo.getEngineNumber()); agPoQuotationVehicle.setVehicleCategory(vehInfo.getCategory());
//初登日期非空 agPoQuotationVehicle.setOwner(vehInfo.getLicenseOwner());
agPoQuotationVehicle.setFirstRegistrationDate(vehInfo.getFirstRegistrationDate()); agPoQuotationVehicle.setOriginCertiType(vehInfo.getLicenseOwnerCertType());
//车牌号非空 agPoQuotationVehicle.setOwnerCertiCode(vehInfo.getLicenseOwnerCertCode());
agPoQuotationVehicle.setPlateNo(vehInfo.getRegistrationNumber()); agPoQuotationVehicle.setOwnerNature(vehInfo.getOwnerNature());
agPoQuotationVehicle.setVehicleCategory(vehInfo.getCategory()); agPoQuotationVehicle.setModelCharacterNumber(vehInfo.getModelCharacterNumber());
agPoQuotationVehicle.setOwner(vehInfo.getLicenseOwner()); //vehInfo.getAttribute;
agPoQuotationVehicle.setOriginCertiType(vehInfo.getLicenseOwnerCertType()); //vehInfo.getBizAttribute;
agPoQuotationVehicle.setOwnerCertiCode(vehInfo.getLicenseOwnerCertCode()); //vehInfo.getBizCategory;
agPoQuotationVehicle.setOwnerNature(vehInfo.getOwnerNature()); agPoQuotationVehicle.setVehicleUseType(vehInfo.getUse());
agPoQuotationVehicle.setModelCharacterNumber(vehInfo.getModelCharacterNumber()); agPoQuotationVehicle.setPriceNewcar(vehInfo.getPurchasePrice());
//vehInfo.getAttribute; agPoQuotationVehicle.setReferencePrice(vehInfo.getKindPrice());
//vehInfo.getBizAttribute; agPoQuotationVehicle.setCurrentPrice(vehInfo.getCurrentValue());
//vehInfo.getBizCategory; agPoQuotationVehicle.setSeatCapacity(vehInfo.getSeatCapacity());
agPoQuotationVehicle.setVehicleUseType(vehInfo.getUse()); agPoQuotationVehicle.setCarryingCapacity(vehInfo.getCarryingCapacity());
agPoQuotationVehicle.setPriceNewcar(vehInfo.getPurchasePrice()); agPoQuotationVehicle.setFuelType(vehInfo.getGlassType());
agPoQuotationVehicle.setReferencePrice(vehInfo.getKindPrice()); agPoQuotationVehicle.setDispacementPower(vehInfo.getEngineSize());
agPoQuotationVehicle.setCurrentPrice(vehInfo.getCurrentValue()); agPoQuotationVehicle.setIsPayoffLoan(vehInfo.getLoanVehicleFlag());
agPoQuotationVehicle.setSeatCapacity(vehInfo.getSeatCapacity()); agPoQuotationVehicle.setBrandmakeModel(vehInfo.getBrand());
agPoQuotationVehicle.setCarryingCapacity(vehInfo.getCarryingCapacity()); agPoQuotationVehicle.setDriveArea(vehInfo.getDrivingArea());
agPoQuotationVehicle.setFuelType(vehInfo.getGlassType()); agPoQuotationVehicle.setDispacementPower(vehInfo.getVehiclePower());
agPoQuotationVehicle.setDispacementPower(vehInfo.getEngineSize()); //vehInfo.getVehiclePowerJY;
agPoQuotationVehicle.setIsPayoffLoan(vehInfo.getLoanVehicleFlag()); agPoQuotationVehicle.setFuelType(vehInfo.getFuelType());
agPoQuotationVehicle.setBrandmakeModel(vehInfo.getBrand()); agPoQuotationVehicle.setIsTransfered(vehInfo.getSpecialCarFlag());
agPoQuotationVehicle.setDriveArea(vehInfo.getDrivingArea()); agPoQuotationVehicle.setPurchaseInvoiceDate(vehInfo.getPurchaseinvoicesDate());
agPoQuotationVehicle.setDispacementPower(vehInfo.getVehiclePower()); agPoQuotationVehicle.setModelIdCode(vehInfo.getModelIdCode());
//vehInfo.getVehiclePowerJY; agPoQuotationVehicle.setPlatformModelCode(vehInfo.getPlatformModelCode());
agPoQuotationVehicle.setFuelType(vehInfo.getFuelType()); agPoQuotationVehicle.setVehicleUseType(vehInfo.getVehicleUsageDetail());
agPoQuotationVehicle.setIsTransfered(vehInfo.getSpecialCarFlag()); //agPoQuotationVehiclevehInfo.getIllegalNumLastYear;
agPoQuotationVehicle.setPurchaseInvoiceDate(vehInfo.getPurchaseinvoicesDate()); //agPoQuotationVehicle.setvehInfo.getTcDesignedAge;
agPoQuotationVehicle.setModelIdCode(vehInfo.getModelIdCode()); //vehInfo.getAnnualMileage;
agPoQuotationVehicle.setPlatformModelCode(vehInfo.getPlatformModelCode()); //vehInfo.getSpecvtype;
agPoQuotationVehicle.setVehicleUseType(vehInfo.getVehicleUsageDetail()); //vehInfo.getInstalment;
//agPoQuotationVehiclevehInfo.getIllegalNumLastYear; //vehInfo.getDesignedAge;
//agPoQuotationVehicle.setvehInfo.getTcDesignedAge; //vehInfo.getDepreciatedExpireAge;
//vehInfo.getAnnualMileage; agPoQuotationVehicle.setPlateColor(vehInfo.getPlateColor());
//vehInfo.getSpecvtype; //agPoQuotationVehicle.vehInfo.getManufacturer;
//vehInfo.getInstalment; agPoQuotationVehicle.setBodyColor(vehInfo.getBodyColor());
//vehInfo.getDesignedAge; //vehInfo.getProducePlaceType;
//vehInfo.getDepreciatedExpireAge; agPoQuotationVehicle.setIndustryVehicleCode(vehInfo.getIndustryVehicleCode());
agPoQuotationVehicle.setPlateColor(vehInfo.getPlateColor()); agPoQuotationVehicle.setPlatformBrand(vehInfo.getPlatformBrand());
//agPoQuotationVehicle.vehInfo.getManufacturer; agPoQuotationVehicle.setBrandCode(vehInfo.getBrandCode());
agPoQuotationVehicle.setBodyColor(vehInfo.getBodyColor()); //vehInfo.getSeries;
//vehInfo.getProducePlaceType; //vehInfo.getSeriesCode;
agPoQuotationVehicle.setIndustryVehicleCode(vehInfo.getIndustryVehicleCode()); agPoQuotationVehicle.setCarName(vehInfo.getCarName());
agPoQuotationVehicle.setPlatformBrand(vehInfo.getPlatformBrand()); //vehInfo.getNoticeType;
agPoQuotationVehicle.setBrandCode(vehInfo.getBrandCode()); agPoQuotationVehicle.setTradeCode(vehInfo.getTradeCode());
//vehInfo.getSeries;
//vehInfo.getSeriesCode; //agPoQuotationVehicle.setActualYearsUsed(vehInfo.get);
agPoQuotationVehicle.setCarName(vehInfo.getCarName()); agPoQuotationVehicle.setCreatedAt(new Date());
//vehInfo.getNoticeType; agPoQuotationVehicle.setCreatedBy(-1L);
agPoQuotationVehicle.setTradeCode(vehInfo.getTradeCode()); return agPoQuotationVehicle;
}
//agPoQuotationVehicle.setActualYearsUsed(vehInfo.get); private void saveAgPoQuotationConfirmNoTrans(ConfirmInfo confirmInfo, AgPoQuotation quotation) {
agPoQuotationVehicle.setCreatedAt(new Date()); // TODO Auto-generated method stub
agPoQuotationVehicle.setCreatedBy(-1L); AgPoQuotationConfirm agPoQuotationConfirm = new AgPoQuotationConfirm();
return agPoQuotationVehicle; agPoQuotationConfirm = initAgPoQuotationConfirmData(confirmInfo);
} agPoQuotationConfirm.setQuotationId(quotation.getId());
private void saveAgPoQuotationConfirmNoTrans(ConfirmInfo confirmInfo, AgPoQuotation quotation) { agPoQuotationConfirm.setQuotationVehicleId(quotation.getQuoteVehicleId());
// TODO Auto-generated method stub agPoQuotationConfirmService.save(agPoQuotationConfirm);
AgPoQuotationConfirm agPoQuotationConfirm = new AgPoQuotationConfirm(); }
agPoQuotationConfirm = initAgPoQuotationConfirmData(confirmInfo); private AgPoQuotationConfirm initAgPoQuotationConfirmData(ConfirmInfo confirmInfo)
agPoQuotationConfirm.setQuotationId(quotation.getId()); {
agPoQuotationConfirm.setQuotationVehicleId(quotation.getQuoteVehicleId()); AgPoQuotationConfirm agPoQuotationConfirm = new AgPoQuotationConfirm();
agPoQuotationConfirmService.save(agPoQuotationConfirm); BeanUtils.copyProperties(confirmInfo, agPoQuotationConfirm);
} agPoQuotationConfirm.setCreatedAt(new Date());
private AgPoQuotationConfirm initAgPoQuotationConfirmData(ConfirmInfo confirmInfo) agPoQuotationConfirm.setCreatedBy(-1L);
{ return agPoQuotationConfirm;
AgPoQuotationConfirm agPoQuotationConfirm = new AgPoQuotationConfirm(); }
BeanUtils.copyProperties(confirmInfo, agPoQuotationConfirm); private void saveAgPoQuotationVehicleTaxNoTrans(VsltaxInfo vsltaxInfo,Double taxAmount,AgPoQuotation quotation) {
agPoQuotationConfirm.setCreatedAt(new Date()); // TODO Auto-generated method stub
agPoQuotationConfirm.setCreatedBy(-1L); AgPoQuotationTax agPoQuotationTax = new AgPoQuotationTax();
return agPoQuotationConfirm; BeanUtils.copyProperties(vsltaxInfo, agPoQuotationTax);
} agPoQuotationTax.setTaxAmount(BigDecimal.valueOf(taxAmount));
private void saveAgPoQuotationVehicleTaxNoTrans(VsltaxInfo vsltaxInfo,Double taxAmount,AgPoQuotation quotation) { agPoQuotationTax.setQuotationId(quotation.getId());
// TODO Auto-generated method stub agPoQuotationTax.setQuotationVehicleId(quotation.getQuoteVehicleId());
AgPoQuotationTax agPoQuotationTax = new AgPoQuotationTax(); agPoQuotationTax.setCreatedAt(new Date());
BeanUtils.copyProperties(vsltaxInfo, agPoQuotationTax); agPoQuotationTax.setCreatedBy(-1L);
agPoQuotationTax.setTaxAmount(BigDecimal.valueOf(taxAmount)); agPoQuotationTaxService.save(agPoQuotationTax);
agPoQuotationTax.setQuotationId(quotation.getId()); }
agPoQuotationTax.setQuotationVehicleId(quotation.getQuoteVehicleId()); @Transactional
agPoQuotationTax.setCreatedAt(new Date()); @Override
agPoQuotationTax.setCreatedBy(-1L); public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation) {
agPoQuotationTaxService.save(agPoQuotationTax); // TODO Auto-generated method stub
} saveAgPoQuotationConfirmNoTrans(confirmInfo,quotation);
@Transactional }
@Override
public void saveAgPoQuotationConfirm(ConfirmInfo confirmInfo,AgPoQuotation quotation) { @Override
// TODO Auto-generated method stub public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId) {
saveAgPoQuotationConfirmNoTrans(confirmInfo,quotation); AgPoQuotationRequestVO agPoQuotationRequestVO = new AgPoQuotationRequestVO();
} AgPoQuotation agPoQuotation = agPoQuotationService.findById(quotationId);
BeanUtils.copyProperties(agPoQuotation, agPoQuotationRequestVO);
@Override return agPoQuotationRequestVO;
public AgPoQuotationRequestVO queryAgPoQuotation(Long quotationId) {
AgPoQuotationRequestVO agPoQuotationRequestVO = new AgPoQuotationRequestVO();
AgPoQuotation agPoQuotation = agPoQuotationService.findById(quotationId); }
BeanUtils.copyProperties(agPoQuotation, agPoQuotationRequestVO);
return agPoQuotationRequestVO;
}
} }
\ 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.UserdataRequestVO;
import com.ajb.car.vo.zhima.user.UserdataResponseVO; 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 ...@@ -56,7 +56,7 @@ spring.jpa.properties.hibernate.format_sql=false
spring.jpa.properties.hibernate.use_sql_comments=false spring.jpa.properties.hibernate.use_sql_comments=false
# Hibernate ddl auto (create, create-drop, update) # Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update spring.jpa.hibernate.ddl-auto = none
# Naming strategy # Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy] #[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
......
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; package com.ajb.common.utils.encryption;
import java.security.Key; import java.security.Key;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import sun.misc.BASE64Encoder;
/** /**
* 加密/解密工具 * 加密/解密工具
* @author ershuai * @author ershuai
* @date 2017年4月18日 上午11:27:36 * @date 2017年4月18日 上午11:27:36
*/ */
public class DESUtils { public class DESUtils {
private final byte[] DESIV = new byte[] { 0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef };// 向量 private final byte[] DESIV = new byte[] { 0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef };// 向量
private AlgorithmParameterSpec iv = null;// 加密算法的参数接口 private AlgorithmParameterSpec iv = null;// 加密算法的参数接口
private Key key = null; private Key key = null;
private String charset = "utf-8"; private String charset = "utf-8";
/** /**
* 初始化 * 初始化
* @param deSkey 密钥 * @param deSkey 密钥
* @return * @return
* @throws Exception * @throws Exception
*/ */
public DESUtils(String deSkey, String charset) throws Exception { public DESUtils(String deSkey, String charset) throws Exception {
if (charset!=null && !charset.isEmpty()) if (charset!=null && !charset.isEmpty())
{ {
this.charset = charset; this.charset = charset;
} }
DESKeySpec keySpec = new DESKeySpec(deSkey.getBytes(this.charset));// 设置密钥参数 DESKeySpec keySpec = new DESKeySpec(deSkey.getBytes(this.charset));// 设置密钥参数
iv = new IvParameterSpec(DESIV);// 设置向量 iv = new IvParameterSpec(DESIV);// 设置向量
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
key = keyFactory.generateSecret(keySpec);// 得到密钥对象 key = keyFactory.generateSecret(keySpec);// 得到密钥对象
} }
/** /**
* 加密 * 加密
* @author ershuai * @author ershuai
* @date 2017年4月19日 上午9:40:53 * @date 2017年4月19日 上午9:40:53
* @param data * @param data
* @return * @return
* @throws Exception * @throws Exception
*/ */
public String encode(String data) throws Exception { public String encode(String data) throws Exception {
Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量 enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8")); byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
BASE64Encoder base64Encoder = new BASE64Encoder(); BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(pasByte); return base64Encoder.encode(pasByte);
} }
/** /**
* 解密 * 解密
* @author ershuai * @author ershuai
* @date 2017年4月19日 上午9:41:01 * @date 2017年4月19日 上午9:41:01
* @param data * @param data
* @return * @return
* @throws Exception * @throws Exception
*/ */
public String decode(String data) throws Exception { public String decode(String data) throws Exception {
Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, key, iv); deCipher.init(Cipher.DECRYPT_MODE, key, iv);
BASE64Decoder base64Decoder = new BASE64Decoder(); BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data)); byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
return new String(pasByte, "UTF-8"); return new String(pasByte, "UTF-8");
} }
public static void main(String[] args) { public static void main(String[] args) {
try { try {
String test = "ershuai"; String test = "ershuai";
String key = "12345678";// 自定义密钥 String key = "12345678";// 自定义密钥
DESUtils des = new DESUtils(key, "utf-8"); DESUtils des = new DESUtils(key, "utf-8");
System.out.println("加密前的字符:" + test); System.out.println("加密前的字符:" + test);
System.out.println("加密后的字符:" + des.encode(test)); System.out.println("加密后的字符:" + des.encode(test));
System.out.println("解密后的字符:" + des.decode(des.encode(test))); System.out.println("解密后的字符:" + des.decode(des.encode(test)));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
package com.ajb.common.utils.encryption; package com.ajb.common.utils.encryption;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.Signature; import java.security.Signature;
import java.security.SignatureException; import java.security.SignatureException;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec; import java.security.spec.X509EncodedKeySpec;
import java.util.Base64; import java.util.Base64;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import com.ajb.common.utils.string.StringUtil; import com.ajb.common.utils.string.StringUtil;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import sun.misc.BASE64Encoder;
public class EncryptUtil { public class EncryptUtil {
private static final Log logger = LogFactory.getLog(EncryptUtil.class); private static final Log logger = LogFactory.getLog(EncryptUtil.class);
private static final String HEX_CHARS = "0123456789abcdef"; private static final String HEX_CHARS = "0123456789abcdef";
/** /**
* 加密 * 加密
* @param source * @param source
* @return * @return
*/ */
public static String encrypt(String source,String charSet) { public static String encrypt(String source,String charSet) {
if(StringUtil.isNullOrBlank(source)){ if(StringUtil.isNullOrBlank(source)){
return null; return null;
} }
if(StringUtil.isNullOrBlank(charSet)){ if(StringUtil.isNullOrBlank(charSet)){
charSet = "utf-8"; charSet = "utf-8";
} }
try { try {
MessageDigest md = MessageDigest.getInstance("MD5"); MessageDigest md = MessageDigest.getInstance("MD5");
try { try {
md.update(source.getBytes(charSet)); md.update(source.getBytes(charSet));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
byte b[] = md.digest(); byte b[] = md.digest();
int i; int i;
StringBuffer buf = new StringBuffer(""); StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) { for (int offset = 0; offset < b.length; offset++) {
i = b[offset]; i = b[offset];
if (i < 0){i += 256;} if (i < 0){i += 256;}
if (i < 16){buf.append("0");} if (i < 16){buf.append("0");}
buf.append(Integer.toHexString(i)); buf.append(Integer.toHexString(i));
} }
//32位加密 //32位加密
return buf.toString(); return buf.toString();
// 16位的加密 // 16位的加密
//return buf.toString().substring(8, 24); //return buf.toString().substring(8, 24);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
// e.printStackTrace(); // e.printStackTrace();
return null; return null;
} }
} }
public static String encryptLiberty(String str,String charSet) { public static String encryptLiberty(String str,String charSet) {
if (StringUtil.isNullOrBlank(str)){ if (StringUtil.isNullOrBlank(str)){
return null; return null;
} }
if(StringUtil.isNullOrBlank(charSet)){ if(StringUtil.isNullOrBlank(charSet)){
charSet = "utf-8"; charSet = "utf-8";
} }
try { try {
MessageDigest md = MessageDigest.getInstance("MD5"); MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(charSet)); md.update(str.getBytes(charSet));
return byteArrayToHexString(md.digest()); return byteArrayToHexString(md.digest());
} catch (Exception e) { } catch (Exception e) {
// System.out.println(e.getMessage()); // System.out.println(e.getMessage());
return null; return null;
} }
} }
public static String byteArrayToHexString(byte[] b) { public static String byteArrayToHexString(byte[] b) {
String result = ""; String result = "";
for (byte aB : b) { for (byte aB : b) {
result += Integer.toString((aB & 0xff) + 0x100, 16).substring(1); result += Integer.toString((aB & 0xff) + 0x100, 16).substring(1);
} }
return result; return result;
} }
/** /**
* SHA256WithRSA 加签 * SHA256WithRSA 加签
* *
* @param content * @param content
* @param privateKey * @param privateKey
* @param charset * @param charset
* @return * @return
*/ */
public static String rsa256Sign(String content, String privateKey,String charset){ public static String rsa256Sign(String content, String privateKey,String charset){
// org.apache.xml.security.utils.Base64 b = null; // org.apache.xml.security.utils.Base64 b = null;
try { try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.getDecoder().decode(privateKey); byte[] encodedKey = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
PrivateKey prikey = keyFactory.generatePrivate(keySpec); PrivateKey prikey = keyFactory.generatePrivate(keySpec);
java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA"); java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");
signature.initSign(prikey); signature.initSign(prikey);
if(charset != null && !"".equals(charset)){ if(charset != null && !"".equals(charset)){
signature.update(content.getBytes(charset)); signature.update(content.getBytes(charset));
}else{ }else{
signature.update(content.getBytes()); signature.update(content.getBytes());
} }
byte[] signed = signature.sign(); byte[] signed = signature.sign();
return new String(Base64.getEncoder().encode(signed)); return new String(Base64.getEncoder().encode(signed));
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
e.printStackTrace(); e.printStackTrace();
} catch (InvalidKeySpecException e){ } catch (InvalidKeySpecException e){
e.printStackTrace(); e.printStackTrace();
} catch (InvalidKeyException e){ } catch (InvalidKeyException e){
e.printStackTrace(); e.printStackTrace();
} catch (UnsupportedEncodingException e){ } catch (UnsupportedEncodingException e){
e.printStackTrace(); e.printStackTrace();
} catch (SignatureException e){ } catch (SignatureException e){
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
/** /**
* SHA256WithRSA 验签 * SHA256WithRSA 验签
* @param content * @param content
* @param sign * @param sign
* @param publicKey * @param publicKey
* @param charset * @param charset
* @return * @return
*/ */
public static boolean rsa256CheckContent(String content, String sign, String publicKey,String charset){ public static boolean rsa256CheckContent(String content, String sign, String publicKey,String charset){
try{ try{
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.getDecoder().decode(publicKey); byte[] encodedKey = Base64.getDecoder().decode(publicKey);
PublicKey pubkey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); PublicKey pubkey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA"); java.security.Signature signature = java.security.Signature.getInstance("SHA256WithRSA");
signature.initVerify(pubkey); signature.initVerify(pubkey);
if(charset != null && !"".equals(charset)){ if(charset != null && !"".equals(charset)){
signature.update(content.getBytes(charset)); signature.update(content.getBytes(charset));
}else{ }else{
signature.update(content.getBytes()); signature.update(content.getBytes());
} }
return signature.verify(Base64.getDecoder().decode(sign.getBytes())); return signature.verify(Base64.getDecoder().decode(sign.getBytes()));
} catch (NoSuchAlgorithmException e){ } catch (NoSuchAlgorithmException e){
e.printStackTrace(); e.printStackTrace();
} catch (InvalidKeySpecException e){ } catch (InvalidKeySpecException e){
e.printStackTrace(); e.printStackTrace();
} catch (InvalidKeyException e) { } catch (InvalidKeyException e) {
e.printStackTrace(); e.printStackTrace();
} catch (SignatureException e) { } catch (SignatureException e) {
e.printStackTrace(); e.printStackTrace();
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
return false; return false;
} }
/** /**
* 私钥加密方法(非对称) * 私钥加密方法(非对称)
*@param parameterStr 明文字符串 *@param parameterStr 明文字符串
*@param aliasName 证书别名 *@param aliasName 证书别名
*@param keystorePwd 证书密码 *@param keystorePwd 证书密码
*@param inputCharset 字符集 *@param inputCharset 字符集
*@param privateFilePath 私钥证书路径 *@param privateFilePath 私钥证书路径
*@return *@return
* @author ex_liukai * @author ex_liukai
* @see * @see
*/ */
public static String axaSign(String parameterStr,String aliasName, public static String axaSign(String parameterStr,String aliasName,
String keystorePwd,String inputCharset,String privateFilePath){ String keystorePwd,String inputCharset,String privateFilePath){
String base64 = ""; String base64 = "";
try{ try{
KeyStore ks = KeyStore.getInstance("PKCS12"); KeyStore ks = KeyStore.getInstance("PKCS12");
//私钥证书地址 //私钥证书地址
FileInputStream ksfis = new FileInputStream(privateFilePath); FileInputStream ksfis = new FileInputStream(privateFilePath);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis); BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
//私钥密码 //私钥密码
char[] keyPwd = keystorePwd.toCharArray(); char[] keyPwd = keystorePwd.toCharArray();
ks.load(ksbufin, keyPwd); ks.load(ksbufin, keyPwd);
PrivateKey priK = (PrivateKey)ks.getKey("test-alias", keyPwd); PrivateKey priK = (PrivateKey)ks.getKey("test-alias", keyPwd);
Signature signature = Signature.getInstance("SHA1withRSA"); Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(priK); signature.initSign(priK);
signature.update(parameterStr.getBytes(inputCharset)); signature.update(parameterStr.getBytes(inputCharset));
BASE64Encoder encoder = new BASE64Encoder(); BASE64Encoder encoder = new BASE64Encoder();
base64 = encoder.encode(signature.sign()); base64 = encoder.encode(signature.sign());
}catch (FileNotFoundException e) { }catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
logger.error(e); logger.error(e);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
logger.error(ex); logger.error(ex);
} }
return base64; return base64;
} }
/** /**
* 解密方法 * 解密方法
*@param parameterStr 明文字符串 *@param parameterStr 明文字符串
*@param sign 加密串 *@param sign 加密串
*@param publicFilePath 公钥证书路径 *@param publicFilePath 公钥证书路径
*@return *@return
* @author ex_liukai * @author ex_liukai
* @see * @see
*/ */
public static boolean axaEnCodeByCer(String parameterStr, String sign,String publicFilePath){ public static boolean axaEnCodeByCer(String parameterStr, String sign,String publicFilePath){
boolean flag = false; boolean flag = false;
try{ try{
//公钥证书文件 //公钥证书文件
InputStream inStream = new FileInputStream(publicFilePath); InputStream inStream = new FileInputStream(publicFilePath);
CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream); X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
PublicKey pk = cert.getPublicKey(); PublicKey pk = cert.getPublicKey();
Signature signature = Signature.getInstance("SHA1withRSA"); Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(pk); signature.initVerify(pk);
signature.update(parameterStr.getBytes()); signature.update(parameterStr.getBytes());
BASE64Decoder decoder = new BASE64Decoder(); BASE64Decoder decoder = new BASE64Decoder();
flag = signature.verify(decoder.decodeBuffer(sign)); flag = signature.verify(decoder.decodeBuffer(sign));
} catch (Exception e) { } catch (Exception e) {
System.out.println(e.toString()); System.out.println(e.toString());
} }
return flag; return flag;
} }
/** /**
* 返回 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 Data to digest * @param data Data to digest
* @return MD5 digest * @return MD5 digest
*/ */
public static byte[] md5(String data,String charSet) { public static byte[] md5(String data,String charSet) {
if(StringUtil.isNullOrBlank(charSet)){ if(StringUtil.isNullOrBlank(charSet)){
charSet = "UTF-8"; charSet = "UTF-8";
} }
byte[] bytes = null; byte[] bytes = null;
try { try {
bytes = md5(data.getBytes(charSet)); bytes = md5(data.getBytes(charSet));
} 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,String charSet) { public static String md5Hex(String data,String charSet) {
return toHexString(md5(data,charSet)); return toHexString(md5(data,charSet));
} }
/** /**
* SHA256加密 * SHA256加密
*/ */
public static String sha256Hex(String data,String charSet) { public static String sha256Hex(String data,String charSet) {
if(StringUtil.isNullOrBlank(charSet)){ if(StringUtil.isNullOrBlank(charSet)){
charSet = "UTF-8"; charSet = "UTF-8";
} }
try { try {
return toHexString(sha256(data.getBytes(charSet))); return toHexString(sha256(data.getBytes(charSet)));
} 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; package com.ajb.common.utils.encryption;
import java.util.Properties; import java.util.Properties;
import javax.persistence.AttributeConverter; import javax.persistence.AttributeConverter;
import javax.persistence.Converter; import javax.persistence.Converter;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@Converter @Converter
public class JPACryptoConverter implements AttributeConverter<String, String> { public class JPACryptoConverter implements AttributeConverter<String, String> {
private static final String secret_property_key = "encryption.key"; private static final String secret_property_key = "encryption.key";
private static final Properties properties = new Properties(); private static final Properties properties = new Properties();
private static String sensitivekey = null; private static String sensitivekey = null;
static { static {
try { try {
properties.load(JPACryptoConverter.class.getClassLoader() properties.load(JPACryptoConverter.class.getClassLoader()
.getResourceAsStream("persistence.properties")); .getResourceAsStream("persistence.properties"));
} catch (Exception e) { } catch (Exception e) {
properties.put(secret_property_key, "12345678"); properties.put(secret_property_key, "12345678");
} }
sensitivekey = (String)properties.get(secret_property_key); sensitivekey = (String)properties.get(secret_property_key);
} }
@Override @Override
public String convertToDatabaseColumn(String sensitive) { public String convertToDatabaseColumn(String sensitive) {
DESUtils des; DESUtils des;
String result = ""; String result = "";
try { try {
des = new DESUtils(sensitivekey, "utf-8"); des = new DESUtils(sensitivekey, "utf-8");
if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive)) if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive))
{ {
result = des.encode(sensitive); result = des.encode(sensitive);
} }
return result; return result;
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return result; return result;
} }
@Override @Override
public String convertToEntityAttribute(String sensitive) { public String convertToEntityAttribute(String sensitive) {
DESUtils des; DESUtils des;
String result = ""; String result = "";
try { try {
des = new DESUtils(sensitivekey, "utf-8"); des = new DESUtils(sensitivekey, "utf-8");
if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive)) if (StringUtils.isNotEmpty(sensitive) && StringUtils.isNoneBlank(sensitive))
{ {
result = des.decode(sensitive); result = des.decode(sensitive);
} }
return result; return result;
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
return result; return result;
} }
} }
package com.ajb.common.utils.encryption; package com.ajb.common.utils.encryption;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* jwt安全验证设置 head tag,seal封条,过期时间,发行,bypass * jwt安全验证设置 head tag,seal封条,过期时间,发行,bypass
* @author Simon Cheng * @author Simon Cheng
*/ */
@Service @Service
public class JPASensitiveSetting { public class JPASensitiveSetting {
@Value("${jpa.sensitivekey}") @Value("${jpa.sensitivekey}")
public String 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; package com.ajb.common.utils.encryption;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
/** /**
* *
*/ */
public class MaskUtils { public class MaskUtils {
public static String maskCellphone(String cellphoneNo) { public static String maskCellphone(String cellphoneNo) {
if ((cellphoneNo == null) || (cellphoneNo.trim().length() != 11)) { if ((cellphoneNo == null) || (cellphoneNo.trim().length() != 11)) {
return cellphoneNo; return cellphoneNo;
} }
return cellphoneNo.substring(0, 3) + "****" + cellphoneNo.substring(cellphoneNo.length() - 4); return cellphoneNo.substring(0, 3) + "****" + cellphoneNo.substring(cellphoneNo.length() - 4);
} }
public static String maskEmail(String email) { public static String maskEmail(String email) {
if (StringUtils.isBlank(email)) { if (StringUtils.isBlank(email)) {
return ""; return "";
} }
int index = StringUtils.indexOf(email, "@"); int index = StringUtils.indexOf(email, "@");
if (index <= 1) if (index <= 1)
return email; return email;
else else
return StringUtils.rightPad(StringUtils.left(email, 1), index, "*") return StringUtils.rightPad(StringUtils.left(email, 1), index, "*")
.concat(StringUtils.mid(email, index, StringUtils.length(email))); .concat(StringUtils.mid(email, index, StringUtils.length(email)));
} }
private static String maskCardNo(String cardNo) { private static String maskCardNo(String cardNo) {
if ((cardNo == null) || (cardNo.trim().length() <= 8)) { if ((cardNo == null) || (cardNo.trim().length() <= 8)) {
return cardNo; return cardNo;
} }
cardNo = cardNo.trim(); cardNo = cardNo.trim();
int length = cardNo.length(); int length = cardNo.length();
String firstFourNo = cardNo.substring(0, 4); String firstFourNo = cardNo.substring(0, 4);
String lastFourNo = cardNo.substring(length - 4); String lastFourNo = cardNo.substring(length - 4);
String mask = ""; String mask = "";
for (int i = 0; i < length - 8; i++) { for (int i = 0; i < length - 8; i++) {
mask = mask + "*"; mask = mask + "*";
} }
return firstFourNo + mask + lastFourNo; return firstFourNo + mask + lastFourNo;
} }
public static String maskIDCardNo(String idCardNo) { public static String maskIDCardNo(String idCardNo) {
return maskCardNo(idCardNo); return maskCardNo(idCardNo);
} }
public static String maskBankCardNo(String bankCardNo) { public static String maskBankCardNo(String bankCardNo) {
return maskCardNo(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.http; package com.ajb.common.utils.http;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.KeyManagementException; import java.security.KeyManagementException;
//import java.security.KeyStore; //import java.security.KeyStore;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletInputStream; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
//import org.apache.http.HttpException; //import org.apache.http.HttpException;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.ConnectionConfig; import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry; import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder; import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig; import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.cookie.Cookie; import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin; import org.apache.http.cookie.CookieOrigin;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
//import org.apache.http.entity.mime.FormBodyPart; //import org.apache.http.entity.mime.FormBodyPart;
//import org.apache.http.entity.mime.HttpMultipartMode; //import org.apache.http.entity.mime.HttpMultipartMode;
//import org.apache.http.entity.mime.MultipartEntityBuilder; //import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BestMatchSpec; import org.apache.http.impl.cookie.BestMatchSpec;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
class AnyTrustStrategy implements TrustStrategy{ class AnyTrustStrategy implements TrustStrategy{
@Override @Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true; return true;
} }
} }
public class HttpUtil { public class HttpUtil {
private static final Log log= LogFactory.getLog(HttpUtil.class); private static final Log log= LogFactory.getLog(HttpUtil.class);
private static int bufferSize= 1024; private static int bufferSize= 1024;
private static volatile HttpUtil instance; private static volatile HttpUtil instance;
private ConnectionConfig connConfig; private ConnectionConfig connConfig;
private SocketConfig socketConfig; private SocketConfig socketConfig;
private ConnectionSocketFactory plainSF; private ConnectionSocketFactory plainSF;
// private KeyStore trustStore; // private KeyStore trustStore;
private SSLContext sslContext; private SSLContext sslContext;
private LayeredConnectionSocketFactory sslSF; private LayeredConnectionSocketFactory sslSF;
private Registry<ConnectionSocketFactory> registry; private Registry<ConnectionSocketFactory> registry;
private PoolingHttpClientConnectionManager connManager; private PoolingHttpClientConnectionManager connManager;
private volatile HttpClient client; private volatile HttpClient client;
private volatile BasicCookieStore cookieStore; private volatile BasicCookieStore cookieStore;
public static String defaultEncoding= "utf-8"; public static String defaultEncoding= "utf-8";
private static List<NameValuePair> paramsConverter(Map<String, String> params){ private static List<NameValuePair> paramsConverter(Map<String, String> params){
List<NameValuePair> nvps = new LinkedList<NameValuePair>(); List<NameValuePair> nvps = new LinkedList<NameValuePair>();
Set<Entry<String, String>> paramsSet= params.entrySet(); Set<Entry<String, String>> paramsSet= params.entrySet();
for (Entry<String, String> paramEntry : paramsSet) { for (Entry<String, String> paramEntry : paramsSet) {
nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue())); nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
} }
return nvps; return nvps;
} }
public static String readStream(InputStream in, String encoding){ public static String readStream(InputStream in, String encoding){
if (in == null){ if (in == null){
return null; return null;
} }
try { try {
InputStreamReader inReader= null; InputStreamReader inReader= null;
if (encoding == null){ if (encoding == null){
inReader= new InputStreamReader(in, defaultEncoding); inReader= new InputStreamReader(in, defaultEncoding);
}else{ }else{
inReader= new InputStreamReader(in, encoding); inReader= new InputStreamReader(in, encoding);
} }
char[] buffer= new char[bufferSize]; char[] buffer= new char[bufferSize];
int readLen= 0; int readLen= 0;
StringBuffer sb= new StringBuffer(); StringBuffer sb= new StringBuffer();
while((readLen= inReader.read(buffer))!=-1){ while((readLen= inReader.read(buffer))!=-1){
sb.append(buffer, 0, readLen); sb.append(buffer, 0, readLen);
} }
inReader.close(); inReader.close();
return sb.toString(); return sb.toString();
} catch (IOException e) { } catch (IOException e) {
log.error("读取返回内容出错", e); log.error("读取返回内容出错", e);
} }
return null; return null;
} }
private static class TrustAnyTrustManager implements X509TrustManager{ private static class TrustAnyTrustManager implements X509TrustManager{
@Override @Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override @Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
@Override @Override
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {}; return new X509Certificate[] {};
} }
} }
private static class TrustAnyHostnameVerifier implements HostnameVerifier{ private static class TrustAnyHostnameVerifier implements HostnameVerifier{
@Override @Override
public boolean verify(String arg0, SSLSession arg1) { public boolean verify(String arg0, SSLSession arg1) {
return true; return true;
} }
} }
// @SuppressWarnings("deprecation") // @SuppressWarnings("deprecation")
private HttpUtil(){ private HttpUtil(){
//设置连接参数 //设置连接参数
connConfig = ConnectionConfig.custom().setCharset(Charset.forName(defaultEncoding)).build(); connConfig = ConnectionConfig.custom().setCharset(Charset.forName(defaultEncoding)).build();
socketConfig = SocketConfig.custom().setSoTimeout(100000).build(); socketConfig = SocketConfig.custom().setSoTimeout(100000).build();
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create(); RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
plainSF = new PlainConnectionSocketFactory(); plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF); registryBuilder.register("http", plainSF);
//指定信任密钥存储对象和连接套接字工厂 //指定信任密钥存储对象和连接套接字工厂
try { try {
// trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, new AnyTrustStrategy()).build(); // sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
sslContext = SSLContext.getInstance("SSL"); sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); sslContext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
// sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
sslSF = new SSLConnectionSocketFactory(sslContext, new TrustAnyHostnameVerifier() ); sslSF = new SSLConnectionSocketFactory(sslContext, new TrustAnyHostnameVerifier() );
registryBuilder.register("https", sslSF); registryBuilder.register("https", sslSF);
// } catch (KeyStoreException e) { // } catch (KeyStoreException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
} catch (KeyManagementException e) { } catch (KeyManagementException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
registry = registryBuilder.build(); registry = registryBuilder.build();
//设置连接管理器 //设置连接管理器
connManager = new PoolingHttpClientConnectionManager(registry); connManager = new PoolingHttpClientConnectionManager(registry);
connManager.setDefaultConnectionConfig(connConfig); connManager.setDefaultConnectionConfig(connConfig);
connManager.setDefaultSocketConfig(socketConfig); connManager.setDefaultSocketConfig(socketConfig);
//指定cookie存储对象 //指定cookie存储对象
cookieStore = new BasicCookieStore(); cookieStore = new BasicCookieStore();
//构建客户端 //构建客户端
client= HttpClientBuilder.create().setDefaultCookieStore(cookieStore).setConnectionManager(connManager).build(); client= HttpClientBuilder.create().setDefaultCookieStore(cookieStore).setConnectionManager(connManager).build();
} }
public static HttpUtil getInstance(){ public static HttpUtil getInstance(){
synchronized (HttpUtil.class) { synchronized (HttpUtil.class) {
if (HttpUtil.instance == null){ if (HttpUtil.instance == null){
instance = new HttpUtil(); instance = new HttpUtil();
} }
return instance; return instance;
} }
} }
public InputStream doGet(String url) throws URISyntaxException, ClientProtocolException, IOException{ public InputStream doGet(String url) throws URISyntaxException, ClientProtocolException, IOException{
HttpResponse response= this.doGet(url, null); HttpResponse response= this.doGet(url, null);
return response!=null ? response.getEntity().getContent() : null; return response!=null ? response.getEntity().getContent() : null;
} }
public String doGetForString(String url) throws URISyntaxException, ClientProtocolException, IOException{ public String doGetForString(String url) throws URISyntaxException, ClientProtocolException, IOException{
return HttpUtil.readStream(this.doGet(url), null); return HttpUtil.readStream(this.doGet(url), null);
} }
public InputStream doGetForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{ public InputStream doGetForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpResponse response= this.doGet(url, queryParams); HttpResponse response= this.doGet(url, queryParams);
return response!=null ? response.getEntity().getContent() : null; return response!=null ? response.getEntity().getContent() : null;
} }
public String doGetForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{ public String doGetForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
return HttpUtil.readStream(this.doGetForStream(url, queryParams), null); return HttpUtil.readStream(this.doGetForStream(url, queryParams), null);
} }
/** /**
* 基本的Get请求 * 基本的Get请求
* @param url 请求url * @param url 请求url
* @param queryParams 请求头的查询参数 * @param queryParams 请求头的查询参数
* @return * @return
* @throws URISyntaxException * @throws URISyntaxException
* @throws IOException * @throws IOException
* @throws ClientProtocolException * @throws ClientProtocolException
*/ */
public HttpResponse doGet(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{ public HttpResponse doGet(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpGet gm = new HttpGet(); HttpGet gm = new HttpGet();
URIBuilder builder = new URIBuilder(url); URIBuilder builder = new URIBuilder(url);
//填入查询参数 //填入查询参数
if (queryParams!=null && !queryParams.isEmpty()){ if (queryParams!=null && !queryParams.isEmpty()){
builder.setParameters(HttpUtil.paramsConverter(queryParams)); builder.setParameters(HttpUtil.paramsConverter(queryParams));
} }
gm.setURI(builder.build()); gm.setURI(builder.build());
return client.execute(gm); return client.execute(gm);
} }
public InputStream doPostForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException { public InputStream doPostForStream(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException {
HttpResponse response = this.doPost(url, queryParams, null); HttpResponse response = this.doPost(url, queryParams, null);
return response!=null ? response.getEntity().getContent() : null; return response!=null ? response.getEntity().getContent() : null;
} }
public String doPostForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException { public String doPostForString(String url, Map<String, String> queryParams) throws URISyntaxException, ClientProtocolException, IOException {
return HttpUtil.readStream(this.doPostForStream(url, queryParams), null); return HttpUtil.readStream(this.doPostForStream(url, queryParams), null);
} }
public InputStream doPostForStream(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{ public InputStream doPostForStream(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpResponse response = this.doPost(url, queryParams, formParams); HttpResponse response = this.doPost(url, queryParams, formParams);
return response!=null ? response.getEntity().getContent() : null; return response!=null ? response.getEntity().getContent() : null;
} }
public String doPostRetString(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{ public String doPostRetString(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
return HttpUtil.readStream(this.doPostForStream(url, queryParams, formParams), null); return HttpUtil.readStream(this.doPostForStream(url, queryParams, formParams), null);
} }
/** /**
* 基本的Post请求 * 基本的Post请求
* @param url 请求url * @param url 请求url
* @param queryParams 请求头的查询参数 * @param queryParams 请求头的查询参数
* @param formParams post表单的参数 * @param formParams post表单的参数
* @return * @return
* @throws URISyntaxException * @throws URISyntaxException
* @throws IOException * @throws IOException
* @throws ClientProtocolException * @throws ClientProtocolException
*/ */
public HttpResponse doPost(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{ public HttpResponse doPost(String url, Map<String, String> queryParams, Map<String, String> formParams) throws URISyntaxException, ClientProtocolException, IOException{
HttpPost pm = new HttpPost(); HttpPost pm = new HttpPost();
URIBuilder builder = new URIBuilder(url); URIBuilder builder = new URIBuilder(url);
//填入查询参数 //填入查询参数
if (queryParams!=null && !queryParams.isEmpty()){ if (queryParams!=null && !queryParams.isEmpty()){
builder.setParameters(HttpUtil.paramsConverter(queryParams)); builder.setParameters(HttpUtil.paramsConverter(queryParams));
} }
pm.setURI(builder.build()); pm.setURI(builder.build());
//填入表单参数 //填入表单参数
if (formParams!=null && !formParams.isEmpty()){ if (formParams!=null && !formParams.isEmpty()){
pm.setEntity(new UrlEncodedFormEntity(HttpUtil.paramsConverter(formParams))); pm.setEntity(new UrlEncodedFormEntity(HttpUtil.paramsConverter(formParams)));
} }
return client.execute(pm); return client.execute(pm);
} }
public String post(String url,String xml){ public String post(String url,String xml){
HttpPost httpost = new HttpPost(url); HttpPost httpost = new HttpPost(url);
StringEntity urlEntity = new StringEntity(xml, "UTF-8"); StringEntity urlEntity = new StringEntity(xml, "UTF-8");
httpost.setEntity(urlEntity); httpost.setEntity(urlEntity);
String responseXML = null; String responseXML = null;
HttpResponse response; HttpResponse response;
try { try {
response = client.execute(httpost); response = client.execute(httpost);
HttpEntity entity = response.getEntity(); HttpEntity entity = response.getEntity();
responseXML = EntityUtils.toString(entity); responseXML = EntityUtils.toString(entity);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
return responseXML; return responseXML;
} }
/** /**
* 多块Post请求 * 多块Post请求
* @param url 请求url * @param url 请求url
* @param queryParams 请求头的查询参数 * @param queryParams 请求头的查询参数
* @param formParts post表单的参数,支持字符串-文件(FilePart)和字符串-字符串(StringPart)形式的参数 * @param formParts post表单的参数,支持字符串-文件(FilePart)和字符串-字符串(StringPart)形式的参数
* @param maxCount 最多尝试请求的次数 * @param maxCount 最多尝试请求的次数
* @return * @return
* @throws URISyntaxException * @throws URISyntaxException
* @throws ClientProtocolException * @throws ClientProtocolException
* @throws HttpException * @throws HttpException
* @throws IOException * @throws IOException
*/ */
// public HttpResponse multipartPost(String url, Map<String, String> queryParams, List<FormBodyPart> formParts) throws URISyntaxException, ClientProtocolException, IOException{ // public HttpResponse multipartPost(String url, Map<String, String> queryParams, List<FormBodyPart> formParts) throws URISyntaxException, ClientProtocolException, IOException{
// HttpPost pm= new HttpPost(); // HttpPost pm= new HttpPost();
// URIBuilder builder = new URIBuilder(url); // URIBuilder builder = new URIBuilder(url);
// //填入查询参数 // //填入查询参数
// if (queryParams!=null && !queryParams.isEmpty()){ // if (queryParams!=null && !queryParams.isEmpty()){
// builder.setParameters(HttpUtil.paramsConverter(queryParams)); // builder.setParameters(HttpUtil.paramsConverter(queryParams));
// } // }
// pm.setURI(builder.build()); // pm.setURI(builder.build());
// //填入表单参数 // //填入表单参数
// if (formParts!=null && !formParts.isEmpty()){ // if (formParts!=null && !formParts.isEmpty()){
// MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); // MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// entityBuilder = entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // entityBuilder = entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// for (FormBodyPart formPart : formParts) { // for (FormBodyPart formPart : formParts) {
// entityBuilder = entityBuilder.addPart(formPart.getName(), formPart.getBody()); // entityBuilder = entityBuilder.addPart(formPart.getName(), formPart.getBody());
// } // }
// pm.setEntity(entityBuilder.build()); // pm.setEntity(entityBuilder.build());
// } // }
// return client.execute(pm); // return client.execute(pm);
// } // }
/** /**
* 获取当前Http客户端状态中的Cookie * 获取当前Http客户端状态中的Cookie
* @param domain 作用域 * @param domain 作用域
* @param port 端口 传null 默认80 * @param port 端口 传null 默认80
* @param path Cookie路径 传null 默认"/" * @param path Cookie路径 传null 默认"/"
* @param useSecure Cookie是否采用安全机制 传null 默认false * @param useSecure Cookie是否采用安全机制 传null 默认false
* @return * @return
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Map<String, Cookie> getCookie(String domain, Integer port, String path, Boolean useSecure){ public Map<String, Cookie> getCookie(String domain, Integer port, String path, Boolean useSecure){
if (domain == null){ if (domain == null){
return null; return null;
} }
if (port==null){ if (port==null){
port= 80; port= 80;
} }
if (path==null){ if (path==null){
path="/"; path="/";
} }
if (useSecure==null){ if (useSecure==null){
useSecure= false; useSecure= false;
} }
List<Cookie> cookies = cookieStore.getCookies(); List<Cookie> cookies = cookieStore.getCookies();
if (cookies==null || cookies.isEmpty()){ if (cookies==null || cookies.isEmpty()){
return null; return null;
} }
CookieOrigin origin= new CookieOrigin(domain, port, path, useSecure); CookieOrigin origin= new CookieOrigin(domain, port, path, useSecure);
BestMatchSpec cookieSpec = new BestMatchSpec(); BestMatchSpec cookieSpec = new BestMatchSpec();
Map<String, Cookie> retVal= new HashMap<String, Cookie>(); Map<String, Cookie> retVal= new HashMap<String, Cookie>();
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
if(cookieSpec.match(cookie, origin)){ if(cookieSpec.match(cookie, origin)){
retVal.put(cookie.getName(), cookie); retVal.put(cookie.getName(), cookie);
} }
} }
return retVal; return retVal;
} }
/** /**
* 批量设置Cookie * 批量设置Cookie
* @param cookies cookie键值对图 * @param cookies cookie键值对图
* @param domain 作用域 不可为空 * @param domain 作用域 不可为空
* @param path 路径 传null默认为"/" * @param path 路径 传null默认为"/"
* @param useSecure 是否使用安全机制 传null 默认为false * @param useSecure 是否使用安全机制 传null 默认为false
* @return 是否成功设置cookie * @return 是否成功设置cookie
*/ */
public boolean setCookie(Map<String, String> cookies, String domain, String path, Boolean useSecure){ public boolean setCookie(Map<String, String> cookies, String domain, String path, Boolean useSecure){
synchronized (cookieStore) { synchronized (cookieStore) {
if (domain==null){ if (domain==null){
return false; return false;
} }
if (path==null){ if (path==null){
path= "/"; path= "/";
} }
if (useSecure==null){ if (useSecure==null){
useSecure= false; useSecure= false;
} }
if (cookies==null || cookies.isEmpty()){ if (cookies==null || cookies.isEmpty()){
return true; return true;
} }
Set<Entry<String, String>> set= cookies.entrySet(); Set<Entry<String, String>> set= cookies.entrySet();
String key= null; String key= null;
String value= null; String value= null;
for (Entry<String, String> entry : set) { for (Entry<String, String> entry : set) {
key= entry.getKey(); key= entry.getKey();
if (key==null || key.isEmpty() || value==null || value.isEmpty()){ if (key==null || key.isEmpty() || value==null || value.isEmpty()){
throw new IllegalArgumentException("cookies key and value both can not be empty"); throw new IllegalArgumentException("cookies key and value both can not be empty");
} }
BasicClientCookie cookie= new BasicClientCookie(key, value); BasicClientCookie cookie= new BasicClientCookie(key, value);
cookie.setDomain(domain); cookie.setDomain(domain);
cookie.setPath(path); cookie.setPath(path);
cookie.setSecure(useSecure); cookie.setSecure(useSecure);
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
} }
return true; return true;
} }
} }
/** /**
* 设置单个Cookie * 设置单个Cookie
* @param key Cookie键 * @param key Cookie键
* @param value Cookie值 * @param value Cookie值
* @param domain 作用域 不可为空 * @param domain 作用域 不可为空
* @param path 路径 传null默认为"/" * @param path 路径 传null默认为"/"
* @param useSecure 是否使用安全机制 传null 默认为false * @param useSecure 是否使用安全机制 传null 默认为false
* @return 是否成功设置cookie * @return 是否成功设置cookie
*/ */
public boolean setCookie(String key, String value, String domain, String path, Boolean useSecure){ public boolean setCookie(String key, String value, String domain, String path, Boolean useSecure){
Map<String, String> cookies= new HashMap<String, String>(); Map<String, String> cookies= new HashMap<String, String>();
cookies.put(key, value); cookies.put(key, value);
return setCookie(cookies, domain, path, useSecure); return setCookie(cookies, domain, path, useSecure);
} }
// @Test // @Test
public void doTest() throws ClientProtocolException, URISyntaxException, IOException{ public void doTest() throws ClientProtocolException, URISyntaxException, IOException{
HttpUtil util = HttpUtil.getInstance(); HttpUtil util = HttpUtil.getInstance();
InputStream in = util.doGet("https://kyfw.12306.cn/otn/leftTicket/init"); InputStream in = util.doGet("https://kyfw.12306.cn/otn/leftTicket/init");
String retVal = HttpUtil.readStream(in, HttpUtil.defaultEncoding); String retVal = HttpUtil.readStream(in, HttpUtil.defaultEncoding);
System.out.println(retVal); System.out.println(retVal);
} }
public static String binaryReader(HttpServletRequest request){ public static String binaryReader(HttpServletRequest request){
ServletInputStream sis = null; ServletInputStream sis = null;
String requestData = null; String requestData = null;
try{ try{
sis = request.getInputStream(); sis = request.getInputStream();
int size = request.getContentLength();// 取HTTP请求流长度 int size = request.getContentLength();// 取HTTP请求流长度
if(size > 0){ if(size > 0){
byte[] buffer = new byte[size];// 用于缓存每次读取的数据 byte[] buffer = new byte[size];// 用于缓存每次读取的数据
byte[] dataByte = new byte[size];// 用于存放结果的数组 byte[] dataByte = new byte[size];// 用于存放结果的数组
int count = 0; int count = 0;
int rbyte = 0; int rbyte = 0;
// System.out.println("读取到的内容长度:"+size); // System.out.println("读取到的内容长度:"+size);
while (count < size) {// 循环读取 while (count < size) {// 循环读取
rbyte = sis.read(buffer);// 每次实际读取长度存于rbyte中 rbyte = sis.read(buffer);// 每次实际读取长度存于rbyte中
for(int i=0;i<rbyte;i++) { for(int i=0;i<rbyte;i++) {
dataByte[count + i] = buffer[i]; dataByte[count + i] = buffer[i];
} }
count += rbyte; count += rbyte;
} }
requestData = new String(dataByte, "UTF-8"); requestData = new String(dataByte, "UTF-8");
} }
}catch(IOException e){ }catch(IOException e){
e.printStackTrace(); e.printStackTrace();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
}finally{ }finally{
if(sis!=null){try{sis.close();}catch(Exception e){e.printStackTrace();}} if(sis!=null){try{sis.close();}catch(Exception e){e.printStackTrace();}}
} }
return requestData; return requestData;
} }
public static String binaryReader(HttpServletRequest request,String encode){ public static String binaryReader(HttpServletRequest request,String encode){
if(encode == null || "".equals(encode)){ if(encode == null || "".equals(encode)){
encode = "UTF-8"; encode = "UTF-8";
} }
String requestData=""; String requestData="";
ServletInputStream sis = null; ServletInputStream sis = null;
try{ try{
int len = request.getContentLength(); int len = request.getContentLength();
if(len > 0){ if(len > 0){
sis = request.getInputStream(); sis = request.getInputStream();
byte[] buffer = new byte[len]; byte[] buffer = new byte[len];
sis.read(buffer, 0, len); sis.read(buffer, 0, len);
requestData = new String(buffer, encode); requestData = new String(buffer, encode);
} }
}catch(IOException e){ }catch(IOException e){
e.printStackTrace(); e.printStackTrace();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
}finally{ }finally{
if(sis!=null){try{sis.close();}catch(Exception e){e.printStackTrace();}} if(sis!=null){try{sis.close();}catch(Exception e){e.printStackTrace();}}
} }
return requestData; return requestData;
} }
public static String charReader(HttpServletRequest request) { public static String charReader(HttpServletRequest request) {
String requestData = null; String requestData = null;
BufferedReader br = null; BufferedReader br = null;
try{ try{
br = request.getReader(); br = request.getReader();
String line = null; String line = null;
while((line = br.readLine()) != null){ while((line = br.readLine()) != null){
requestData += line; requestData += line;
} }
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
}finally{ }finally{
if(br!=null){try{br.close();}catch(Exception e){e.printStackTrace();};} if(br!=null){try{br.close();}catch(Exception e){e.printStackTrace();};}
} }
return requestData; return requestData;
} }
} }
package com.ajb.common.utils.office; package com.ajb.common.utils.office;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ajb.common.utils.string.StringUtil; import com.ajb.common.utils.string.StringUtil;
public class ExcelUtils { public class ExcelUtils {
/** /**
* 是否是2003的excel,返回true是2003 * 是否是2003的excel,返回true是2003
* @param fileName * @param fileName
* @return * @return
*/ */
public static boolean isExcel2003(String fileName) { public static boolean isExcel2003(String fileName) {
return fileName.matches("^.+\\.(?i)(xls)$"); return fileName.matches("^.+\\.(?i)(xls)$");
} }
/** /**
* 是否是2007的excel,返回true是2007 * 是否是2007的excel,返回true是2007
* @param fileName * @param fileName
* @return * @return
*/ */
public static boolean isExcel2007(String fileName) { public static boolean isExcel2007(String fileName) {
return fileName.matches("^.+\\.(?i)(xlsx)$"); return fileName.matches("^.+\\.(?i)(xlsx)$");
} }
/** /**
* 验证EXCEL文件 * 验证EXCEL文件
* @param filePath * @param filePath
* @return * @return
*/ */
public static boolean validateExcel(String fileName){ public static boolean validateExcel(String fileName){
if(fileName == null || !(isExcel2003(fileName) || isExcel2007(fileName))){ if(fileName == null || !(isExcel2003(fileName) || isExcel2007(fileName))){
return false; return false;
} }
return true; return true;
} }
/** /**
* 通用性检查:1、文件是否为空 * 通用性检查:1、文件是否为空
* 2、格式是否为excel * 2、格式是否为excel
* 3、长度是否为空 * 3、长度是否为空
* @param file * @param file
* @return * @return
*/ */
public static String commonUploadCheck(MultipartFile file){ public static String commonUploadCheck(MultipartFile file){
String checkResult = ""; String checkResult = "";
if(file == null){ if(file == null){
checkResult = "文件不能为空"; checkResult = "文件不能为空";
}else{ }else{
String fileName = file.getOriginalFilename(); String fileName = file.getOriginalFilename();
if(!ExcelUtils.validateExcel(fileName)){ if(!ExcelUtils.validateExcel(fileName)){
checkResult = "文件必须为excel格式!请检查文件后缀名是否为.xls或.xlsx"; checkResult = "文件必须为excel格式!请检查文件后缀名是否为.xls或.xlsx";
}else{ }else{
long size = file.getSize(); long size = file.getSize();
if(StringUtils.isEmpty(fileName) || size == 0){ if(StringUtils.isEmpty(fileName) || size == 0){
checkResult = "文件不能为空"; checkResult = "文件不能为空";
} }
} }
} }
return checkResult; return checkResult;
} }
/** /**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象 * 描述:获取IO流中的数据,组装成List<List<Object>>对象
* @param in,fileName * @param in,fileName
* @return * @return
* @throws IOException * @throws IOException
*/ */
public static List<List<Object>> getBankListByExcel(InputStream is,String fileName) throws Exception{ public static List<List<Object>> getBankListByExcel(InputStream is,String fileName) throws Exception{
List<List<Object>> list = null; List<List<Object>> list = null;
Workbook work = getWorkbook(is,fileName);//创建Excel工作薄 Workbook work = getWorkbook(is,fileName);//创建Excel工作薄
if(null == work){ if(null == work){
throw new Exception("创建Excel工作薄为空!"); throw new Exception("创建Excel工作薄为空!");
} }
Sheet sheet = null; Sheet sheet = null;
Row row = null; Row row = null;
Cell cell = null; Cell cell = null;
list = new ArrayList<List<Object>>(); list = new ArrayList<List<Object>>();
for (int i = 0; i < work.getNumberOfSheets(); i++) {//遍历Excel中所有的sheet for (int i = 0; i < work.getNumberOfSheets(); i++) {//遍历Excel中所有的sheet
sheet = work.getSheetAt(i); sheet = work.getSheetAt(i);
if(sheet==null){continue;} if(sheet==null){continue;}
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {//遍历当前sheet中的所有行 for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {//遍历当前sheet中的所有行
row = sheet.getRow(j); row = sheet.getRow(j);
if(row == null){continue;}//||row.getFirstCellNum() == j if(row == null){continue;}//||row.getFirstCellNum() == j
List<Object> li = new ArrayList<Object>();//遍历所有的列 List<Object> li = new ArrayList<Object>();//遍历所有的列
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++){ for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++){
cell = row.getCell(y); cell = row.getCell(y);
li.add(getCellValue(cell)); li.add(getCellValue(cell));
} }
list.add(li); list.add(li);
} }
} }
// work.close(); // work.close();
return list; return list;
} }
/** /**
* 描述:根据文件后缀,自适应上传文件的版本 * 描述:根据文件后缀,自适应上传文件的版本
* @param inStr,fileName * @param inStr,fileName
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static Workbook getWorkbook(InputStream is,String fileName) throws Exception{ public static Workbook getWorkbook(InputStream is,String fileName) throws Exception{
Workbook wb = null; Workbook wb = null;
if(ExcelUtils.isExcel2003(fileName)){ if(ExcelUtils.isExcel2003(fileName)){
wb = new HSSFWorkbook(is); wb = new HSSFWorkbook(is);
}else{ }else{
wb = new XSSFWorkbook(is); wb = new XSSFWorkbook(is);
} }
return wb; return wb;
} }
private static boolean isDateCell(String dataFormatString){ private static boolean isDateCell(String dataFormatString){
boolean isDateCell = false; boolean isDateCell = false;
if(StringUtil.isNullOrBlank(dataFormatString)){ if(StringUtil.isNullOrBlank(dataFormatString)){
return false; return false;
} }
if(dataFormatString.contains("y") && dataFormatString.contains("m") && dataFormatString.contains("d")){ if(dataFormatString.contains("y") && dataFormatString.contains("m") && dataFormatString.contains("d")){
isDateCell = true; isDateCell = true;
} }
return isDateCell; return isDateCell;
} }
/** /**
* 描述:对表格中数值进行格式化 * 描述:对表格中数值进行格式化
* @param cell * @param cell
* @return * @return
*/ */
public static String getCellValue(Cell cell){ public static String getCellValue(Cell cell){
String value = null; String value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符 DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //日期格式化 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //日期格式化
// DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字 // DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
/*String message = "单元格类型:"; /*String message = "单元格类型:";
if(cell.getCellType() == 0){ if(cell.getCellType() == 0){
message += "NUMBERIC"; message += "NUMBERIC";
}else if(cell.getCellType() == 1){ }else if(cell.getCellType() == 1){
message += "STRING"; message += "STRING";
}else if(cell.getCellType() == 4){ }else if(cell.getCellType() == 4){
message += "BOOLEAN"; message += "BOOLEAN";
}else if(cell.getCellType() == 2){ }else if(cell.getCellType() == 2){
message += "FORMULA"; message += "FORMULA";
}else{ }else{
message += "其他类型"; message += "其他类型";
}*/ }*/
String dataFormStr = cell.getCellStyle().getDataFormatString(); String dataFormStr = cell.getCellStyle().getDataFormatString();
switch (cell.getCellType()) { switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: case Cell.CELL_TYPE_NUMERIC:
// message += " DataFormatString:"+cell.getCellStyle().getDataFormatString()+" NumericCellValue:"+cell.getNumericCellValue()+" DateCellValue:"+cell.getDateCellValue(); // message += " DataFormatString:"+cell.getCellStyle().getDataFormatString()+" NumericCellValue:"+cell.getNumericCellValue()+" DateCellValue:"+cell.getDateCellValue();
if("General".equals(dataFormStr)){ if("General".equals(dataFormStr)){
value = df.format(cell.getNumericCellValue()); value = df.format(cell.getNumericCellValue());
}else if(isDateCell(dataFormStr)){ }else if(isDateCell(dataFormStr)){
value = sdf.format(cell.getDateCellValue()); value = sdf.format(cell.getDateCellValue());
}else{ }else{
value = df.format(cell.getNumericCellValue()); value = df.format(cell.getNumericCellValue());
} }
break; break;
case Cell.CELL_TYPE_STRING: case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString(); value = cell.getRichStringCellValue().getString();
break; break;
case Cell.CELL_TYPE_BOOLEAN: case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue()+""; value = cell.getBooleanCellValue()+"";
break; break;
case Cell.CELL_TYPE_FORMULA: // 公式 case Cell.CELL_TYPE_FORMULA: // 公式
value = cell.getStringCellValue()+ ""; value = cell.getStringCellValue()+ "";
break; break;
case Cell.CELL_TYPE_BLANK: case Cell.CELL_TYPE_BLANK:
value = ""; value = "";
break; break;
case Cell.CELL_TYPE_ERROR: // 故障 case Cell.CELL_TYPE_ERROR: // 故障
value = "非法字符"; value = "非法字符";
break; break;
default: default:
value = "未知类型"; value = "未知类型";
break; break;
} }
// message += " value:"+value; // message += " value:"+value;
// System.out.println(message); // System.out.println(message);
if(value != null){ if(value != null){
value = value.trim(); value = value.trim();
} }
return value; return value;
} }
/*int totalRows = sheet.getPhysicalNumberOfRows();//得到Excel的行数 /*int totalRows = sheet.getPhysicalNumberOfRows();//得到Excel的行数
int totalCells = 0;//总列数 int totalCells = 0;//总列数
if(totalRows>=2 && sheet.getRow(1) != null){//得到Excel的列数(前提是有行数),从第二行算起 if(totalRows>=2 && sheet.getRow(1) != null){//得到Excel的列数(前提是有行数),从第二行算起
totalCells=sheet.getRow(1).getPhysicalNumberOfCells(); totalCells=sheet.getRow(1).getPhysicalNumberOfCells();
} }
StringBuffer sbf = new StringBuffer(); StringBuffer sbf = new StringBuffer();
for(int r=0;r<totalRows;r++){//循环Excel行数,从第二行开始。标题不入库 for(int r=0;r<totalRows;r++){//循环Excel行数,从第二行开始。标题不入库
Row row = sheet.getRow(r); Row row = sheet.getRow(r);
if (row == null){ if (row == null){
System.out.println("第"+(r+1)+"行数据有问题,请仔细检查!"); System.out.println("第"+(r+1)+"行数据有问题,请仔细检查!");
continue; continue;
} }
for(int c = 0; c <totalCells; c++){ for(int c = 0; c <totalCells; c++){
Cell cell = row.getCell(c); Cell cell = row.getCell(c);
if (null != cell){ if (null != cell){
System.out.print(cell.getStringCellValue()+" "); System.out.print(cell.getStringCellValue()+" ");
sbf.append(cell.getStringCellValue()+" "); sbf.append(cell.getStringCellValue()+" ");
} }
} }
System.out.println(); System.out.println();
sbf.append("\n"); sbf.append("\n");
}*/ }*/
public static boolean checkEnd(List<Object> rowData){ public static boolean checkEnd(List<Object> rowData){
boolean endFlag = false; boolean endFlag = false;
if(rowData == null || rowData.size() == 0){ if(rowData == null || rowData.size() == 0){
endFlag = true; endFlag = true;
}else{ }else{
endFlag = true; endFlag = true;
for(Object item : rowData){ for(Object item : rowData){
String value = (String)item; String value = (String)item;
if(value != null && !"".equals(value.trim())){ if(value != null && !"".equals(value.trim())){
endFlag = false; endFlag = false;
break; break;
} }
} }
} }
return endFlag; return endFlag;
} }
public static void main(String[] args){ public static void main(String[] args){
File file = new File("C:\\Users\\zxh\\Desktop\\test.xlsx"); File file = new File("C:\\Users\\zxh\\Desktop\\test.xlsx");
List<List<Object>> dataList = null; List<List<Object>> dataList = null;
try { try {
dataList = getBankListByExcel(new FileInputStream(file),file.getName()); dataList = getBankListByExcel(new FileInputStream(file),file.getName());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
for(List<Object> row : dataList){ for(List<Object> row : dataList){
for(Object data : row){ for(Object data : row){
System.out.print(data.toString()+" "); System.out.print(data.toString()+" ");
} }
System.out.println(); System.out.println();
} }
} }
} }
package com.ajb.common.utils.string;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
public class CommonUtil {
private static final String EMAIL_REGEX="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";//邮箱正则表达式
/*
* 日期格式:http://blog.csdn.net/linghu_java/article/details/38379603
* yyyy-MM-dd HH:mm:ss:SSS 24小时制
* yyyy-MM-dd hh:mm:ss:SSS 12小时制
*/
/**
* 日期转换成字符串
* @param source
* @param pattern 例如 yyyy-MM-dd HH:mm:ss
* @return
*/
public static String dateParseString(Date source,String pattern){
if(source == null){
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(source);
}
/**
* 字符串转换成日期
* @param source
* @param pattern 例如 yyyy-MM-dd HH:mm:ss
* @return
*/
public static Date stringParseDate(String source,String pattern){
if(isNullOrBlank(source) || isNullOrBlank(pattern)){
return null;
}
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
date = sdf.parse(source);
} catch (ParseException e) {
return null;
}
return date;
}
public static double doubleFormat(Double source,int num){
if(source == null){
source = 0d;
}
BigDecimal bd = new BigDecimal(source);
double result = bd.setScale(num,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
public static String doubleParseString(Double source,String parten){
if(source == null){
source = 0d;
}
if(parten == null){
parten = "##,###,###,##0.00";
}
DecimalFormat fmt = new DecimalFormat(parten);
return fmt.format(source);
}
public static String longParseString(Long source,String parten){
if(source == null){
source = 0L;
}
if(parten == null){
parten = "##,###,###,###";
}
DecimalFormat fmt = new DecimalFormat(parten);
return fmt.format(source);
}
/**
* 空字符串付默认值
* @param source
* @param defaultValue
* @return
*/
public static String nullStringToDefault(String source,String defaultValue){
String result = source;
if(isNullOrBlank(source)){
result = defaultValue;
}
return result;
}
public static Integer stringParseInt(String source){
Integer result = null;
if(isNullOrBlank(source)){
return null;
}else{
try{
result = Integer.parseInt(source);
}catch(Exception e){}
}
return result;
}
public static Long stringParseLong(String source){
Long result = null;
if(isNullOrBlank(source)){
return null;
}else{
try{
result = Long.parseLong(source);
}catch(Exception e){}
}
return result;
}
public static Double stringParseDouble(String source){
Double result = null;
if(isNullOrBlank(source)){
return null;
}else{
try{
result = Double.parseDouble(source);
}catch(Exception e){}
}
return result;
}
public static boolean isNullOrBlank(String source){
boolean result = false;
if(source == null){
result = true;
}else if("".equals(source.trim())){
result = true;
}
return result ;
}
public static String getClassType(Object source){
String classType = "Integer";
if(source == null){
return null;
}
String className = source.getClass().getName();
if(className.contains("java.lang.Integer")){
classType = "Integer";
}else if(className.contains("java.lang.Long")){
classType = "Long";
}else if(className.contains("java.lang.Double")){
classType = "Double";
}else if(className.contains("java.math.BigInteger")){
classType = "BigInteger";
}else if(className.contains("java.math.BigDecimal")){
classType = "BigDecimal";
}
return classType;
}
public static Integer intValue(Object source){
Integer result = null;
if(source == null){
return 0;
}
try{
if("Integer".equals(getClassType(source))){
result = ((Integer)source).intValue();
}else if("BigInteger".equals(getClassType(source))){
result = ((BigInteger)source).intValue();
}else if("BigDecimal".equals(getClassType(source))){
result = ((BigDecimal)source).intValue();
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static boolean isNullOrZero(Object source){
boolean result = false;
if(source == null){
result = true;
}else{
if("Integer".equals(getClassType(source))){
int value = ((Integer)source).intValue();
if(value == 0){
result = true;
}
}else if("Long".equals(getClassType(source))){
long value = ((Long)source).longValue();
if(value == 0){
result = true;
}
}else if("Double".equals(getClassType(source))){
double value = ((Double)source).doubleValue();
if(value == 0){
result = true;
}
}else if("BigInteger".equals(getClassType(source))){
double value = ((BigInteger)source).doubleValue();
if(value == 0){
result = true;
}
}else if("BigDecimal".equals(getClassType(source))){
double value = ((BigDecimal)source).doubleValue();
if(value == 0){
result = true;
}
}
}
return result ;
}
/**
* 求时间差
* @param source 终止时间
* @param target 开始时间
* @param unit D天 H小时 M分 S秒 MS毫秒
* @return
*/
public static long getDatePeriod(Date source,Date target,String unit){
long result = 0;
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long ms = 1;
// 获得两个时间的毫秒时间差异
long diff = source.getTime() - target.getTime();
/*
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns;
//return day + "天" + hour + "小时" + min + "分钟";
*/
if("D".equals(unit)){
result = diff / nd;
}else if("H".equals(unit)){
result = diff / nh;
}else if("M".equals(unit)){
result = diff / nm;
}else if("S".equals(unit)){
result = diff / ns;
}else if("MS".equals(unit)){
result = diff / ms;
}
return result;
}
/**
*
* @param source
* @param operation ADD或SUB
* @param unit S秒 M分钟 H小时 D天 W周 Mon月 Y年
* @param number
* @return
*/
public static Date dateOperation(Date source,String operation,String unit,int number){
Date result = null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(source);
int field = Calendar.SECOND;
if("S".equals(unit)){
field = Calendar.SECOND;
}else if("M".equals(unit)){
field = Calendar.MINUTE;
}else if("H".equals(unit)){
field = Calendar.HOUR_OF_DAY;
}else if("D".equals(unit)){
field = Calendar.DATE;
}else if("W".equals(unit)){
field = Calendar.WEEK_OF_MONTH;
}else if("Mon".equals(unit)){
field = Calendar.MONTH;
}else if("Y".equals(unit)){
field = Calendar.YEAR;
}
if("SUB".equals(operation)){
calendar.add(field, -number);
}else{
calendar.add(field, number);
}
result = calendar.getTime();
return result;
}
/**
* 由出生日期获得年龄
* @param birthDay
* @return
* @throws Exception
*/
public static int getAge(Date birthDay){
int age = 0;
if(birthDay == null){
return 0;
}
try{
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
// throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
return -1;
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth){
age--;
}
}else{
age--;
}
}
}catch(Exception e){}
return age;
}
/**
* 根据异常对象获取异常堆栈字符串
* @param e
* @return
*/
public static String parseExceptionStack(Exception e){
String exceptionStack = null;
/*StringBuffer sbf = new StringBuffer();
StackTraceElement[] stack = e.getStackTrace();
StackTraceElement element = null;
String message = e.toString();
sbf.append(message+"\n");
for(int i=0;i<stack.length;i++){
element = stack[i];
String fileName = element.getFileName();
String methodName = element.getMethodName();
String className = element.getClassName();
int lineNumber = element.getLineNumber();
String append = fileName+":"+lineNumber;
boolean isNativeMethod = element.isNativeMethod();
if(isNativeMethod){
append = "Native Method";
}
sbf.append(" at "+className+"."+methodName+"("+append+")\n");
}
exceptionStack = sbf.toString();*/
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
exceptionStack = sw.toString();
return exceptionStack;
}
public static boolean isValidDate(String source,String pattern) {
boolean convertSuccess = true;
if(isNullOrBlank(source)){
return false;
}
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
format.setLenient(false);
format.parse(source);
}catch(Exception e) {
convertSuccess=false;
}
return convertSuccess;
}
public static boolean checkEmail(String email){
return Pattern.matches(EMAIL_REGEX, email.trim());
}
/**
*
* @param area 省份名、城市名、县名
* @param birthDay 出生日期,格式(19891019)
* @param gender 性别(范围:1-9,男:奇数,女:偶数)
* @param age
* @return
*/
public static String createID(String area,String birthDay,String gender,Integer age){
String idNo = null;
String areaCode = null;
String seqNo = getRandomNum(2)+""; // (两位)顺序号,格式(00-99)
Random random = new Random();
String areaCodeFile = CommonUtil.class.getResource("").getPath()+File.separator+"areaCode.txt";
List<String> areaList = readFile(areaCodeFile, "UTF-8");
if(area == null || "".equals(area)){
String item = areaList.get(random.nextInt(areaList.size()) -1);
areaCode = item.split(" ")[0];
}else{
for(String item : areaList){
if(item.contains(area)){
areaCode = item.split(" ")[0];
break;
}
}
}
if(areaCode == null){areaCode = "110101";}
if(birthDay == null || "".equals(birthDay)){
if(age == null || age <= 0){
int[] arr = new int[]{1,2,3,4};
int a = arr[random.nextInt(4)];
String ageStr = a+getRandomNum(1);
age = Integer.parseInt(ageStr);
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -age);
int randomDay = 1+(int)(Math.random()*360);
calendar.add(Calendar.DAY_OF_YEAR, -randomDay);
birthDay = dateParseString(calendar.getTime(), "yyyyMMdd");
}
if(gender == null || "".equals(gender)){
gender = getRandomNum(1)+"";
}
// 前17位要除以的数:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
int finalAreaCode = Integer.parseInt(areaCode.substring(0, 1)) * 7
+ Integer.parseInt(areaCode.substring(1, 2)) * 9
+ Integer.parseInt(areaCode.substring(2, 3)) * 10
+ Integer.parseInt(areaCode.substring(3, 4)) * 5
+ Integer.parseInt(areaCode.substring(4, 5)) * 8
+ Integer.parseInt(areaCode.substring(5, 6)) * 4;
int finalBirthday = Integer.parseInt(birthDay.substring(0, 1)) * 2
+ Integer.parseInt(birthDay.substring(1, 2)) * 1
+ Integer.parseInt(birthDay.substring(2, 3)) * 6
+ Integer.parseInt(birthDay.substring(3, 4)) * 3
+ Integer.parseInt(birthDay.substring(4, 5)) * 7
+ Integer.parseInt(birthDay.substring(5, 6)) * 9
+ Integer.parseInt(birthDay.substring(6, 7)) * 10
+ Integer.parseInt(birthDay.substring(7, 8)) * 5;
int NoIs = (Integer.parseInt(seqNo.substring(0, 1))) * 8
+ (Integer.parseInt(seqNo.substring(1, 2))) * 4;
int sexNo = (Integer.parseInt(gender.substring(0, 1))) * 2;
int checkCode = (finalAreaCode + finalBirthday + NoIs + sexNo) % 11;
int finalCheckCode = 0;
// 余数范围: 0 1 2 3 4 5 6 7 8 9 10
// 余数对应的数:1 0 X 9 8 7 6 5 4 3 2
// 计算出最终的校验码:finalCheckCode
switch (checkCode) {
case 0:
finalCheckCode = 1;
break;
case 1:
finalCheckCode = 0;
break;
case 2:
finalCheckCode = -3;
break;
case 3:
finalCheckCode = 9;
break;
case 4:
finalCheckCode = 8;
break;
case 5:
finalCheckCode = 7;
break;
case 6:
finalCheckCode = 6;
break;
case 7:
finalCheckCode = 5;
break;
case 8:
finalCheckCode = 4;
break;
case 9:
finalCheckCode = 3;
break;
case 10:
finalCheckCode = 2;
break;
default:
break;
}
// 区域编号(6位数)+出生日期(8位数)+顺序编号(2位数)+性别号(1位数)+校验码(1位数)=身份证号(18位数)
String checkInd = null;
if(finalCheckCode == -3){
checkInd = "X";
}else{
checkInd = finalCheckCode+"";
}
idNo = areaCode + birthDay + seqNo + gender + checkInd;
return idNo;
}
public static String createMail(){
String mail = getRandomString(5)+"@163.com";
return mail;
}
public static String createPhoneNo(){
return "139"+getRandomNum(8);
}
public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static String getRandomNum(int length) { //length表示生成字符串的长度
String base = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static String createName(){
Random random=new Random(System.currentTimeMillis());
/* 598 百家姓 */
String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
int index=random.nextInt(Surname.length-1);
String name = Surname[index]; //获得一个随机的姓氏
/* 从常用字中选取一个或两个字作为名 */
if(random.nextBoolean()){
name+=getChinese()+getChinese();
}else {
name+=getChinese();
}
// System.out.println(name);
return name;
}
public static String getChinese() {
String str = null;
int highPos, lowPos;
Random random = new Random();
highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字
random=new Random();
lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列
byte[] bArr = new byte[2];
bArr[0] = (new Integer(highPos)).byteValue();
bArr[1] = (new Integer(lowPos)).byteValue();
try {
str = new String(bArr, "GB2312"); //区位码组合成汉字
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args){
// String idNo = createID("南部县", "19940929", "1", null);
String idNo = createID("长丰县", null, "1", 31);
System.out.println(idNo);
System.out.println(IDcardValidator.isIdcardValid(idNo));
}
@SuppressWarnings("rawtypes")
public static String currentIP(){
String currentIP = null;
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){
ip = (InetAddress) addresses.nextElement();
if(ip != null && ip instanceof Inet4Address){
if(currentIP == null){
currentIP = "";
}
currentIP += ip.getHostAddress()+";";
// System.out.println("本机的IP = " + currentIP);
}
if(ip != null && ip instanceof Inet6Address){
if(currentIP == null){
currentIP = "";
}
currentIP += ip.getHostAddress()+":";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return currentIP;
}
/**
* 获取HttpServletRequest请求IP
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
@SuppressWarnings("rawtypes")
public static void simpleObjectCopy(Object source,Object target){
if(source == null || target == null){ return; }
try {
Method[] sourceMethods = source.getClass().getDeclaredMethods();
for(Method smethod : sourceMethods){
Class returnType = smethod.getReturnType();
String sourceMethodName = smethod.getName();
if(!returnType.getTypeName().equals("void") && sourceMethodName.startsWith("get")){
Object[] paramArr = null;
Object getValue = smethod.invoke(source,paramArr);
if(getValue != null){
// System.out.println("--------------in simpleObjectCopy returnType : "+returnType.getTypeName()+" sourceMethodName="+sourceMethodName);
Method[] targetMethods = target.getClass().getDeclaredMethods();
for(Method tmethod : targetMethods){
String targetMethodName = tmethod.getName();
if(targetMethodName.equals("set"+sourceMethodName.substring(3))){
Class[] parameterTypes = tmethod.getParameterTypes();
if(parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].getTypeName().equals(returnType.getTypeName())){
// System.out.println("--------------in simpleObjectCopy targetMethodName:"+targetMethodName);
tmethod.invoke(target,getValue);
}//set value
break;
}//set
}//for targetMethod
}//get value != null
}//get
}//for sourceMethod
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
public static String getInputStreamContent(InputStream inputStream,String charset)throws Exception{
String content = null;
if(inputStream == null){
return null;
}
if(charset == null ){
charset = "UTF-8";
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,charset));// 为了进行一行读取操作
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
content = buffer.toString();
return content;
}
public static List<String> readFile(String fileName,String encoding){
List<String> contents = new ArrayList<String>();
File file = new File(fileName);
FileInputStream fi = null;
InputStreamReader ir = null;
BufferedReader br = null;
try {
fi = new FileInputStream(file);
ir = new InputStreamReader(fi,encoding);
br = new BufferedReader(ir);
while(br.ready()){
String line = br.readLine();
contents.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
fi.close();
ir.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return contents;
}
public static void writeFile(List<String> contents,String fileName,boolean appending,String encoding){
File file = new File(fileName);
FileOutputStream fo = null;
OutputStreamWriter or = null;
BufferedWriter bw = null;
try {
fo = new FileOutputStream(file,appending);
or = new OutputStreamWriter(fo,encoding);
bw = new BufferedWriter(or);
for(String line : contents){
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
fo.close();
or.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断是否是数字
*/
private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]*");
public static boolean isNumeric(String str){
// Pattern pattern = Pattern.compile("[0-9]*");
// Matcher isNum = pattern.matcher(str);
Matcher numMatcher = NUMBER_PATTERN.matcher(str);
if( !numMatcher.matches() ){
return false;
}
return true;
}
// 根据Unicode编码完美的判断中文汉字和符号
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
return true;
}
return false;
}
public static Double calcuPersonalTAX(Double amount){
Double tax = 0d;
if(amount <= 800){
tax = 0.0d;
}else if(800 < amount && amount <= 4000){
tax = (amount - 800 ) * 0.2 ;
}else if(4000 < amount && amount <= 25000){
tax = amount * (1-0.2) * 0.2 ;
}else if(25000 < amount && amount <= 62500){
tax = amount * (1-0.2) * 0.3 -2000 ;
}else if(62500 < amount){
tax = amount * (1-0.2) * 0.4 - 7000 ;
}
return tax;
}
/**
* 判断字符串中是否含有数字
* @param content
* @return
*/
public static boolean hasDigit(String content) {
boolean flag = false;
Pattern pattern = Pattern.compile(".*\\d+.*");
Matcher m = pattern.matcher(content);
if (m.matches()) {
flag = true;
}
return flag;
}
/**
* 判断是否含有特殊字符
*
* @param str
* @return true为包含,false为不包含
*/
public static final String DEFAULT_QUERY_REGEX = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
public static boolean isSpecialCharacter(String str) {
Pattern p = Pattern.compile(DEFAULT_QUERY_REGEX);
Matcher m = p.matcher(str);
return m.find();
}
/**
* 通过ip地址获取该ip的实际地理地址
* @param ip
* @return
*/
public static String getAddressByIP(String ip){
String address = null;
try{
URL url = new URL( "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
StringBuffer result = new StringBuffer();
while((line = reader.readLine()) != null){
result.append(line);
}
reader.close();
String ipInfo = result.toString();
IpToAddress ipToAddress = (IpToAddress) JsonUtil.jsonToObj(ipInfo, IpToAddress.class);
if (ipToAddress != null) {
if("0".equals(ipToAddress.getCode())){
String area = ipToAddress.getData().getCountry();
if (area == null && "".equals(area)) {
area = ipToAddress.getData().getArea();
}
String region = ipToAddress.getData().getRegion();
String city = ipToAddress.getData().getCity();
String isp = ipToAddress.getData().getIsp();
address = area+"_"+region+"_"+city+"_"+isp;
}
}
}
catch( IOException e){
System.out.println( "获取失败!!!!");
}
return address;
}
/**
* 判断姓名(中文姓名和英文姓名)
*/
public static boolean isConSpeCharacters(String str) {
if (str.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() == 0) {
return false;
}
return true;
}
/**
* 通过身份证号码获取出生日期、性别、年龄
* @param certificateNo
* @return 返回的出生日期格式:1990-01-01 性别格式:F-女,M-男
*/
/**
* 通过身份证号码获取出生日期、性别、年龄
* @param certificateNo 身份证号码
* @param type birthday -- 出生年月日 age--年龄 sex--性别
* @return 结果 sex--性别 1-男 2-女
*/
public static String getBirAgeSex(String certificateNo,String type) {
String birthday = "";
String age = "";
String sexCode = "";
String result = "";
int year = Calendar.getInstance().get(Calendar.YEAR);
char[] number = certificateNo.toCharArray();
boolean flag = true;
if (number.length == 15) {
for (int x = 0; x < number.length; x++) {
if (!flag) return null;
flag = Character.isDigit(number[x]);
}
} else if (number.length == 18) {
for (int x = 0; x < number.length - 1; x++) {
if (!flag) return null;
flag = Character.isDigit(number[x]);
}
}
if (flag && certificateNo.length() == 15) {
birthday = "19" + certificateNo.substring(6, 8) + "-"
+ certificateNo.substring(8, 10) + "-"
+ certificateNo.substring(10, 12);
sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M";
age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
} else if (flag && certificateNo.length() == 18) {
birthday = certificateNo.substring(6, 10) + "-"
+ certificateNo.substring(10, 12) + "-"
+ certificateNo.substring(12, 14);
sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M";
age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
}
Map<String, String> map = new HashMap<String, String>();
map.put("birthday", birthday);
map.put("age", age);
map.put("sexCode", sexCode);
if ("birthday".equals(type)) {
result = birthday;
}else if("age".equals(type)){
result = age;
}else if("sex".equals(type)){
if("F".equals(sexCode)){
sexCode = "2";
}else if ("M".equals(sexCode)) {
sexCode = "1";
}
result = sexCode;
}
return result;
}
}
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; package com.ajb.common.utils.string;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
/** /**
* <p> * <p>
* 身份证合法性校验0 * 身份证合法性校验0
* </p> * </p>
* <pre> * <pre>
* --15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日期,第15位代表性别,奇数为男,偶数为女。 * --15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日期,第15位代表性别,奇数为男,偶数为女。
* --18位身份证号码:第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。 * --18位身份证号码:第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。
* 最后一位为校验位 * 最后一位为校验位
* </pre> * </pre>
* *
*/ */
public class IDcardValidator { public class IDcardValidator {
/** /**
* <pre> * <pre>
* 省、直辖市代码表: * 省、直辖市代码表:
* 11 : 北京 12 : 天津 13 : 河北 14 : 山西 15 : 内蒙古 * 11 : 北京 12 : 天津 13 : 河北 14 : 山西 15 : 内蒙古
* 21 : 辽宁 22 : 吉林 23 : 黑龙江 31 : 上海 32 : 江苏 * 21 : 辽宁 22 : 吉林 23 : 黑龙江 31 : 上海 32 : 江苏
* 33 : 浙江 34 : 安徽 35 : 福建 36 : 江西 37 : 山东 * 33 : 浙江 34 : 安徽 35 : 福建 36 : 江西 37 : 山东
* 41 : 河南 42 : 湖北 43 : 湖南 44 : 广东 45 : 广西 46 : 海南 * 41 : 河南 42 : 湖北 43 : 湖南 44 : 广东 45 : 广西 46 : 海南
* 50 : 重庆 51 : 四川 52 : 贵州 53 : 云南 54 : 西藏 * 50 : 重庆 51 : 四川 52 : 贵州 53 : 云南 54 : 西藏
* 61 : 陕西 62 : 甘肃 63 : 青海 64 : 宁夏 65 : 新疆 * 61 : 陕西 62 : 甘肃 63 : 青海 64 : 宁夏 65 : 新疆
* 71 : 台湾 * 71 : 台湾
* 81 : 香港 82 : 澳门 * 81 : 香港 82 : 澳门
* 91 : 国外 * 91 : 国外
* </pre> * </pre>
*/ */
private static String cityCode[] = { "11", "12", "13", "14", "15", "21", private static String cityCode[] = { "11", "12", "13", "14", "15", "21",
"22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42",
"43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
"63", "64", "65", "71", "81", "82", "91" }; "63", "64", "65", "71", "81", "82", "91" };
/** /**
* 每位加权因子 * 每位加权因子
*/ */
private static int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, private static int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,
8, 4, 2 }; 8, 4, 2 };
/** /**
* 验证所有的身份证的合法性 * 验证所有的身份证的合法性
* *
* @param idcard * @param idcard
* 身份证 * 身份证
* @return 合法返回true,否则返回false * @return 合法返回true,否则返回false
*/ */
public static boolean isIdcardValid(String idcard) { public static boolean isIdcardValid(String idcard) {
if(idcard == null || "".equals(idcard)) { if(idcard == null || "".equals(idcard)) {
return false; return false;
} }
if(idcard.length() == 15) { if(idcard.length() == 15) {
return validate15IDCard(idcard); return validate15IDCard(idcard);
}else{ }else{
return validate18Idcard(idcard); return validate18Idcard(idcard);
} }
} }
/** /**
* <p> * <p>
* 判断18位身份证的合法性 * 判断18位身份证的合法性
* </p> * </p>
* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。 * 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。
* 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。 * 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
* <p> * <p>
* 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。 * 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。
* </p> * </p>
* <p> * <p>
* 1.前1、2位数字表示:所在省份的代码; 2.第3、4位数字表示:所在城市的代码; 3.第5、6位数字表示:所在区县的代码; * 1.前1、2位数字表示:所在省份的代码; 2.第3、4位数字表示:所在城市的代码; 3.第5、6位数字表示:所在区县的代码;
* 4.第7~14位数字表示:出生年、月、日; 5.第15、16位数字表示:所在地的派出所的代码; * 4.第7~14位数字表示:出生年、月、日; 5.第15、16位数字表示:所在地的派出所的代码;
* 6.第17位数字表示性别:奇数表示男性,偶数表示女性; * 6.第17位数字表示性别:奇数表示男性,偶数表示女性;
* 7.第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。 * 7.第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。
* </p> * </p>
* <p> * <p>
* 第十八位数字(校验码)的计算方法为: 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4 * 第十八位数字(校验码)的计算方法为: 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4
* 2 1 6 3 7 9 10 5 8 4 2 * 2 1 6 3 7 9 10 5 8 4 2
* </p> * </p>
* <p> * <p>
* 2.将这17位数字和系数相乘的结果相加。 * 2.将这17位数字和系数相乘的结果相加。
* </p> * </p>
* <p> * <p>
* 3.用加出来和除以11,看余数是多少 * 3.用加出来和除以11,看余数是多少
* </p> * </p>
* 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3 * 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3
* 2。 * 2。
* <p> * <p>
* 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。 * 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。
* </p> * </p>
* *
* @param idcard * @param idcard
* @return * @return
*/ */
public static boolean validate18Idcard(String idcard) { public static boolean validate18Idcard(String idcard) {
if (idcard == null) { if (idcard == null) {
return false; return false;
} }
// 非18位为假 // 非18位为假
if (idcard.length() != 18) { if (idcard.length() != 18) {
return false; return false;
} }
// 获取前17位 // 获取前17位
String idcard17 = idcard.substring(0, 17); String idcard17 = idcard.substring(0, 17);
// 前17位全部为数字 // 前17位全部为数字
if (!isDigital(idcard17)) { if (!isDigital(idcard17)) {
return false; return false;
} }
String provinceid = idcard.substring(0, 2); String provinceid = idcard.substring(0, 2);
// 校验省份 // 校验省份
if (!checkProvinceid(provinceid)) { if (!checkProvinceid(provinceid)) {
return false; return false;
} }
// 校验出生日期 // 校验出生日期
String birthday = idcard.substring(6, 14); String birthday = idcard.substring(6, 14);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try { try {
Date birthDate = sdf.parse(birthday); Date birthDate = sdf.parse(birthday);
String tmpDate = sdf.format(birthDate); String tmpDate = sdf.format(birthDate);
if (!tmpDate.equals(birthday)) {// 出生年月日不正确 if (!tmpDate.equals(birthday)) {// 出生年月日不正确
return false; return false;
} }
} catch (ParseException e1) { } catch (ParseException e1) {
return false; return false;
} }
// 获取第18位 // 获取第18位
String idcard18Code = idcard.substring(17, 18); String idcard18Code = idcard.substring(17, 18);
char c[] = idcard17.toCharArray(); char c[] = idcard17.toCharArray();
int bit[] = converCharToInt(c); int bit[] = converCharToInt(c);
int sum17 = 0; int sum17 = 0;
sum17 = getPowerSum(bit); sum17 = getPowerSum(bit);
// 将和值与11取模得到余数进行校验码判断 // 将和值与11取模得到余数进行校验码判断
String checkCode = getCheckCodeBySum(sum17); String checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) { if (null == checkCode) {
return false; return false;
} }
// 将身份证的第18位与算出来的校码进行匹配,不相等就为假 // 将身份证的第18位与算出来的校码进行匹配,不相等就为假
if (!idcard18Code.equalsIgnoreCase(checkCode)) { if (!idcard18Code.equalsIgnoreCase(checkCode)) {
return false; return false;
} }
return true; return true;
} }
/** /**
* 校验15位身份证 * 校验15位身份证
* *
* <pre> * <pre>
* 只校验省份和出生年月日 * 只校验省份和出生年月日
* </pre> * </pre>
* *
* @param idcard * @param idcard
* @return * @return
*/ */
public static boolean validate15IDCard(String idcard) { public static boolean validate15IDCard(String idcard) {
if (idcard == null) { if (idcard == null) {
return false; return false;
} }
// 非15位为假 // 非15位为假
if (idcard.length() != 15) { if (idcard.length() != 15) {
return false; return false;
} }
// 15全部为数字 // 15全部为数字
if (!isDigital(idcard)) { if (!isDigital(idcard)) {
return false; return false;
} }
String provinceid = idcard.substring(0, 2); String provinceid = idcard.substring(0, 2);
// 校验省份 // 校验省份
if (!checkProvinceid(provinceid)) { if (!checkProvinceid(provinceid)) {
return false; return false;
} }
String birthday = idcard.substring(6, 12); String birthday = idcard.substring(6, 12);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
try { try {
Date birthDate = sdf.parse(birthday); Date birthDate = sdf.parse(birthday);
String tmpDate = sdf.format(birthDate); String tmpDate = sdf.format(birthDate);
if (!tmpDate.equals(birthday)) {// 身份证日期错误 if (!tmpDate.equals(birthday)) {// 身份证日期错误
return false; return false;
} }
} catch (ParseException e1) { } catch (ParseException e1) {
return false; return false;
} }
return true; return true;
} }
/** /**
* 将15位的身份证转成18位身份证 * 将15位的身份证转成18位身份证
* *
* @param idcard * @param idcard
* @return * @return
*/ */
public static String convertIdcarBy15bit(String idcard) { public static String convertIdcarBy15bit(String idcard) {
if (idcard == null) { if (idcard == null) {
return null; return null;
} }
// 非15位身份证 // 非15位身份证
if (idcard.length() != 15) { if (idcard.length() != 15) {
return null; return null;
} }
// 15全部为数字 // 15全部为数字
if (!isDigital(idcard)) { if (!isDigital(idcard)) {
return null; return null;
} }
String provinceid = idcard.substring(0, 2); String provinceid = idcard.substring(0, 2);
// 校验省份 // 校验省份
if (!checkProvinceid(provinceid)) { if (!checkProvinceid(provinceid)) {
return null; return null;
} }
String birthday = idcard.substring(6, 12); String birthday = idcard.substring(6, 12);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
Date birthdate = null; Date birthdate = null;
try { try {
birthdate = sdf.parse(birthday); birthdate = sdf.parse(birthday);
String tmpDate = sdf.format(birthdate); String tmpDate = sdf.format(birthdate);
if (!tmpDate.equals(birthday)) {// 身份证日期错误 if (!tmpDate.equals(birthday)) {// 身份证日期错误
return null; return null;
} }
} catch (ParseException e1) { } catch (ParseException e1) {
return null; return null;
} }
Calendar cday = Calendar.getInstance(); Calendar cday = Calendar.getInstance();
cday.setTime(birthdate); cday.setTime(birthdate);
String year = String.valueOf(cday.get(Calendar.YEAR)); String year = String.valueOf(cday.get(Calendar.YEAR));
String idcard17 = idcard.substring(0, 6) + year + idcard.substring(8); String idcard17 = idcard.substring(0, 6) + year + idcard.substring(8);
char c[] = idcard17.toCharArray(); char c[] = idcard17.toCharArray();
String checkCode = ""; String checkCode = "";
// 将字符数组转为整型数组 // 将字符数组转为整型数组
int bit[] = converCharToInt(c); int bit[] = converCharToInt(c);
int sum17 = 0; int sum17 = 0;
sum17 = getPowerSum(bit); sum17 = getPowerSum(bit);
// 获取和值与11取模得到余数进行校验码 // 获取和值与11取模得到余数进行校验码
checkCode = getCheckCodeBySum(sum17); checkCode = getCheckCodeBySum(sum17);
// 获取不到校验位 // 获取不到校验位
if (null == checkCode) { if (null == checkCode) {
return null; return null;
} }
// 将前17位与第18位校验码拼接 // 将前17位与第18位校验码拼接
idcard17 += checkCode; idcard17 += checkCode;
return idcard17; return idcard17;
} }
/** /**
* 校验省份 * 校验省份
* *
* @param provinceid * @param provinceid
* @return 合法返回TRUE,否则返回FALSE * @return 合法返回TRUE,否则返回FALSE
*/ */
private static boolean checkProvinceid(String provinceid) { private static boolean checkProvinceid(String provinceid) {
for (String id : cityCode) { for (String id : cityCode) {
if (id.equals(provinceid)) { if (id.equals(provinceid)) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* 数字验证 * 数字验证
* *
* @param str * @param str
* @return * @return
*/ */
private static boolean isDigital(String str) { private static boolean isDigital(String str) {
return str.matches("^[0-9]*$"); return str.matches("^[0-9]*$");
} }
/** /**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值 * 将身份证的每位和对应位的加权因子相乘之后,再得到和值
* *
* @param bit * @param bit
* @return * @return
*/ */
private static int getPowerSum(int[] bit) { private static int getPowerSum(int[] bit) {
int sum = 0; int sum = 0;
if (power.length != bit.length) { if (power.length != bit.length) {
return sum; return sum;
} }
for (int i = 0; i < bit.length; i++) { for (int i = 0; i < bit.length; i++) {
for (int j = 0; j < power.length; j++) { for (int j = 0; j < power.length; j++) {
if (i == j) { if (i == j) {
sum = sum + bit[i] * power[j]; sum = sum + bit[i] * power[j];
} }
} }
} }
return sum; return sum;
} }
/** /**
* 将和值与11取模得到余数进行校验码判断 * 将和值与11取模得到余数进行校验码判断
* *
* @param checkCode * @param checkCode
* @param sum17 * @param sum17
* @return 校验位 * @return 校验位
*/ */
private static String getCheckCodeBySum(int sum17) { private static String getCheckCodeBySum(int sum17) {
String checkCode = null; String checkCode = null;
switch (sum17 % 11) { switch (sum17 % 11) {
case 10: case 10:
checkCode = "2"; checkCode = "2";
break; break;
case 9: case 9:
checkCode = "3"; checkCode = "3";
break; break;
case 8: case 8:
checkCode = "4"; checkCode = "4";
break; break;
case 7: case 7:
checkCode = "5"; checkCode = "5";
break; break;
case 6: case 6:
checkCode = "6"; checkCode = "6";
break; break;
case 5: case 5:
checkCode = "7"; checkCode = "7";
break; break;
case 4: case 4:
checkCode = "8"; checkCode = "8";
break; break;
case 3: case 3:
checkCode = "9"; checkCode = "9";
break; break;
case 2: case 2:
checkCode = "x"; checkCode = "x";
break; break;
case 1: case 1:
checkCode = "0"; checkCode = "0";
break; break;
case 0: case 0:
checkCode = "1"; checkCode = "1";
break; break;
} }
return checkCode; return checkCode;
} }
/** /**
* 将字符数组转为整型数组 * 将字符数组转为整型数组
* *
* @param c * @param c
* @return * @return
* @throws NumberFormatException * @throws NumberFormatException
*/ */
private static int[] converCharToInt(char[] c) throws NumberFormatException { private static int[] converCharToInt(char[] c) throws NumberFormatException {
int[] a = new int[c.length]; int[] a = new int[c.length];
int k = 0; int k = 0;
for (char temp : c) { for (char temp : c) {
a[k++] = Integer.parseInt(String.valueOf(temp)); a[k++] = Integer.parseInt(String.valueOf(temp));
} }
return a; return a;
} }
public static String getGenderFromID(String idcard){ public static String getGenderFromID(String idcard){
String gender = "M"; String gender = "M";
int idxGenderStart = 16; int idxGenderStart = 16;
//如果是15位的证件号码 //如果是15位的证件号码
if(idcard.length() == 15) { if(idcard.length() == 15) {
idxGenderStart = 14; idxGenderStart = 14;
} }
//性别 //性别
String idxGenderStr = idcard.substring(idxGenderStart, idxGenderStart + 1); String idxGenderStr = idcard.substring(idxGenderStart, idxGenderStart + 1);
int idxGender = Integer.parseInt(idxGenderStr) % 2; int idxGender = Integer.parseInt(idxGenderStr) % 2;
gender = (idxGender == 1) ? "M" : "F"; gender = (idxGender == 1) ? "M" : "F";
return gender; return gender;
} }
public static String getBirthDateFromID(String idcard){ public static String getBirthDateFromID(String idcard){
String birthDate = null; String birthDate = null;
int birthYearSpan = 4; int birthYearSpan = 4;
//如果是15位的证件号码 //如果是15位的证件号码
if(idcard.length() == 15) { if(idcard.length() == 15) {
birthYearSpan = 2; birthYearSpan = 2;
} }
//出生日期 //出生日期
String year = (birthYearSpan == 2 ? "19" : "") + idcard.substring(6, 6 + birthYearSpan); String year = (birthYearSpan == 2 ? "19" : "") + idcard.substring(6, 6 + birthYearSpan);
String month = idcard.substring(6 + birthYearSpan, 6 + birthYearSpan + 2); String month = idcard.substring(6 + birthYearSpan, 6 + birthYearSpan + 2);
String day = idcard.substring(8 + birthYearSpan, 8 + birthYearSpan + 2); String day = idcard.substring(8 + birthYearSpan, 8 + birthYearSpan + 2);
birthDate = year + '-' + month + '-' + day; birthDate = year + '-' + month + '-' + day;
return birthDate; return birthDate;
} }
public static boolean checkGenderWithID(String idCard,String gender){ public static boolean checkGenderWithID(String idCard,String gender){
boolean result = true; boolean result = true;
String genderFormID = getGenderFromID(idCard); String genderFormID = getGenderFromID(idCard);
if( ("M".equals(genderFormID) && "2".equals(gender)) if( ("M".equals(genderFormID) && "2".equals(gender))
|| ||
("F".equals(genderFormID) && "1".equals(gender)) ("F".equals(genderFormID) && "1".equals(gender))
){ ){
result = false; result = false;
} }
return result; return result;
} }
public static boolean checkBirthDateWithID(String idCard,String birthDate){ public static boolean checkBirthDateWithID(String idCard,String birthDate){
boolean result = true; boolean result = true;
String birthDateFromID = getBirthDateFromID(idCard); String birthDateFromID = getBirthDateFromID(idCard);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try { try {
Date inputDate = sdf.parse(birthDate); Date inputDate = sdf.parse(birthDate);
Date idDate = sdf.parse(birthDateFromID); Date idDate = sdf.parse(birthDateFromID);
if(inputDate.compareTo(idDate) != 0){ if(inputDate.compareTo(idDate) != 0){
result = false; result = false;
} }
} catch (ParseException e) { } catch (ParseException e) {
result = false; result = false;
} }
return result; return result;
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
// String idcard = "130321860311519"; // String idcard = "130321860311519";
// String idcard = "34062119861001846X"; // String idcard = "34062119861001846X";
// String idcard = "340121198612204058"; // String idcard = "340121198612204058";
// System.out.println(isIdcardValid(idcard)); // System.out.println(isIdcardValid(idcard));
// System.out.println(getGenderFromID(idcard)); // System.out.println(getGenderFromID(idcard));
// System.out.println(getBirthDateFromID(idcard)); // System.out.println(getBirthDateFromID(idcard));
// // 15位身份证转18位身份证 // // 15位身份证转18位身份证
// System.out.println(convertIdcarBy15bit(idcard15)); // System.out.println(convertIdcarBy15bit(idcard15));
// String birthDate = "1997-1-1"; // String birthDate = "1997-1-1";
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Date date = sdf.parse(birthDate); // Date date = sdf.parse(birthDate);
// String result = sdf.format(date); // String result = sdf.format(date);
// System.out.println(result); // System.out.println(result);
// System.out.println(checkGenderWithID(idcard, "2")); // System.out.println(checkGenderWithID(idcard, "2"));
// System.out.println(checkBirthDateWithID(idcard, "1986-10-1")); // System.out.println(checkBirthDateWithID(idcard, "1986-10-1"));
} }
} }
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();
} }
} }
package com.ajb.common.utils.string; package com.ajb.common.utils.string;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.Inet4Address; import java.net.Inet4Address;
import java.net.Inet6Address; import java.net.Inet6Address;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.NetworkInterface; import java.net.NetworkInterface;
import java.net.SocketException; import java.net.SocketException;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class StringUtil { public class StringUtil {
private static final String EMAIL_REGEX="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";//邮箱正则表达式 private static final String EMAIL_REGEX="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";//邮箱正则表达式
/* /*
* 日期格式:http://blog.csdn.net/linghu_java/article/details/38379603 * 日期格式:http://blog.csdn.net/linghu_java/article/details/38379603
* yyyy-MM-dd HH:mm:ss:SSS 24小时制 * yyyy-MM-dd HH:mm:ss:SSS 24小时制
* yyyy-MM-dd hh:mm:ss:SSS 12小时制 * yyyy-MM-dd hh:mm:ss:SSS 12小时制
*/ */
/** /**
* 日期转换成字符串 * 日期转换成字符串
* @param source * @param source
* @param pattern 例如 yyyy-MM-dd HH:mm:ss * @param pattern 例如 yyyy-MM-dd HH:mm:ss
* @return * @return
*/ */
public static String dateParseString(Date source,String pattern){ public static String dateParseString(Date source,String pattern){
if(source == null){ if(source == null){
return null; return null;
} }
SimpleDateFormat sdf = new SimpleDateFormat(pattern); SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(source); return sdf.format(source);
} }
/** /**
* 字符串转换成日期 * 字符串转换成日期
* @param source * @param source
* @param pattern 例如 yyyy-MM-dd HH:mm:ss * @param pattern 例如 yyyy-MM-dd HH:mm:ss
* @return * @return
*/ */
public static Date stringParseDate(String source,String pattern){ public static Date stringParseDate(String source,String pattern){
if(isNullOrBlank(source) || isNullOrBlank(pattern)){ if(isNullOrBlank(source) || isNullOrBlank(pattern)){
return null; return null;
} }
Date date = null; Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern); SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try { try {
date = sdf.parse(source); date = sdf.parse(source);
} catch (ParseException e) { } catch (ParseException e) {
return null; return null;
} }
return date; return date;
} }
public static double doubleFormat(Double source,int num){ public static double doubleFormat(Double source,int num){
if(source == null){ if(source == null){
source = 0d; source = 0d;
} }
BigDecimal bd = new BigDecimal(source); BigDecimal bd = new BigDecimal(source);
double result = bd.setScale(num,BigDecimal.ROUND_HALF_UP).doubleValue(); double result = bd.setScale(num,BigDecimal.ROUND_HALF_UP).doubleValue();
return result; return result;
} }
public static String doubleParseString(Double source,String parten){ public static String doubleParseString(Double source,String parten){
if(source == null){ if(source == null){
source = 0d; source = 0d;
} }
if(parten == null){ if(parten == null){
parten = "##,###,###,##0.00"; parten = "##,###,###,##0.00";
} }
DecimalFormat fmt = new DecimalFormat(parten); DecimalFormat fmt = new DecimalFormat(parten);
return fmt.format(source); return fmt.format(source);
} }
public static String longParseString(Long source,String parten){ public static String longParseString(Long source,String parten){
if(source == null){ if(source == null){
source = 0L; source = 0L;
} }
if(parten == null){ if(parten == null){
parten = "##,###,###,###"; parten = "##,###,###,###";
} }
DecimalFormat fmt = new DecimalFormat(parten); DecimalFormat fmt = new DecimalFormat(parten);
return fmt.format(source); return fmt.format(source);
} }
/** /**
* 空字符串付默认值 * 空字符串付默认值
* @param source * @param source
* @param defaultValue * @param defaultValue
* @return * @return
*/ */
public static String nullStringToDefault(String source,String defaultValue){ public static String nullStringToDefault(String source,String defaultValue){
String result = source; String result = source;
if(isNullOrBlank(source)){ if(isNullOrBlank(source)){
result = defaultValue; result = defaultValue;
} }
return result; return result;
} }
public static Integer stringParseInt(String source){ public static Integer stringParseInt(String source){
Integer result = null; Integer result = null;
if(isNullOrBlank(source)){ if(isNullOrBlank(source)){
return null; return null;
}else{ }else{
try{ try{
result = Integer.parseInt(source); result = Integer.parseInt(source);
}catch(Exception e){} }catch(Exception e){}
} }
return result; return result;
} }
public static Long stringParseLong(String source){ public static Long stringParseLong(String source){
Long result = null; Long result = null;
if(isNullOrBlank(source)){ if(isNullOrBlank(source)){
return null; return null;
}else{ }else{
try{ try{
result = Long.parseLong(source); result = Long.parseLong(source);
}catch(Exception e){} }catch(Exception e){}
} }
return result; return result;
} }
public static Double stringParseDouble(String source){ public static Double stringParseDouble(String source){
Double result = null; Double result = null;
if(isNullOrBlank(source)){ if(isNullOrBlank(source)){
return null; return null;
}else{ }else{
try{ try{
result = Double.parseDouble(source); result = Double.parseDouble(source);
}catch(Exception e){} }catch(Exception e){}
} }
return result; return result;
} }
public static boolean isNullOrBlank(String source){ public static boolean isNullOrBlank(String source){
boolean result = false; boolean result = false;
if(source == null){ if(source == null){
result = true; result = true;
}else if("".equals(source.trim())){ }else if("".equals(source.trim())){
result = true; result = true;
} }
return result ; return result ;
} }
public static String getClassType(Object source){ public static String getClassType(Object source){
String classType = "Integer"; String classType = "Integer";
if(source == null){ if(source == null){
return null; return null;
} }
String className = source.getClass().getName(); String className = source.getClass().getName();
if(className.contains("java.lang.Integer")){ if(className.contains("java.lang.Integer")){
classType = "Integer"; classType = "Integer";
}else if(className.contains("java.lang.Long")){ }else if(className.contains("java.lang.Long")){
classType = "Long"; classType = "Long";
}else if(className.contains("java.lang.Double")){ }else if(className.contains("java.lang.Double")){
classType = "Double"; classType = "Double";
}else if(className.contains("java.math.BigInteger")){ }else if(className.contains("java.math.BigInteger")){
classType = "BigInteger"; classType = "BigInteger";
}else if(className.contains("java.math.BigDecimal")){ }else if(className.contains("java.math.BigDecimal")){
classType = "BigDecimal"; classType = "BigDecimal";
} }
return classType; return classType;
} }
public static Integer intValue(Object source){ public static Integer intValue(Object source){
Integer result = null; Integer result = null;
if(source == null){ if(source == null){
return 0; return 0;
} }
try{ try{
if("Integer".equals(getClassType(source))){ if("Integer".equals(getClassType(source))){
result = ((Integer)source).intValue(); result = ((Integer)source).intValue();
}else if("BigInteger".equals(getClassType(source))){ }else if("BigInteger".equals(getClassType(source))){
result = ((BigInteger)source).intValue(); result = ((BigInteger)source).intValue();
}else if("BigDecimal".equals(getClassType(source))){ }else if("BigDecimal".equals(getClassType(source))){
result = ((BigDecimal)source).intValue(); result = ((BigDecimal)source).intValue();
} }
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return result; return result;
} }
public static boolean isNullOrZero(Object source){ public static boolean isNullOrZero(Object source){
boolean result = false; boolean result = false;
if(source == null){ if(source == null){
result = true; result = true;
}else{ }else{
if("Integer".equals(getClassType(source))){ if("Integer".equals(getClassType(source))){
int value = ((Integer)source).intValue(); int value = ((Integer)source).intValue();
if(value == 0){ if(value == 0){
result = true; result = true;
} }
}else if("Long".equals(getClassType(source))){ }else if("Long".equals(getClassType(source))){
long value = ((Long)source).longValue(); long value = ((Long)source).longValue();
if(value == 0){ if(value == 0){
result = true; result = true;
} }
}else if("Double".equals(getClassType(source))){ }else if("Double".equals(getClassType(source))){
double value = ((Double)source).doubleValue(); double value = ((Double)source).doubleValue();
if(value == 0){ if(value == 0){
result = true; result = true;
} }
}else if("BigInteger".equals(getClassType(source))){ }else if("BigInteger".equals(getClassType(source))){
double value = ((BigInteger)source).doubleValue(); double value = ((BigInteger)source).doubleValue();
if(value == 0){ if(value == 0){
result = true; result = true;
} }
}else if("BigDecimal".equals(getClassType(source))){ }else if("BigDecimal".equals(getClassType(source))){
double value = ((BigDecimal)source).doubleValue(); double value = ((BigDecimal)source).doubleValue();
if(value == 0){ if(value == 0){
result = true; result = true;
} }
} }
} }
return result ; return result ;
} }
/** /**
* 求时间差 * 求时间差
* @param source 终止时间 * @param source 终止时间
* @param target 开始时间 * @param target 开始时间
* @param unit D天 H小时 M分 S秒 MS毫秒 * @param unit D天 H小时 M分 S秒 MS毫秒
* @return * @return
*/ */
public static long getDatePeriod(Date source,Date target,String unit){ public static long getDatePeriod(Date source,Date target,String unit){
long result = 0; long result = 0;
long nd = 1000 * 24 * 60 * 60; long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60; long nh = 1000 * 60 * 60;
long nm = 1000 * 60; long nm = 1000 * 60;
long ns = 1000; long ns = 1000;
long ms = 1; long ms = 1;
// 获得两个时间的毫秒时间差异 // 获得两个时间的毫秒时间差异
long diff = source.getTime() - target.getTime(); long diff = source.getTime() - target.getTime();
/* /*
// 计算差多少天 // 计算差多少天
long day = diff / nd; long day = diff / nd;
// 计算差多少小时 // 计算差多少小时
long hour = diff % nd / nh; long hour = diff % nd / nh;
// 计算差多少分钟 // 计算差多少分钟
long min = diff % nd % nh / nm; long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果 // 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns; long sec = diff % nd % nh % nm / ns;
//return day + "天" + hour + "小时" + min + "分钟"; //return day + "天" + hour + "小时" + min + "分钟";
*/ */
if("D".equals(unit)){ if("D".equals(unit)){
result = diff / nd; result = diff / nd;
}else if("H".equals(unit)){ }else if("H".equals(unit)){
result = diff / nh; result = diff / nh;
}else if("M".equals(unit)){ }else if("M".equals(unit)){
result = diff / nm; result = diff / nm;
}else if("S".equals(unit)){ }else if("S".equals(unit)){
result = diff / ns; result = diff / ns;
}else if("MS".equals(unit)){ }else if("MS".equals(unit)){
result = diff / ms; result = diff / ms;
} }
return result; return result;
} }
/** /**
* *
* @param source * @param source
* @param operation ADD或SUB * @param operation ADD或SUB
* @param unit S秒 M分钟 H小时 D天 W周 Mon月 Y年 * @param unit S秒 M分钟 H小时 D天 W周 Mon月 Y年
* @param number * @param number
* @return * @return
*/ */
public static Date dateOperation(Date source,String operation,String unit,int number){ public static Date dateOperation(Date source,String operation,String unit,int number){
Date result = null; Date result = null;
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(source); calendar.setTime(source);
int field = Calendar.SECOND; int field = Calendar.SECOND;
if("S".equals(unit)){ if("S".equals(unit)){
field = Calendar.SECOND; field = Calendar.SECOND;
}else if("M".equals(unit)){ }else if("M".equals(unit)){
field = Calendar.MINUTE; field = Calendar.MINUTE;
}else if("H".equals(unit)){ }else if("H".equals(unit)){
field = Calendar.HOUR_OF_DAY; field = Calendar.HOUR_OF_DAY;
}else if("D".equals(unit)){ }else if("D".equals(unit)){
field = Calendar.DATE; field = Calendar.DATE;
}else if("W".equals(unit)){ }else if("W".equals(unit)){
field = Calendar.WEEK_OF_MONTH; field = Calendar.WEEK_OF_MONTH;
}else if("Mon".equals(unit)){ }else if("Mon".equals(unit)){
field = Calendar.MONTH; field = Calendar.MONTH;
}else if("Y".equals(unit)){ }else if("Y".equals(unit)){
field = Calendar.YEAR; field = Calendar.YEAR;
} }
if("SUB".equals(operation)){ if("SUB".equals(operation)){
calendar.add(field, -number); calendar.add(field, -number);
}else{ }else{
calendar.add(field, number); calendar.add(field, number);
} }
result = calendar.getTime(); result = calendar.getTime();
return result; return result;
} }
/** /**
* 由出生日期获得年龄 * 由出生日期获得年龄
* @param birthDay * @param birthDay
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static int getAge(Date birthDay){ public static int getAge(Date birthDay){
int age = 0; int age = 0;
if(birthDay == null){ if(birthDay == null){
return 0; return 0;
} }
try{ try{
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) { if (cal.before(birthDay)) {
// throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!"); // throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
return -1; return -1;
} }
int yearNow = cal.get(Calendar.YEAR); int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH); int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay); cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR); int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH); int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
age = yearNow - yearBirth; age = yearNow - yearBirth;
if (monthNow <= monthBirth) { if (monthNow <= monthBirth) {
if (monthNow == monthBirth) { if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth){ if (dayOfMonthNow < dayOfMonthBirth){
age--; age--;
} }
}else{ }else{
age--; age--;
} }
} }
}catch(Exception e){} }catch(Exception e){}
return age; return age;
} }
/** /**
* 根据异常对象获取异常堆栈字符串 * 根据异常对象获取异常堆栈字符串
* @param e * @param e
* @return * @return
*/ */
public static String parseExceptionStack(Exception e){ public static String parseExceptionStack(Exception e){
String exceptionStack = null; String exceptionStack = null;
/*StringBuffer sbf = new StringBuffer(); /*StringBuffer sbf = new StringBuffer();
StackTraceElement[] stack = e.getStackTrace(); StackTraceElement[] stack = e.getStackTrace();
StackTraceElement element = null; StackTraceElement element = null;
String message = e.toString(); String message = e.toString();
sbf.append(message+"\n"); sbf.append(message+"\n");
for(int i=0;i<stack.length;i++){ for(int i=0;i<stack.length;i++){
element = stack[i]; element = stack[i];
String fileName = element.getFileName(); String fileName = element.getFileName();
String methodName = element.getMethodName(); String methodName = element.getMethodName();
String className = element.getClassName(); String className = element.getClassName();
int lineNumber = element.getLineNumber(); int lineNumber = element.getLineNumber();
String append = fileName+":"+lineNumber; String append = fileName+":"+lineNumber;
boolean isNativeMethod = element.isNativeMethod(); boolean isNativeMethod = element.isNativeMethod();
if(isNativeMethod){ if(isNativeMethod){
append = "Native Method"; append = "Native Method";
} }
sbf.append(" at "+className+"."+methodName+"("+append+")\n"); sbf.append(" at "+className+"."+methodName+"("+append+")\n");
} }
exceptionStack = sbf.toString();*/ exceptionStack = sbf.toString();*/
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw); PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw); e.printStackTrace(pw);
exceptionStack = sw.toString(); exceptionStack = sw.toString();
return exceptionStack; return exceptionStack;
} }
public static boolean isValidDate(String source,String pattern) { public static boolean isValidDate(String source,String pattern) {
boolean convertSuccess = true; boolean convertSuccess = true;
if(isNullOrBlank(source)){ if(isNullOrBlank(source)){
return false; return false;
} }
SimpleDateFormat format = new SimpleDateFormat(pattern); SimpleDateFormat format = new SimpleDateFormat(pattern);
try { try {
format.setLenient(false); format.setLenient(false);
format.parse(source); format.parse(source);
}catch(Exception e) { }catch(Exception e) {
convertSuccess=false; convertSuccess=false;
} }
return convertSuccess; return convertSuccess;
} }
public static boolean checkEmail(String email){ public static boolean checkEmail(String email){
return Pattern.matches(EMAIL_REGEX, email.trim()); return Pattern.matches(EMAIL_REGEX, email.trim());
} }
/** /**
* *
* @param area 省份名、城市名、县名 * @param area 省份名、城市名、县名
* @param birthDay 出生日期,格式(19891019) * @param birthDay 出生日期,格式(19891019)
* @param gender 性别(范围:1-9,男:奇数,女:偶数) * @param gender 性别(范围:1-9,男:奇数,女:偶数)
* @param age * @param age
* @return * @return
*/ */
public static String createID(String area,String birthDay,String gender,Integer age){ public static String createID(String area,String birthDay,String gender,Integer age){
String idNo = null; String idNo = null;
String areaCode = null; String areaCode = null;
String seqNo = getRandomNum(2)+""; // (两位)顺序号,格式(00-99) String seqNo = getRandomNum(2)+""; // (两位)顺序号,格式(00-99)
Random random = new Random(); Random random = new Random();
String areaCodeFile = StringUtil.class.getResource("").getPath()+File.separator+"areaCode.txt"; String areaCodeFile = StringUtil.class.getResource("").getPath()+File.separator+"areaCode.txt";
List<String> areaList = readFile(areaCodeFile, "UTF-8"); List<String> areaList = readFile(areaCodeFile, "UTF-8");
if(area == null || "".equals(area)){ if(area == null || "".equals(area)){
String item = areaList.get(random.nextInt(areaList.size()) -1); String item = areaList.get(random.nextInt(areaList.size()) -1);
areaCode = item.split(" ")[0]; areaCode = item.split(" ")[0];
}else{ }else{
for(String item : areaList){ for(String item : areaList){
if(item.contains(area)){ if(item.contains(area)){
areaCode = item.split(" ")[0]; areaCode = item.split(" ")[0];
break; break;
} }
} }
} }
if(areaCode == null){areaCode = "110101";} if(areaCode == null){areaCode = "110101";}
if(birthDay == null || "".equals(birthDay)){ if(birthDay == null || "".equals(birthDay)){
if(age == null || age <= 0){ if(age == null || age <= 0){
int[] arr = new int[]{1,2,3,4}; int[] arr = new int[]{1,2,3,4};
int a = arr[random.nextInt(4)]; int a = arr[random.nextInt(4)];
String ageStr = a+getRandomNum(1); String ageStr = a+getRandomNum(1);
age = Integer.parseInt(ageStr); age = Integer.parseInt(ageStr);
} }
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -age); calendar.add(Calendar.YEAR, -age);
int randomDay = 1+(int)(Math.random()*360); int randomDay = 1+(int)(Math.random()*360);
calendar.add(Calendar.DAY_OF_YEAR, -randomDay); calendar.add(Calendar.DAY_OF_YEAR, -randomDay);
birthDay = dateParseString(calendar.getTime(), "yyyyMMdd"); birthDay = dateParseString(calendar.getTime(), "yyyyMMdd");
} }
if(gender == null || "".equals(gender)){ if(gender == null || "".equals(gender)){
gender = getRandomNum(1)+""; gender = getRandomNum(1)+"";
} }
// 前17位要除以的数:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 // 前17位要除以的数:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
int finalAreaCode = Integer.parseInt(areaCode.substring(0, 1)) * 7 int finalAreaCode = Integer.parseInt(areaCode.substring(0, 1)) * 7
+ Integer.parseInt(areaCode.substring(1, 2)) * 9 + Integer.parseInt(areaCode.substring(1, 2)) * 9
+ Integer.parseInt(areaCode.substring(2, 3)) * 10 + Integer.parseInt(areaCode.substring(2, 3)) * 10
+ Integer.parseInt(areaCode.substring(3, 4)) * 5 + Integer.parseInt(areaCode.substring(3, 4)) * 5
+ Integer.parseInt(areaCode.substring(4, 5)) * 8 + Integer.parseInt(areaCode.substring(4, 5)) * 8
+ Integer.parseInt(areaCode.substring(5, 6)) * 4; + Integer.parseInt(areaCode.substring(5, 6)) * 4;
int finalBirthday = Integer.parseInt(birthDay.substring(0, 1)) * 2 int finalBirthday = Integer.parseInt(birthDay.substring(0, 1)) * 2
+ Integer.parseInt(birthDay.substring(1, 2)) * 1 + Integer.parseInt(birthDay.substring(1, 2)) * 1
+ Integer.parseInt(birthDay.substring(2, 3)) * 6 + Integer.parseInt(birthDay.substring(2, 3)) * 6
+ Integer.parseInt(birthDay.substring(3, 4)) * 3 + Integer.parseInt(birthDay.substring(3, 4)) * 3
+ Integer.parseInt(birthDay.substring(4, 5)) * 7 + Integer.parseInt(birthDay.substring(4, 5)) * 7
+ Integer.parseInt(birthDay.substring(5, 6)) * 9 + Integer.parseInt(birthDay.substring(5, 6)) * 9
+ Integer.parseInt(birthDay.substring(6, 7)) * 10 + Integer.parseInt(birthDay.substring(6, 7)) * 10
+ Integer.parseInt(birthDay.substring(7, 8)) * 5; + Integer.parseInt(birthDay.substring(7, 8)) * 5;
int NoIs = (Integer.parseInt(seqNo.substring(0, 1))) * 8 int NoIs = (Integer.parseInt(seqNo.substring(0, 1))) * 8
+ (Integer.parseInt(seqNo.substring(1, 2))) * 4; + (Integer.parseInt(seqNo.substring(1, 2))) * 4;
int sexNo = (Integer.parseInt(gender.substring(0, 1))) * 2; int sexNo = (Integer.parseInt(gender.substring(0, 1))) * 2;
int checkCode = (finalAreaCode + finalBirthday + NoIs + sexNo) % 11; int checkCode = (finalAreaCode + finalBirthday + NoIs + sexNo) % 11;
int finalCheckCode = 0; int finalCheckCode = 0;
// 余数范围: 0 1 2 3 4 5 6 7 8 9 10 // 余数范围: 0 1 2 3 4 5 6 7 8 9 10
// 余数对应的数:1 0 X 9 8 7 6 5 4 3 2 // 余数对应的数:1 0 X 9 8 7 6 5 4 3 2
// 计算出最终的校验码:finalCheckCode // 计算出最终的校验码:finalCheckCode
switch (checkCode) { switch (checkCode) {
case 0: case 0:
finalCheckCode = 1; finalCheckCode = 1;
break; break;
case 1: case 1:
finalCheckCode = 0; finalCheckCode = 0;
break; break;
case 2: case 2:
finalCheckCode = -3; finalCheckCode = -3;
break; break;
case 3: case 3:
finalCheckCode = 9; finalCheckCode = 9;
break; break;
case 4: case 4:
finalCheckCode = 8; finalCheckCode = 8;
break; break;
case 5: case 5:
finalCheckCode = 7; finalCheckCode = 7;
break; break;
case 6: case 6:
finalCheckCode = 6; finalCheckCode = 6;
break; break;
case 7: case 7:
finalCheckCode = 5; finalCheckCode = 5;
break; break;
case 8: case 8:
finalCheckCode = 4; finalCheckCode = 4;
break; break;
case 9: case 9:
finalCheckCode = 3; finalCheckCode = 3;
break; break;
case 10: case 10:
finalCheckCode = 2; finalCheckCode = 2;
break; break;
default: default:
break; break;
} }
// 区域编号(6位数)+出生日期(8位数)+顺序编号(2位数)+性别号(1位数)+校验码(1位数)=身份证号(18位数) // 区域编号(6位数)+出生日期(8位数)+顺序编号(2位数)+性别号(1位数)+校验码(1位数)=身份证号(18位数)
String checkInd = null; String checkInd = null;
if(finalCheckCode == -3){ if(finalCheckCode == -3){
checkInd = "X"; checkInd = "X";
}else{ }else{
checkInd = finalCheckCode+""; checkInd = finalCheckCode+"";
} }
idNo = areaCode + birthDay + seqNo + gender + checkInd; idNo = areaCode + birthDay + seqNo + gender + checkInd;
return idNo; return idNo;
} }
public static String createMail(){ public static String createMail(){
String mail = getRandomString(5)+"@163.com"; String mail = getRandomString(5)+"@163.com";
return mail; return mail;
} }
public static String createPhoneNo(){ public static String createPhoneNo(){
return "139"+getRandomNum(8); return "139"+getRandomNum(8);
} }
public static String getRandomString(int length) { //length表示生成字符串的长度 public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789"; String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random(); Random random = new Random();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length()); int number = random.nextInt(base.length());
sb.append(base.charAt(number)); sb.append(base.charAt(number));
} }
return sb.toString(); return sb.toString();
} }
public static String getRandomNum(int length) { //length表示生成字符串的长度 public static String getRandomNum(int length) { //length表示生成字符串的长度
String base = "0123456789"; String base = "0123456789";
Random random = new Random(); Random random = new Random();
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length()); int number = random.nextInt(base.length());
sb.append(base.charAt(number)); sb.append(base.charAt(number));
} }
return sb.toString(); return sb.toString();
} }
public static String createName(){ public static String createName(){
Random random=new Random(System.currentTimeMillis()); Random random=new Random(System.currentTimeMillis());
/* 598 百家姓 */ /* 598 百家姓 */
String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许", String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎", "何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷", "鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和", "罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒", "穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟", "屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应", "徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀", "宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山", "羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景", "谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠", "詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却", "蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习", "璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄", "宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空", "阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉", "曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨", "督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼", "哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨", "疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾", "木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正", "闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇", "濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生", "南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门", "梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"}; "毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
int index=random.nextInt(Surname.length-1); int index=random.nextInt(Surname.length-1);
String name = Surname[index]; //获得一个随机的姓氏 String name = Surname[index]; //获得一个随机的姓氏
/* 从常用字中选取一个或两个字作为名 */ /* 从常用字中选取一个或两个字作为名 */
if(random.nextBoolean()){ if(random.nextBoolean()){
name+=getChinese()+getChinese(); name+=getChinese()+getChinese();
}else { }else {
name+=getChinese(); name+=getChinese();
} }
// System.out.println(name); // System.out.println(name);
return name; return name;
} }
public static String getChinese() { public static String getChinese() {
String str = null; String str = null;
int highPos, lowPos; int highPos, lowPos;
Random random = new Random(); Random random = new Random();
highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字 highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字
random=new Random(); random=new Random();
lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列 lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列
byte[] bArr = new byte[2]; byte[] bArr = new byte[2];
bArr[0] = (new Integer(highPos)).byteValue(); bArr[0] = (new Integer(highPos)).byteValue();
bArr[1] = (new Integer(lowPos)).byteValue(); bArr[1] = (new Integer(lowPos)).byteValue();
try { try {
str = new String(bArr, "GB2312"); //区位码组合成汉字 str = new String(bArr, "GB2312"); //区位码组合成汉字
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
return str; return str;
} }
public static void main(String[] args){ public static void main(String[] args){
// String idNo = createID("南部县", "19940929", "1", null); // String idNo = createID("南部县", "19940929", "1", null);
String idNo = createID("长丰县", null, "1", 31); String idNo = createID("长丰县", null, "1", 31);
System.out.println(idNo); System.out.println(idNo);
System.out.println(IDcardValidator.isIdcardValid(idNo)); System.out.println(IDcardValidator.isIdcardValid(idNo));
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static String currentIP(){ public static String currentIP(){
String currentIP = null; String currentIP = null;
try { try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null; InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()){ while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//System.out.println(netInterface.getName()); //System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses(); Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){ while (addresses.hasMoreElements()){
ip = (InetAddress) addresses.nextElement(); ip = (InetAddress) addresses.nextElement();
if(ip != null && ip instanceof Inet4Address){ if(ip != null && ip instanceof Inet4Address){
if(currentIP == null){ if(currentIP == null){
currentIP = ""; currentIP = "";
} }
currentIP += ip.getHostAddress()+";"; currentIP += ip.getHostAddress()+";";
// System.out.println("本机的IP = " + currentIP); // System.out.println("本机的IP = " + currentIP);
} }
if(ip != null && ip instanceof Inet6Address){ if(ip != null && ip instanceof Inet6Address){
if(currentIP == null){ if(currentIP == null){
currentIP = ""; currentIP = "";
} }
currentIP += ip.getHostAddress()+":"; currentIP += ip.getHostAddress()+":";
} }
} }
} }
} catch (SocketException e) { } catch (SocketException e) {
e.printStackTrace(); e.printStackTrace();
} }
return currentIP; return currentIP;
} }
/** /**
* 获取HttpServletRequest请求IP * 获取HttpServletRequest请求IP
* @param request * @param request
* @return * @return
*/ */
/*public static String getIpAddress(HttpServletRequest request) { /*public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for"); String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP"); ip = request.getHeader("Proxy-Client-IP");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP"); ip = request.getHeader("WL-Proxy-Client-IP");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP"); ip = request.getHeader("HTTP_CLIENT_IP");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR"); ip = request.getHeader("HTTP_X_FORWARDED_FOR");
} }
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr(); ip = request.getRemoteAddr();
} }
return ip; return ip;
}*/ }*/
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public static void simpleObjectCopy(Object source,Object target){ public static void simpleObjectCopy(Object source,Object target){
if(source == null || target == null){ return; } if(source == null || target == null){ return; }
try { try {
Method[] sourceMethods = source.getClass().getDeclaredMethods(); Method[] sourceMethods = source.getClass().getDeclaredMethods();
for(Method smethod : sourceMethods){ for(Method smethod : sourceMethods){
Class returnType = smethod.getReturnType(); Class returnType = smethod.getReturnType();
String sourceMethodName = smethod.getName(); String sourceMethodName = smethod.getName();
if(!returnType.getTypeName().equals("void") && sourceMethodName.startsWith("get")){ if(!returnType.getTypeName().equals("void") && sourceMethodName.startsWith("get")){
Object[] paramArr = null; Object[] paramArr = null;
Object getValue = smethod.invoke(source,paramArr); Object getValue = smethod.invoke(source,paramArr);
if(getValue != null){ if(getValue != null){
// System.out.println("--------------in simpleObjectCopy returnType : "+returnType.getTypeName()+" sourceMethodName="+sourceMethodName); // System.out.println("--------------in simpleObjectCopy returnType : "+returnType.getTypeName()+" sourceMethodName="+sourceMethodName);
Method[] targetMethods = target.getClass().getDeclaredMethods(); Method[] targetMethods = target.getClass().getDeclaredMethods();
for(Method tmethod : targetMethods){ for(Method tmethod : targetMethods){
String targetMethodName = tmethod.getName(); String targetMethodName = tmethod.getName();
if(targetMethodName.equals("set"+sourceMethodName.substring(3))){ if(targetMethodName.equals("set"+sourceMethodName.substring(3))){
Class[] parameterTypes = tmethod.getParameterTypes(); Class[] parameterTypes = tmethod.getParameterTypes();
if(parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].getTypeName().equals(returnType.getTypeName())){ if(parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].getTypeName().equals(returnType.getTypeName())){
// System.out.println("--------------in simpleObjectCopy targetMethodName:"+targetMethodName); // System.out.println("--------------in simpleObjectCopy targetMethodName:"+targetMethodName);
tmethod.invoke(target,getValue); tmethod.invoke(target,getValue);
}//set value }//set value
break; break;
}//set }//set
}//for targetMethod }//for targetMethod
}//get value != null }//get value != null
}//get }//get
}//for sourceMethod }//for sourceMethod
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static String getInputStreamContent(InputStream inputStream,String charset)throws Exception{ public static String getInputStreamContent(InputStream inputStream,String charset)throws Exception{
String content = null; String content = null;
if(inputStream == null){ if(inputStream == null){
return null; return null;
} }
if(charset == null ){ if(charset == null ){
charset = "UTF-8"; charset = "UTF-8";
} }
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,charset));// 为了进行一行读取操作 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,charset));// 为了进行一行读取操作
StringBuilder buffer = new StringBuilder(); StringBuilder buffer = new StringBuilder();
String line = ""; String line = "";
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
buffer.append(line); buffer.append(line);
} }
content = buffer.toString(); content = buffer.toString();
return content; return content;
} }
public static List<String> readFile(String fileName,String encoding){ public static List<String> readFile(String fileName,String encoding){
List<String> contents = new ArrayList<String>(); List<String> contents = new ArrayList<String>();
File file = new File(fileName); File file = new File(fileName);
FileInputStream fi = null; FileInputStream fi = null;
InputStreamReader ir = null; InputStreamReader ir = null;
BufferedReader br = null; BufferedReader br = null;
try { try {
fi = new FileInputStream(file); fi = new FileInputStream(file);
ir = new InputStreamReader(fi,encoding); ir = new InputStreamReader(fi,encoding);
br = new BufferedReader(ir); br = new BufferedReader(ir);
while(br.ready()){ while(br.ready()){
String line = br.readLine(); String line = br.readLine();
contents.add(line); contents.add(line);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally{ } finally{
try { try {
fi.close(); fi.close();
ir.close(); ir.close();
br.close(); br.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return contents; return contents;
} }
public static void writeFile(List<String> contents,String fileName,boolean appending,String encoding){ public static void writeFile(List<String> contents,String fileName,boolean appending,String encoding){
File file = new File(fileName); File file = new File(fileName);
FileOutputStream fo = null; FileOutputStream fo = null;
OutputStreamWriter or = null; OutputStreamWriter or = null;
BufferedWriter bw = null; BufferedWriter bw = null;
try { try {
fo = new FileOutputStream(file,appending); fo = new FileOutputStream(file,appending);
or = new OutputStreamWriter(fo,encoding); or = new OutputStreamWriter(fo,encoding);
bw = new BufferedWriter(or); bw = new BufferedWriter(or);
for(String line : contents){ for(String line : contents){
bw.write(line); bw.write(line);
bw.newLine(); bw.newLine();
} }
bw.flush(); bw.flush();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally{ } finally{
try { try {
fo.close(); fo.close();
or.close(); or.close();
bw.close(); bw.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
/** /**
* 判断是否是数字 * 判断是否是数字
*/ */
private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]*"); private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]*");
public static boolean isNumeric(String str){ public static boolean isNumeric(String str){
// Pattern pattern = Pattern.compile("[0-9]*"); // Pattern pattern = Pattern.compile("[0-9]*");
// Matcher isNum = pattern.matcher(str); // Matcher isNum = pattern.matcher(str);
Matcher numMatcher = NUMBER_PATTERN.matcher(str); Matcher numMatcher = NUMBER_PATTERN.matcher(str);
if( !numMatcher.matches() ){ if( !numMatcher.matches() ){
return false; return false;
} }
return true; return true;
} }
// 根据Unicode编码完美的判断中文汉字和符号 // 根据Unicode编码完美的判断中文汉字和符号
public static boolean isChinese(char c) { public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
return true; return true;
} }
return false; return false;
} }
public static Double calcuPersonalTAX(Double amount){ public static Double calcuPersonalTAX(Double amount){
Double tax = 0d; Double tax = 0d;
if(amount <= 800){ if(amount <= 800){
tax = 0.0d; tax = 0.0d;
}else if(800 < amount && amount <= 4000){ }else if(800 < amount && amount <= 4000){
tax = (amount - 800 ) * 0.2 ; tax = (amount - 800 ) * 0.2 ;
}else if(4000 < amount && amount <= 25000){ }else if(4000 < amount && amount <= 25000){
tax = amount * (1-0.2) * 0.2 ; tax = amount * (1-0.2) * 0.2 ;
}else if(25000 < amount && amount <= 62500){ }else if(25000 < amount && amount <= 62500){
tax = amount * (1-0.2) * 0.3 -2000 ; tax = amount * (1-0.2) * 0.3 -2000 ;
}else if(62500 < amount){ }else if(62500 < amount){
tax = amount * (1-0.2) * 0.4 - 7000 ; tax = amount * (1-0.2) * 0.4 - 7000 ;
} }
return tax; return tax;
} }
/** /**
* 判断字符串中是否含有数字 * 判断字符串中是否含有数字
* @param content * @param content
* @return * @return
*/ */
public static boolean hasDigit(String content) { public static boolean hasDigit(String content) {
boolean flag = false; boolean flag = false;
Pattern pattern = Pattern.compile(".*\\d+.*"); Pattern pattern = Pattern.compile(".*\\d+.*");
Matcher m = pattern.matcher(content); Matcher m = pattern.matcher(content);
if (m.matches()) { if (m.matches()) {
flag = true; flag = true;
} }
return flag; return flag;
} }
} }
\ No newline at end of file
package com.ajb.common.utils.string; package com.ajb.common.utils.string;
import java.io.StringReader; import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Collection; import java.util.Collection;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller; import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.io.OutputFormat; import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader; import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; import org.dom4j.io.XMLWriter;
//import org.apache.commons.lang.StringUtils; //import org.apache.commons.lang.StringUtils;
/** /**
* 使用Jaxb2.0实现XML<->Java Object的Binder. * 使用Jaxb2.0实现XML<->Java Object的Binder.
* *
* 特别支持Root对象是List的情形. * 特别支持Root对象是List的情形.
* *
* @author * @author
*/ */
public class XmlUtil { public class XmlUtil {
// 多线程安全的Context. // 多线程安全的Context.
private JAXBContext jaxbContext; private JAXBContext jaxbContext;
/** /**
* @param types * @param types
* 所有需要序列化的Root对象的类型. * 所有需要序列化的Root对象的类型.
*/ */
public XmlUtil(Class<?>... types) { public XmlUtil(Class<?>... types) {
try { try {
jaxbContext = JAXBContext.newInstance(types); jaxbContext = JAXBContext.newInstance(types);
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Java Object->Xml. * Java Object->Xml.
*/ */
public String toXml(Object root, String encoding) { public String toXml(Object root, String encoding) {
try { try {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(root, writer); createMarshaller(encoding).marshal(root, writer);
return writer.toString(); return writer.toString();
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* Java Object->Xml, 特别支持对Root Element是Collection的情形. * Java Object->Xml, 特别支持对Root Element是Collection的情形.
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public String toXml(Collection root, String rootName, String encoding) { public String toXml(Collection root, String rootName, String encoding) {
try { try {
CollectionWrapper wrapper = new CollectionWrapper(); CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection = root; wrapper.collection = root;
JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>( JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(
new QName(rootName), CollectionWrapper.class, wrapper); new QName(rootName), CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(wrapperElement, writer); createMarshaller(encoding).marshal(wrapperElement, writer);
return writer.toString(); return writer.toString();
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* Xml->Java Object. * Xml->Java Object.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T fromXml(String xml) { public <T> T fromXml(String xml) {
if(xml == null || "".equals(xml.trim())){ if(xml == null || "".equals(xml.trim())){
return null; return null;
} }
try { try {
StringReader reader = new StringReader(xml); StringReader reader = new StringReader(xml);
return (T) createUnmarshaller().unmarshal(reader); return (T) createUnmarshaller().unmarshal(reader);
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* Xml->Java Object, 支持大小写敏感或不敏感. * Xml->Java Object, 支持大小写敏感或不敏感.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T fromXml(String xml, boolean caseSensitive) { public <T> T fromXml(String xml, boolean caseSensitive) {
try { try {
String fromXml = xml; String fromXml = xml;
if (!caseSensitive){ if (!caseSensitive){
fromXml = xml.toLowerCase(); fromXml = xml.toLowerCase();
} }
StringReader reader = new StringReader(fromXml); StringReader reader = new StringReader(fromXml);
return (T) createUnmarshaller().unmarshal(reader); return (T) createUnmarshaller().unmarshal(reader);
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* 创建Marshaller, 设定encoding(可为Null). * 创建Marshaller, 设定encoding(可为Null).
*/ */
public Marshaller createMarshaller(String encoding) { public Marshaller createMarshaller(String encoding) {
try { try {
Marshaller marshaller = jaxbContext.createMarshaller(); Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// if (StringUtils.isNotBlank(encoding)) { // if (StringUtils.isNotBlank(encoding)) {
if(encoding != null && !"".equals(encoding.trim())){ if(encoding != null && !"".equals(encoding.trim())){
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
} }
return marshaller; return marshaller;
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* 创建UnMarshaller. * 创建UnMarshaller.
*/ */
public Unmarshaller createUnmarshaller() { public Unmarshaller createUnmarshaller() {
try { try {
return jaxbContext.createUnmarshaller(); return jaxbContext.createUnmarshaller();
} catch (JAXBException e) { } catch (JAXBException e) {
// throw new RuntimeException(e); // throw new RuntimeException(e);
return null; return null;
} }
} }
/** /**
* 封装Root Element 是 Collection的情况. * 封装Root Element 是 Collection的情况.
*/ */
public static class CollectionWrapper { public static class CollectionWrapper {
// @SuppressWarnings("unchecked") // @SuppressWarnings("unchecked")
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@XmlAnyElement @XmlAnyElement
protected Collection collection; protected Collection collection;
} }
public static String getNodeValue(String xml,String nodeName){ public static String getNodeValue(String xml,String nodeName){
String nodeValue = null; String nodeValue = null;
if(xml != null && xml.length() > 0){ if(xml != null && xml.length() > 0){
String head = "<"+nodeName+">"; String head = "<"+nodeName+">";
String tail = "</"+nodeName+">"; String tail = "</"+nodeName+">";
if(xml.contains(head) && xml.contains(tail)){ if(xml.contains(head) && xml.contains(tail)){
int beginIndex = xml.indexOf(head)+head.length(); int beginIndex = xml.indexOf(head)+head.length();
int endIndex = xml.indexOf(tail); int endIndex = xml.indexOf(tail);
nodeValue = xml.substring(beginIndex, endIndex); nodeValue = xml.substring(beginIndex, endIndex);
if(nodeValue != null && nodeValue.length() >0){ if(nodeValue != null && nodeValue.length() >0){
if(nodeValue.startsWith("<![CDATA[") && nodeValue.endsWith("]]>")){ if(nodeValue.startsWith("<![CDATA[") && nodeValue.endsWith("]]>")){
nodeValue = nodeValue.substring(9, nodeValue.length()-3); nodeValue = nodeValue.substring(9, nodeValue.length()-3);
} }
} }
} }
} }
return nodeValue; return nodeValue;
} }
public static String format(String str) { public static String format(String str) {
if(str == null || "".equals(str.trim())){ if(str == null || "".equals(str.trim())){
return null; return null;
} }
String formatXml = str; String formatXml = str;
try{ try{
SAXReader reader = new SAXReader(); SAXReader reader = new SAXReader();
// System.out.println(reader); // System.out.println(reader);
// 注释:创建一个串的字符输入流 // 注释:创建一个串的字符输入流
StringReader in = new StringReader(str); StringReader in = new StringReader(str);
Document doc = reader.read(in); Document doc = reader.read(in);
// System.out.println(doc.getRootElement()); // System.out.println(doc.getRootElement());
// 注释:创建输出格式 // 注释:创建输出格式
OutputFormat formater = OutputFormat.createPrettyPrint(); OutputFormat formater = OutputFormat.createPrettyPrint();
//formater=OutputFormat.createCompactFormat(); //formater=OutputFormat.createCompactFormat();
// 注释:设置xml的输出编码 // 注释:设置xml的输出编码
formater.setEncoding("utf-8"); formater.setEncoding("utf-8");
// 注释:创建输出(目标) // 注释:创建输出(目标)
StringWriter out = new StringWriter(); StringWriter out = new StringWriter();
// 注释:创建输出流 // 注释:创建输出流
XMLWriter writer = new XMLWriter(out, formater); XMLWriter writer = new XMLWriter(out, formater);
// 注释:输出格式化的串到目标中,执行后。格式化后的串保存在out中。 // 注释:输出格式化的串到目标中,执行后。格式化后的串保存在out中。
writer.write(doc); writer.write(doc);
writer.close(); writer.close();
// System.out.println(out.toString()); // System.out.println(out.toString());
// 注释:返回我们格式化后的结果 // 注释:返回我们格式化后的结果
formatXml = out.toString(); formatXml = out.toString();
}catch(Exception e){ }catch(Exception e){
e.printStackTrace(); e.printStackTrace();
} }
return formatXml; return formatXml;
} }
public static void main(String[] args){ public static void main(String[] args){
String xml = "" String xml = ""
+"<xml><return_code><![CDATA[SUCCESS]]></return_code>" +"<xml><return_code><![CDATA[SUCCESS]]></return_code>"
+"<return_msg><![CDATA[OK]]></return_msg>" +"<return_msg><![CDATA[OK]]></return_msg>"
+"<appid><![CDATA[wx350e0551f15c891d]]></appid>" +"<appid><![CDATA[wx350e0551f15c891d]]></appid>"
+"<mch_id><![CDATA[1467966602]]></mch_id>" +"<mch_id><![CDATA[1467966602]]></mch_id>"
+"<nonce_str><![CDATA[sIKggVGaBFGavGlA]]></nonce_str>" +"<nonce_str><![CDATA[sIKggVGaBFGavGlA]]></nonce_str>"
+"<sign><![CDATA[845C8A7FF9A0D456DB2E7C8D68B1CAD3]]></sign>" +"<sign><![CDATA[845C8A7FF9A0D456DB2E7C8D68B1CAD3]]></sign>"
+"<result_code><![CDATA[SUCCESS]]></result_code>" +"<result_code><![CDATA[SUCCESS]]></result_code>"
+"<prepay_id><![CDATA[wx20170509102930c05e819bdf0584738530]]></prepay_id>" +"<prepay_id><![CDATA[wx20170509102930c05e819bdf0584738530]]></prepay_id>"
+"<trade_type><![CDATA[NATIVE]]></trade_type>" +"<trade_type><![CDATA[NATIVE]]></trade_type>"
+"<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=FrUICJf]]></code_url>" +"<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=FrUICJf]]></code_url>"
+"</xml>"; +"</xml>";
String nodeName = "result_code";// "return_code"; String nodeName = "result_code";// "return_code";
String nodeValue = null; String nodeValue = null;
if(xml != null && xml.length() > 0){ if(xml != null && xml.length() > 0){
String head = "<"+nodeName+">"; String head = "<"+nodeName+">";
String tail = "</"+nodeName+">"; String tail = "</"+nodeName+">";
if(xml.contains(head) && xml.contains(tail)){ if(xml.contains(head) && xml.contains(tail)){
int beginIndex = xml.indexOf(head)+head.length(); int beginIndex = xml.indexOf(head)+head.length();
int endIndex = xml.indexOf(tail); int endIndex = xml.indexOf(tail);
nodeValue = xml.substring(beginIndex, endIndex); nodeValue = xml.substring(beginIndex, endIndex);
if(nodeValue != null && nodeValue.length() >0){ if(nodeValue != null && nodeValue.length() >0){
if(nodeValue.startsWith("<![CDATA[") && nodeValue.endsWith("]]>")){ if(nodeValue.startsWith("<![CDATA[") && nodeValue.endsWith("]]>")){
nodeValue = nodeValue.substring(9, nodeValue.length()-3); nodeValue = nodeValue.substring(9, nodeValue.length()-3);
} }
} }
} }
} }
System.out.println(nodeValue); System.out.println(nodeValue);
} }
} }
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; ...@@ -5,6 +5,9 @@ import java.math.BigDecimal;
import com.ajb.car.vo.common.CommonResult; import com.ajb.car.vo.common.CommonResult;
public class QuotationResponse { public class QuotationResponse {
private String errorCode;//错误代码,E01-入参校验不通过,E02-重复投保,S01-保存失败
private String errorMessage;//错误信息
private Integer total = 0; private Integer total = 0;
private BigDecimal totalPremium = new BigDecimal(0); private BigDecimal totalPremium = new BigDecimal(0);
private BigDecimal bzPremium = new BigDecimal(0); private BigDecimal bzPremium = new BigDecimal(0);
...@@ -69,4 +72,20 @@ public class QuotationResponse { ...@@ -69,4 +72,20 @@ public class QuotationResponse {
this.bzPremium = bzPremium; 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