Commit f81fa805 authored by liwenbin's avatar liwenbin

资产入库

parent 115bc0dd
......@@ -121,6 +121,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
......
package com.quantgroup.asset.distribution.config.http;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @author renfeng
* @version v1.0
* @date: 2017年5月8日 下午12:21:48
*/
@Configuration
public class HttpClientConfig {
@Bean(name = "httpClient")
public CloseableHttpClient httpClient() throws NoSuchAlgorithmException, KeyManagementException {
/**
* 忽略证书
*/
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
/**
* 创建TrustManager
*/
X509TrustManager xtm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, ignoreHostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslsf)
.build();
// connection manager
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(10000);
connectionManager.setDefaultMaxPerRoute(1000);
HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException arg0, int retryTimes, HttpContext arg2) {
if (retryTimes >= 2)
return false;
if (arg0 instanceof UnknownHostException || arg0 instanceof ConnectTimeoutException
|| !(arg0 instanceof SSLException) || arg0 instanceof SocketTimeoutException)
return true;
HttpClientContext clientContext = HttpClientContext.adapt(arg2);
HttpRequest request = clientContext.getRequest();
if (!(request instanceof HttpEntityEnclosingRequest)) // 如果请求被认为是幂等的,那么就重试。即重复执行不影响程序其他效果的
return true;
return false;
}
};
// keep alive strategy
ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy();
// httpclient
return HttpClients.custom()
.setConnectionManager(connectionManager)
.setRetryHandler(retryHandler)
.setKeepAliveStrategy(keepAliveStrategy)
.build();
}
}
package com.quantgroup.asset.distribution.config.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.quantgroup.asset.distribution.config.web.interceptor.AuthorityInterceptor;
/**
*
* @author liwenbin
......@@ -13,11 +16,16 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration
public class WebMvcConfigure extends WebMvcConfigurerAdapter {
@Autowired
private AuthorityInterceptor authorityInterceptor;
/**
* 添加拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorityInterceptor)
.addPathPatterns("/biz/**");
}
@Override
......@@ -26,6 +34,7 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter {
.allowedOrigins("*")
.allowedMethods("HEAD", "GET", "POST")
.allowedHeaders("X-Auth-Token", "Origin", "No-Cache", "X-Requested-With", "If-Modified-Since", "Pragma", "Last-Modified", "Cache-Control", "Expires", "Content-Type", "Authorization")
.allowCredentials(true).maxAge(3600);
.allowCredentials(true)
.maxAge(3600);
}
}
\ No newline at end of file
package com.quantgroup.asset.distribution.config.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.quantgroup.asset.distribution.enums.response.AuthorityResponse;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.IAuthorityService;
import com.quantgroup.asset.distribution.service.jpa.entity.AuthorityConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAuthorityRepository;
import lombok.extern.slf4j.Slf4j;
/**
* 权限认证
* @author liwenbin
*
*/
@Slf4j
@Component
public class AuthorityInterceptor implements HandlerInterceptor{
@Autowired
private IAuthorityService authorityService;
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
GlobalResponse globalResponse = authoriity(request);
if(globalResponse!=null){
log.info("系统校验失败,原因 : {} ",globalResponse.getMsg());
globalResponse.writeJson(response);
return false;
}
return true;
}
/**
* 权限验证
* @param request
* @return
*/
private GlobalResponse authoriity(HttpServletRequest request) {
String key = request.getHeader("as_auth_key");
if (StringUtils.isEmpty(key)) { return GlobalResponse.create(AuthorityResponse.AS_AUTH_KEY_IS_EMPTY); }
String pass = request.getHeader("as_auth_pass");
if (StringUtils.isEmpty(pass)) { return GlobalResponse.create(AuthorityResponse.AS_AUTH_PASS_IS_EMPTY); }
AuthorityConfig authorityConfig = authorityService.findByAuthKeyAndAuthPass(key, pass);
if (authorityConfig == null) { return GlobalResponse.create(AuthorityResponse.AS_AUTH_KEY_AND_PASS_IS_NOT_EXIST); }
return null;
}
}
package com.quantgroup.asset.distribution.controller;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Stopwatch;
import com.quantgroup.asset.distribution.enums.response.AssetResponse;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.IAssetService;
import com.quantgroup.asset.distribution.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
/**
* 资产入库Controller
* @author liwenbin
*
*/
@RestController
@Slf4j
@RequestMapping("/biz")
public class AssetController {
@Autowired
private IAssetService assetService;
@RequestMapping("/asset_in")
public GlobalResponse assetsIn(AssetForm assetForm) {
Stopwatch stopwatch = Stopwatch.createStarted();
assetForm.setAssetNo(UUIDUtil.getAssetNo());
log.info("资产入库开始, assetForm : {}", JSON.toJSONString(assetForm));
GlobalResponse response = assetService.checkAssetForm(assetForm);
assetService.assetsIn(assetForm);
log.info("资产入库结束, assetForm : {}, response : {}, 耗时 : {}", JSON.toJSONString(assetForm), JSON.toJSONString(response), stopwatch.stop().elapsed(TimeUnit.MILLISECONDS));
return response;
}
}
package com.quantgroup.asset.distribution.enums.response;
import lombok.Getter;
/**
* 资产系统返回值
* @author liwenbin
*
*/
public enum AssetResponse implements GlobalResponseEnum{
ASSET_FORM_IS_ERROR(2001, "资产入库参数错误!");
@Getter
private int code;
@Getter
private String businessCode;
@Getter
private String msg;
@Getter
private Object body;
AssetResponse(int code, String msg) {
this.code = code;
this.businessCode = null;
this.msg = msg;
this.body = null;
}
AssetResponse(int code, String businessCode, String msg) {
this.code = code;
this.businessCode = businessCode;
this.msg = msg;
}
}
package com.quantgroup.asset.distribution.enums.response;
import lombok.Getter;
/**
* 权限认证返回错误信息
* 102X
* @author liwenbin
*
*/
public enum AuthorityResponse implements GlobalResponseEnum{
AS_AUTH_KEY_IS_EMPTY(1021, "as_auth_key不能为空"),
AS_AUTH_PASS_IS_EMPTY(1022, "as_auth_pass不能为空"),
AS_AUTH_KEY_AND_PASS_IS_NOT_EXIST(1023, "权限认证失败, 请检查!");
@Getter
private int code;
@Getter
private String businessCode;
@Getter
private String msg;
@Getter
private Object body;
AuthorityResponse(int code, String msg) {
this.code = code;
this.businessCode = null;
this.msg = msg;
this.body = null;
}
AuthorityResponse(int code, String businessCode, String msg) {
this.code = code;
this.businessCode = businessCode;
this.msg = msg;
}
}
package com.quantgroup.asset.distribution.enums.response;
public interface GlobalResponseEnum {
public int getCode();
public String getBusinessCode();
public String getMsg();
public Object getBody();
}
package com.quantgroup.asset.distribution.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
/**
* 全局异常捕获
*
* @author liwenbin
*
*/
@ControllerAdvice({ "com.quantgroup.asset.distribution" })
@Slf4j
public class GlobalControllerHandler {
// 定义全局异常处理,value属性可以过滤拦截条件,此处拦截所有的Exception
@ExceptionHandler(value = Exception.class)
@ResponseBody
public GlobalResponse exception(Exception ex, WebRequest request) {
log.error("系统出现异常, ", ex);
return new GlobalResponse(QGException.wrap(ex));
}
}
/*
* Copyright 2014-present Miyou tech inc. All Rights Reserved.
*/
package com.quantgroup.asset.distribution.exception;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.quantgroup.asset.distribution.exception.QGExceptionType.COMMON_SERVER_ERROR;
import static com.quantgroup.asset.distribution.exception.QGExceptionType.COMMON_THIRD_PARTY_TIMEOUT;
import java.net.SocketTimeoutException;
import java.util.Arrays;
public class QGException extends RuntimeException {
private static final Logger LOGGER = LoggerFactory.getLogger(QGException.class);
public QGExceptionType qgExceptionType;
public boolean isToastFormat = false;
public String detail;
public QGException(String detail, QGExceptionType qgExceptionType, Object... args) {
super(detail);
try {
if (StringUtils.isNoneBlank(qgExceptionType.frontEndToastTemplate)) {
isToastFormat = true;
initException(String.format(qgExceptionType.frontEndToastTemplate, args), qgExceptionType);
} else {
initException(qgExceptionType);
}
} catch (Exception e) {
LOGGER.error("format front end toast err, " + qgExceptionType + ", args: " + Arrays.toString(args), e);
initException(COMMON_SERVER_ERROR);
}
}
public QGException(QGExceptionType qgExceptionType, Object... args) {
super(qgExceptionType.text);
try {
if (StringUtils.isNoneBlank(qgExceptionType.frontEndToastTemplate)) {
isToastFormat = true;
initException(String.format(qgExceptionType.frontEndToastTemplate, args), qgExceptionType);
} else {
initException(qgExceptionType);
}
} catch (Exception e) {
LOGGER.error("format front end toast err, " + qgExceptionType + ", args: " + Arrays.toString(args), e);
initException(COMMON_SERVER_ERROR);
}
}
public QGException(String detail, Throwable cause, QGExceptionType qgExceptionType) {
super(detail, cause);
this.initException(detail, qgExceptionType);
}
public QGException(String detail, QGExceptionType qgExceptionType) {
super(detail);
initException(detail, qgExceptionType);
}
public QGException(QGExceptionType qgExceptionType) {
super(qgExceptionType.text);
initException(qgExceptionType);
}
public QGException(Throwable cause, QGExceptionType qgExceptionType, Object... args) {
super(qgExceptionType.text, cause);
try {
if (StringUtils.isNoneBlank(qgExceptionType.frontEndToastTemplate)) {
isToastFormat = true;
initException(String.format(qgExceptionType.frontEndToastTemplate, args), qgExceptionType);
} else {
initException(qgExceptionType);
}
} catch (Exception e) {
LOGGER.error("format front end toast err, " + qgExceptionType + ", args: " + Arrays.toString(args), e);
initException(COMMON_SERVER_ERROR);
}
}
public static QGException wrap(Throwable e) {
return wrap(e, COMMON_SERVER_ERROR);
}
public static QGException wrap(Throwable e, QGExceptionType exceptionType) {
if (e instanceof QGException) {
return (QGException) e;
}
if (e instanceof SocketTimeoutException)
return new QGException(COMMON_THIRD_PARTY_TIMEOUT);
return new QGException(e, exceptionType);
}
public static QGException wrap(Throwable e, QGExceptionType exceptionType, Object... args) {
if (e instanceof QGException) {
return (QGException) e;
}
if (e instanceof SocketTimeoutException)
return new QGException(COMMON_THIRD_PARTY_TIMEOUT);
return new QGException(e, exceptionType, args);
}
private void initException(QGExceptionType QGExceptionType) {
this.initException(QGExceptionType.text, QGExceptionType);
}
private void initException(String detail, QGExceptionType QGExceptionType) {
this.qgExceptionType = QGExceptionType;
this.detail = detail;
}
}
\ No newline at end of file
/*
* Copyright 2014-present Miyou tech inc. All Rights Reserved.
*/
package com.quantgroup.asset.distribution.exception;
import lombok.extern.slf4j.Slf4j;
/**
* 系统使用Exception来进行Error Code处理。如果LogType为Error,
* 代表这种Error不应该返回给客户端,应该统一打印出服务器端错误;
* 如果是WARNING的话,就将对应的Exception Text返回给客户端。
*/
@Slf4j
public enum QGExceptionType {
COMMON_SERVER_ERROR(1001, "系统异常,请稍后再试"),
COMMON_ILLEGAL_STATE(1002, "断言错误"),
COMMON_ILLEGAL_PARAM_TOAST(1003, "参数异常", "%s"),
COMMON_AUTH_ERROR(1004, "系统异常,请稍后再试"),
COMMON_ILLEGAL_PARAM(1010, "参数异常"),
COMMON_THIRD_PARTY_TIMEOUT(1011, "第三方服务超时"),
ASSET_IN_CODE_ERROR(2001, "资产入库code异常! uuid : %s, bizNo : %s, code : %s"),
GET_DEC_ATTRIBUTE_VALUE_ERROR(2002, "获取决策资产属性值异常, uuid : %s, keys : %s");
public int code;
public String text;
public String frontEndToastTemplate;
QGExceptionType(int code, String text) {
this.code = code;
this.text = text;
this.frontEndToastTemplate = text;
}
QGExceptionType(int code, String text, String frontEndToastTemplate) {
this.code = code;
this.text = text;
this.frontEndToastTemplate = frontEndToastTemplate;
}
public static QGExceptionType fromCode(int code) {
for (QGExceptionType exceptionType : QGExceptionType.values()) {
if (exceptionType.code == code) {
return exceptionType;
}
}
return null;
}
@Override
public String toString() {
return "error_code: " + code + ", text: " + text + ", frontEndToastTemplate: " + frontEndToastTemplate;
}
}
package com.quantgroup.asset.distribution.exception;
public class QGPreconditions {
private QGPreconditions() {
}
public static void checkArgument(boolean expression) {
checkArgument(expression, QGExceptionType.COMMON_ILLEGAL_PARAM);
}
public static void checkArgument(boolean expression, Object errorMessage) {
checkArgument(expression, QGExceptionType.COMMON_ILLEGAL_PARAM, errorMessage);
}
public static void checkArgument(boolean expression,
String errorMessageTemplate, Object... errorMessageArgs) {
checkArgument(expression, QGExceptionType.COMMON_ILLEGAL_PARAM, errorMessageTemplate, errorMessageArgs);
}
public static void checkArgument(boolean expression, QGExceptionType exceptionType) {
if (!expression) {
throw new QGException(exceptionType);
}
}
public static void checkArgument(boolean expression, QGExceptionType exceptionType, Object... errorMessage) {
if (!expression) {
throw new QGException(exceptionType, errorMessage);
}
}
}
package com.quantgroup.asset.distribution.model.form;
import java.io.Serializable;
import com.quantgroup.asset.distribution.service.jpa.entity.Asset;
import lombok.Data;
@Data
public class AssetForm implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String code;
private String msg;
private String uuid;
private String bizChannel;
private String bizNo;
private String bizType;
private String auditResult;
private String amount;
private String deadLine;
private String exData;
private String otherInformation;
private String financeProducts;
private String assetNo;
public Asset transToAsset() {
Asset asset = new Asset();
asset.setAssetNo(this.assetNo);
asset.setBizNo(this.bizNo);
asset.setUuid(this.uuid);
asset.setBizChannel(this.bizChannel);
asset.setFinanceProductType("0".equals(this.bizType) ? 0 : 1);
asset.setAuditResult("true".equals(auditResult) ? 1 : 0);
return asset;
}
}
package com.quantgroup.asset.distribution.model.response;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.quantgroup.asset.distribution.enums.response.GlobalResponseEnum;
import com.quantgroup.asset.distribution.exception.QGException;
import com.quantgroup.asset.distribution.exception.QGExceptionType;
import lombok.Data;
@Data
public class GlobalResponse {
private static final String JSON_CONTENT_TYPE = "application/json;charset=UTF-8";
private int code;
private String businessCode;
private String msg;
private Object body;
public GlobalResponse() {
}
private GlobalResponse(Object object) {
body = object;
code = 0;
msg = "";
}
private GlobalResponse(int code, String msg, Object object) {
this.body = object;
this.code = code;
this.msg = msg;
}
private GlobalResponse(int code, String businessCode, String msg, Object object) {
this.code = code;
this.businessCode = businessCode;
this.msg = msg;
this.body = object;
}
public static GlobalResponse success() {
return new GlobalResponse(0, "success", null);
}
public static GlobalResponse success(Object data) {
return new GlobalResponse(0, "success", data);
}
public static GlobalResponse create(String businessCode, String msg, Object object) {
return new GlobalResponse(0, businessCode, msg, object);
}
public static GlobalResponse create(GlobalResponseEnum responseEnum) {
return new GlobalResponse(responseEnum.getCode(), responseEnum.getBusinessCode(), responseEnum.getMsg(), responseEnum.getBody());
}
public static GlobalResponse create(GlobalResponseEnum responseEnum, Object object) {
return new GlobalResponse(responseEnum.getCode(), responseEnum.getBusinessCode(), responseEnum.getMsg(), object);
}
public static GlobalResponse error(String msg) {
return new GlobalResponse(1, msg, null);
}
public static GlobalResponse error(int code, Object data) {
return new GlobalResponse(code, null, data);
}
public GlobalResponse(Object code, String msg) {
if (code instanceof String && StringUtils.isNumeric(((String) code))) {
this.code = Integer.parseInt(((String) code));
} else {
this.code = QGExceptionType.COMMON_SERVER_ERROR.code;
}
this.msg = msg;
}
public GlobalResponse(QGException ex) {
code = ex.qgExceptionType.code;
msg = StringUtils.isNotBlank(ex.detail) ? ex.detail : ex.qgExceptionType.text;
}
public static GlobalResponse generate(Object o) {
return new GlobalResponse(o);
}
public void writeJson(HttpServletResponse response) throws Exception {
response.setContentType(JSON_CONTENT_TYPE);
response.setCharacterEncoding("UTF-8");
PrintWriter out= response.getWriter();
String responeJosn = JSON.toJSONString(this);
out.print(responeJosn);
out.flush();
out.close();
}
}
package com.quantgroup.asset.distribution.service;
import java.util.List;
import java.util.Map;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.service.jpa.entity.AssetAttributeExtendConfig;
/**
* 资产属性Service
* @author liwenbin
*
*/
public interface IAssetAttributeService {
// public List<AssetAttributeExtendConfig> getAllExtendCon
/**
* 获取所有资产属性值
* @param assetAttributeExtendConfigList
* @return
*/
public Map<String, Object> getAllAssetAttributeValue(List<AssetAttributeExtendConfig> assetAttributeExtendConfigList, AssetForm assetForm);
}
package com.quantgroup.asset.distribution.service;
public class IAssetService {
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
/**
* 资产Service
* @author liwenbin
*
*/
public interface IAssetService {
/**
* 资产入库
* @param assetForm
* @return
*/
public void assetsIn(AssetForm assetForm);
/**
* 检查资产内容
* @param assetForm
* @return
*/
public GlobalResponse checkAssetForm(AssetForm assetForm);
}
package com.quantgroup.asset.distribution.service;
import com.quantgroup.asset.distribution.service.jpa.entity.AuthorityConfig;
/**
* 权限认证Service
* @author liwenbin
*
*/
public interface IAuthorityService {
/**
* 根据auth_key和auth_pass查找权限
* @param auth_key
* @param auth_pass
* @return
*/
public AuthorityConfig findByAuthKeyAndAuthPass(String authKey, String authPass);
/**
* 根据authKey和authPass清楚缓存
* @param authKey
* @param authPass
*/
public void clearCacheByAuthKeyAndAuthPass(String authKey, String authPass);
}
package com.quantgroup.asset.distribution.service.httpclient;
import java.util.Map;
public interface IHttpService {
/**
* Http Get
*
* @param uri
* @return
*/
String get(String uri);
String get(String uri, int timeOut);
<T> T get(String uri, Class<T> classOfT);
/**
* Http Get
*
* @param uri
* @param parameters
* @return
*/
String get(String uri, Map<String, String> parameters);
/**
* Http Get
*
* @param uri
* @param headers
* @param parameters
* @return
*/
String get(String uri, Map<String, String> headers, Map<String, String> parameters);
/**
* Http Post
*
* @param uri
* @return
*/
String post(String uri);
/**
* Http Post
*
* @param uri
* @param parameters
* @return
*/
String post(String uri, Map<String, String> parameters);
/**
* Http Post
*
* @param uri
* @param headers
* @param parameters
* @return
*/
String post(String uri, Map<String, String> headers, Map<String, String> parameters);
public String post(String uri, Map<String, String> headers,Map<String, String> parameters, boolean isLog);
public String postJson(String uri, Map<String, String> headers, String jsonParams) ;
public String postObj(String uri, Map<String, Object> parameters);
public String postObj(String uri, Map<String, String> headers, Map<String, Object> parameters) ;
/**
* 不需要返回结果的请求
* @param url
* @param parameters
* @return
*/
public int postNoResponse(String url, Map<String, String> parameters);
public Map<String,String> postHasResponse(String url, Map<String, String> parameters);
public String post(String uri, Map<String, String> headers,Map<String, String> parameters,boolean isLog,int timeOut);
}
package com.quantgroup.asset.distribution.service.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quantgroup.asset.distribution.exception.QGExceptionType;
import com.quantgroup.asset.distribution.exception.QGPreconditions;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.service.IAssetAttributeService;
import com.quantgroup.asset.distribution.service.httpclient.IHttpService;
import com.quantgroup.asset.distribution.service.jpa.entity.AssetAttributeExtendConfig;
import lombok.extern.slf4j.Slf4j;
/**
* 资产扩展属性Service
*
* @author liwenbin
*
*/
@Slf4j
@Service
public class AssetAttributeServiceImpl implements IAssetAttributeService {
@Autowired
private IHttpService httpService;
@Value("${rule.engine.url}")
private String ruleEngineURL;
/**
* 获取所有资产扩展属性value
*/
@Override
public Map<String, Object> getAllAssetAttributeValue(List<AssetAttributeExtendConfig> assetAttributeExtendConfigList, AssetForm assetForm) {
Map<String, Object> data = new HashMap<>();
// 决策特征Set
Set<String> decKeys = new HashSet<>();
// 默认增加一个用户类型
decKeys.add("user_loan_type_latest");
if (assetAttributeExtendConfigList != null && assetAttributeExtendConfigList.size() > 0) {
for (AssetAttributeExtendConfig config : assetAttributeExtendConfigList) {
if (config.getAssetAttributeType() == 1) {
// 模型分
decKeys.add(config.getAssetAttributeCode());
}
}
}
// 去请求决策特征
Map<String, Object> decAttributeValue = getDecAttributeValue(decKeys, assetForm);
data.putAll(decAttributeValue);
return data;
}
/**
* 获取所有决策特征属性值
* @param decKeys
* @return
*/
public Map<String, Object> getDecAttributeValue(Set<String> decKeys, AssetForm assetForm) {
if (CollectionUtils.isEmpty(decKeys)) { return MapUtils.EMPTY_MAP; }
String result = httpService.post(ruleEngineURL + "/feature/get", new HashMap<String, String>(){{
put("uuid", assetForm.getUuid());
put("bizChannel", assetForm.getBizChannel());
put("bizNo", assetForm.getBizNo());
put("bizType", assetForm.getBizType());
put("keys", StringUtils.join(decKeys, ","));
}});
JSONObject resultJSON = null;
QGPreconditions.checkArgument(StringUtils.isNotEmpty(result) && (resultJSON = JSON.parseObject(result)).getInteger("code") == 0, QGExceptionType.GET_DEC_ATTRIBUTE_VALUE_ERROR, assetForm.getUuid(), JSON.toJSONString(decKeys));
Map<String, Object > data = resultJSON.getJSONObject("body");
log.info("决策特征属性获取完成, uuid : {}, bizChannel : {}, bizNo : {}, bizType : {}, data : {}", assetForm.getUuid(), assetForm.getBizChannel(), assetForm.getBizNo(), assetForm.getBizType(), JSON.toJSONString(data));
return data;
}
}
package com.quantgroup.asset.distribution.service.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.quantgroup.asset.distribution.exception.QGException;
import com.quantgroup.asset.distribution.exception.QGExceptionType;
import com.quantgroup.asset.distribution.exception.QGPreconditions;
import com.quantgroup.asset.distribution.model.form.AssetForm;
import com.quantgroup.asset.distribution.model.response.GlobalResponse;
import com.quantgroup.asset.distribution.service.IAssetService;
import com.quantgroup.asset.distribution.service.httpclient.IHttpService;
import com.quantgroup.asset.distribution.service.jpa.entity.Asset;
import com.quantgroup.asset.distribution.service.jpa.entity.AssetAttributeExtendConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAssetAttributeExtendConfigRepository;
import com.quantgroup.asset.distribution.util.UUIDUtil;
/**
* 资产Service
* @author liwenbin
*
*/
@Service
public class AssetServiceImpl implements IAssetService{
@Autowired
private IAssetAttributeExtendConfigRepository assetAttributeExtendConfigRepository;
@Async
@Override
public void assetsIn(AssetForm assetForm) {
// try {
// QGPreconditions.checkArgument("0".equals(assetForm.getCode()), QGExceptionType.ASSET_IN_CODE_ERROR, assetForm.getUuid(), assetForm.getBizNo(), assetForm.getCode());
// Asset asset = assetForm.transToAsset();
// // 获取所有资产扩展属性配置
// List<AssetAttributeExtendConfig> assetAttributeExtendConfigList = assetAttributeExtendConfigRepository.findByEnableIsTrue();
//
// return null;
// } catch (QGException qe) {
// log.error("风控审核出现错误:{},审核次数 : {} ,uuid : {} ,bizChannel:{},productId:{},bizNo : {},auditNo:{} ",
// qe.qgExceptionType.code + "->" + qe.detail, bizAuditForm.getRepeatCount(),
// bizAuditForm.getUuid(), bizAuditForm.getBizChannel(), bizAuditForm.getProductId(),
// bizAuditForm.getBizNo(), bizAuditForm.getAuditNo());
// // 审核失败放队列 来日继续审核
// iRedisService.rightPushEx("AUDIT.ERROR.USER.9981_01",
// bizAuditForm.setRepeatCount(bizAuditForm.getRepeatCount() + 1)
// .setFailReason(qe.qgExceptionType.code + "->" + qe.detail)
// .setSpaceTime(System.currentTimeMillis()),
// 1, TimeUnit.DAYS);
// // 报警机制
// if (qe.qgExceptionType.code != 2007 || bizAuditForm.getRepeatCount() > 1) {//规则数据为空 一次不报警 因为太多了
// iMonitorAlarmService.alarm("风控审核出现错误",
// "审核次数 : " + bizAuditForm.getRepeatCount() + " ,bizChannel : " + bizAuditForm.getBizChannel()
// + " , productId : " + bizAuditForm.getProductId() + " , bizNo : "
// + bizAuditForm.getBizNo() + " , uuid : " + bizAuditForm.getUuid() + " , 错误信息 : "
// + qe.qgExceptionType.code + "->" + qe.detail,
// "Warn");
// }
// return;
// } catch (Exception ex) {
// log.error("风控审核出现异常,审核次数 : {} ,uuid: {} ,bizChannel : {} ,productId:{},bizNo : {},auditNo:{} ",
// bizAuditForm.getRepeatCount(), bizAuditForm.getUuid(), bizAuditForm.getBizChannel(),
// bizAuditForm.getProductId(), bizAuditForm.getBizNo(), bizAuditForm.getAuditNo(), ex);
// // 审核失败放队列 来日继续审核
// iRedisService.rightPushEx("AUDIT.ERROR.USER.9981_01",
// bizAuditForm.setRepeatCount(bizAuditForm.getRepeatCount() + 1).setFailReason("未知异常")
// .setSpaceTime(System.currentTimeMillis()),
// 1, TimeUnit.DAYS);
// // 报警机制
// iMonitorAlarmService.alarm("风控审核出现异常",
// "审核次数 : " + bizAuditForm.getRepeatCount() + " , bizChannel : " + bizAuditForm.getBizChannel()
// + " , productId : " + bizAuditForm.getProductId() + " , bizNo : "
// + bizAuditForm.getBizNo() + " , uuid : " + bizAuditForm.getUuid() + " , 错误信息 : 未知错误",
// "Warn");
// return;
// }
}
@Override
public GlobalResponse checkAssetForm(AssetForm assetForm) {
return null;
}
}
package com.quantgroup.asset.distribution.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Service;
import com.quantgroup.asset.distribution.service.IAuthorityService;
import com.quantgroup.asset.distribution.service.jpa.entity.AuthorityConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAuthorityRepository;
import lombok.extern.slf4j.Slf4j;
/**
* 权限配置Service
* @author liwenbin
*
*/
@Slf4j
@Service
public class AuthorityServiceImpl implements IAuthorityService{
@Autowired
private IAuthorityRepository authorityRepository;
@Override
@Cacheable(value="cacheManager",key="#authKey+'_'+#authPass+'_1021ASSET'")
public AuthorityConfig findByAuthKeyAndAuthPass(String authKey, String authPass) {
return authorityRepository.findByAuthKeyAndAuthPassAndEnableIsTrue(authKey, authPass);
}
@Override
@CacheEvict(value = "cacheManager", key = "#authKey+'_'+#authPass+'_1021ASSET'")
public void clearCacheByAuthKeyAndAuthPass(String authKey, String authPass) {
log.info("权限配置清楚缓存成功, authKey = {}, authPass = {}", authKey, authPass);
}
}
package com.quantgroup.asset.distribution.service.jpa.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
......@@ -17,12 +22,56 @@ import lombok.Setter;
*/
@Table(name = "asset")
@Entity
@Getter
@Setter
@Data
public class Asset {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "asset_no")
private String assetNo;
@Column(name = "biz_no")
private String bizNo;
@Column(name = "uuid")
private String uuid;
@Column(name = "user_loan_type")
private Integer userLoanType;
@Column(name = "biz_channel")
private String bizChannel;
@Column(name = "finance_product_type")
private Integer financeProductType;
@Column(name = "effective_time")
private Timestamp effectiveTime;
@Column(name = "audit_result")
private Integer auditResult;
@Column(name = "enable")
private Integer enable;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updatedAt;
@PrePersist
public void prePersist() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
createdAt = timestamp;
updatedAt = timestamp;
}
@PreUpdate
public void preUpdate() {
updatedAt = new Timestamp(System.currentTimeMillis());
}
}
package com.quantgroup.asset.distribution.service.jpa.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import lombok.Data;
/**
* 资产属性扩展表
* @author liwenbin
*
*/
@Table(name = "asset_atrribute_extend")
@Entity
@Data
public class AssetAttributeExtend {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "asset_no")
private String assetNo;
@Column(name = "asset_attribute_name")
private String assetAttributeName;
@Column(name = "asset_attribute_code")
private String assetAttributeCode;
@Column(name = "asset_attribute_type")
private Integer assetAttributeType;
@Column(name = "asset_attribute_value")
private String assetAttributeValue;
@Column(name = "enable")
private Boolean enable;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updatedAt;
@PrePersist
public void prePersist() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
createdAt = timestamp;
updatedAt = timestamp;
}
@PreUpdate
public void preUpdate() {
updatedAt = new Timestamp(System.currentTimeMillis());
}
}
package com.quantgroup.asset.distribution.service.jpa.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import lombok.Data;
/**
* 资产属性扩展配置表
* @author liwenbin
*
*/
@Table(name = "asset_atrribute_extend_config")
@Entity
@Data
public class AssetAttributeExtendConfig {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "asset_attribute_name")
private String assetAttributeName;
@Column(name = "asset_attribute_code")
private String assetAttributeCode;
@Column(name = "asset_attribute_type")
private Integer assetAttributeType;
@Column(name = "asset_attribute_value_type")
private String assetAttributeValueType;
@Column(name = "is_page_config")
private Integer isPageConfig;
@Column(name = "enable")
private Boolean enable;
@Column(name = "created_by")
private String createdBy;
@Column(name = "updated_by")
private String updatedBy;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updatedAt;
@PrePersist
public void prePersist() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
createdAt = timestamp;
updatedAt = timestamp;
}
@PreUpdate
public void preUpdate() {
updatedAt = new Timestamp(System.currentTimeMillis());
}
}
package com.quantgroup.asset.distribution.service.jpa.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import lombok.Data;
/**
* 权限认证表
* @author liwenbin
*
*/
@Table(name = "authority_config")
@Entity
@Data
public class AuthorityConfig {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "auth_key")
private String authKey;
@Column(name = "auth_pass")
private String authPass;
@Column(name = "auth_name")
private String authName;
@Column(name = "enable")
private Boolean enable;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "updated_at")
private Timestamp updatedAt;
@PrePersist
public void prePersist() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
createdAt = timestamp;
updatedAt = timestamp;
}
@PreUpdate
public void preUpdate() {
updatedAt = new Timestamp(System.currentTimeMillis());
}
}
package com.quantgroup.asset.distribution.service.jpa.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.quantgroup.asset.distribution.service.jpa.entity.AssetAttributeExtendConfig;
public interface IAssetAttributeExtendConfigRepository extends JpaRepository<AssetAttributeExtendConfig, Integer>{
public List<AssetAttributeExtendConfig> findByEnableIsTrue();
}
package com.quantgroup.asset.distribution.service.jpa.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.quantgroup.asset.distribution.service.jpa.entity.AssetAttributeExtend;
public interface IAssetAttributeExtendRepository extends JpaRepository<AssetAttributeExtend, Long>{
}
package com.quantgroup.asset.distribution.service.jpa.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.quantgroup.asset.distribution.service.jpa.entity.AuthorityConfig;
/**
* 权限认证Repository
* @author liwenbin
*
*/
public interface IAuthorityRepository extends JpaRepository<AuthorityConfig, Integer>{
/**
* 根据authKey和authPass查到配置
* @param authKey
* @param authPass
* @return
*/
public AuthorityConfig findByAuthKeyAndAuthPassAndEnableIsTrue(String authKey, String authPass);
}
package com.quantgroup.asset.distribution.util;
import java.util.UUID;
/**
* UUID工具类
* @author liwenbin
*
*/
public class UUIDUtil {
private static final String ASSET_STR = "ASET";
/**
* 获取资产编号
* @return
*/
public static String getAssetNo() {
return ASSET_STR + UUID.randomUUID().toString().replaceAll("-", "");
}
public static void main(String[] args) {
System.out.println(getAssetNo());
}
}
package com.quantgroup.asset.distribution.authority;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.quantgroup.asset.distribution.AssetDistributionBootstrap;
import com.quantgroup.asset.distribution.service.jpa.entity.AuthorityConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAuthorityRepository;
/**
* 权限配置测试类
* @author liwenbin
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AssetDistributionBootstrap.class)
public class AuthorityTest {
@Autowired
private IAuthorityRepository authorityRepository;
@Test
public void testAuthorityRepository() {
AuthorityConfig config = authorityRepository.findByAuthKeyAndAuthPassAndEnableIsTrue("lz_mo_fang", "123456");
System.out.println(config);
}
}
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