Commit 73af2972 by 陶光胜

Merge branch 'developer' into 'master'

Developer

See merge request !1
parents 6e6c92cd ae8d41b3
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>com.gic</groupId> <groupId>com.gic</groupId>
<artifactId>gic-enterprise-base</artifactId> <artifactId>gic-pom-base</artifactId>
<version>4.0-SNAPSHOT</version> <version>4.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
...@@ -12,6 +12,31 @@ ...@@ -12,6 +12,31 @@
<groupId>com.gic</groupId> <groupId>com.gic</groupId>
<artifactId>gic-enterprise-base-api</artifactId> <artifactId>gic-enterprise-base-api</artifactId>
<version>4.0-SNAPSHOT</version> <version>4.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<libraryVersion>4.0-SNAPSHOT</libraryVersion>
<gic-redis-data>4.0-SNAPSHOT</gic-redis-data>
</properties>
<distributionManagement>
<repository>
<!-- 和 Maven setting 保持一致 -->
<id>nexus-snapshots</id>
<name>nexus distribution snapshot repository</name>
<!-- 这里使用 /content/repositories/snapshots/ -->
<url>http://182.254.134.223:8081/nexus/content/repositories/snapshots/</url>
<!--<url>http://stream.banli.mobi:8081/content/repositories/snapshots/</url>-->
</repository>
<snapshotRepository>
<!-- 和 Maven setting 保持一致 -->
<id>nexus-snapshots</id>
<name>nexus distribution snapshot repository</name>
<!-- 这里使用 /content/repositories/snapshots/ -->
<url>http://182.254.134.223:8081/nexus/content/repositories/Snapshots-1/</url>
<!--<url>http://stream.banli.mobi:8081/content/repositories/snapshots/</url>-->
</snapshotRepository>
</distributionManagement>
<dependencies> <dependencies>
<dependency> <dependency>
...@@ -25,7 +50,68 @@ ...@@ -25,7 +50,68 @@
<version>4.12</version> <version>4.12</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!--参数验证-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-log-api</artifactId>
<version>${gic-log-api}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-commons</artifactId>
<version>${gic-commons}</version>
</dependency>
<dependency>
<groupId>com.gic </groupId>
<artifactId>gic-redis-data </artifactId>
<version>${gic-redis-data} </version>
</dependency>
</dependencies> </dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<flattenMode>defaults</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>
\ No newline at end of file
package com.gic.enterprise.base;
import java.io.Serializable;
import java.util.Date;
public class EnterpriseInfo implements Serializable {
/**
* 企业主键
*/
private Integer enterpriseId;
/**
* 商户名称
*/
private String enterpriseName;
/**
* 公司名称
*/
private String companyName;
/**
*
*/
private String logo;
/**
*
*/
private String areaId;
/**
* 详细地址
*/
private String address;
/**
* 状态;1有效; 0无效;2停用
*/
private Integer status;
/**
*
*/
private Date createTime;
/**
*
*/
private Date updateTime;
/**
* 是否完成初始化
*/
private Integer isInitComplete;
/**
* 基础服务过期时间
*/
private Date auditTime;
/**
* 版本code
*/
private String versionCode;
/**
* 版本名称
*/
private String versionName;
/**
* 服务状态 0:无服务 1:正常 2:停用
*/
private Integer serviceStatus;
public Integer getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(Integer enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getEnterpriseName() {
return enterpriseName;
}
public void setEnterpriseName(String enterpriseName) {
this.enterpriseName = enterpriseName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getAreaId() {
return areaId;
}
public void setAreaId(String areaId) {
this.areaId = areaId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getIsInitComplete() {
return isInitComplete;
}
public void setIsInitComplete(Integer isInitComplete) {
this.isInitComplete = isInitComplete;
}
public Date getAuditTime() {
return auditTime;
}
public void setAuditTime(Date auditTime) {
this.auditTime = auditTime;
}
public String getVersionCode() {
return versionCode;
}
public void setVersionCode(String versionCode) {
this.versionCode = versionCode;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public Integer getServiceStatus() {
return serviceStatus;
}
public void setServiceStatus(Integer serviceStatus) {
this.serviceStatus = serviceStatus;
}
}
package com.gic.enterprise.base;
import java.io.Serializable;
/**
* 菜单
* @ClassName: MenuInfo

* @Description: 

* @author guojuxing

* @date 2019/11/7 10:26 AM

*/
public class MenuInfo implements Serializable{
private static final long serialVersionUID = -8742818837296730949L;
private Integer menuId;
private String menuName;
private Integer parentId;
private Integer level;
/**
* 菜单路由
*/
private String menuUrl;
/**
* 前端使用:二级域名,也就是项目的部署路径,比如门店项目部署在/damo-store下面,那么就是/damo-store
*/
private String projectUrlForWeb;
public Integer getMenuId() {
return menuId;
}
public void setMenuId(Integer menuId) {
this.menuId = menuId;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getMenuUrl() {
return menuUrl;
}
public void setMenuUrl(String menuUrl) {
this.menuUrl = menuUrl;
}
public String getProjectUrlForWeb() {
return projectUrlForWeb;
}
public void setProjectUrlForWeb(String projectUrlForWeb) {
this.projectUrlForWeb = projectUrlForWeb;
}
}
package com.gic.enterprise.base;
import java.io.Serializable;
import java.util.Date;
public class UserInfo implements Serializable {
/**
* 用户id
*/
private Integer userId;
/**
* 用户名
*/
private String userName;
/**
* 手机号码
*/
private String phoneNumber;
/**
* 密码
*/
private String password;
/**
* 1:自动生成 2:自定义密码
*/
private Integer passwordType;
/**
* 确认密码
*/
private String confirmPassword;
/**
* 是否是超级管理员
*/
private Integer superAdmin;
/**
* 状态,1有效,0无效
*/
private Integer status;
/**
*
*/
private Date createTime;
/**
*
*/
private Date updateTime;
/**
*
*/
private Integer enterpriseId;
/**
* 国际区号,如中国 86
*/
private String phoneAreaCode;
/**
* 受审组,可以有多个,用英文逗号隔开
*/
private String userGroupIds;
/**
* 登陆账号类型 1:运营 0:默认GIC
*/
private Integer loginType;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getPasswordType() {
return passwordType;
}
public void setPasswordType(Integer passwordType) {
this.passwordType = passwordType;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public Integer getSuperAdmin() {
return superAdmin;
}
public void setSuperAdmin(Integer superAdmin) {
this.superAdmin = superAdmin;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Integer getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(Integer enterpriseId) {
this.enterpriseId = enterpriseId;
}
public String getPhoneAreaCode() {
return phoneAreaCode;
}
public void setPhoneAreaCode(String phoneAreaCode) {
this.phoneAreaCode = phoneAreaCode;
}
public String getUserGroupIds() {
return userGroupIds;
}
public void setUserGroupIds(String userGroupIds) {
this.userGroupIds = userGroupIds;
}
public Integer getLoginType() {
return loginType;
}
public void setLoginType(Integer loginType) {
this.loginType = loginType;
}
}
package com.gic.enterprise.base;
import java.io.Serializable;
/**
*
* @Description:
* @author zhiwj
* @date 2019/8/28 18:18
*/
public class UserResourceInfo implements Serializable {
private static final long serialVersionUID = 1609787491094703550L;
private Long userResource;
/**
* 门店资源
*/
private Long storeResource;
/**
* 商品资源
*/
private Long goodsResourceId;
/**
* 订单资源
[
{
"channel":1, // 渠道 1:线下门店, 2:达摩微商城, 3:微盟微商城
"storeContent":1 // 门店id或门店选择器id, 多个逗号隔开
}
]
*/
private Integer orderResource;
private String orderResourceJson;
/**
* 应用资源
[
{
appId:1, // 应用id
appName:微商城 // 应用名称
child:[
appId: 10, // 子应用id
appName: 短信发送 // 子应用名称
]
}
]
*/
private Integer appResource;
private String appResourceJson;
/**
* 短信签名资源
[
{
"type":1, // 全部签名:1, 部分签名:2
"ids":[1,2,3]
}
]
*/
private Integer smsSignResource;
private String smsSignResourceJson;
public Long getStoreResource() {
return storeResource;
}
public void setStoreResource(Long storeResource) {
this.storeResource = storeResource;
}
public Long getGoodsResourceId() {
return goodsResourceId;
}
public void setGoodsResourceId(Long goodsResourceId) {
this.goodsResourceId = goodsResourceId;
}
public Integer getOrderResource() {
return orderResource;
}
public void setOrderResource(Integer orderResource) {
this.orderResource = orderResource;
}
public String getOrderResourceJson() {
return orderResourceJson;
}
public void setOrderResourceJson(String orderResourceJson) {
this.orderResourceJson = orderResourceJson;
}
public Integer getAppResource() {
return appResource;
}
public void setAppResource(Integer appResource) {
this.appResource = appResource;
}
public String getAppResourceJson() {
return appResourceJson;
}
public void setAppResourceJson(String appResourceJson) {
this.appResourceJson = appResourceJson;
}
public Integer getSmsSignResource() {
return smsSignResource;
}
public void setSmsSignResource(Integer smsSignResource) {
this.smsSignResource = smsSignResource;
}
public String getSmsSignResourceJson() {
return smsSignResourceJson;
}
public void setSmsSignResourceJson(String smsSignResourceJson) {
this.smsSignResourceJson = smsSignResourceJson;
}
public Long getUserResource() {
return userResource;
}
public void setUserResource(Long userResource) {
this.userResource = userResource;
}
}
package com.gic.enterprise.constants;
public class Constants {
public static String INDEX_ENTERPRISEID = "test-enterprise-20190716";
public static String STORE_SCENECODE = "store";
public static String ColumnCategoryCode = "enterprise-store";
public static String USER_TOKEN = "token";
public static String TOKEN_KEY = "enterprise:user:";
public static Integer NORMAL_STATUS = 1;
public static Integer DEL_STATUS = 0;
}
package com.gic.enterprise.context;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestContext {
private static final Logger log = LogManager.getLogger(RequestContext.class);
private ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<>();
private ThreadLocal<HttpServletResponse> responseThreadLocal = new ThreadLocal<>();
private static RequestContext requestContext = null;
public static RequestContext getContext(){
if(requestContext == null){
synchronized (RequestContext.class){
if(requestContext == null){
try{
requestContext = new RequestContext();
}catch (Exception e){
log.info("创建对象失败");
}
}
}
}
return requestContext;
}
public void init(HttpServletRequest request, HttpServletResponse response){
requestThreadLocal.set(request);
responseThreadLocal.set(response);
}
public void destroy(){
requestThreadLocal.remove();
responseThreadLocal.remove();
}
public HttpServletRequest getRequest(){
return requestThreadLocal.get();
}
public HttpServletResponse getResponse(){
return responseThreadLocal.get();
}
}
package com.gic.enterprise.context;
import com.gic.commons.util.ToolUtil;
import com.gic.enterprise.constants.Constants;
import com.gic.enterprise.utils.UserDetail;
import com.gic.redis.data.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
public class UserContext {
public static final Long expireLength = 1l;
private static UserContext userContext = null;
private static final Logger log = LogManager.getLogger(UserContext.class);
public static UserContext getContext(){
if (null == userContext) {
synchronized (UserContext.class) {
if (null == userContext) {
try {
userContext = new UserContext();
} catch (Exception e) {
log.info("创建对象失败");
}
}
}
}
return userContext;
}
public UserDetail get(){
String token = getToken();
if(StringUtils.isBlank(token)){
return new UserDetail();
}
String key = Constants.TOKEN_KEY + token;
Object cache = RedisUtil.getCache(key);
if(cache != null){
return (UserDetail) cache;
}
return new UserDetail();
}
public UserDetail getByToken(String token) {
if(StringUtils.isBlank(token)){
return new UserDetail();
}
String key = Constants.TOKEN_KEY + token;
Object cache = RedisUtil.getCache(key);
if(cache != null){
return (UserDetail) cache;
}
return new UserDetail();
}
/**
* 返回token值
* @Title: init

* @Description:

 * @author guojuxing
* @param userDetail

* @return java.lang.String


 */
public String init(UserDetail userDetail){
String uuId = ToolUtil.randomUUID();
String key = Constants.TOKEN_KEY+uuId;
RedisUtil.setCache(key, userDetail, expireLength, TimeUnit.HOURS);
Cookie cookie = new Cookie(Constants.USER_TOKEN, uuId);
cookie.setPath("/");
HttpServletResponse response = RequestContext.getContext().getResponse();
if(response != null){
response.addCookie(cookie);
}
return uuId;
}
public void refresh(){
String key = Constants.TOKEN_KEY + getToken();
RedisUtil.getRedisClient().getBucket(key).expire(expireLength, TimeUnit.HOURS);
}
public void destory(){
String key = Constants.TOKEN_KEY + getToken();
RedisUtil.delCache(key);
}
public String getToken(){
String token = null;
HttpServletRequest request = RequestContext.getContext().getRequest();
if (request != null){
Cookie[] cookies = request.getCookies();
if(cookies != null){
for (Cookie cookie : cookies) {
if (Constants.USER_TOKEN.equals(cookie.getName())) {
token = cookie.getValue();
break;
}
}
}
}
return token;
}
}
...@@ -8,31 +8,42 @@ public enum ErrorCode implements Error{ ...@@ -8,31 +8,42 @@ public enum ErrorCode implements Error{
/** /**
* 缺少参数 * 缺少参数
*/ */
ERR_2("0002", "缺少参数"), MISS_PARAMETER("0002", "缺少参数"),
/** /**
* 系统异常 * 系统异常
*/ */
ERR_3("0003", "系统异常"), SYSTEM_ERROR("0003", "系统异常"),
/** /**
* 登录异常 * 登录异常
*/ */
ERR_4("0004", "登录异常"), LOGIN_ERROR("0004", "登录异常"),
/** /**
* 输入参数错误 * 输入参数错误
*/ */
ERR_5("0005", "输入参数错误"), PARAMETER_ERROR("0005", "输入参数错误"),
/** /**
* 数据已存在 * 数据已存在
*/ */
ERR_6("0006", "数据已存在"), DATA_EXISTS("0006", "数据已存在"),
/** /**
* 失效操作失败 * 失效操作失败
*/ */
ERR_7("0007", "失效操作失败"), OPERATION_FAILED("0007", "失效操作失败"),
ERR_9999("9999", "未知错误"); NOTEXISTS("0008", "记录不存在"),
NOT_SUPPORT("0009", "不支持文本类型"),
ENTERPRISE_EMPTY("0010", "企业id不能为空"),
UNKNOWN_ERROR("9999", "未知错误"),
LOGIN_ERR("0011", "用户名或密码错误"),
AUTHCODE_ERR("0012", "验证码异常"),
AUTHCODE_EXPIRE("0013", "验证码失效"),
AUTHCODE_MISTAKE("0014", "验证码错误"),
AUTHCODE_USED("0015", "验证码已经被使用"),
LOGIN_INVALID("6666", "登录信息失效,请重新登录"),
ISNEEDNEWVERSION("0016", "保存后需提交小程序审核后方可生效。提交流程请联系相关项目经理");
private String code; private String code;
...@@ -54,11 +65,11 @@ public enum ErrorCode implements Error{ ...@@ -54,11 +65,11 @@ public enum ErrorCode implements Error{
@Override @Override
public String getErrorCode() { public String getErrorCode() {
return null; return code;
} }
@Override @Override
public String getErrorMsg() { public String getErrorMsg() {
return null; return msg;
} }
} }
package com.gic.enterprise.exception;
import com.gic.api.base.commons.ServiceResponse;
/**
* 公共异常
* @ClassName: CommonException

* @Description: 

* @author guojuxing

* @date 2019/8/15 1:56 PM

*/
public class CommonException extends RuntimeException{
private String errorCode;
public CommonException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public CommonException(ServiceResponse serviceResponse) {
super(serviceResponse.getMessage());
this.errorCode = serviceResponse.getCode();
}
public String getErrorCode() {
return errorCode;
}
}
package com.gic.enterprise.filter;
import com.alibaba.fastjson.JSON;
import com.gic.enterprise.constants.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;
@Activate(group = {CommonConstants.PROVIDER})
public class ServiceValidateFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String token = invocation.getAttachment(Constants.USER_TOKEN);
RpcContext.getContext();
if(StringUtils.isNotBlank(token)){
RpcContext.getContext().setAttachment(Constants.USER_TOKEN, token);
}
System.out.println("profilter attachments"+ JSON.toJSONString(invocation.getAttachments()));
System.out.println("参数:"+JSON.toJSONString(invocation.getArguments()));
Class<?>[] parameterTypes = invocation.getParameterTypes();
String methodName = invocation.getMethodName();
Method[] declaredMethods = invoker.getInterface().getDeclaredMethods();
for(Method method : declaredMethods){
if(method.getName().equals(methodName) && checkMethodParameter(parameterTypes, method.getParameterTypes())){
for(int i=0; i<parameterTypes.length; i++){
Class<?> parameterType = parameterTypes[i];
Annotation[] annotations = parameterType.getAnnotations();
}
}
}
return invoker.invoke(invocation);
}
private boolean checkMethodParameter(Class<?>[] parameterTypes, Class<?>[] parameterTypes2){
if(parameterTypes.length != parameterTypes2.length){
return false;
}
for(int i=0; i<parameterTypes.length; i++){
if(!parameterTypes[i].equals(parameterTypes2[i])){
return false;
}
}
return true;
}
}
package com.gic.enterprise.filter;
import com.gic.enterprise.constants.Constants;
import com.gic.enterprise.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.filter.ConsumerContextFilter;
@Activate(group = {CommonConstants.CONSUMER}, order = -1000)
public class UserTokenFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String token = invocation.getAttachment(Constants.USER_TOKEN);
RpcContext rpcContext = RpcContext.getContext();
if(StringUtils.isNotBlank(token)){
TokenUtils.set(token);
RpcContext.getContext().setAttachment(Constants.USER_TOKEN, token);
}else {
RpcContext.getContext().setAttachment(Constants.USER_TOKEN, TokenUtils.get());
}
try{
return invoker.invoke(invocation);
}finally {
TokenUtils.remove();
}
}
}
package com.gic.enterprise.qo;
import java.io.Serializable;
/**
* 分页数据
* @ClassName: PageQO

* @Description: 

* @author guojuxing

* @date 2019/8/13 11:29 AM

*/
public class PageQO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 页码
*/
private Integer currentPage = 1;
/**
* 分页大小
*/
private Integer pageSize = 20;
public Integer getCurrentPage() {
if (currentPage == null) {
currentPage = 1;
}
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
if (pageSize == null) {
pageSize = 20;
}
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
}
package com.gic.enterprise.utils;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
/**
* 异步回调工具
* @ClassName: AsyncCallbackUtils

* @Description: 

* @author guojuxing

* @date 2019/10/31 3:41 PM

*/
public class AsyncCallbackUtils {
private static Logger logger = LogManager.getLogger(AsyncCallbackUtils.class);
/**
* 回调
* @Title: callBack

* @Description:

 * @author guojuxing
* @param obj 需要传递的参数对象
* @param interfaceUrl 接口路径 例如com.gic.open.api.service.market.PayCallbackApiService
* @param method
 方法名称 payCallbackTransfer
* @return void


 */
public static void callBack(Object obj, String interfaceUrl, String method) {
logger.info("回调:{},接口路径:{},接口方法名称:{}" ,JSONObject.toJSONString(obj), interfaceUrl, method);
RegistryConfig registry = new RegistryConfig();
registry.setAddress("zookeeper://10.105.220.75:2199");
registry.setCheck(false);
ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
reference.setInterface(interfaceUrl);
reference.setRegistry(registry);
reference.setGeneric(true);
ReferenceConfigCache cache = ReferenceConfigCache.getCache();
GenericService genericService = cache.get(reference);
// 注意! Cache会持有ReferenceConfig,不要在外部再调用ReferenceConfig的destroy方法,导致Cache内的ReferenceConfig失效!
genericService.$invoke(method, new String[]{String.class.getName()}, new String[]{JSONObject.toJSONString(obj)});
}
}
package com.gic.enterprise.utils;
import com.gic.commons.util.Md5Util;
public class AutoCreatePasswordUtils {
/**
* 自动生成length位中英文密码
* @Title: autoCreatePassword

* @Description:

 * @author guojuxing
* @param length

* @return java.lang.String


 */
public static String autoCreatePassword(int length) {
String password = CreateRandomUtils.generateNumberStr(length);
return encryptPassword(password);
}
public static String encryptPassword(String password) {
Md5Util md5 = new Md5Util();
return md5.encrypt(password + password);
}
}
package com.gic.enterprise.utils;
import java.util.Random;
/**
* 生成随机数工具类
* @ClassName: CreatePasswordAutoUtils

* @Description: 

* @author guojuxing

* @date 2019/8/9 4:39 PM

*/
public class CreateRandomUtils {
/**
* 随机生成字母、数字参合的密码
* @param length 生成多少位数的密码
* @return
*/
public static String getStringRandom(int length) {
String val = "";
Random random = new Random();
//length为几位密码
for (int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
//输出字母还是数字
if ("char".equalsIgnoreCase(charOrNum)) {
//输出是大写字母还是小写字母
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (random.nextInt(26) + temp);
} else if ("num".equalsIgnoreCase(charOrNum)) {
val += String.valueOf(random.nextInt(10));
}
}
return val;
}
/**
* 随机生成0-9的数字
* @Title: generateNumberStr

* @Description:

 * @author guojuxing
* @param length
 生成多少位数
* @return java.lang.String


 */
public static String generateNumberStr(int length) {
String numberChar = "0123456789";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(numberChar.charAt(random.nextInt(numberChar.length())));
}
return sb.toString();
}
}
package com.gic.enterprise.utils;
import java.util.List;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.exception.CommonException;
/**
* controller统一返回结果
* @ClassName: ResultControllerUtils

* @Description: 

* @author guojuxing

* @date 2019/8/15 2:34 PM

*/
public class ResultControllerUtils {
/**
* 统一返回成功结果
* @Title: commonResult

* @Description:

 * @author guojuxing
* @param response

* @return java.lang.Object


 */
public static RestResponse commonResult(ServiceResponse response) {
if (response.isSuccess()) {
return RestResponse.success(response.getResult());
} else {
return RestResponse.failure(response.getCode(), response.getMessage());
}
}
/**
* 返回正确结果
* @Title: commonResultObject

* @Description:

 * @author guojuxing
* @param response

* @return java.lang.Object


 */
public static Object commonResultObject(ServiceResponse response) {
if (response.isSuccess()) {
return response.getResult();
} else {
throw new CommonException(response);
}
}
/**
* 返回分页正确结果
* @Title: commonResultPage

* @Description:

 * @author guojuxing
* @param response

* @return java.lang.Object


 */
public static Page commonResultPage(ServiceResponse response) {
if (response.isSuccess()) {
return (Page) response.getResult();
} else {
throw new CommonException(response);
}
}
/**
* 返回分页正确结果
* @Title: commonResultPage

* @Description:

 * @author guojuxing
* @param response

* @return java.lang.Object


 */
public static Page commonResultPage(ServiceResponse response, Class<?> clazz) {
if (response.isSuccess()) {
Page page = (Page) response.getResult();
page.setResult(EntityUtil.changeEntityListNew(clazz, page.getResult()));
return page;
} else {
throw new CommonException(response);
}
}
/**
* 统一返回成功结果(分页DTO转为VO)
* @Title: commonResultOfListVO

* @Description:

 * @author guojuxing
* @param response
* @param clazz

* @return com.gic.commons.webapi.reponse.RestResponse


 */
public static RestResponse commonPageResult(ServiceResponse response, Class<?> clazz) {
if (response.isSuccess()) {
Page page = (Page) response.getResult();
page.setResult(EntityUtil.changeEntityListNew(clazz, page.getResult()));
return RestResponse.success(page);
} else {
return RestResponse.failure(response.getCode(), response.getMessage());
}
}
/**
* 统一返回成功结果 list(DTO转为VO)
* @Title: commonResultOfListVO

* @Description:

 * @author guojuxing
* @param response
* @param clazz

* @return com.gic.commons.webapi.reponse.RestResponse


 */
public static RestResponse commonResult(ServiceResponse response, Class<?> clazz) {
if (response.isSuccess()) {
return RestResponse.success(EntityUtil.changeEntityListNew(clazz, (List<?>) response.getResult()));
} else {
return RestResponse.failure(response.getCode(), response.getMessage());
}
}
/**
* 统一返回成功结果 单条数据(DTO转为VO)
* @Title: commonResultOfListVO

* @Description:

 * @author guojuxing
* @param response
* @param clazz

* @return com.gic.commons.webapi.reponse.RestResponse


 */
public static RestResponse commonResultOne(ServiceResponse response, Class<?> clazz) {
if (response.isSuccess()) {
return RestResponse.success(EntityUtil.changeEntityNew(clazz, response.getResult()));
} else {
return RestResponse.failure(response.getCode(), response.getMessage());
}
}
}
package com.gic.enterprise.utils;
public class TokenUtils {
private static ThreadLocal<String> tokenThreadLocal = new ThreadLocal<>();
public static void set(String token){
tokenThreadLocal.set(token);
}
public static String get(){
String token = tokenThreadLocal.get();
return token;
}
public static void remove(){
tokenThreadLocal.remove();
}
}
package com.gic.enterprise.utils;
import com.gic.enterprise.base.EnterpriseInfo;
import com.gic.enterprise.base.MenuInfo;
import com.gic.enterprise.base.UserInfo;
import com.gic.enterprise.base.UserResourceInfo;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public class UserDetail implements Serializable {
private Integer userId = 2222;
private UserInfo userInfo;
private EnterpriseInfo enterpriseInfo;
private UserResourceInfo userResourceInfo;
/**
* 用户登陆所有拥有的菜单权限,用于权限拦截
*/
private Map<String, Object> menuUrlMap;
private List<MenuInfo> menuInfoList;
private Map<String, MenuInfo> moduleUrlMap;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getEnterpriseId() {
return enterpriseInfo.getEnterpriseId();
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public EnterpriseInfo getEnterpriseInfo() {
return enterpriseInfo;
}
public void setEnterpriseInfo(EnterpriseInfo enterpriseInfo) {
this.enterpriseInfo = enterpriseInfo;
}
public UserResourceInfo getUserResourceInfo() {
return userResourceInfo;
}
public void setUserResourceInfo(UserResourceInfo userResourceInfo) {
this.userResourceInfo = userResourceInfo;
}
public Map<String, Object> getMenuUrlMap() {
return menuUrlMap;
}
public void setMenuUrlMap(Map<String, Object> menuUrlMap) {
this.menuUrlMap = menuUrlMap;
}
public List<MenuInfo> getMenuInfoList() {
return menuInfoList;
}
public void setMenuInfoList(List<MenuInfo> menuInfoList) {
this.menuInfoList = menuInfoList;
}
public Map<String, MenuInfo> getModuleUrlMap() {
return moduleUrlMap;
}
public void setModuleUrlMap(Map<String, MenuInfo> moduleUrlMap) {
this.moduleUrlMap = moduleUrlMap;
}
}
package com.gic.enterprise.utils;
import com.gic.enterprise.context.UserContext;
public class UserDetailUtils {
public static UserDetail getUserDetail(){
return UserContext.getContext().get();
}
/**
* 返回token值
* @Title: setUserDetail

* @Description:

 * @author guojuxing
* @param userDetail

* @return java.lang.String


 */
public static String setUserDetail(UserDetail userDetail){
return UserContext.getContext().init(userDetail);
}
public static void destory(){
UserContext.getContext().destory();
}
}
package com.gic.enterprise.utils.valid;
import java.util.Iterator;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import com.gic.enterprise.exception.CommonException;
import org.hibernate.validator.HibernateValidator;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.enterprise.error.ErrorCode;
/**
* service层面的参数校验工具
* @ClassName: ValidUtil

* @Description: 

* @author guojuxing

* @date 2019/7/9 10:49 AM

*/
public class ValidParamsUtils {
/**
* 开启快速结束模式 failFast (true)
*/
private static Validator failFastValidator = Validation.byProvider(HibernateValidator.class).configure()
.failFast(true).buildValidatorFactory().getValidator();
/**
* 全部校验
*/
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
private ValidParamsUtils() {
}
/**
* 输出第一个参数错误的信息
* @Title: fastFailValidate

* @Description:

 * @author guojuxing
* @param obj
* @param groups
 分组接口
* @return com.gic.api.base.commons.ServiceResponse


 */
public static <T> ServiceResponse fastFailValidate(T obj, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = failFastValidator.validate(obj, groups);
if (constraintViolations.size() > 0) {
String paramName = constraintViolations.iterator().next().getPropertyPath().toString();
String paramError = constraintViolations.iterator().next().getMessage();
return ServiceResponse.failure(ErrorCode.PARAMETER_ERROR.getCode(), getFailFastMsg(paramName, paramError));
}
return ServiceResponse.success();
}
/**
* 输出所有参数错误的信息
* @Title: allCheckValidate

* @Description:

 * @author guojuxing
* @param obj
* @param groups

* @return com.gic.api.base.commons.ServiceResponse


 */
public static <T> ServiceResponse allCheckValidate(T obj, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, groups);
if (constraintViolations.size() > 0) {
StringBuilder errorMessages = new StringBuilder();
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while (iterator.hasNext()) {
ConstraintViolation<T> violation = iterator.next();
errorMessages.append(getFailFastMsg(violation.getPropertyPath().toString(), violation.getMessage()))
.append(",");
}
return ServiceResponse.failure(ErrorCode.PARAMETER_ERROR.getCode(), errorMessages.toString());
}
return ServiceResponse.success();
}
/**
* 输出所有参数错误的信息
* @Title: allCheckValidate

* @Description:

 * @author guojuxing
* @param obj
* @param groups

* @return com.gic.api.base.commons.ServiceResponse


 */
public static <T> void allCheckValidateOfException(T obj, Class<?>... groups) {
Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj, groups);
if (constraintViolations.size() > 0) {
StringBuilder errorMessages = new StringBuilder();
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while (iterator.hasNext()) {
ConstraintViolation<T> violation = iterator.next();
errorMessages.append(getFailFastMsg(violation.getPropertyPath().toString(), violation.getMessage()))
.append(",");
}
throw new CommonException(ErrorCode.PARAMETER_ERROR.getCode(), errorMessages.toString());
}
}
public static String getFailFastMsg(String paramName, String paramError) {
return String.format("%s:%s", paramName, paramError);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />
\ No newline at end of file
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>com.gic</groupId> <groupId>com.gic</groupId>
<artifactId>gic-enterprise-base</artifactId> <artifactId>gic-pom-base</artifactId>
<version>4.0-SNAPSHOT</version> <version>4.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
...@@ -13,12 +13,93 @@ ...@@ -13,12 +13,93 @@
<artifactId>gic-enterprise-common</artifactId> <artifactId>gic-enterprise-common</artifactId>
<version>4.0-SNAPSHOT</version> <version>4.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<libraryVersion>4.0-SNAPSHOT</libraryVersion>
</properties>
<distributionManagement>
<repository>
<!-- 和 Maven setting 保持一致 -->
<id>nexus-snapshots</id>
<name>nexus distribution snapshot repository</name>
<!-- 这里使用 /content/repositories/snapshots/ -->
<url>http://182.254.134.223:8081/nexus/content/repositories/snapshots/</url>
<!--<url>http://stream.banli.mobi:8081/content/repositories/snapshots/</url>-->
</repository>
<snapshotRepository>
<!-- 和 Maven setting 保持一致 -->
<id>nexus-snapshots</id>
<name>nexus distribution snapshot repository</name>
<!-- 这里使用 /content/repositories/snapshots/ -->
<url>http://182.254.134.223:8081/nexus/content/repositories/Snapshots-1/</url>
<!--<url>http://stream.banli.mobi:8081/content/repositories/snapshots/</url>-->
</snapshotRepository>
</distributionManagement>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.gic</groupId> <groupId>com.gic</groupId>
<artifactId>gic-base-api</artifactId>
<version>${gic-base-api}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-commons</artifactId> <artifactId>gic-commons</artifactId>
<version>${gic-commons}</version> <version>${gic-commons}</version>
</dependency> </dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-enterprise-base-api</artifactId>
<version>${gic-enterprise-base-api}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-log-api</artifactId>
<version>${gic-log-api}</version>
</dependency>
</dependencies> </dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<flattenMode>defaults</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>
\ No newline at end of file
package com.gic.enterprise.ano;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @ClassName: IgnoreAuth
* @Description: 忽略登录认证的请求
* @author xugh
* @date 2018年5月28日 下午1:45:56
*
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreLogin {
}
package com.gic.enterprise.exception;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.error.ErrorCode;
/**
* 全局异常处理类
*
* @author hua
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public RestResponse controllerException(HttpServletResponse response, Exception ex) {
logger.error("err", ex);
RestResponse failureResponse = getRestResponse(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMsg());
StringBuilder sb = new StringBuilder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (PrintWriter printWriter = new PrintWriter(baos)) {
ex.printStackTrace(printWriter);
}
try {
sb.append(baos.toString());
} catch (Exception ignored) {
}
if (sb.length() == 0) {
sb.append(ex.getMessage());
}
// 输出详细错误信息,便于调试
failureResponse.setDetailError(sb.toString());
return failureResponse;
}
/**
* 参数校验异常统一处理
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public RestResponse customException(BindException e) {
List<FieldError> fieldErrors = e.getFieldErrors();
StringBuilder errorMessage = new StringBuilder();
fieldErrors.forEach(fieldError -> {
errorMessage
.append(fieldError.getDefaultMessage())
.append(",");
});
String error = errorMessage.toString();
return getRestResponse(ErrorCode.PARAMETER_ERROR.getCode(), error.substring(0, error.length() - 1));
}
@ExceptionHandler(ConstraintViolationException.class)
public RestResponse constraintViolationException(ConstraintViolationException e) {
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
String paramName = constraintViolations.iterator().next().getPropertyPath().toString();
String paramError = constraintViolations.iterator().next().getMessage();
return getRestResponse(ErrorCode.PARAMETER_ERROR.getCode(), getFailFastMsg(paramName, paramError));
}
@ResponseBody
@ExceptionHandler(CommonException.class)
public RestResponse customException(CommonException e) {
return getRestResponse(e.getErrorCode(), e.getMessage());
}
private RestResponse getRestResponse(String errorCode, String message) {
return RestResponse.failure(errorCode, message);
}
private static String getFailFastMsg(String paramName, String paramError) {
return String.format("%s:%s", paramName, paramError);
}
}
package com.gic.enterprise.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CrossFilter implements Filter{
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) _request;
HttpServletResponse response = (HttpServletResponse) _response;
String origin = request.getHeader("Origin");
if (null != origin) {
response.addHeader("Access-Control-Allow-Origin", origin);
} else {
response.addHeader("Access-Control-Allow-Origin", "*");
}
String head = request.getHeader("Access-Control-Request-Headers") ;
if(null == head) {
response.addHeader("Access-Control-Allow-Headers", "*");
}else {
response.addHeader("Access-Control-Allow-Headers", head);
}
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods", "*");
// 设置过期时间
response.addHeader("Access-Control-Max-Age", "3600");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("Pragma", "no-cache");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
package com.gic.enterprise.filter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new CrossFilter());
bean.addUrlPatterns("/*");
return bean;
}
}
package com.gic.enterprise.interceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSON;
import com.gic.enterprise.ano.IgnoreLogin;
import com.gic.enterprise.base.MenuInfo;
import com.gic.enterprise.constants.Constants;
import com.gic.enterprise.context.UserContext;
import com.gic.enterprise.error.ErrorCode;
import com.gic.enterprise.exception.CommonException;
import com.gic.enterprise.utils.UserDetail;
import com.gic.enterprise.utils.UserDetailUtils;
public class AuthInterceptor extends HandlerInterceptorAdapter {
private static final Logger log = LogManager.getLogger(AuthInterceptor.class);
private static final Map<String, Object> ignoreUriBeforeLoginMap = new HashMap<>(16);
private static final Map<String, Object> ignoreUriAfterLoginMap = new HashMap<>(16);
static {
ignoreUriBeforeLoginMap.put("/gic-auth-web/login", "1");
ignoreUriBeforeLoginMap.put("/gic-auth-web/logout", "1");
ignoreUriBeforeLoginMap.put("/gic-auth-web/list-enterprise-by-phone", "1");
ignoreUriAfterLoginMap.put("/gic-auth-web/login-user-menu", "1");
ignoreUriAfterLoginMap.put("/gic-auth-web/login-user-operation-item", "1");
ignoreUriBeforeLoginMap.put("/api-plug/dict-district-list", "1");
ignoreUriBeforeLoginMap.put("/api-plug/upload-images", "1");
ignoreUriBeforeLoginMap.put("/api-plug/query-provinces", "1");
ignoreUriBeforeLoginMap.put("/api-plug/query-city", "1");
ignoreUriBeforeLoginMap.put("/api-plug/query-county", "1");
ignoreUriBeforeLoginMap.put("/api-plug/query-district", "1");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
String token = UserContext.getContext().getToken();
RpcContext.getContext().getAttachments().put(Constants.USER_TOKEN, token);
System.out.println(JSON.toJSONString(RpcContext.getContext().getArguments()));
// 更新redis
UserContext.getContext().refresh();
if (!(object.getClass().isAssignableFrom(HandlerMethod.class))) {
return true;
}
HandlerMethod handler = (HandlerMethod) object;
//免登录接口路由
IgnoreLogin ignoreLogin = handler.getMethodAnnotation(IgnoreLogin.class);
if (null != ignoreLogin) {
return true;
}
//获取uri
String uri = request.getRequestURI();
//操作项标志位
String isControl = request.getHeader("isControl");
//是否是操作项请求
boolean isOperationItemRequest = StringUtils.isNotBlank(isControl);
log.info("用户接口访问标志:{}", isControl);
log.info("用户接口访问路由:{}", uri);
//不需要拦截的路径
if (ignoreUriBeforeLoginMap.containsKey(uri)) {
return true;
}
//判断是否有权限的路径
UserDetail userDetail = UserDetailUtils.getUserDetail();
if (userDetail == null || userDetail.getUserInfo() == null) {
throw new CommonException(ErrorCode.LOGIN_INVALID.getErrorCode(), "登录信息不存在,请登录");
}
//不需要拦截的路径
if (ignoreUriAfterLoginMap.containsKey(uri)) {
return true;
}
//接口调用,操作项类型的操作,需要 获取操作模块,一级、二级的ID和名称
if (isOperationItemRequest) {
List<MenuInfo> menuInfoList = userDetail.getMenuInfoList();
Map<String, MenuInfo> moduleUrlMap = userDetail.getModuleUrlMap();
//页面路径
String moduleUrl = request.getHeader("Referer");
log.info("完整路由:{}", moduleUrl);
//project_url_for_web + menu_url
moduleUrl = getModuleUrl(moduleUrl);
log.info("操作模块的路由:{}", moduleUrl);
//获取当前操作项数据
MenuInfo menuInfo = moduleUrlMap.get(moduleUrl);
if (menuInfo != null) {
Map<String, MenuInfo> tempMap = listToMap(menuInfoList);
Integer temp = menuInfo.getMenuId();
//获取第二层级的页面
if (menuInfo.getLevel().intValue() > 2) {
temp = getOperationModule(menuInfo.getMenuId(), tempMap);
while (tempMap.get(temp.toString()).getLevel().intValue() != 2) {
temp = getOperationModule(tempMap.get(temp.toString()).getMenuId(), tempMap);
}
}
int secondLevelMenuId = 0;
String secondLevelMenuName = "无";
int firstLevelMenuId;
String firstLevelMenuName;
//用于下载文件,跳转到频道页的地址
String secondLevelUrl = "https://four.gicdev.com";
//如果是第二级的
if (menuInfo.getLevel().intValue() == 2) {
MenuInfo secondMenuInfo = tempMap.get(temp.toString());
secondLevelMenuId = secondMenuInfo.getMenuId();
secondLevelMenuName = secondMenuInfo.getMenuName();
secondLevelUrl = secondLevelUrl + secondMenuInfo.getProjectUrlForWeb() + secondMenuInfo.getMenuUrl();
//获取第一层级的页面
temp = getOperationModule(secondMenuInfo.getMenuId(), tempMap);
firstLevelMenuId = tempMap.get(temp.toString()).getMenuId();
firstLevelMenuName = tempMap.get(temp.toString()).getMenuName();
} else {
//第一级
MenuInfo firstMenuInfo = tempMap.get(temp.toString());
firstLevelMenuId = firstMenuInfo.getMenuId();
secondLevelMenuId = firstMenuInfo.getMenuId();
firstLevelMenuName = firstMenuInfo.getMenuName();
secondLevelUrl = secondLevelUrl + firstMenuInfo.getProjectUrlForWeb() + firstMenuInfo.getMenuUrl();
}
log.info("一级页面的ID和名称:{},{}", firstLevelMenuId, firstLevelMenuName);
log.info("二级页面的ID和名称:{},{}", secondLevelMenuId, secondLevelMenuName);
log.info("二级页面的地址:{}", secondLevelUrl);
request.setAttribute("moduleMenuId", secondLevelMenuId);
request.setAttribute("moduleMenuUrl", secondLevelUrl);
request.setAttribute("moduleMenuName", firstLevelMenuName + "-" + secondLevelMenuName);
}
}
//超级管理员不限制
if (userDetail.getUserInfo().getSuperAdmin().intValue() == 1) {
return true;
}
//判断是否有权限
Map<String, Object> menuUrlMap = userDetail.getMenuUrlMap();
if (menuUrlMap == null || menuUrlMap.isEmpty()) {
throw new CommonException(ErrorCode.SYSTEM_ERROR.getErrorCode(), "sorry,您无该页面的访问权限,请联系超级管理员!");
}
if (isOperationItemRequest) {
//说明是操作项
//如果匹配上了,说明是没权限
if (menuUrlMap.containsKey(uri)) {
throw new CommonException(ErrorCode.SYSTEM_ERROR.getErrorCode(), "sorry,您无该页面的访问权限,请联系超级管理员!");
}
} else {
//说明是页面
//如果没有匹配上,说明没权限
if (!menuUrlMap.containsKey(uri)) {
throw new CommonException(ErrorCode.SYSTEM_ERROR.getErrorCode(), "sorry,您无该页面的访问权限,请联系超级管理员!");
}
}
return true;
}
private static Integer getOperationModule(Integer menuId, Map<String, MenuInfo> tempMap) {
MenuInfo temp = tempMap.get(menuId.toString());
if (temp != null) {
return temp.getParentId();
}
return null;
}
private static Map<String, MenuInfo> listToMap(List<MenuInfo> list) {
Map<String, MenuInfo> map = new HashMap<>(16);
if (CollectionUtils.isNotEmpty(list)) {
for (MenuInfo menuInfo : list) {
map.put(menuInfo.getMenuId().toString(), menuInfo);
}
}
return map;
}
/**
* 截取域名后面的路径
* @param url
* @return
*/
private static String getModuleUrl(String url) {
//形如https://four.gicdev.com/damo-system/account-manage/create-admin
String regex = "/";
String[] stringArr = url.split(regex);
//去掉0、1、2
StringBuilder result = new StringBuilder();
for (int i = 3, length = stringArr.length; i < length; i ++) {
if (i == length - 1) {
//最有一个,需要去掉参数,即?后面的东西
String temp = stringArr[i];
result.append(regex).append(temp.split("[?]")[0]);
} else {
result.append(regex).append(stringArr[i]);
}
}
return result.toString();
}
}
package com.gic.enterprise.interceptor;
import com.gic.commons.web.RequestThreadLocal;
import com.gic.commons.web.ResponseThreadLocal;
import com.gic.enterprise.context.RequestContext;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @ClassName: RequestInteceptor
* @Description: TODO(这里用一句话描述这个类的作用)
* @author xugh
* @date 2018年5月31日 下午4:53:23
*
*/
public class RequestInteceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
RequestContext.getContext().init(request, response);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
RequestContext.getContext().destroy();
}
}
...@@ -2,9 +2,14 @@ package com.gic.enterprise.response; ...@@ -2,9 +2,14 @@ package com.gic.enterprise.response;
import com.gic.api.base.commons.ServiceResponse; import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse; import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.error.Error;
public class EnterpriseRestResponse extends RestResponse { public class EnterpriseRestResponse extends RestResponse {
public static RestResponse failure(ServiceResponse serviceResponse){ public static RestResponse failure(ServiceResponse serviceResponse){
return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage(), serviceResponse.getResult()); return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage(), serviceResponse.getResult());
} }
public static RestResponse failure(Error error){
return RestResponse.failure(error.getErrorCode(), error.getErrorMsg());
}
} }
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:interceptors>
<bean class="com.gic.enterprise.interceptor.RequestInteceptor"></bean>
<bean class="com.gic.commons.interceptor.HeaderTagInterceptor"/>
<bean class="com.gic.enterprise.interceptor.AuthInterceptor"></bean>
</mvc:interceptors>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.gic</groupId>
<artifactId>gic-pom-base</artifactId>
<version>4.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.gic</groupId>
<artifactId>gic-enterprise-download</artifactId>
<version>4.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<libraryVersion>4.0-SNAPSHOT</libraryVersion>
</properties>
<distributionManagement>
<repository>
<!-- 和 Maven setting 保持一致 -->
<id>nexus-snapshots</id>
<name>nexus distribution snapshot repository</name>
<!-- 这里使用 /content/repositories/snapshots/ -->
<url>http://182.254.134.223:8081/nexus/content/repositories/snapshots/</url>
<!--<url>http://stream.banli.mobi:8081/content/repositories/snapshots/</url>-->
</repository>
<snapshotRepository>
<!-- 和 Maven setting 保持一致 -->
<id>nexus-snapshots</id>
<name>nexus distribution snapshot repository</name>
<!-- 这里使用 /content/repositories/snapshots/ -->
<url>http://182.254.134.223:8081/nexus/content/repositories/Snapshots-1/</url>
<!--<url>http://stream.banli.mobi:8081/content/repositories/snapshots/</url>-->
</snapshotRepository>
</distributionManagement>
<dependencies>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-base-api</artifactId>
<version>${gic-base-api}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-commons</artifactId>
<version>${gic-commons}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-enterprise-base-api</artifactId>
<version>${gic-enterprise-base-api}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-platform-enterprise-api</artifactId>
<version>${gic-platform-enterprise-api}</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-log-api</artifactId>
<version>${gic-log-api}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-thirdparty-sdk</artifactId>
<version>4.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-platform-config</artifactId>
<version>${gic-platform-config}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<flattenMode>defaults</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.gic.download.constants;
/**
* Excel文件下载扩展类型
* @ClassName: ExcelExtensionEnum

* @Description: 

* @author guojuxing

* @date 2019/11/6 9:41 AM

*/
public enum ExcelExtensionEnum {
EXCEL_2007(1, ".xlsx"),
EXCEL_2003(2, ".xls"),
CSV(3, ".csv");
private int code;
private String extension;
private ExcelExtensionEnum(int code, String extension) {
this.code = code;
this.extension = extension;
}
public static String getExtensionByCode(Integer code) {
if (code == null) {
return ".csv";
}
for (ExcelExtensionEnum extensionEnum : values()) {
if (code.intValue() == extensionEnum.getCode()) {
return extensionEnum.getExtension();
}
}
return ".csv";
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
package com.gic.download.utils;
import java.io.Serializable;
import java.util.List;
/**
* 工具初始化参数
* @ClassName: DataDownload

* @Description: 

* @author guojuxing

* @date 2019/11/5 9:53 AM

*/
public class DataDownload implements Serializable{
private static final long serialVersionUID = -3448865281389941085L;
/**
* 报表中心ID
*/
private Integer reportId;
/**
* 待下载文件名
*/
private String fileName;
/**
* 待下载文件临时路径
*/
private String tempPath;
/**
* 下载字段名,用于反射获取字段值
*/
private List<String> fieldList;
/**
* 待下载文件标题,一一对应字段名
*/
private List<String> titleList;
/**
* 数据总页数,用于分页生成csv,避免内存溢出
*/
private int totalPage;
public Integer getReportId() {
return reportId;
}
public void setReportId(Integer reportId) {
this.reportId = reportId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getTempPath() {
return tempPath;
}
public void setTempPath(String tempPath) {
this.tempPath = tempPath;
}
public List<String> getFieldList() {
return fieldList;
}
public void setFieldList(List<String> fieldList) {
this.fieldList = fieldList;
}
public List<String> getTitleList() {
return titleList;
}
public void setTitleList(List<String> titleList) {
this.titleList = titleList;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
}
package com.gic.download.utils;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.enterprise.dto.DownloadReportDTO;
import com.gic.enterprise.exception.CommonException;
import com.gic.enterprise.service.DownloadReportApiService;
import com.gic.thirdparty.BucketNameEnum;
import com.gic.thirdparty.FileOperateUtils;
@Component
public class DataDownloadUtils {
private static final Logger LOGGER = LogManager.getLogger(DataDownloadUtils.class);
private static DataDownloadUtils dataDownloadUtils;
@Autowired
private DownloadReportApiService downloadReportApiService;
@PostConstruct
public void init() {
dataDownloadUtils = this;
dataDownloadUtils.downloadReportApiService = downloadReportApiService;
}
/**
* 初始化参数
*/
private DataDownload params;
private File csvFile = null;
private BufferedWriter writer = null;
/**
* 是否已经写入标题
*/
private boolean hasWriteTitle = false;
/**
* 分页数索引
*/
private int index = 0;
/**
* 腾讯云文件路径
*/
private String fileUrl;
/**
* 初始化生成报表中心记录
* @Title: createDownloadReport

* @Description:

 * @author guojuxing
* @param dto

* @return java.lang.Integer


 */
public static Integer createDownloadReport(DownloadReport dto) {
DownloadReportDTO record = EntityUtil.changeEntityNew(DownloadReportDTO.class, dto);
ServiceResponse<Integer> result = dataDownloadUtils.downloadReportApiService.saveDownloadReport(record);
if (result.isSuccess()) {
return result.getResult();
}
throw new CommonException(result);
}
public DataDownloadUtils() {
}
/**
* 初始化下载工具类
* @param initParams
* @throws IOException
*/
public DataDownloadUtils(DataDownload initParams) throws IOException {
LOGGER.info("初始化下载工具类参数值:{}", JSON.toJSONString(initParams));
//初始化字段值
params = EntityUtil.changeEntityNew(DataDownload.class, initParams);
//重置临时文件路径
DataDownloadUtils.mkDir(new File(params.getTempPath()));
File file = new File(params.getTempPath());
//初始化数据
this.csvFile = File.createTempFile(initParams.getFileName(), ".csv", file);
this.writer = new BufferedWriter((new OutputStreamWriter(new FileOutputStream(csvFile), "gbk")));
}
/**
* 写数据
* @param dataList
*/
public void write(List<?> dataList) {
index++;
this.writeTitle();
this.writeData(dataList);
LOGGER.info("index:" + index + ",totalPage:" + params.getTotalPage());
if (index == params.getTotalPage()) {
this.uploadFileToCloud();
DataDownloadUtils.uploadFile(params.getReportId(), this.fileUrl);
}
}
/**
* 删除文件夹
* @param file
*/
public static void mkDir(File file) {
if (file.getParentFile().exists()) {
file.mkdir();
} else {
mkDir(file.getParentFile());
file.mkdir();
}
}
/**
* csv写入标题
*/
private void writeTitle() {
try {
if (!hasWriteTitle) {
if (params.getTitleList() != null) {
for (int i = 0, length = params.getTitleList().size(); i < length; i++) {
writer.append(params.getTitleList().get(i) + ",");
}
writer.newLine();
hasWriteTitle = true;
}
}
} catch (IOException e) {
LOGGER.warn(e);
}
}
private void uploadFileToCloud() {
try {
writer.flush();
String fieldCode = "/" + System.currentTimeMillis() + "_" + params.getFileName() + ".csv";
//文件存进腾讯云
String url = FileOperateUtils.simpleUploadFileFromLocal(csvFile, fieldCode, BucketNameEnum.REPORT_50000.getName());
if (StringUtils.isNotBlank(url)) {
url = "https://" + url;
}
this.fileUrl = url;
LOGGER.info("上传文件到腾讯云,路径:" + url);
csvFile.deleteOnExit();
} catch (IOException e) {
LOGGER.warn(e);
} finally {
this.close();
}
}
/**
* 关闭流
*/
private void close() {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
LOGGER.warn(e);
}
}
/**
* csv写入数据
* @param dataList
*/
private void writeData(List<?> dataList) {
if (dataList == null || params.getFieldList() == null) {
return;
}
try {
for (int i = 0; i < dataList.size(); i++) {
StringBuffer sb = new StringBuffer();
for (int j = 0, length = params.getFieldList().size(); j < length; j++) {
String fieldName = params.getFieldList().get(j);
Object o = DataDownloadUtils.getFieldValue(dataList.get(i), fieldName);
if (o == null) {
sb.append(",");
} else if (o.toString().equals("-1")) {
sb.append(",");
} else if (o instanceof Double) {
DecimalFormat format = new DecimalFormat("0.00");
sb.append(format.format(o) + ",");
} else if (o instanceof Integer) {
sb.append(o + ",");
} else if (o instanceof Date) {
sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(o) + "\t,");
} else {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(o.toString());
if (isNum.matches()) {
if (o.toString().length() >= 12) {
sb.append(o + "\t,");
} else {
sb.append(o + ",");
}
} else {
//去除换行符
o = o.toString().replace("\n", "");
o = o.toString().replace("\r", "");
//英文逗号转义
o = DataDownloadUtils.trimChars(o.toString());
sb.append(o + ",");
}
}
}
writer.append(sb.toString());
writer.flush();
writer.newLine();
}
} catch (IOException e) {
LOGGER.warn(e);
}
}
/**
* @Title: trimRubbishChar
* @Description: 导出的时候需要对一格的内容进行检查,看是否有非法字符,以免串行
* @Since: 2016年8月2日 下午8:13:42
* @Author: niewj
* @param content
* @return
* @throws
*/
private static String trimChars(String content) {
if (content == null) {
return "";
}
// @====> 1.包含,同时包含",那么先替换双引号"为两个"" + 然后在包裹在双引号里。
if (content.contains(",") && content.contains("\"")) {
//content = content.replaceAll(",", " "); // 逗号替换为空格
content = content.replaceAll("\"", "\"\"");
content = "\"" + content + "\"";
} else if (content.contains(",") && !content.contains("\"")) {
// @====> 2.如果仅仅包含逗号,则用引号包裹即可。
//content = content.replaceAll(",", " "); // 逗号替换为空格
content = "\"" + content + "\"";
} else if (content.contains("\"") && !content.contains(",")) {
// @====> 3.如果仅仅包含引号,则双引号代替一个引号,再最外层在包裹即可。
content = "\"" + content.replaceAll("\"", "\"\"") + "\"";
}
return content;
}
/**
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
*/
private static Object getFieldValue(final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
throw new IllegalArgumentException("no field [" + fieldName + "]");
}
Object result = null;
try {
Method method = obj.getClass()
.getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), null);
return method.invoke(obj, null);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private static Field getAccessibleField(final Object obj, final String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 更新报表记录的腾讯云文件url
* @param reportId
* @param fileUrl
*/
public static void uploadFile(Integer reportId, String fileUrl) {
ServiceResponse<Integer> result = dataDownloadUtils.downloadReportApiService
.updateDownloadUrl(reportId, fileUrl);
if (!result.isSuccess()) {
throw new CommonException(result);
}
}
}
package com.gic.download.utils;
import java.io.Serializable;
import java.util.Date;
/**
* 创建下载记录的参数
* @ClassName: DownloadReport

* @Description: 

* @author guojuxing

* @date 2019/11/4 7:52 PM

*/
public class DownloadReport implements Serializable{
private static final long serialVersionUID = -8175883273955206619L;
private Integer enterpriseId;
/**
* 申请人ID
*/
private Integer applyUserId;
/**
* 待下载数据的开始世界
*/
private Date reportStartTime;
/**
* 待下载数据的结束世界
*/
private Date reportEndTime;
/**
* 待下载文件名
*/
private String fileName;
/**
* 数据源(频道页),用 "-" 隔开上级和本级
*/
private String dataContent;
/**
* 数据源超链接,用于点击跳转对应频道页面
*/
private String dataUrl;
/**
* 报告类型 1:完整数据, 2:脱敏数据, 3:二维码
*/
private Integer dataType;
/**
* 待下载数据的数据总量
*/
private Integer dataCount;
public Integer getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(Integer enterpriseId) {
this.enterpriseId = enterpriseId;
}
public Integer getApplyUserId() {
return applyUserId;
}
public void setApplyUserId(Integer applyUserId) {
this.applyUserId = applyUserId;
}
public Date getReportStartTime() {
return reportStartTime;
}
public void setReportStartTime(Date reportStartTime) {
this.reportStartTime = reportStartTime;
}
public Date getReportEndTime() {
return reportEndTime;
}
public void setReportEndTime(Date reportEndTime) {
this.reportEndTime = reportEndTime;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDataContent() {
return dataContent;
}
public void setDataContent(String dataContent) {
this.dataContent = dataContent;
}
public String getDataUrl() {
return dataUrl;
}
public void setDataUrl(String dataUrl) {
this.dataUrl = dataUrl;
}
public Integer getDataType() {
return dataType;
}
public void setDataType(Integer dataType) {
this.dataType = dataType;
}
public Integer getDataCount() {
return dataCount;
}
public void setDataCount(Integer dataCount) {
this.dataCount = dataCount;
}
}
package com.gic.download.utils;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import com.gic.download.constants.ExcelExtensionEnum;
import com.gic.thirdparty.BucketNameEnum;
import com.gic.thirdparty.FileOperateUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DownloadUtils {
private static final Logger LOGGER = LogManager.getLogger(DownloadUtils.class);
private static final String SUFFIX_EXCEL_2007 = "xlsx";
private static final String SUFFIX_CSV = "csv";
private static final String SUFFIX_EXCEL_2003 = "xls";
/**
* 分页下载数据获取类
* @author Silver
* @date 2017年3月16日 上午11:45:13
*
* @param <T>
*
*/
protected abstract class DownloadDataLoader<T> {
/**
* 分页下载属性值控制操作类
* @param bean
* @param propertyName
* @param property
* @return
* @author Silver
* @date 2017年3月16日 上午11:45:45
*/
protected String convertProperty(T bean, String propertyName, Object property) {
try {
Class clazz = getPropertyType(bean, propertyName);
if (Date.class.equals(clazz)) {
//如果是日期类型
SimpleDateFormat format = new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy", Locale.US);
SimpleDateFormat resultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return resultFormat.format(format.parse(property.toString()));
}
} catch (Exception e) {
LOGGER.info("bean:" + bean + ",Property:" + propertyName + e.getMessage(), e);
return null;
}
return property == null ? "" : property.toString();
}
protected Class getPropertyType(T bean, String propertyName) {
try {
return new PropertyUtilsBean().getPropertyType(bean, propertyName);
} catch (Throwable e) {
LOGGER.info("bean:" + bean + ",Property:" + propertyName + e.getMessage(), e);
return null;
}
}
/**
* 分页下载属性赋值
* @param bean
* @param propertyName
* @return
* @author Silver
* @date 2017年3月16日 上午11:46:37
*/
protected Object getProperty(T bean, String propertyName) {
try {
return BeanUtils.getProperty(bean, propertyName);
} catch (Throwable e) {
LOGGER.info("bean:" + bean + ",Property:" + propertyName + e.getMessage(), e);
return null;
}
}
/**
* 数据获取接口
* @param pageNum -- 从0计数
* @return
* @throws Exception
* @author Silver
* @date 2017年3月16日 上午11:47:07
*/
protected abstract List<T> getDownloadData(Integer pageNum) throws Exception;
};
protected static interface Writer {
public void write(Collection<String> row) throws IOException;
}
/**
* Web下载文件
* @param tempPath 临时路径
* @param reportId 报表中心ID
* @param fileName 文件名称
* @param excelExtensionCode Excel文件扩展名 枚举 ExcelExtensionEnum
* @param headerList 表头名称
* @param propertyNameList 字段名
* @param loader 数据加载类
* @param needEncryptField 需要加密的字段,每一个元素存的是字段,如phone(电话)
* @param columnWidth 列宽
* @throws Exception
* @author Silver
* @date 2017年3月16日 上午11:47:31
*/
protected <T> void download(String tempPath, Integer reportId, String fileName, Integer excelExtensionCode, List<String> headerList, List<String> propertyNameList, DownloadDataLoader<T> loader, List<String> needEncryptField, List<Integer> columnWidth) throws Exception {
if (StringUtils.isEmpty(fileName) || loader == null || CollectionUtils.isEmpty(propertyNameList)) {
throw new RuntimeException("参数错误。FileName:" + fileName + ",DataLoader:" + loader + ",PropertyName:" + propertyNameList);
}
// 获取输出流,设置content-type等头域
//final OutputStream out = getResponseStream(response ,fileName);
File tempFile = null;
//重置临时文件路径
DataDownloadUtils.mkDir(new File(tempPath));
File file = new File(tempPath);
//初始化数据
if (fileName.length() < 3) {
//如果长度太短
fileName = fileName + "__";
}
tempFile = File.createTempFile(fileName, ExcelExtensionEnum.getExtensionByCode(excelExtensionCode), file);
final OutputStream out = new FileOutputStream(tempFile);
try {
Writer writer = null;
// 获取文件后缀名
String extension = ExcelExtensionEnum.getExtensionByCode(excelExtensionCode);
// 如果是excel的后缀
if (ExcelExtensionEnum.EXCEL_2003.getExtension().equalsIgnoreCase(extension) || ExcelExtensionEnum.EXCEL_2007.getExtension().equalsIgnoreCase(extension)) {
Workbook workbook;
if (ExcelExtensionEnum.EXCEL_2003.getExtension().equalsIgnoreCase(extension)) {
workbook = new HSSFWorkbook();
} else {
workbook = new XSSFWorkbook();
}
Sheet sheet = workbook.createSheet("sheet1");
final List<Collection<String>> rows = new ArrayList<>();
writer = new Writer() {
@Override
public void write(Collection<String> row) {
rows.add(row);
}
};
writeOutputStream(loader, propertyNameList, writer, needEncryptField);
// 写入excel
if (!ExcelUtils.setExcelInfo(sheet, columnWidth, headerList, rows)) {
throw new IOException("设置导出文件内容失败。");
}
workbook.write(out);
} else if (ExcelExtensionEnum.CSV.getExtension().equalsIgnoreCase(extension)) {
writer = new Writer() {
@Override
public void write(Collection<String> row) throws IOException {
String str = ExcelUtils.collectionToCsvString(row);
byte[] content = org.apache.commons.codec.binary.StringUtils.getBytesUnchecked(str + "\n",
"GBK");
IOUtils.write(content, out);
out.flush();
}
};
// 写文件头
writer.write(headerList);
// 写文件
writeOutputStream(loader, propertyNameList, writer, needEncryptField);
} else {
writer = new Writer() {
@Override
public void write(Collection<String> row) throws IOException {
IOUtils.write(org.apache.commons.codec.binary.StringUtils.getBytesUnchecked(row + "\n",
"GBK"), out);
out.flush();
}
};
// 写文件头
writer.write(headerList);
// 写文件
writeOutputStream(loader, propertyNameList, writer, needEncryptField);
}
out.flush();
tempFile.deleteOnExit();
//上传文件
String fieldCode = "/" + System.currentTimeMillis() + "_" + fileName + ExcelExtensionEnum.getExtensionByCode(excelExtensionCode);
//文件存进腾讯云
String url = FileOperateUtils.simpleUploadFileFromLocal(tempFile, fieldCode, BucketNameEnum.REPORT_50000.getName());
if (org.apache.commons.lang.StringUtils.isNotBlank(url)) {
url = "https://" + url;
}
LOGGER.info("上传文件到腾讯云,路径:" + url);
//更新数据
DataDownloadUtils.uploadFile(reportId, url);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* 获得输出流
*
* @return
* @throws IOException
*/
protected OutputStream getResponseStream(HttpServletResponse response, String fileName) throws IOException {
if (StringUtils.isEmpty(fileName)) {
fileName = DateUtils.formatDate(new Date(), "yyyy-MM-dd_HH-mm-ss") + SUFFIX_CSV;
}
response.reset();
String extension = FilenameUtils.getExtension(fileName);
if(SUFFIX_EXCEL_2007.equalsIgnoreCase(extension)){
// 部分window版本生成后的xlsx打不开,默认改成xls打开
fileName = fileName.substring(0, fileName.length() -1);
}
//设置响应编码
response.setCharacterEncoding("UTF-8");
//设置对应的contentType
response.setContentType("application/x-download;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="
+ new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
OutputStream out = response.getOutputStream();
return out;
}
protected <T> void writeOutputStream(DownloadDataLoader<T> loader, List<String> propertyNames,
Writer writer, List<String> needEncryptField) throws Exception {
int pageNum = 1;
int maxLength = 102400;
while (maxLength -- > 0) {
// 分页获取数据
List<T> objList = null;
try {
objList = loader.getDownloadData(pageNum++);
} catch (Exception e) {
LOGGER.error("获得到处数据异常:{}",e.getMessage(), e);
}
if (CollectionUtils.isEmpty(objList)) {
break;
}
for (T bean : objList) {
if (bean == null) {
continue;
}
Collection<String> result = new ArrayList<String>();
// 遍历指定属性
for (String name : propertyNames) {
// 获得属性值
Object property = loader.getProperty(bean, name);
// 将属性值转换成字符串
String convertValue = loader.convertProperty(bean, name, property);
//加密处理
if (needEncryptField != null && needEncryptField.contains(name)) {
convertValue = encrypt(convertValue);
}
// 组装成row
result.add(convertValue);
}
if (CollectionUtils.isEmpty(result)) {
continue;
}
writer.write(result);
}
}
}
private static String encrypt(String data) {
if (StringUtils.isBlank(data)) {
return data;
}
//手机号或者会员卡号 第5-8位用*代替
int length = data.length();
if (length > 8) {
return data.substring(0, 4) + "****" + data.substring(8);
} else if (length > 4) {
return data.substring(0, 4) + "****";
} else {
return "****";
}
}
}
package com.gic.download.utils;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelUtils {
/**
* logger
*/
private static final Logger logger = LogManager.getLogger(ExcelUtils.class);
/**
* 设置列格式
*
* @param sheet
* @param columnWidthList
*/
public static boolean setSheetStyle(Sheet sheet, List<Integer> columnWidthList) {
if (sheet == null || columnWidthList == null) {
return false;
}
// 设置所有列的宽度
for (int indx = 0, iMax = columnWidthList.size(); indx < iMax; indx++) {
Integer columnWidth = columnWidthList.get(indx);
if (columnWidth == null) {
continue;
}
sheet.setColumnWidth(indx, columnWidth.intValue() * 256);
}
return true;
}
/**
* 设置行信息
*
* @param row
* @param rowObj
* @return
*/
public static boolean setRowInfo(Row row, Collection<Object> rowObj) {
if (row == null || rowObj == null) {
if (logger.isInfoEnabled()) {
logger.info("Row:" + row + ",rowObj" + rowObj);
}
return false;
}
// 填充每一列数据
int indxColumn = 0;
for (Object object : rowObj) {
Cell cell = row.createCell(indxColumn++);
if (object == null) {
if (logger.isDebugEnabled()) {
logger.debug("Row:" + row + ",Column:" + indxColumn + ",is empty");
}
continue;
}
String columnValue = object.toString();
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(columnValue);
}
return true;
}
/**
* 设置行信息
*
* @param row
* @param rowObj
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean setRowInfo(Row row, Object rowObj) {
if (row == null || rowObj == null) {
if (logger.isInfoEnabled()) {
logger.info("Row:" + row + ",rowObj" + rowObj);
}
return false;
}
try {
Collection<Object> rowContent = null;
if (rowObj instanceof Map) {
rowContent = ((Map) rowObj).values();
} else if (rowObj instanceof Collection) {
rowContent = (Collection) rowObj;
} else {
rowContent = (new BeanMap(rowObj)).values();
}
if (rowContent == null || rowContent.isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Row:" + row + ",is empty");
}
return false;
}
return setRowInfo(row, rowContent);
} catch (Throwable e) {
logger.info(rowObj + "convertFailed,row:" + row, e);
return false;
}
}
/**
* 将数据写入excel
*
* @param sheet
* @param columnWidth
* @param header
* @param content
* @return
*/
public static boolean setExcelInfo(Sheet sheet, List<Integer> columnWidth, List<String> header, List<?> content) {
if (sheet == null) {
logger.info("sheet is null");
return false;
}
// 设置sheet格式
setSheetStyle(sheet, columnWidth);
// 设置头信息
int indexRow = 0;
Row row = sheet.createRow(indexRow++);
setRowInfo(row, header);
// 如果内容为空 则退出
if (content == null || content.isEmpty()) {
logger.info("content is null,cannot write excel");
return true;
}
for (Object rowContent : content) {
row = sheet.createRow(indexRow++);
setRowInfo(row, rowContent);
}
return true;
}
/**
* 導出到excel
*
* @param title
* sheet Title
* @param columnWidthList
* 所有列的寬度,可以不指定
* @param content
* 內容, 每一項為一行,每一行內是List代表所有列
* @return
*/
public static Workbook setupXls(String title, List<Integer> columnWidthList, List<List<String>> content) {
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(title);
if (columnWidthList != null) {
// 设置所有列的宽度
for (int indx = 0, iMax = columnWidthList.size(); indx < iMax; indx++) {
Integer columnWidth = columnWidthList.get(indx);
if (columnWidth == null) {
continue;
}
sheet.setColumnWidth(indx, columnWidth.intValue() * 256);
}
}
if (content == null || content.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info("content is null,cannot write excel,title:" + title);
}
return wb;
}
// 遍歷一行
for (int indxRow = 0, iMaxRow = content.size(); indxRow < iMaxRow; indxRow++) {
Row row = sheet.createRow(indxRow);
List<String> rowContent = content.get(indxRow);
if (rowContent == null || rowContent.isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("Row:" + indxRow + ",is empty,title:" + title);
}
continue;
}
// 填充每一列数据
for (int indxColumn = 0, iMaxColumn = rowContent.size(); indxColumn < iMaxColumn; indxColumn++) {
Cell cell = row.createCell(indxColumn);
String columnValue = rowContent.get(indxColumn);
if (columnValue == null || columnValue.length() == 0) {
if (logger.isDebugEnabled()) {
logger.debug("Row:" + indxRow + ",Column:" + indxColumn + ",is empty,title:" + title);
}
continue;
}
cell.setCellValue(columnValue);
}
}
return wb;
}
/**
* 加載Excel 默認實現方式
*
* @param wb
* @return
*/
public static List<List<String>> loadXls(Workbook wb) {
// 默認 只讀第一個sheet, 且從第二行開始遍歷,默认读取到最大列
return loadXls(wb, 0, 1, 0);
}
/**
* 加载excel
*
* @param wb
* @param sheetIndex
* 要加载excel的sheet页的index
* @param startRowIndex
* 要加载Row的index
* @param iMaxColumn
* 最大读到Cloumn的index
* @return List<List<>>
*/
public static List<List<String>> loadXls(Workbook wb, int sheetIndex, int startRowIndex, int iMaxColumn) {
List<List<String>> resList = new ArrayList<>();
if (wb == null || sheetIndex < 0 || startRowIndex < 0 || iMaxColumn < 0) {
logger.error("param error,return empty list,Workbook:" + wb + ",sheetIndex:" + sheetIndex + ",startRowNo:" + startRowIndex + ",iMaxColumn:" + iMaxColumn);
return resList;
}
Sheet sheet = wb.getSheetAt(sheetIndex);
if (sheet == null) {
logger.error("sheet is null,return empty list,Workbook:" + wb + ",sheetIndex:" + sheetIndex + ",startRowNo:" + startRowIndex);
return resList;
}
// 從指定行開始遍歷
for (int indexRow = startRowIndex, iMaxRow = sheet.getLastRowNum(); indexRow <= iMaxRow; indexRow++) {
Row row = sheet.getRow(indexRow);
if (row == null) {
if (logger.isDebugEnabled()) {
logger.debug("Row is null,sheetIndex:" + sheetIndex + ",RowNo:" + indexRow);
}
continue;
}
List<String> rowContent = new ArrayList<String>();
// 當最大列為0時 讀取最大CellNum
if (iMaxColumn == 0) {
iMaxColumn = row.getLastCellNum();
}
boolean hasContent = false;
for (int indexColumn = 0; indexColumn < iMaxColumn; indexColumn++) {
String cellValue = null;
Cell cell = row.getCell(indexColumn);
if (cell == null) {
if (logger.isDebugEnabled()) {
logger.debug("Cell is null,sheetIndex:" + sheetIndex + ",RowNo:" + indexRow + ",CellNo:" + indexColumn);
}
} else {
cellValue = getCellStrValue(cell);
}
// 如果 读到的内容不是空 代表这行有数据
if (cellValue != null && cellValue.length() > 0) {
hasContent = true;
}
// 不论当前格是否有数据都加入.
rowContent.add(cellValue);
}
// 这一行有内容 则加入
if (hasContent) {
resList.add(rowContent);
}
}
return resList;
}
public static String getCellStrValue(Cell cell) {
String res = "";
try {
res = cell.getStringCellValue();
} catch (Exception e) {
DecimalFormat df = new DecimalFormat("#");
res = df.format(cell.getNumericCellValue()) + "";
}
return res;
}
/**
*
* @Description: 将集合转换成字符串输出
* @param coll
* @return 设定文件
* @author albert.su suzy@malam.com
* @date 2014年5月7日 下午12:35:55
*/
public static String collectionToCsvString(Collection<?> coll) {
if (CollectionUtils.isEmpty(coll)) {
return "";
}
StringBuilder sb = new StringBuilder();
Iterator<?> it = coll.iterator();
while (it.hasNext()) {
Object object = it.next();
if (String.valueOf(object).matches("[0-9,\\.]+") || String.valueOf(object).contains(",")) {
sb.append("\"\t");
sb.append(object);
sb.append("\"");
} else {
sb.append("\t");
sb.append(object);
}
if (it.hasNext()) {
sb.append(",");
}
}
return sb.toString();
}
// 以下为糯米的代码, 建议少用
/**
* 从InputStream读取Excel workbook
*
* @param ins
* @return
* @throws IOException
* @throws FileNotFoundException
*/
public static HSSFWorkbook readWorkbook(InputStream ins) throws IOException, FileNotFoundException {
ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
BufferedInputStream bis = new BufferedInputStream(ins);
byte[] by = new byte[512];
int t = bis.read(by, 0, by.length);
while (t > 0) {
// read 512
byteOS.write(by, 0, 512);
t = bis.read(by, 0, by.length);
}
byteOS.close();
InputStream byteIS = new ByteArrayInputStream(byteOS.toByteArray());
HSSFWorkbook wbDest = new HSSFWorkbook(byteIS);
return wbDest;
}
public static void writeToResponse(HttpServletResponse response, HSSFWorkbook wb, String fileName) throws IOException {
response.setContentType("application/ms-download");
response.setCharacterEncoding("gb2312");
response.setHeader("Content-Disposition", "filename=" + fileName);
OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
}
/**
* 判断单元格的格式
*
* @param cell
* 单元格
* @return String 将excel各种单元格的类型转换为String类型
*/
public static String getCellStringValue(HSSFCell cell) {
// 转换后单元格的值
String value = "";
if (cell != null) {
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
value = sdf.format(date);
} else {
DecimalFormat formatter = new DecimalFormat("########");
value = formatter.format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
value = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
default:
break;
}
}
return value;
}
/**
* 到出excel的Helper类
*
* @author Administrator
*
*/
public static class ExcelRowBuilder {
private HSSFRow row;
private short index = 0;
public ExcelRowBuilder(HSSFRow row) {
this.row = row;
}
@SuppressWarnings("deprecation")
public ExcelRowBuilder addCell(String str) {
HSSFCell cell = row.createCell(index++);
cell.setCellValue(new HSSFRichTextString(str));
return this;
}
@SuppressWarnings("deprecation")
public ExcelRowBuilder addCell(long value) {
HSSFCell cell = row.createCell(index++);
cell.setCellValue(value);
return this;
}
@SuppressWarnings("deprecation")
public ExcelRowBuilder addCell(double value) {
HSSFCell cell = row.createCell(index++);
cell.setCellValue(value);
return this;
}
}
}
package com.gic.download.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.inject.Singleton;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池单例类
* 用于导出数据异步使用
* @ClassName: ExecutorPoolSingleton

* @Description: 

* @author guojuxing

* @date 2019/11/5 7:56 PM

*/
public class ExecutorPoolSingleton {
private Logger logger = LogManager.getLogger(ExecutorPoolSingleton.class);
private static final int availableProcessor = Runtime.getRuntime().availableProcessors();
private static ExecutorService executorService;
private ExecutorPoolSingleton() {
if (executorService == null) {
int coreNum = availableProcessor / 2;
// 用单例模式创建线程池,保留2个核心线程,最多线程为CPU个数的2n+1的两倍.
int maxProcessor = (availableProcessor * 2 + 1) * 2 ;
executorService = new ThreadPoolExecutor(coreNum > 2 ? 2 : coreNum, maxProcessor,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
}
private static ExecutorPoolSingleton instance;
public static ExecutorPoolSingleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new ExecutorPoolSingleton();
}
}
}
return instance;
}
int executeThreadNum = 1;
/**
* 执行任务
* @param runnable
*/
public void executeTask(Runnable runnable) {
executorService.execute(runnable);
logger.info("异步线程执行了%d次:{} ", executeThreadNum++);
}
}
package com.gic.download.utils;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.download.utils.log.LogUtils;
public class OperationResultUtils {
public static final String LOG_NEW = "新增";
public static final String LOG_EDIT = "修改";
public static final String LOG_DELETE = "删除";
public static final String LOG_SORT = "排序";
/**
* 新增/编辑/删除接口(含日志)
* @param response
* @return
*/
public static RestResponse operationResult(ServiceResponse response, String content, String operationObject) {
if (response.isSuccess()) {
LogUtils.createLog(content, operationObject);
return RestResponse.success(response.getResult());
} else {
return RestResponse.failure(response.getCode(), response.getMessage());
}
}
public static String getOperationObject(ServiceResponse<String> result) {
return result.isSuccess() ? result.getResult() : null;
}
}
package com.gic.download.utils.log;
import com.alibaba.fastjson.JSON;
import com.gic.download.utils.ExecutorPoolSingleton;
import com.gic.enterprise.context.RequestContext;
import com.gic.enterprise.utils.UserDetail;
import com.gic.enterprise.utils.UserDetailUtils;
import com.gic.log.api.dto.SystemSetLogDTO;
import com.gic.log.api.service.LogApiService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class LogUtils {
private static final Logger LOGGER = LogManager.getLogger(LogUtils.class);
private static LogApiService logApiService;
@Autowired
public void setLogApiService(LogApiService logApiService) {
LogUtils.logApiService = logApiService;
}
/**
* 添加日志
* @Title: createLog

* @Description:

 * @author guojuxing
* @param content 操作内容
* @param operationObject
 操作对象
* @return void


 */
public static void createLog(String content, String operationObject) {
UserDetail userDetail = UserDetailUtils.getUserDetail();
SystemSetLogDTO logDTO = new SystemSetLogDTO();
//操作时间
logDTO.setCreateTime(new Date());
//操作人
logDTO.setUserId(Long.valueOf(userDetail.getUserInfo().getUserId()));
logDTO.setUserName(userDetail.getUserInfo().getUserName());
//操作内容
logDTO.setContent(content);
//操作模块
String moduleMenuName = (String) RequestContext.getContext().getRequest().getAttribute("moduleMenuName");
Integer moduleMenuId = (Integer) RequestContext.getContext().getRequest().getAttribute("moduleMenuId");
if (moduleMenuId != null) {
logDTO.setRelationId(Long.valueOf(moduleMenuId));
} else {
LOGGER.info("操作模块数据有误");
}
//操作对象
//账号(手机号)?
logDTO.setEnterpriesId(Long.valueOf(userDetail.getEnterpriseInfo().getEnterpriseId()));
logDTO.setEnterpriseName(userDetail.getEnterpriseInfo().getEnterpriseName());
ExecutorPoolSingleton.getInstance().executeTask(new Runnable() {
@Override
public void run() {
LOGGER.info("添加日志了,恭喜发财。{}", JSON.toJSONString(logDTO));
logApiService.saveSystemSetLog(logDTO);
}
});
}
/**
* 添加日志
* @Title: createLog

* @Description:

 * @author guojuxing
* @param content 操作内容
* @param operationObject
 操作对象
* @return void


 */
public static void createLog(String content, String operationObject, String username, Integer enterpriseId, String enterpriseName) {
UserDetail userDetail = UserDetailUtils.getUserDetail();
SystemSetLogDTO logDTO = new SystemSetLogDTO();
//操作时间
logDTO.setCreateTime(new Date());
//操作人
// logDTO.setUserId(Long.valueOf(userDetail.getUserInfo().getUserId()));
logDTO.setUserName(username);
//操作内容
logDTO.setContent(content);
//操作模块
// String moduleMenuName = (String) RequestContext.getContext().getRequest().getAttribute("moduleMenuName");
// Integer moduleMenuId = (Integer) RequestContext.getContext().getRequest().getAttribute("moduleMenuId");
// if (moduleMenuId != null) {
// logDTO.setRelationId(Long.valueOf(moduleMenuId));
// } else {
// LOGGER.info("操作模块数据有误");
// }
//操作对象
//账号(手机号)?
logDTO.setEnterpriesId(Long.valueOf(enterpriseId));
logDTO.setEnterpriseName(enterpriseName);
ExecutorPoolSingleton.getInstance().executeTask(new Runnable() {
@Override
public void run() {
LOGGER.info("添加日志了,恭喜发财。{}", JSON.toJSONString(logDTO));
logApiService.saveSystemSetLog(logDTO);
}
});
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
...@@ -11,6 +11,7 @@ ...@@ -11,6 +11,7 @@
<groupId>com.gic</groupId> <groupId>com.gic</groupId>
<artifactId>gic-enterprise-base</artifactId> <artifactId>gic-enterprise-base</artifactId>
<packaging>pom</packaging>
<version>4.0-SNAPSHOT</version> <version>4.0-SNAPSHOT</version>
<properties> <properties>
...@@ -22,47 +23,7 @@ ...@@ -22,47 +23,7 @@
<modules> <modules>
<module>gic-enterprise-base-api</module> <module>gic-enterprise-base-api</module>
<module>gic-enterprise-common</module> <module>gic-enterprise-common</module>
<module>gic-enterprise-download</module>
</modules> </modules>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<flattenMode>defaults</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>
\ No newline at end of file
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