diff --git a/iBase4J-Biz-Web/src/main/java/org/ibase4j/core/shiro/Realm.java b/iBase4J-Biz-Web/src/main/java/org/ibase4j/core/shiro/Realm.java index fe9017dc..2edf2862 100644 --- a/iBase4J-Biz-Web/src/main/java/org/ibase4j/core/shiro/Realm.java +++ b/iBase4J-Biz-Web/src/main/java/org/ibase4j/core/shiro/Realm.java @@ -20,8 +20,8 @@ import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.ibase4j.core.util.WebUtil; -import org.ibase4j.model.sys.SysSession; -import org.ibase4j.model.sys.SysUser; +import org.ibase4j.model.SysSession; +import org.ibase4j.model.SysUser; import org.ibase4j.service.sys.SysAuthorizeService; import org.ibase4j.service.sys.SysSessionService; import org.ibase4j.service.sys.SysUserService; diff --git a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysAuthorizeService.java b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysAuthorizeService.java index bcf1d1c8..1bbaca81 100644 --- a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysAuthorizeService.java +++ b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysAuthorizeService.java @@ -4,11 +4,11 @@ import org.ibase4j.core.exception.IllegalParameterException; import org.ibase4j.core.util.WebUtil; -import org.ibase4j.model.sys.SysMenu; -import org.ibase4j.model.sys.SysRoleMenu; -import org.ibase4j.model.sys.SysUserMenu; -import org.ibase4j.model.sys.SysUserRole; -import org.ibase4j.provider.sys.ISysAuthorizeProvider; +import org.ibase4j.model.SysMenu; +import org.ibase4j.model.SysRoleMenu; +import org.ibase4j.model.SysUserMenu; +import org.ibase4j.model.SysUserRole; +import org.ibase4j.provider.ISysAuthorizeProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysEventService.java b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysEventService.java index 5fa6ba3c..17790cc8 100644 --- a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysEventService.java +++ b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysEventService.java @@ -1,112 +1,16 @@ package org.ibase4j.service.sys; -import java.io.IOException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.ibase4j.core.Constants; import org.ibase4j.core.base.BaseService; +import org.ibase4j.core.support.ISysEventService; import org.ibase4j.core.support.dubbo.spring.annotation.DubboReference; -import org.ibase4j.core.util.DateUtil; -import org.ibase4j.core.util.ExceptionUtil; -import org.ibase4j.core.util.WebUtil; -import org.ibase4j.model.sys.SysEvent; -import org.ibase4j.provider.sys.ISysEventProvider; +import org.ibase4j.model.SysEvent; +import org.ibase4j.provider.ISysEventProvider; import org.springframework.stereotype.Service; -import com.alibaba.fastjson.JSON; - -import cz.mallat.uasparser.OnlineUpdater; -import cz.mallat.uasparser.UASparser; -import cz.mallat.uasparser.UserAgentInfo; - @Service -public class SysEventService extends BaseService - implements org.ibase4j.core.support.SysEventService { +public class SysEventService extends BaseService implements ISysEventService { @DubboReference public void setProvider(ISysEventProvider provider) { this.provider = provider; } - static UASparser uasParser = null; - - // 初始化uasParser对象 - static { - try { - uasParser = new UASparser(OnlineUpdater.getVendoredInputStream()); - } catch (IOException e) { - logger.error("", e); - } - } - - private ExecutorService executorService = Executors.newCachedThreadPool(); - - public void saveEvent(final HttpServletRequest request, final HttpServletResponse response, final Exception ex, - final Long startTime, final Long endTime) { - String userAgent = null; - try { - UserAgentInfo userAgentInfo = uasParser.parse(request.getHeader("user-agent")); - userAgent = userAgentInfo.getOsName() + " " + userAgentInfo.getType() + " " + userAgentInfo.getUaName(); - } catch (IOException e) { - logger.error("", e); - } - String path = request.getServletPath(); - if (!path.contains("/read/") && !path.contains("/unauthorized") && !path.contains("/forbidden")) { - final SysEvent record = new SysEvent(); - Long uid = WebUtil.getCurrentUser(); - record.setMethod(request.getMethod()); - record.setRequestUri(request.getServletPath()); - record.setClientHost(WebUtil.getHost(request)); - record.setUserAgent(userAgent); - if (path.contains("/upload/")) { - record.setParameters(""); - } else { - record.setParameters(JSON.toJSONString(request.getParameterMap())); - } - record.setStatus(response.getStatus()); - record.setCreateBy(uid); - record.setUpdateBy(uid); - final String msg = (String) request.getAttribute("msg"); - - executorService.submit(new Runnable() { - public void run() { - try { // 保存操作 - record.setTitle((String) request.getAttribute(Constants.OPERATION_NAME)); - if (StringUtils.isNotBlank(msg)) { - record.setRemark(msg); - } else { - record.setRemark(ExceptionUtil.getStackTraceAsString(ex)); - } - - update(record); - // 内存信息 - if (logger.isDebugEnabled()) { - String message = "开始时间: {}; 结束时间: {}; 耗时: {}s; URI: {}; "; - // 最大内存: {}M; 已分配内存: {}M; 已分配内存中的剩余空间: {}M; 最大可用内存: - // {}M. - // long total = Runtime.getRuntime().totalMemory() / - // 1024 / 1024; - // long max = Runtime.getRuntime().maxMemory() / - // 1024 / 1024; - // long free = Runtime.getRuntime().freeMemory() / - // 1024 / 1024; - // , max, total, free, max - total + free - logger.debug(message, DateUtil.format(startTime, "HH:mm:ss.SSS"), - DateUtil.format(endTime, "HH:mm:ss.SSS"), (endTime - startTime) / 1000.00, - record.getRequestUri()); - } - } catch (Exception e) { - logger.error("Save event log cause error :", e); - } - } - }); - } else if (path.contains("/unauthorized")) { - logger.warn("用户[{}]没有登录", WebUtil.getHost(request) + "@" + userAgent); - } else if (path.contains("/forbidden")) { - logger.warn("用户[{}]没有权限", WebUtil.getCurrentUser() + "@" + WebUtil.getHost(request) + "@" + userAgent); - } - } } diff --git a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysSessionService.java b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysSessionService.java index 16c23c27..30b62064 100644 --- a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysSessionService.java +++ b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysSessionService.java @@ -4,8 +4,8 @@ import java.util.Map; import org.ibase4j.core.support.Assert; -import org.ibase4j.model.sys.SysSession; -import org.ibase4j.provider.sys.ISysSessionProvider; +import org.ibase4j.model.SysSession; +import org.ibase4j.provider.ISysSessionProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.stereotype.Service; diff --git a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysUserService.java b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysUserService.java index be85e3b0..f8ccb4a5 100644 --- a/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysUserService.java +++ b/iBase4J-Biz-Web/src/main/java/org/ibase4j/service/sys/SysUserService.java @@ -7,8 +7,8 @@ import org.ibase4j.core.support.login.LoginHelper; import org.ibase4j.core.support.login.ThirdPartyUser; import org.ibase4j.core.util.WebUtil; -import org.ibase4j.model.sys.SysUser; -import org.ibase4j.provider.sys.ISysUserProvider; +import org.ibase4j.model.SysUser; +import org.ibase4j.provider.ISysUserProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CachePut; import org.springframework.stereotype.Service; diff --git a/iBase4J-Common/pom.xml b/iBase4J-Common/pom.xml index cdec33ec..7550126f 100644 --- a/iBase4J-Common/pom.xml +++ b/iBase4J-Common/pom.xml @@ -126,5 +126,28 @@ springfox-swagger-ui 2.5.0 + + + org.db4j + reflectasm + 1.11.4-2 + + + + com.google.zxing + core + ${zxing.version} + + + com.google.zxing + javase + ${zxing.version} + + + + cz.mallat.uasparser + uasparser + 0.6.2 + \ No newline at end of file diff --git a/iBase4J-Common/src/main/java/org/ibase4j/Generator.java b/iBase4J-Common/src/main/java/org/ibase4j/Generator.java index e7454fd2..28158c18 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/Generator.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/Generator.java @@ -52,12 +52,10 @@ public static void main(String[] args) { mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); - strategy.setTablePrefix("sys_");// 此处可以修改为您的表前缀 + strategy.containsTablePrefix("sys_");// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 // strategy.setInclude(new String[] { "user" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 - // 字段名生成策略 - strategy.setFieldNaming(NamingStrategy.underline_to_camel); // 自定义实体父类 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // 自定义实体,公共字段 diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/Constants.java b/iBase4J-Common/src/main/java/org/ibase4j/core/Constants.java index ab85ba4d..52750c99 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/Constants.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/Constants.java @@ -1,5 +1,9 @@ package org.ibase4j.core; +import java.util.Map; + +import org.ibase4j.core.util.InstanceUtil; + /** * 常量表 * @@ -12,6 +16,8 @@ public interface Constants { * 非常遗憾的通知您,程序发生了异常 */ public static final String Exception_Head = "OH,MY GOD! SOME ERRORS OCCURED! AS FOLLOWS :"; + /** 缓存键值 */ + public static final Map, String> cacheKeyMap = InstanceUtil.newHashMap(); /** 操作名称 */ public static final String OPERATION_NAME = "OPERATION_NAME"; /** 客户端语言 */ @@ -20,18 +26,20 @@ public interface Constants { public static final String WEBTHEME = "webTheme"; /** 当前用户 */ public static final String CURRENT_USER = "CURRENT_USER"; - /** 在线用户数量 */ - public static final String ALLUSER_NUMBER = "ALLUSER_NUMBER"; - /** 登录用户数量 */ - public static final String USER_NUMBER = "USER_NUMBER"; /** 上次请求地址 */ public static final String PREREQUEST = "PREREQUEST"; /** 上次请求时间 */ public static final String PREREQUEST_TIME = "PREREQUEST_TIME"; + /** 登录地址 */ + public static final String LOGIN_URL = "/login.html"; /** 非法请求次数 */ public static final String MALICIOUS_REQUEST_TIMES = "MALICIOUS_REQUEST_TIMES"; /** 缓存命名空间 */ public static final String CACHE_NAMESPACE = "iBase4J:"; + /** 在线用户数量 */ + public static final String ALLUSER_NUMBER = "SYSTEM:" + CACHE_NAMESPACE + "ALLUSER_NUMBER"; + /** TOKEN */ + public static final String TOKEN_KEY = CACHE_NAMESPACE + "TOKEN_KEY"; /** 日志表状态 */ public interface JOBSTATE { diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/aspect/DataSourceAspect.java b/iBase4J-Common/src/main/java/org/ibase4j/core/aspect/DataSourceAspect.java index c8d6909c..4521d669 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/aspect/DataSourceAspect.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/aspect/DataSourceAspect.java @@ -21,7 +21,7 @@ public class DataSourceAspect { private final Logger logger = LogManager.getLogger(); - @Pointcut("execution(* org.ibase4j.provider..*.*(..))") + @Pointcut("execution(* org.ibase4j.service..*.*(..))") public void aspect() { } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/base/BaseProviderImpl.java b/iBase4J-Common/src/main/java/org/ibase4j/core/base/BaseProviderImpl.java index 540aef5d..fa65cb41 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/base/BaseProviderImpl.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/base/BaseProviderImpl.java @@ -12,6 +12,8 @@ import org.ibase4j.core.util.InstanceUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.plugins.Page; @@ -23,10 +25,15 @@ * @author ShenHuaJie * @version 2016年5月20日 下午3:19:19 */ -public abstract class BaseProviderImpl implements BaseProvider { +public abstract class BaseProviderImpl implements BaseProvider, ApplicationContextAware { protected Logger logger = LogManager.getLogger(getClass()); @Autowired protected BaseMapper mapper; + protected ApplicationContext applicationContext; + + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } /** 分页查询 */ public static Page getPage(Map params) { diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/exception/FtpException.java b/iBase4J-Common/src/main/java/org/ibase4j/core/exception/FtpException.java index a8ebc071..17e9d57b 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/exception/FtpException.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/exception/FtpException.java @@ -1,5 +1,7 @@ package org.ibase4j.core.exception; +import org.ibase4j.core.support.HttpCode; + /** * FTP异常 * @@ -7,15 +9,19 @@ * @version 2016年5月20日 下午3:19:19 */ @SuppressWarnings("serial") -public class FtpException extends RuntimeException { - public FtpException() { - } +public class FtpException extends BaseException { + public FtpException() { + } + + public FtpException(String message) { + super(message); + } - public FtpException(String message) { - super(message); - } + public FtpException(String message, Throwable throwable) { + super(message, throwable); + } - public FtpException(String message, Throwable throwable) { - super(message, throwable); - } + protected HttpCode getHttpCode() { + return HttpCode.INTERNAL_SERVER_ERROR; + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/exception/InstanceException.java b/iBase4J-Common/src/main/java/org/ibase4j/core/exception/InstanceException.java new file mode 100644 index 00000000..9e1899b3 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/exception/InstanceException.java @@ -0,0 +1,26 @@ +/** + * + */ +package org.ibase4j.core.exception; + +import org.ibase4j.core.support.HttpCode; + +/** + * + * @author ShenHuaJie + * @version 2017年3月24日 下午9:30:10 + */ +@SuppressWarnings("serial") +public class InstanceException extends BaseException { + public InstanceException() { + super(); + } + + public InstanceException(Throwable t) { + super(t); + } + + protected HttpCode getHttpCode() { + return HttpCode.INTERNAL_SERVER_ERROR; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/filter/TokenFilter.java b/iBase4J-Common/src/main/java/org/ibase4j/core/filter/TokenFilter.java new file mode 100644 index 00000000..65319ecc --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/filter/TokenFilter.java @@ -0,0 +1,147 @@ +package org.ibase4j.core.filter; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.ibase4j.core.support.HttpCode; +import org.ibase4j.core.support.Token; +import org.ibase4j.core.util.DataUtil; +import org.ibase4j.core.util.InstanceUtil; +import org.ibase4j.core.util.TokenUtil; +import org.ibase4j.core.util.WebUtil; + +import com.alibaba.fastjson.JSON; + +/** + * @author ShenHuaJie + * @since 2017年3月19日 上午10:21:59 + */ +public class TokenFilter implements Filter { + private static final Logger logger = LogManager.getLogger(TokenFilter.class); + + // 白名单 + private List whiteUrls; + + private int _size = 0; + + public void init(FilterConfig config) throws ServletException { + // 读取文件 + String path = CsrfFilter.class.getResource("/").getFile(); + whiteUrls = readFile(path + "tokenWhite.txt"); + _size = null == whiteUrls ? 0 : whiteUrls.size(); + } + + public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) servletRequest; + if (isWhiteReq(request.getRequestURI())) { + chain.doFilter(request, response); + } else { + String token = request.getHeader("token"); + if (StringUtils.isNotBlank(token)) { + try { + Token tokenInfo = TokenUtil.getTokenInfo(token); + if (tokenInfo != null) { + Long now = System.currentTimeMillis(); + if (now - tokenInfo.getTime() < 1000 * 60 * 30) { + String value = tokenInfo.getValue(); + TokenUtil.setTokenInfo(token, value); + WebUtil.saveCurrentUser(request, value); + } + } + } catch (Exception e) { + logger.error("token检查发生异常:", e); + } + } + // 响应 + if (DataUtil.isEmpty(WebUtil.getCurrentUser(request))) { + response.setContentType("text/html; charset=UTF-8"); + Map modelMap = InstanceUtil.newLinkedHashMap(); + modelMap.put("httpCode", HttpCode.UNAUTHORIZED.value()); + modelMap.put("msg", HttpCode.UNAUTHORIZED.msg()); + modelMap.put("timestamp", System.currentTimeMillis()); + PrintWriter out = response.getWriter(); + out.println(JSON.toJSONString(modelMap)); + out.flush(); + out.close(); + } else { + chain.doFilter(request, response); + } + } + } + + public void destroy() { + } + + /* + * 判断是否是白名单 + */ + private boolean isWhiteReq(String requestUrl) { + if (_size == 0) { + return true; + } else { + for (String urlTemp : whiteUrls) { + if (requestUrl.indexOf(urlTemp.toLowerCase()) > -1) { + return true; + } + } + } + + return false; + } + + private List readFile(String fileName) { + List list = new ArrayList(); + BufferedReader reader = null; + FileInputStream fis = null; + try { + File f = new File(fileName); + if (f.isFile() && f.exists()) { + fis = new FileInputStream(f); + reader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); + String line; + while ((line = reader.readLine()) != null) { + if (!"".equals(line)) { + list.add(line); + } + } + } + } catch (Exception e) { + logger.error("readFile", e); + } finally { + try { + if (reader != null) { + reader.close(); + } + } catch (IOException e) { + logger.error("InputStream关闭异常", e); + } + try { + if (fis != null) { + fis.close(); + } + } catch (IOException e) { + logger.error("FileInputStream关闭异常", e); + } + } + return list; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/EventInterceptor.java b/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/EventInterceptor.java index d302796a..ebf3b4f4 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/EventInterceptor.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/EventInterceptor.java @@ -1,14 +1,29 @@ package org.ibase4j.core.interceptor; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.ibase4j.core.Constants; -import org.ibase4j.core.support.SysEventService; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.ibase4j.core.support.ISysEventService; +import org.ibase4j.core.util.DateUtil; +import org.ibase4j.core.util.ExceptionUtil; +import org.ibase4j.core.util.WebUtil; +import org.ibase4j.model.SysEvent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.NamedThreadLocal; import org.springframework.web.method.HandlerMethod; +import com.alibaba.fastjson.JSON; + +import cz.mallat.uasparser.OnlineUpdater; +import cz.mallat.uasparser.UASparser; +import cz.mallat.uasparser.UserAgentInfo; import io.swagger.annotations.ApiOperation; /** @@ -18,29 +33,105 @@ * @version 2016年6月14日 下午6:18:46 */ public class EventInterceptor extends BaseInterceptor { - @Autowired - private SysEventService sysEventService; + protected static Logger logger = LogManager.getLogger(); + + private final ThreadLocal startTimeThreadLocal = new NamedThreadLocal("ThreadLocal StartTime"); + private ExecutorService executorService = Executors.newCachedThreadPool(); + + @Autowired + private ISysEventService sysEventService; + + static UASparser uasParser = null; + + // 初始化uasParser对象 + static { + try { + uasParser = new UASparser(OnlineUpdater.getVendoredInputStream()); + } catch (IOException e) { + logger.error("", e); + } + } - private final ThreadLocal startTimeThreadLocal = new NamedThreadLocal("ThreadLocal StartTime"); + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + // 开始时间(该数据只有当前请求的线程可见) + startTimeThreadLocal.set(System.currentTimeMillis()); + return super.preHandle(request, response, handler); + } - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - // 开始时间(该数据只有当前请求的线程可见) - startTimeThreadLocal.set(System.currentTimeMillis()); + public void afterCompletion(final HttpServletRequest request, HttpServletResponse response, Object handler, + final Exception ex) throws Exception { + final Long startTime = startTimeThreadLocal.get(); + final Long endTime = System.currentTimeMillis(); + // 保存日志 + + String userAgent = null; try { - HandlerMethod handlerMethod = (HandlerMethod) handler; - ApiOperation apiOperation = handlerMethod.getMethod().getAnnotation(ApiOperation.class); - request.setAttribute(Constants.OPERATION_NAME, apiOperation.value()); - } catch (Exception e) { + UserAgentInfo userAgentInfo = uasParser.parse(request.getHeader("user-agent")); + userAgent = userAgentInfo.getOsName() + " " + userAgentInfo.getType() + " " + userAgentInfo.getUaName(); + } catch (IOException e) { logger.error("", e); } - return super.preHandle(request, response, handler); - } - - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) - throws Exception { - // 保存日志 - sysEventService.saveEvent(request, response, ex, startTimeThreadLocal.get(), System.currentTimeMillis()); - super.afterCompletion(request, response, handler, ex); - } + String path = request.getServletPath(); + if (!path.contains("/read/") && !path.contains("/unauthorized") && !path.contains("/forbidden")) { + final SysEvent record = new SysEvent(); + Long uid = WebUtil.getCurrentUser(); + record.setMethod(request.getMethod()); + record.setRequestUri(request.getServletPath()); + record.setClientHost(WebUtil.getHost(request)); + record.setUserAgent(userAgent); + if (path.contains("/upload/")) { + record.setParameters(""); + } else { + record.setParameters(JSON.toJSONString(request.getParameterMap())); + } + record.setStatus(response.getStatus()); + record.setCreateBy(uid); + record.setUpdateBy(uid); + final String msg = (String) request.getAttribute("msg"); + try { + HandlerMethod handlerMethod = (HandlerMethod) handler; + ApiOperation apiOperation = handlerMethod.getMethod().getAnnotation(ApiOperation.class); + record.setTitle(apiOperation.value()); + } catch (Exception e) { + logger.error("", e); + } + executorService.submit(new Runnable() { + public void run() { + try { // 保存操作 + if (StringUtils.isNotBlank(msg)) { + record.setRemark(msg); + } else { + record.setRemark(ExceptionUtil.getStackTraceAsString(ex)); + } + + sysEventService.update(record); + // 内存信息 + if (logger.isDebugEnabled()) { + String message = "开始时间: {}; 结束时间: {}; 耗时: {}s; URI: {}; "; + // 最大内存: {}M; 已分配内存: {}M; 已分配内存中的剩余空间: {}M; 最大可用内存: + // {}M. + // long total = Runtime.getRuntime().totalMemory() / + // 1024 / 1024; + // long max = Runtime.getRuntime().maxMemory() / + // 1024 / 1024; + // long free = Runtime.getRuntime().freeMemory() / + // 1024 / 1024; + // , max, total, free, max - total + free + logger.debug(message, DateUtil.format(startTime, "HH:mm:ss.SSS"), + DateUtil.format(endTime, "HH:mm:ss.SSS"), (endTime - startTime) / 1000.00, + record.getRequestUri()); + } + } catch (Exception e) { + logger.error("Save event log cause error :", e); + } + } + }); + } else if (path.contains("/unauthorized")) { + logger.warn("用户[{}]没有登录", WebUtil.getHost(request) + "@" + userAgent); + } else if (path.contains("/forbidden")) { + logger.warn("用户[{}]没有权限", WebUtil.getCurrentUser() + "@" + WebUtil.getHost(request) + "@" + userAgent); + } + super.afterCompletion(request, response, handler, ex); + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/MaliciousRequestInterceptor.java b/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/MaliciousRequestInterceptor.java index 0fe85cfa..9d455779 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/MaliciousRequestInterceptor.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/interceptor/MaliciousRequestInterceptor.java @@ -14,54 +14,57 @@ * @version 2016年5月20日 下午3:16:57 */ public class MaliciousRequestInterceptor extends BaseInterceptor { - private Boolean allRequest = false; // 拦截所有请求,否则拦截相同请求 - private Long minRequestIntervalTime; // 允许的最小请求间隔 - private Integer maxMaliciousTimes; // 允许的最大恶意请求次数 + private Boolean allRequest = false; // 拦截所有请求,否则拦截相同请求 + private Long minRequestIntervalTime; // 允许的最小请求间隔 + private Integer maxMaliciousTimes; // 允许的最大恶意请求次数 - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - response.setHeader("Access-Control-Allow-Origin", "*"); - response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE"); - response.setHeader("Access-Control-Allow-Headers", - "x-requested-with,Access-Control-Allow-Origin,EX-SysAuthToken,EX-JSESSIONID"); + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE"); + response.setHeader("Access-Control-Allow-Headers", + "x-requested-with,Access-Control-Allow-Origin,EX-SysAuthToken,EX-JSESSIONID"); - HttpSession session = request.getSession(); - String preRequest = (String)session.getAttribute(Constants.PREREQUEST); - Long preRequestTime = (Long)session.getAttribute(Constants.PREREQUEST_TIME); - String url = request.getServletPath(); - if (preRequestTime != null && preRequest != null) { // 过滤频繁操作 - if ((url.equals(preRequest) || allRequest) - && System.currentTimeMillis() - preRequestTime < minRequestIntervalTime) { - Integer maliciousRequestTimes = (Integer)session.getAttribute(Constants.MALICIOUS_REQUEST_TIMES); - if (maliciousRequestTimes == null) { - maliciousRequestTimes = 1; - } else { - maliciousRequestTimes++; - } - session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, maliciousRequestTimes); - if (maliciousRequestTimes > maxMaliciousTimes) { - response.setStatus(HttpCode.MULTI_STATUS.value()); - logger.warn("To intercept a malicious request : {}", url); - return false; - } - } else { - session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, 0); - } - } - session.setAttribute(Constants.PREREQUEST, url); - session.setAttribute(Constants.PREREQUEST_TIME, System.currentTimeMillis()); - return super.preHandle(request, response, handler); - } + String url = request.getServletPath(); + if (url.endsWith("/unauthorized") || url.endsWith("/forbidden")) { + return super.preHandle(request, response, handler); + } + HttpSession session = request.getSession(); + String preRequest = (String) session.getAttribute(Constants.PREREQUEST); + Long preRequestTime = (Long) session.getAttribute(Constants.PREREQUEST_TIME); + if (preRequestTime != null && preRequest != null) { // 过滤频繁操作 + if ((url.equals(preRequest) || allRequest) + && System.currentTimeMillis() - preRequestTime < minRequestIntervalTime) { + Integer maliciousRequestTimes = (Integer) session.getAttribute(Constants.MALICIOUS_REQUEST_TIMES); + if (maliciousRequestTimes == null) { + maliciousRequestTimes = 1; + } else { + maliciousRequestTimes++; + } + session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, maliciousRequestTimes); + if (maliciousRequestTimes > maxMaliciousTimes) { + response.setStatus(HttpCode.MULTI_STATUS.value()); + logger.warn("To intercept a malicious request : {}", url); + return false; + } + } else { + session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, 0); + } + } + session.setAttribute(Constants.PREREQUEST, url); + session.setAttribute(Constants.PREREQUEST_TIME, System.currentTimeMillis()); + return super.preHandle(request, response, handler); + } - public void setAllRequest(Boolean allRequest) { - this.allRequest = allRequest; - } + public void setAllRequest(Boolean allRequest) { + this.allRequest = allRequest; + } - public void setMinRequestIntervalTime(Long minRequestIntervalTime) { - this.minRequestIntervalTime = minRequestIntervalTime; - } + public void setMinRequestIntervalTime(Long minRequestIntervalTime) { + this.minRequestIntervalTime = minRequestIntervalTime; + } - public void setMaxMaliciousTimes(Integer maxMaliciousTimes) { - this.maxMaliciousTimes = maxMaliciousTimes; - } + public void setMaxMaliciousTimes(Integer maxMaliciousTimes) { + this.maxMaliciousTimes = maxMaliciousTimes; + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/listener/SessionListener.java b/iBase4J-Common/src/main/java/org/ibase4j/core/listener/SessionListener.java new file mode 100644 index 00000000..b7ee5bce --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/listener/SessionListener.java @@ -0,0 +1,79 @@ +package org.ibase4j.core.listener; + +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; +import javax.servlet.http.HttpSessionListener; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.ibase4j.core.Constants; +import org.ibase4j.core.util.CacheUtil; + +/** + * 会话监听器 + * + * @author ShenHuaJie + * @version $Id: SessionListener.java, v 0.1 2014年3月28日 上午9:06:12 ShenHuaJie Exp + */ +public class SessionListener implements HttpSessionListener { + private Logger logger = LogManager.getLogger(SessionListener.class); + + /* + * (non-Javadoc) + * + * @see + * javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http + * .HttpSessionEvent) + */ + public void sessionCreated(HttpSessionEvent event) { + HttpSession session = event.getSession(); + session.setAttribute(Constants.WEBTHEME, "default"); + logger.info("创建了一个Session连接:[" + session.getId() + "]"); + setAllUserNumber(1); + } + + /* + * (non-Javadoc) + * + * @see + * javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet + * .http.HttpSessionEvent) + */ + public void sessionDestroyed(HttpSessionEvent event) { + HttpSession session = event.getSession(); + if (getAllUserNumber() > 0) { + logger.info("销毁了一个Session连接:[" + session.getId() + "]"); + } + session.removeAttribute(Constants.CURRENT_USER); + setAllUserNumber(-1); + } + + private void setAllUserNumber(int n) { + String key = Constants.CACHE_NAMESPACE + "SESSION:LOCK"; + while (!CacheUtil.getLock(key)) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + } + try { + Integer number = getAllUserNumber() + n; + if (number >= 0) { + logger.info("用户数:" + number); + CacheUtil.getCache().set(Constants.ALLUSER_NUMBER, number); + } + } finally { + CacheUtil.unlock(key); + } + } + + /** 获取在线用户数量 */ + public static Integer getAllUserNumber() { + Integer v = (Integer) CacheUtil.getCache().get(Constants.ALLUSER_NUMBER); + if (v != null) { + return v; + } + return 0; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/provider/scheduler/CoreTaskProvider.java b/iBase4J-Common/src/main/java/org/ibase4j/core/provider/scheduler/CoreTaskProvider.java deleted file mode 100644 index e1a7f442..00000000 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/provider/scheduler/CoreTaskProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.ibase4j.core.provider.scheduler; - -public interface CoreTaskProvider { - void cleanExpiredSessions(); -} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/ISysEventService.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/ISysEventService.java new file mode 100644 index 00000000..7edfae33 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/ISysEventService.java @@ -0,0 +1,13 @@ +package org.ibase4j.core.support; + +import java.util.Map; + +import org.ibase4j.model.SysEvent; + +import com.baomidou.mybatisplus.plugins.Page; + +public interface ISysEventService { + public void update(SysEvent sysEvent); + + public Page queryMap(Map params); +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/SysEventService.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/SysEventService.java deleted file mode 100644 index 4d601d9c..00000000 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/SysEventService.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.ibase4j.core.support; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import com.baomidou.mybatisplus.plugins.Page; - -public interface SysEventService { - - void saveEvent(HttpServletRequest request, HttpServletResponse response, Exception ex, Long startTime, - Long endTime); - - public Page> queryMap(Map params); -} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/Token.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/Token.java new file mode 100644 index 00000000..4ef34186 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/Token.java @@ -0,0 +1,25 @@ +package org.ibase4j.core.support; + +import java.io.Serializable; + +@SuppressWarnings("serial") +public class Token implements Serializable { + private String value; + private Long time; + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public Long getTime() { + return time; + } + + public void setTime(Long time) { + this.time = time; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/CacheManager.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/CacheManager.java index 9d48d96a..aa63b909 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/CacheManager.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/CacheManager.java @@ -3,32 +3,38 @@ import java.io.Serializable; import java.util.Set; -public abstract class CacheManager { - public abstract Object get(final String key); +public interface CacheManager { + public Object get(final String key); - public abstract Set getAll(final String pattern); + public Set getAll(final String pattern); - public abstract void set(final String key, final Serializable value, int seconds); + public void set(final String key, final Serializable value, int seconds); - public abstract void set(final String key, final Serializable value); + public void set(final String key, final Serializable value); - public abstract Boolean exists(final String key); + public Boolean exists(final String key); - public abstract void del(final String key); + public void del(final String key); - public abstract void delAll(final String pattern); + public void delAll(final String pattern); - public abstract String type(final String key); + public String type(final String key); - public abstract Boolean expire(final String key, final int seconds); + public Boolean expire(final String key, final int seconds); - public abstract Boolean expireAt(final String key, final long unixTime); + public Boolean expireAt(final String key, final long unixTime); - public abstract Long ttl(final String key); + public Long ttl(final String key); - public abstract Object getSet(final String key, final Serializable value); + public Object getSet(final String key, final Serializable value); - public abstract boolean setnx(final String key, final Serializable value); + public boolean setnx(final String key, final Serializable value); - public abstract void unlock(String key); + public void unlock(String key); + + public void hset(String key, String field, String value); + + public Object hget(String key, String field); + + public void hdel(String key, String field); } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/JedisHelper.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/JedisHelper.java index 408edab3..1565493d 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/JedisHelper.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/JedisHelper.java @@ -6,8 +6,10 @@ import java.util.Map; import java.util.Set; -import org.ibase4j.core.support.jedis.Executor; -import org.ibase4j.core.support.jedis.JedisTemplate; +import org.ibase4j.core.support.cache.jedis.Executor; +import org.ibase4j.core.support.cache.jedis.JedisTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import com.alibaba.fastjson.JSON; @@ -22,18 +24,26 @@ * @author ShenHuaJie * @version 2016年4月2日 下午4:17:22 */ -public class JedisHelper extends CacheManager { +@Configuration +public class JedisHelper implements CacheManager { + JedisTemplate jedisTemplate; + + @Bean + public JedisTemplate setJedisTemplate() { + jedisTemplate = new JedisTemplate(); + return jedisTemplate; + } public final Object get(final String key) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.get(key); } }); } - public static final String get(final String key, final Integer... expire) { - return JedisTemplate.run(key, new Executor() { + public final String get(final String key, final Integer... expire) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.get(key); } @@ -41,7 +51,7 @@ public String execute(ShardedJedis jedis) { } public void set(final String key, final Serializable value) { - JedisTemplate.run(key, new Executor() { + jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.set(key, JSON.toJSONString(value)); } @@ -49,7 +59,7 @@ public String execute(ShardedJedis jedis) { } public final void set(final String key, final Serializable value, final int seconds) { - JedisTemplate.run(key, new Executor() { + jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.setex(key, seconds, JSON.toJSONString(value)); } @@ -57,7 +67,7 @@ public String execute(ShardedJedis jedis) { } public final Boolean exists(final String key) { - return JedisTemplate.run((String) key, new Executor() { + return jedisTemplate.run((String) key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.exists((String) key); } @@ -65,7 +75,7 @@ public Boolean execute(ShardedJedis jedis) { } public final void del(final String key) { - JedisTemplate.run((String) key, new Executor() { + jedisTemplate.run((String) key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.del((String) key); } @@ -73,7 +83,7 @@ public Long execute(ShardedJedis jedis) { } public final String type(final String key) { - return JedisTemplate.run((String) key, new Executor() { + return jedisTemplate.run((String) key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.type((String) key); } @@ -86,7 +96,7 @@ public String execute(ShardedJedis jedis) { * @return */ public final Boolean expire(final String key, final int seconds) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.expire(key, seconds); } @@ -101,7 +111,7 @@ public Long execute(ShardedJedis jedis) { * @return */ public final Boolean expireAt(final String key, final long unixTime) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.expireAt(key, unixTime); } @@ -109,39 +119,39 @@ public Long execute(ShardedJedis jedis) { } public final Long ttl(final String key) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.ttl(key); } }); } - public static final Boolean setbit(final String key, final long offset, final boolean value) { - return JedisTemplate.run(key, new Executor() { + public final Boolean setbit(final String key, final long offset, final boolean value) { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.setbit(key, offset, value); } }); } - public static final Boolean getbit(final String key, final long offset) { - return JedisTemplate.run(key, new Executor() { + public final Boolean getbit(final String key, final long offset) { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.getbit(key, offset); } }); } - public static final Long setrange(final String key, final long offset, final String value) { - return JedisTemplate.run(key, new Executor() { + public final Long setrange(final String key, final long offset, final String value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.setrange(key, offset, value); } }); } - public static final String getrange(final String key, final long startOffset, final long endOffset) { - return JedisTemplate.run(key, new Executor() { + public final String getrange(final String key, final long startOffset, final long endOffset) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.getrange(key, startOffset, endOffset); } @@ -149,247 +159,247 @@ public String execute(ShardedJedis jedis) { } public final Object getSet(final String key, final Serializable value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.getSet(key, JSON.toJSONString(value)); } }); } - public static final Long setnx(final String key, final String value) { - return JedisTemplate.run(key, new Executor() { + public final Long setnx(final String key, final String value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.setnx(key, value); } }); } - public static final String setex(final String key, final int seconds, final String value) { - return JedisTemplate.run(key, new Executor() { + public final String setex(final String key, final int seconds, final String value) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.setex(key, seconds, value); } }, seconds, seconds); } - public static final Long decrBy(final String key, final long integer) { - return JedisTemplate.run(key, new Executor() { + public final Long decrBy(final String key, final long integer) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.decrBy(key, integer); } }); } - public static final Long decr(final String key) { - return JedisTemplate.run(key, new Executor() { + public final Long decr(final String key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.decr(key); } }); } - public static final Long incrBy(final String key, final long integer) { - return JedisTemplate.run(key, new Executor() { + public final Long incrBy(final String key, final long integer) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.incrBy(key, integer); } }); } - public static final Long incr(final String key) { - return JedisTemplate.run(key, new Executor() { + public final Long incr(final String key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.incr(key); } }); } - public static final Long append(final String key, final String value) { - return JedisTemplate.run(key, new Executor() { + public final Long append(final String key, final String value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.append(key, value); } }); } - public static final String substr(final String key, final int start, final int end) { - return JedisTemplate.run(key, new Executor() { + public final String substr(final String key, final int start, final int end) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.substr(key, start, end); } }); } - public static final Long hset(final String key, final String field, final String value) { - return JedisTemplate.run(key, new Executor() { - public Long execute(ShardedJedis jedis) { + public final void hset(final String key, final String field, final String value) { + jedisTemplate.run(key, new Executor() { + public Object execute(ShardedJedis jedis) { return jedis.hset(key, field, value); } }); } - public static final String hget(final String key, final String field) { - return JedisTemplate.run(key, new Executor() { + public final String hget(final String key, final String field) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.hget(key, field); } }); } - public static final Long hsetnx(final String key, final String field, final String value) { - return JedisTemplate.run(key, new Executor() { + public final Long hsetnx(final String key, final String field, final String value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hsetnx(key, field, value); } }); } - public static final String hmset(final String key, final Map hash) { - return JedisTemplate.run(key, new Executor() { + public final String hmset(final String key, final Map hash) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.hmset(key, hash); } }); } - public static final List hmget(final String key, final String... fields) { - return JedisTemplate.run(key, new Executor>() { + public final List hmget(final String key, final String... fields) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.hmget(key, fields); } }); } - public static final Long hincrBy(final String key, final String field, final long value) { - return JedisTemplate.run(key, new Executor() { + public final Long hincrBy(final String key, final String field, final long value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hincrBy(key, field, value); } }); } - public static final Boolean hexists(final String key, final String field) { - return JedisTemplate.run(key, new Executor() { + public final Boolean hexists(final String key, final String field) { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.hexists(key, field); } }); } - public static final Long hdel(final String key, final String field) { - return JedisTemplate.run(key, new Executor() { + public final void hdel(final String key, final String field) { + jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hdel(key, field); } }); } - public static final Long hlen(final String key) { - return JedisTemplate.run(key, new Executor() { + public final Long hlen(final String key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hlen(key); } }); } - public static final Set hkeys(final String key) { - return JedisTemplate.run(key, new Executor>() { + public final Set hkeys(final String key) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.hkeys(key); } }); } - public static final List hvals(final String key) { - return JedisTemplate.run(key, new Executor>() { + public final List hvals(final String key) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.hvals(key); } }); } - public static final Map hgetAll(final String key) { - return JedisTemplate.run(key, new Executor>() { + public final Map hgetAll(final String key) { + return jedisTemplate.run(key, new Executor>() { public Map execute(ShardedJedis jedis) { return jedis.hgetAll(key); } }); } - public static final Long rpush(final String key, final String string) { - return JedisTemplate.run(key, new Executor() { + public final Long rpush(final String key, final String string) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.rpush(key, string); } }); } - public static final Long lpush(final String key, final String string) { - return JedisTemplate.run(key, new Executor() { + public final Long lpush(final String key, final String string) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.lpush(key, string); } }); } - public static final Long llen(final String key) { - return JedisTemplate.run(key, new Executor() { + public final Long llen(final String key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.llen(key); } }); } - public static final List lrange(final String key, final long start, final long end) { - return JedisTemplate.run(key, new Executor>() { + public final List lrange(final String key, final long start, final long end) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.lrange(key, start, end); } }); } - public static final String ltrim(final String key, final long start, final long end) { - return JedisTemplate.run(key, new Executor() { + public final String ltrim(final String key, final long start, final long end) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.ltrim(key, start, end); } }); } - public static final String lindex(final String key, final long index) { - return JedisTemplate.run(key, new Executor() { + public final String lindex(final String key, final long index) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.lindex(key, index); } }); } - public static final String lset(final String key, final long index, final String value) { - return JedisTemplate.run(key, new Executor() { + public final String lset(final String key, final long index, final String value) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.lset(key, index, value); } }); } - public static final Long lrem(final String key, final long count, final String value) { - return JedisTemplate.run(key, new Executor() { + public final Long lrem(final String key, final long count, final String value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.lrem(key, count, value); } }); } - public static final String lpop(final String key) { - return JedisTemplate.run(key, new Executor() { + public final String lpop(final String key) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.lpop(key); } }); } - public static final String rpop(final String key) { - return JedisTemplate.run(key, new Executor() { + public final String rpop(final String key) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.rpop(key); } @@ -398,325 +408,324 @@ public String execute(ShardedJedis jedis) { // return 1 add a not exist value , // return 0 add a exist value - public static final Long sadd(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Long sadd(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.sadd(key, member); } }); } - public static final Set smembers(final String key) { - return JedisTemplate.run(key, new Executor>() { + public final Set smembers(final String key) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.smembers(key); } }); } - public static final Long srem(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Long srem(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.srem(key, member); } }); } - public static final String spop(final String key) { - return JedisTemplate.run(key, new Executor() { + public final String spop(final String key) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.spop(key); } }); } - public static final Long scard(final String key) { - return JedisTemplate.run(key, new Executor() { + public final Long scard(final String key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.scard(key); } }); } - public static final Boolean sismember(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Boolean sismember(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.sismember(key, member); } }); } - public static final String srandmember(final String key) { - return JedisTemplate.run(key, new Executor() { + public final String srandmember(final String key) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.srandmember(key); } }); } - public static final Long zadd(final String key, final double score, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Long zadd(final String key, final double score, final String member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zadd(key, score, member); } }); } - public static final Set zrange(final String key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrange(final String key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrange(key, start, end); } }); } - public static final Long zrem(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Long zrem(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zrem(key, member); } }); } - public static final Double zincrby(final String key, final double score, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Double zincrby(final String key, final double score, final String member) { + return jedisTemplate.run(key, new Executor() { public Double execute(ShardedJedis jedis) { return jedis.zincrby(key, score, member); } }); } - public static final Long zrank(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Long zrank(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zrank(key, member); } }); } - public static final Long zrevrank(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Long zrevrank(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zrevrank(key, member); } }); } - public static final Set zrevrange(final String key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrange(final String key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrange(key, start, end); } }); } - public static final Set zrangeWithScores(final String key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeWithScores(final String key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeWithScores(key, start, end); } }); } - public static final Set zrevrangeWithScores(final String key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeWithScores(final String key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeWithScores(key, start, end); } }); } - public static final Long zcard(final String key) { - return JedisTemplate.run(key, new Executor() { + public final Long zcard(final String key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zcard(key); } }); } - public static final Double zscore(final String key, final String member) { - return JedisTemplate.run(key, new Executor() { + public final Double zscore(final String key, final String member) { + return jedisTemplate.run(key, new Executor() { public Double execute(ShardedJedis jedis) { return jedis.zscore(key, member); } }); } - public static final List sort(final String key) { - return JedisTemplate.run(key, new Executor>() { + public final List sort(final String key) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.sort(key); } }); } - public static final List sort(final String key, final SortingParams sortingParameters) { - return JedisTemplate.run(key, new Executor>() { + public final List sort(final String key, final SortingParams sortingParameters) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.sort(key, sortingParameters); } }); } - public static final Long zcount(final String key, final double min, final double max) { - return JedisTemplate.run(key, new Executor() { + public final Long zcount(final String key, final double min, final double max) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zcount(key, min, max); } }); } - public static final Set zrangeByScore(final String key, final double min, final double max) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeByScore(final String key, final double min, final double max) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScore(key, min, max); } }); } - public static final Set zrevrangeByScore(final String key, final double max, final double min) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeByScore(final String key, final double max, final double min) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScore(key, max, min); } }); } - public static final Set zrangeByScore(final String key, final double min, final double max, - final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeByScore(final String key, final double min, final double max, final int offset, + final int count) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScore(key, min, max, offset, count); } }); } - public static final Set zrevrangeByScore(final String key, final double max, final double min, - final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeByScore(final String key, final double max, final double min, final int offset, + final int count) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScore(key, max, min, offset, count); } }); } - public static final Set zrangeByScoreWithScores(final String key, final double min, final double max) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeByScoreWithScores(final String key, final double min, final double max) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScoreWithScores(key, min, max); } }); } - public static final Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScoreWithScores(key, max, min); } }); } - public static final Set zrangeByScoreWithScores(final String key, final double min, final double max, + public final Set zrangeByScoreWithScores(final String key, final double min, final double max, final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScoreWithScores(key, min, max, offset, count); } }); } - public static final Set zrevrangeByScoreWithScores(final String key, final double max, final double min, + public final Set zrevrangeByScoreWithScores(final String key, final double max, final double min, final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScoreWithScores(key, max, min, offset, count); } }); } - public static final Long zremrangeByRank(final String key, final int start, final int end) { - return JedisTemplate.run(key, new Executor() { + public final Long zremrangeByRank(final String key, final int start, final int end) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zremrangeByRank(key, start, end); } }); } - public static final Long zremrangeByScore(final String key, final double start, final double end) { - return JedisTemplate.run(key, new Executor() { + public final Long zremrangeByScore(final String key, final double start, final double end) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zremrangeByScore(key, start, end); } }); } - public static final Long linsert(final String key, final LIST_POSITION where, final String pivot, - final String value) { - return JedisTemplate.run(key, new Executor() { + public final Long linsert(final String key, final LIST_POSITION where, final String pivot, final String value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.linsert(key, where, pivot, value); } }); } - public static final String set(final byte[] key, final byte[] value, final Integer... expire) { - return JedisTemplate.run(key, new Executor() { + public final String set(final byte[] key, final byte[] value, final Integer... expire) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.set(key, value); } }, expire); } - public static final byte[] get(final byte[] key, final Integer... expire) { - return JedisTemplate.run(key, new Executor() { + public final byte[] get(final byte[] key, final Integer... expire) { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.get(key); } }, expire); } - public static final Boolean exists(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final Boolean exists(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.exists(key); } }); } - public static final String type(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final String type(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.type(key); } }); } - public static final Long expire(final byte[] key, final int seconds) { - return JedisTemplate.run(key, new Executor() { + public final Long expire(final byte[] key, final int seconds) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.expire(key, seconds); } }, seconds, seconds); } - public static final Long expireAt(final byte[] key, final long unixTime) { - return JedisTemplate.run(key, new Executor() { + public final Long expireAt(final byte[] key, final long unixTime) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.expireAt(key, unixTime); } }); } - public static final Long ttl(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final Long ttl(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.ttl(key); } }); } - public static final Long del(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final Long del(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.del(key); } @@ -724,7 +733,7 @@ public Long execute(ShardedJedis jedis) { } public byte[] getSet(final byte[] key, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.getSet(key, value); } @@ -732,7 +741,7 @@ public byte[] execute(ShardedJedis jedis) { } public Long setnx(final byte[] key, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.setnx(key, value); } @@ -740,7 +749,7 @@ public Long execute(ShardedJedis jedis) { } public String setex(final byte[] key, final int seconds, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.setex(key, seconds, value); } @@ -748,7 +757,7 @@ public String execute(ShardedJedis jedis) { } public Long decrBy(final byte[] key, final long integer) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.decrBy(key, integer); } @@ -756,7 +765,7 @@ public Long execute(ShardedJedis jedis) { } public Long decr(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.decr(key); } @@ -764,7 +773,7 @@ public Long execute(ShardedJedis jedis) { } public Long incrBy(final byte[] key, final long integer) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.incrBy(key, integer); } @@ -772,7 +781,7 @@ public Long execute(ShardedJedis jedis) { } public Long incr(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.incr(key); } @@ -780,7 +789,7 @@ public Long execute(ShardedJedis jedis) { } public Long append(final byte[] key, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.append(key, value); } @@ -788,7 +797,7 @@ public Long execute(ShardedJedis jedis) { } public byte[] substr(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.substr(key, start, end); } @@ -796,7 +805,7 @@ public byte[] execute(ShardedJedis jedis) { } public Long hset(final byte[] key, final byte[] field, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hset(key, field, value); } @@ -804,7 +813,7 @@ public Long execute(ShardedJedis jedis) { } public byte[] hget(final byte[] key, final byte[] field) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.hget(key, field); } @@ -812,7 +821,7 @@ public byte[] execute(ShardedJedis jedis) { } public Long hsetnx(final byte[] key, final byte[] field, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hsetnx(key, field, value); } @@ -820,7 +829,7 @@ public Long execute(ShardedJedis jedis) { } public String hmset(final byte[] key, final Map hash) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.hmset(key, hash); } @@ -828,7 +837,7 @@ public String execute(ShardedJedis jedis) { } public List hmget(final byte[] key, final byte[]... fields) { - return JedisTemplate.run(key, new Executor>() { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.hmget(key, fields); } @@ -836,7 +845,7 @@ public List execute(ShardedJedis jedis) { } public Long hincrBy(final byte[] key, final byte[] field, final long value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hincrBy(key, field, value); } @@ -844,7 +853,7 @@ public Long execute(ShardedJedis jedis) { } public Boolean hexists(final byte[] key, final byte[] field) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.hexists(key, field); } @@ -852,7 +861,7 @@ public Boolean execute(ShardedJedis jedis) { } public Long hdel(final byte[] key, final byte[] field) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hdel(key, field); } @@ -860,380 +869,379 @@ public Long execute(ShardedJedis jedis) { } public Long hlen(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.hlen(key); } }); } - public static final Set hkeys(final byte[] key) { - return JedisTemplate.run(key, new Executor>() { + public final Set hkeys(final byte[] key) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.hkeys(key); } }); } - public static final Collection hvals(final byte[] key) { - return JedisTemplate.run(key, new Executor>() { + public final Collection hvals(final byte[] key) { + return jedisTemplate.run(key, new Executor>() { public Collection execute(ShardedJedis jedis) { return jedis.hvals(key); } }); } - public static final Map hgetAll(final byte[] key) { - return JedisTemplate.run(key, new Executor>() { + public final Map hgetAll(final byte[] key) { + return jedisTemplate.run(key, new Executor>() { public Map execute(ShardedJedis jedis) { return jedis.hgetAll(key); } }); } - public static final Long rpush(final byte[] key, final byte[] string) { - return JedisTemplate.run(key, new Executor() { + public final Long rpush(final byte[] key, final byte[] string) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.rpush(key, string); } }); } - public static final Long lpush(final byte[] key, final byte[] string) { - return JedisTemplate.run(key, new Executor() { + public final Long lpush(final byte[] key, final byte[] string) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.lpush(key, string); } }); } - public static final Long llen(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final Long llen(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.llen(key); } }); } - public static final List lrange(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final List lrange(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.lrange(key, start, end); } }); } - public static final String ltrim(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor() { + public final String ltrim(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.ltrim(key, start, end); } }); } - public static final byte[] lindex(final byte[] key, final int index) { - return JedisTemplate.run(key, new Executor() { + public final byte[] lindex(final byte[] key, final int index) { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.lindex(key, index); } }); } - public static final String lset(final byte[] key, final int index, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + public final String lset(final byte[] key, final int index, final byte[] value) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.lset(key, index, value); } }); } - public static final Long lrem(final byte[] key, final int count, final byte[] value) { - return JedisTemplate.run(key, new Executor() { + public final Long lrem(final byte[] key, final int count, final byte[] value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.lrem(key, count, value); } }); } - public static final byte[] lpop(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final byte[] lpop(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.lpop(key); } }); } - public static final byte[] rpop(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final byte[] rpop(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.rpop(key); } }); } - public static final Long sadd(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Long sadd(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.sadd(key, member); } }); } - public static final Set smembers(final byte[] key) { - return JedisTemplate.run(key, new Executor>() { + public final Set smembers(final byte[] key) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.smembers(key); } }); } - public static final Long srem(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Long srem(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.srem(key, member); } }); } - public static final byte[] spop(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final byte[] spop(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.spop(key); } }); } - public static final Long scard(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final Long scard(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.scard(key); } }); } - public static final Boolean sismember(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Boolean sismember(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Boolean execute(ShardedJedis jedis) { return jedis.sismember(key, member); } }); } - public static final byte[] srandmember(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final byte[] srandmember(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public byte[] execute(ShardedJedis jedis) { return jedis.srandmember(key); } }); } - public static final Long zadd(final byte[] key, final double score, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Long zadd(final byte[] key, final double score, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zadd(key, score, member); } }); } - public static final Set zrange(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrange(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrange(key, start, end); } }); } - public static final Long zrem(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Long zrem(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zrem(key, member); } }); } - public static final Double zincrby(final byte[] key, final double score, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Double zincrby(final byte[] key, final double score, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Double execute(ShardedJedis jedis) { return jedis.zincrby(key, score, member); } }); } - public static final Long zrank(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Long zrank(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zrank(key, member); } }); } - public static final Long zrevrank(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Long zrevrank(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zrevrank(key, member); } }); } - public static final Set zrevrange(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrange(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrange(key, start, end); } }); } - public static final Set zrangeWithScores(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeWithScores(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeWithScores(key, start, end); } }); } - public static final Set zrevrangeWithScores(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeWithScores(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeWithScores(key, start, end); } }); } - public static final Long zcard(final byte[] key) { - return JedisTemplate.run(key, new Executor() { + public final Long zcard(final byte[] key) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zcard(key); } }); } - public static final Double zscore(final byte[] key, final byte[] member) { - return JedisTemplate.run(key, new Executor() { + public final Double zscore(final byte[] key, final byte[] member) { + return jedisTemplate.run(key, new Executor() { public Double execute(ShardedJedis jedis) { return jedis.zscore(key, member); } }); } - public static final List sort(final byte[] key) { - return JedisTemplate.run(key, new Executor>() { + public final List sort(final byte[] key) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.sort(key); } }); } - public static final List sort(final byte[] key, final SortingParams sortingParameters) { - return JedisTemplate.run(key, new Executor>() { + public final List sort(final byte[] key, final SortingParams sortingParameters) { + return jedisTemplate.run(key, new Executor>() { public List execute(ShardedJedis jedis) { return jedis.sort(key, sortingParameters); } }); } - public static final Long zcount(final byte[] key, final double min, final double max) { - return JedisTemplate.run(key, new Executor() { + public final Long zcount(final byte[] key, final double min, final double max) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zcount(key, min, max); } }); } - public static final Set zrangeByScore(final byte[] key, final double min, final double max) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeByScore(final byte[] key, final double min, final double max) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScore(key, min, max); } }); } - public static final Set zrangeByScore(final byte[] key, final double min, final double max, - final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeByScore(final byte[] key, final double min, final double max, final int offset, + final int count) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScore(key, min, max, offset, count); } }); } - public static final Set zrangeByScoreWithScores(final byte[] key, final double min, final double max) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrangeByScoreWithScores(final byte[] key, final double min, final double max) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScoreWithScores(key, min, max); } }); } - public static final Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, + public final Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrangeByScoreWithScores(key, min, max, offset, count); } }); } - public static final Set zrevrangeByScore(final byte[] key, final double max, final double min) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeByScore(final byte[] key, final double max, final double min) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScore(key, max, min); } }); } - public static final Set zrevrangeByScore(final byte[] key, final double max, final double min, - final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, + final int count) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScore(key, max, min, offset, count); } }); } - public static final Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - return JedisTemplate.run(key, new Executor>() { + public final Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScoreWithScores(key, max, min); } }); } - public static final Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, + public final Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { - return JedisTemplate.run(key, new Executor>() { + return jedisTemplate.run(key, new Executor>() { public Set execute(ShardedJedis jedis) { return jedis.zrevrangeByScoreWithScores(key, max, min, offset, count); } }); } - public static final Long zremrangeByRank(final byte[] key, final int start, final int end) { - return JedisTemplate.run(key, new Executor() { + public final Long zremrangeByRank(final byte[] key, final int start, final int end) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zremrangeByRank(key, start, end); } }); } - public static final Long zremrangeByScore(final byte[] key, final double start, final double end) { - return JedisTemplate.run(key, new Executor() { + public final Long zremrangeByScore(final byte[] key, final double start, final double end) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.zremrangeByScore(key, start, end); } }); } - public static final Long linsert(final byte[] key, final LIST_POSITION where, final byte[] pivot, - final byte[] value) { - return JedisTemplate.run(key, new Executor() { + public final Long linsert(final byte[] key, final LIST_POSITION where, final byte[] pivot, final byte[] value) { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.linsert(key, where, pivot, value); } }); } - public static final String getKeyTag(final String key) { - return JedisTemplate.run(key, new Executor() { + public final String getKeyTag(final String key) { + return jedisTemplate.run(key, new Executor() { public String execute(ShardedJedis jedis) { return jedis.getKeyTag(key); } @@ -1248,7 +1256,7 @@ public void delAll(String pattern) { } public boolean setnx(final String key, final Serializable value) { - return JedisTemplate.run(key, new Executor() { + return jedisTemplate.run(key, new Executor() { public Long execute(ShardedJedis jedis) { return jedis.setnx(key, JSON.toJSONString(value)); } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedisHelper.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedisHelper.java index 518f22ac..6b1fdf93 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedisHelper.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedisHelper.java @@ -5,11 +5,11 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.web.context.ContextLoader; -import org.springframework.web.context.WebApplicationContext; import org.ibase4j.core.util.InstanceUtil; import org.ibase4j.core.util.PropertiesUtil; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.data.redis.core.RedisTemplate; /** * Redis缓存辅助类 @@ -17,114 +17,131 @@ * @author ShenHuaJie * @version 2016年4月2日 下午4:17:22 */ -public final class RedisHelper extends CacheManager { - - private RedisTemplate redisTemplate = null; - private Integer EXPIRE = PropertiesUtil.getInt("redis.expiration"); - - // 获取连接 - @SuppressWarnings("unchecked") - private RedisTemplate getRedis() { - if (redisTemplate == null) { - synchronized (RedisHelper.class) { - if (redisTemplate == null) { - WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); - redisTemplate = (RedisTemplate) wac.getBean("redisTemplate"); - } - } - } - return redisTemplate; - } - - public final Object get(final String key) { - expire(key, EXPIRE); - return getRedis().boundValueOps(key).get(); - } - - public final Set getAll(final String pattern) { - Set values = InstanceUtil.newHashSet(); - Set keys = getRedis().keys(pattern); - for (Serializable key : keys) { - expire(key.toString(), EXPIRE); - values.add(getRedis().opsForValue().get(key)); - } - return values; - } - - public final void set(final String key, final Serializable value, int seconds) { - getRedis().boundValueOps(key).set(value); - expire(key, seconds); - } - - public final void set(final String key, final Serializable value) { - getRedis().boundValueOps(key).set(value); - expire(key, EXPIRE); - } - - public final Boolean exists(final String key) { - return getRedis().hasKey(key); - } - - public final void del(final String key) { - getRedis().delete(key); - } - - public final void delAll(final String pattern) { - getRedis().delete(getRedis().keys(pattern)); - } - - public final String type(final String key) { - expire(key, EXPIRE); - return getRedis().type(key).getClass().getName(); - } - - /** - * 在某段时间后失效 - * - * @return - */ - public final Boolean expire(final String key, final int seconds) { - return getRedis().expire(key, seconds, TimeUnit.SECONDS); - } - - /** - * 在某个时间点失效 - * - * @param key - * @param unixTime - * @return - */ - public final Boolean expireAt(final String key, final long unixTime) { - return getRedis().expireAt(key, new Date(unixTime)); - } - - public final Long ttl(final String key) { - return getRedis().getExpire(key, TimeUnit.SECONDS); - } - - public final void setrange(final String key, final long offset, final String value) { - expire(key, EXPIRE); - getRedis().boundValueOps(key).set(value, offset); - } - - public final String getrange(final String key, final long startOffset, final long endOffset) { - expire(key, EXPIRE); - return getRedis().boundValueOps(key).get(startOffset, endOffset); - } - - public final Object getSet(final String key, final Serializable value) { - expire(key, EXPIRE); - return getRedis().boundValueOps(key).getAndSet(value); - } - - public boolean setnx(String key, Serializable value) { - getRedis().boundValueOps(key).setIfAbsent(value); - return false; - } - - public void unlock(String key) { - del(key); - } - - // 未完,待续... +public final class RedisHelper implements CacheManager, ApplicationContextAware { + + private RedisTemplate redisTemplate = null; + private Integer EXPIRE = PropertiesUtil.getInt("redis.expiration"); + + protected ApplicationContext applicationContext; + + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + // 获取连接 + @SuppressWarnings("unchecked") + private RedisTemplate getRedis() { + if (redisTemplate == null) { + synchronized (RedisHelper.class) { + if (redisTemplate == null) { + redisTemplate = (RedisTemplate)applicationContext + .getBean("redisTemplate"); + } + } + } + return redisTemplate; + } + + public final Object get(final String key) { + expire(key, EXPIRE); + return getRedis().boundValueOps(key).get(); + } + + public final Set getAll(final String pattern) { + Set values = InstanceUtil.newHashSet(); + Set keys = getRedis().keys(pattern); + for (Serializable key : keys) { + expire(key.toString(), EXPIRE); + values.add(getRedis().opsForValue().get(key)); + } + return values; + } + + public final void set(final String key, final Serializable value, int seconds) { + getRedis().boundValueOps(key).set(value); + expire(key, seconds); + } + + public final void set(final String key, final Serializable value) { + getRedis().boundValueOps(key).set(value); + expire(key, EXPIRE); + } + + public final Boolean exists(final String key) { + return getRedis().hasKey(key); + } + + public final void del(final String key) { + getRedis().delete(key); + } + + public final void delAll(final String pattern) { + getRedis().delete(getRedis().keys(pattern)); + } + + public final String type(final String key) { + expire(key, EXPIRE); + return getRedis().type(key).getClass().getName(); + } + + /** + * 在某段时间后失效 + * + * @return + */ + public final Boolean expire(final String key, final int seconds) { + return getRedis().expire(key, seconds, TimeUnit.SECONDS); + } + + /** + * 在某个时间点失效 + * + * @param key + * @param unixTime + * @return + */ + public final Boolean expireAt(final String key, final long unixTime) { + return getRedis().expireAt(key, new Date(unixTime)); + } + + public final Long ttl(final String key) { + return getRedis().getExpire(key, TimeUnit.SECONDS); + } + + public final void setrange(final String key, final long offset, final String value) { + getRedis().boundValueOps(key).set(value, offset); + expire(key, EXPIRE); + } + + public final String getrange(final String key, final long startOffset, final long endOffset) { + expire(key, EXPIRE); + return getRedis().boundValueOps(key).get(startOffset, endOffset); + } + + public final Object getSet(final String key, final Serializable value) { + expire(key, EXPIRE); + return getRedis().boundValueOps(key).getAndSet(value); + } + + public boolean setnx(String key, Serializable value) { + return getRedis().boundValueOps(key).setIfAbsent(value); + } + + public void unlock(String key) { + del(key); + } + + public void hset(String key, String field, String value) { + getRedis().boundHashOps(key).put(field, value); + } + + public Object hget(String key, String field) { + return getRedis().boundHashOps(key).get(field); + } + + public void hdel(String key, String field) { + getRedis().boundHashOps(key).delete(field); + } + + // 未完,待续... } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedissonHelper.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedissonHelper.java index d8049bf7..e4960d17 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedissonHelper.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/RedissonHelper.java @@ -7,30 +7,34 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import org.redisson.Redisson; +import org.ibase4j.core.util.InstanceUtil; +import org.ibase4j.core.util.PropertiesUtil; import org.redisson.api.RBucket; import org.redisson.api.RType; import org.redisson.api.RedissonClient; -import org.springframework.web.context.ContextLoader; -import org.springframework.web.context.WebApplicationContext; -import org.ibase4j.core.util.InstanceUtil; -import org.ibase4j.core.util.PropertiesUtil; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; /** * Redis缓存辅助类 */ -public class RedissonHelper extends CacheManager { +public class RedissonHelper implements CacheManager, ApplicationContextAware { private RedissonClient redisTemplate = null; private Integer EXPIRE = PropertiesUtil.getInt("redis.expiration"); + protected ApplicationContext applicationContext; + + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + // 获取连接 private RedissonClient getRedis() { if (redisTemplate == null) { synchronized (RedissonHelper.class) { if (redisTemplate == null) { - WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); - redisTemplate = wac.getBean(Redisson.class); + redisTemplate = applicationContext.getBean(RedissonClient.class); } } } @@ -49,14 +53,14 @@ public final Object get(final String key) { public final void set(final String key, final Serializable value) { RBucket temp = getRedisBucket(key); - expire(temp, EXPIRE); temp.set(value); + expire(temp, EXPIRE); } public final void set(final String key, final Serializable value, int seconds) { RBucket temp = getRedisBucket(key); - expire(temp, seconds); temp.set(value); + expire(temp, seconds); } public final void multiSet(final Map temps) { @@ -90,7 +94,7 @@ public final String type(final String key) { * @return */ private final void expire(final RBucket bucket, final int seconds) { - bucket.expireAsync(seconds, TimeUnit.SECONDS); + bucket.expire(seconds, TimeUnit.SECONDS); } /** @@ -137,4 +141,16 @@ public boolean setnx(String key, Serializable value) { public void unlock(String key) { getRedis().getLock(key).unlock(); } + + public void hset(String key, String field, String value) { + getRedis().getMap(key).put(field, value); + } + + public Object hget(String key, String field) { + return getRedis().getMap(key).get(field); + } + + public void hdel(String key, String field) { + getRedis().getMap(key).remove(field); + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/jedis/Executor.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/Executor.java similarity index 76% rename from iBase4J-Common/src/main/java/org/ibase4j/core/support/jedis/Executor.java rename to iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/Executor.java index 51b82667..bd702284 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/jedis/Executor.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/Executor.java @@ -1,4 +1,4 @@ -package org.ibase4j.core.support.jedis; +package org.ibase4j.core.support.cache.jedis; import redis.clients.jedis.ShardedJedis; diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisShardInfo.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisShardInfo.java new file mode 100644 index 00000000..733fad05 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisShardInfo.java @@ -0,0 +1,24 @@ +/** + * + */ +package org.ibase4j.core.support.cache.jedis; + +import org.apache.commons.lang3.StringUtils; + +/** + * + * @author ShenHuaJie + * @version 2017年3月27日 下午12:47:53 + */ +public class JedisShardInfo extends redis.clients.jedis.JedisShardInfo { + + public JedisShardInfo(String host, int port) { + super(host, port); + } + + public void setPassword(String password) { + if (StringUtils.isNotBlank(password)) { + super.setPassword(password); + } + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/jedis/JedisTemplate.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisTemplate.java similarity index 65% rename from iBase4J-Common/src/main/java/org/ibase4j/core/support/jedis/JedisTemplate.java rename to iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisTemplate.java index fd737c7c..305ebc33 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/jedis/JedisTemplate.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisTemplate.java @@ -1,11 +1,17 @@ -package org.ibase4j.core.support.jedis; +package org.ibase4j.core.support.cache.jedis; + +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.ibase4j.core.util.InstanceUtil; import org.ibase4j.core.util.PropertiesUtil; -import org.springframework.web.context.ContextLoader; -import org.springframework.web.context.WebApplicationContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; +import org.springframework.stereotype.Component; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; @@ -13,27 +19,32 @@ * @author ShenHuaJie * @version 2016年5月20日 下午3:19:19 */ +@Component public class JedisTemplate { private static final Logger logger = LogManager.getLogger(); private static ShardedJedisPool shardedJedisPool = null; private static Integer EXPIRE = PropertiesUtil.getInt("redis.expiration"); + @Autowired + private JedisConnectionFactory jedisConnectionFactory; // 获取线程 - private static ShardedJedis getJedis() { + private ShardedJedis getJedis() { if (shardedJedisPool == null) { synchronized (EXPIRE) { if (shardedJedisPool == null) { - WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); - shardedJedisPool = wac.getBean(ShardedJedisPool.class); + JedisPoolConfig poolConfig = jedisConnectionFactory.getPoolConfig(); + JedisShardInfo shardInfo = jedisConnectionFactory.getShardInfo(); + List list = InstanceUtil.newArrayList(shardInfo); + shardedJedisPool = new ShardedJedisPool(poolConfig, list); } } } return shardedJedisPool.getResource(); } - public static K run(String key, Executor executor, Integer... expire) { + public K run(String key, Executor executor, Integer... expire) { ShardedJedis jedis = getJedis(); if (jedis == null) { return null; @@ -58,7 +69,7 @@ public static K run(String key, Executor executor, Integer... expire) { return null; } - public static K run(byte[] key, Executor executor, Integer... expire) { + public K run(byte[] key, Executor executor, Integer... expire) { ShardedJedis jedis = getJedis(); if (jedis == null) { return null; diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/shiro/RedisCache.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/shiro/RedisCache.java new file mode 100644 index 00000000..6a39f046 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/shiro/RedisCache.java @@ -0,0 +1,132 @@ +/** + * + */ +package org.ibase4j.core.support.cache.shiro; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.shiro.cache.Cache; +import org.apache.shiro.cache.CacheException; +import org.apache.shiro.util.CollectionUtils; +import org.ibase4j.core.util.CacheUtil; + +/** + * + * @author ShenHuaJie + * @version 2017年3月24日 下午8:54:08 + */ +public class RedisCache implements Cache { + private final Logger logger = LogManager.getLogger(); + + /** + * The Redis key prefix for the sessions + */ + private String keyPrefix = "shiro_redis_session:"; + + /** + * Returns the Redis session keys + * prefix. + * @return The prefix + */ + public String getKeyPrefix() { + return keyPrefix; + } + + /** + * Sets the Redis sessions key + * prefix. + * @param keyPrefix The prefix + */ + public void setKeyPrefix(String keyPrefix) { + this.keyPrefix = keyPrefix; + } + + /** + * Constructs a cache instance with the specified + * Redis manager and using a custom key prefix. + * @param prefix The Redis key prefix + */ + public RedisCache(String prefix) { + // set the prefix + this.keyPrefix = prefix; + } + + @Override + public V get(K key) throws CacheException { + logger.debug("根据key从Redis中获取对象 key [" + key + "]"); + @SuppressWarnings("unchecked") + V value = (V)CacheUtil.getCache().get(getKey(key)); + return value; + } + + @Override + public V put(K key, V value) throws CacheException { + logger.debug("根据key从存储 key [" + key + "]"); + CacheUtil.getCache().set(getKey(key), (Serializable)value); + return value; + } + + @Override + public V remove(K key) throws CacheException { + logger.debug("从redis中删除 key [" + key + "]"); + V previous = get(key); + CacheUtil.getCache().del(getKey(key)); + return previous; + } + + @Override + public void clear() throws CacheException { + logger.debug("从redis中删除所有元素"); + CacheUtil.getCache().delAll(this.keyPrefix + "*"); + } + + @Override + public int size() { + return CacheUtil.getCache().getAll(this.keyPrefix + "*").size(); + } + + @SuppressWarnings("unchecked") + @Override + public Set keys() { + Set keys = CacheUtil.getCache().getAll(this.keyPrefix + "*"); + if (CollectionUtils.isEmpty(keys)) { + return Collections.emptySet(); + } else { + Set newKeys = new HashSet(); + for (Object key : keys) { + newKeys.add((K)key); + } + return newKeys; + } + } + + @Override + public Collection values() { + Set keys = CacheUtil.getCache().getAll(this.keyPrefix + "*"); + if (!CollectionUtils.isEmpty(keys)) { + List values = new ArrayList(keys.size()); + for (Object key : keys) { + @SuppressWarnings("unchecked") + V value = get((K)key); + if (value != null) { + values.add(value); + } + } + return Collections.unmodifiableList(values); + } else { + return Collections.emptyList(); + } + } + + private String getKey(K key) { + return this.keyPrefix + key; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/shiro/RedisCacheManager.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/shiro/RedisCacheManager.java new file mode 100644 index 00000000..b1098a63 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/shiro/RedisCacheManager.java @@ -0,0 +1,68 @@ +/** + * + */ +package org.ibase4j.core.support.cache.shiro; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.shiro.cache.Cache; +import org.apache.shiro.cache.CacheException; +import org.apache.shiro.cache.CacheManager; +import org.ibase4j.core.Constants; + +/** + * + * @author ShenHuaJie + * @version 2017年3月24日 下午8:50:14 + */ +public class RedisCacheManager implements CacheManager { + private final Logger logger = LogManager.getLogger(); + + // fast lookup by name map + @SuppressWarnings("rawtypes") + private final ConcurrentMap caches = new ConcurrentHashMap(); + /** + * The Redis key prefix for caches + */ + private String keyPrefix = Constants.CACHE_NAMESPACE + "shiro_redis_cache:"; + + /** + * Returns the Redis session keys + * prefix. + * @return The prefix + */ + public String getKeyPrefix() { + return keyPrefix; + } + + /** + * Sets the Redis sessions key + * prefix. + * @param keyPrefix The prefix + */ + public void setKeyPrefix(String keyPrefix) { + this.keyPrefix = keyPrefix; + } + + /* (non-Javadoc) + * @see org.apache.shiro.cache.CacheManager#getCache(java.lang.String) */ + @SuppressWarnings({"rawtypes", "unchecked"}) + public Cache getCache(String name) throws CacheException { + logger.debug("获取名称为: " + name + " 的RedisCache实例"); + + Cache c = caches.get(name); + + if (c == null) { + // create a new cache instance + c = new RedisCache(keyPrefix); + + // add it to the cache collection + caches.put(name, c); + } + return c; + } + +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileManager.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileManager.java index 82519710..ba786714 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileManager.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileManager.java @@ -1,19 +1,17 @@ package org.ibase4j.core.support.fastdfs; import java.io.IOException; -import java.net.InetSocketAddress; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.csource.common.MyException; import org.csource.common.NameValuePair; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.FileInfo; -import org.csource.fastdfs.ServerInfo; import org.csource.fastdfs.StorageClient; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; -import org.csource.fastdfs.TrackerGroup; import org.csource.fastdfs.TrackerServer; import org.csource.fastdht.FastDHTClient; import org.csource.fastdht.KeyInfo; @@ -28,136 +26,99 @@ @SuppressWarnings("serial") public class FileManager implements Config { private static Logger logger = LogManager.getLogger(); - private static TrackerClient trackerClient; - private static TrackerServer trackerServer; - private static StorageServer storageServer; - private static StorageClient storageClient; - private static FastDHTClient fastDHTClient; - - static { // Initialize Fast DFS Client configurations - try { - initFastDFSClient(); - //org.csource.fastdht.ClientGlobal.init(fdhtClientConfigFilePath); - trackerClient = new TrackerClient(); - trackerServer = trackerClient.getConnection(); - storageClient = new StorageClient(trackerServer, storageServer); - fastDHTClient = new FastDHTClient(true); - } catch (Exception e) { - logger.error("", e); - } - } - - private static void initFastDFSClient() throws MyException { - String[] szTrackerServers; - String[] parts; - - ClientGlobal.g_connect_timeout = PropertiesUtil.getInt("fastDFS.connect_timeout", - ClientGlobal.DEFAULT_CONNECT_TIMEOUT); - if (ClientGlobal.g_connect_timeout < 0) { - ClientGlobal.g_connect_timeout = ClientGlobal.DEFAULT_CONNECT_TIMEOUT; - } - ClientGlobal.g_connect_timeout *= 1000; // millisecond - - ClientGlobal.g_network_timeout = PropertiesUtil.getInt("fastDFS.network_timeout", - ClientGlobal.DEFAULT_NETWORK_TIMEOUT); - if (ClientGlobal.g_network_timeout < 0) { - ClientGlobal.g_network_timeout = ClientGlobal.DEFAULT_NETWORK_TIMEOUT; - } - ClientGlobal.g_network_timeout *= 1000; // millisecond - - ClientGlobal.g_charset = PropertiesUtil.getString("fastDFS.charset"); - if (ClientGlobal.g_charset == null || ClientGlobal.g_charset.length() == 0) { - ClientGlobal.g_charset = "ISO8859-1"; - } - - szTrackerServers = PropertiesUtil.getString("fastDFS.tracker_server").split(","); - if (szTrackerServers == null) { - throw new MyException("item \"tracker_server\" in not found"); - } - - InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length]; - for (int i = 0; i < szTrackerServers.length; i++) { - parts = szTrackerServers[i].split("\\:", 2); - if (parts.length != 2) { - throw new MyException( - "the value of item \"tracker_server\" is invalid, the correct format is host:port"); - } - - tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim())); - } - ClientGlobal.g_tracker_group = new TrackerGroup(tracker_servers); - - ClientGlobal.g_tracker_http_port = PropertiesUtil.getInt("fastDFS.http.tracker_http_port", 80); - ClientGlobal.g_anti_steal_token = PropertiesUtil.getBoolean("fastDFS.http.anti_steal_token", false); - if (ClientGlobal.g_anti_steal_token) { - ClientGlobal.g_secret_key = PropertiesUtil.getString("fastDFS.http.secret_key"); - } - } - - public static void upload(FileModel file) { - logger.info("File Name: " + file.getFilename() + ". File Length: " + file.getContent().length); - - NameValuePair[] meta_list = new NameValuePair[]{new NameValuePair("mime", file.getMime()), - new NameValuePair("size", file.getSize()), new NameValuePair("filename", file.getFilename())}; - - long startTime = System.currentTimeMillis(); - String[] uploadResults = null; - try { - uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list); - } catch (IOException e) { - logger.error("IO Exception when uploadind the file: " + file.getFilename(), e); - } catch (Exception e) { - logger.error("Non IO Exception when uploadind the file: " + file.getFilename(), e); - } - logger.info("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms"); - - if (uploadResults == null) { - logger.error("upload file fail, error code: " + storageClient.getErrorCode()); - } - - String groupName = uploadResults[0]; - String remoteFileName = uploadResults[1]; - - String fileAbsolutePath = PROTOCOL + trackerServer.getInetSocketAddress().getHostName() + SEPARATOR - + TRACKER_NGNIX_PORT + SEPARATOR + groupName + SEPARATOR + remoteFileName; - file.setRemotePath(fileAbsolutePath); - logger.info( - "upload file successfully!!! " + "group_name: " + groupName + ", remoteFileName:" + " " + remoteFileName); - try { - KeyInfo keyInfo = new KeyInfo(file.getNamespace(), file.getObjectId(), file.getKey()); - FastDfsFile fastDfsFile = new FastDfsFile(); - fastDfsFile.setGroupName(groupName); - fastDfsFile.setFileName(remoteFileName); - fastDfsFile.setNameValuePairs(meta_list); - fastDHTClient.set(keyInfo, JSON.toJSONString(fastDfsFile)); - } catch (Exception e) { - logger.error("", e); - } - } - - public static FileInfo getFile(String namespace, String objectId, String key) { - try { - KeyInfo keyInfo = new KeyInfo(namespace, objectId, key); - String info = fastDHTClient.get(keyInfo); - FastDfsFile fastDfsFile = JSON.parseObject(info, FastDfsFile.class); - return storageClient.get_file_info(fastDfsFile.getGroupName(), fastDfsFile.getFileName()); - } catch (IOException e) { - logger.error("IO Exception: Get File from Fast DFS failed", e); - } catch (Exception e) { - logger.error("Non IO Exception: Get File from Fast DFS failed", e); - } - return null; - } - - public static void deleteFile(String groupName, String remoteFileName) throws Exception { - storageClient.delete_file(groupName, remoteFileName); - } - - public static StorageServer[] getStoreStorages(String groupName) throws IOException { - return trackerClient.getStoreStorages(trackerServer, groupName); - } - - public static ServerInfo[] getFetchStorages(String groupName, String remoteFileName) throws IOException { - return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName); - } + private TrackerServer trackerServer; + private StorageServer storageServer; + private StorageClient storageClient; + private FastDHTClient fastDHTClient; + + private ExecutorService searchService = Executors.newSingleThreadExecutor(); + + static { // Initialize Fast DFS Client configurations + try { + String path = FileManager.class.getResource("/").toString().replace("file:/", ""); + ClientGlobal.init(path + "fdfs_client.conf"); + org.csource.fastdht.ClientGlobal.init(path + "fdht_client.conf"); + } catch (Exception e) { + logger.error("", e); + } + } + + public static FileManager getInstance() { + return new FileManager(); + } + + private FileManager() { + try { + TrackerClient trackerClient = new TrackerClient(); + this.trackerServer = trackerClient.getConnection(); + this.storageClient = new StorageClient(trackerServer, storageServer); + fastDHTClient = new FastDHTClient(true); + } catch (Exception ex) { + logger.error("", ex); + } + } + + public void upload(final FileModel file) { + logger.info("File Name: " + file.getFilename() + ". File Length: " + file.getContent().length); + + final NameValuePair[] meta_list = new NameValuePair[] { new NameValuePair("mime", file.getMime()), + new NameValuePair("size", file.getSize()), new NameValuePair("filename", file.getFilename()) }; + + long startTime = System.currentTimeMillis(); + String[] uploadResults = null; + try { + uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list); + } catch (IOException e) { + logger.error("IO Exception when uploadind the file: " + file.getFilename(), e); + } catch (Exception e) { + logger.error("Non IO Exception when uploadind the file: " + file.getFilename(), e); + } + + if (uploadResults == null) { + logger.error("upload file fail, error code: " + storageClient.getErrorCode()); + } else { + + final String groupName = uploadResults[0]; + final String remoteFileName = uploadResults[1]; + + String fileAbsolutePath = PropertiesUtil.getString("remote.file.uri.prefix") + groupName + SEPARATOR + + remoteFileName; + file.setRemotePath(fileAbsolutePath); + logger.info("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms. group_name: " + + groupName + ", remoteFileName:" + " " + remoteFileName); + + searchService.execute(new Runnable() { + public void run() { + try { + KeyInfo keyInfo = new KeyInfo(file.getNamespace(), file.getObjectId(), file.getKey()); + FastDfsFile fastDfsFile = new FastDfsFile(); + fastDfsFile.setGroupName(groupName); + fastDfsFile.setFileName(remoteFileName); + fastDfsFile.setNameValuePairs(meta_list); + fastDHTClient.set(keyInfo, JSON.toJSONString(fastDfsFile)); + } catch (Exception e) { + logger.error("", e); + } + } + }); + } + } + + public FileInfo getFile(String namespace, String objectId, String key) { + try { + KeyInfo keyInfo = new KeyInfo(namespace, objectId, key); + String info = fastDHTClient.get(keyInfo); + FastDfsFile fastDfsFile = JSON.parseObject(info, FastDfsFile.class); + return storageClient.get_file_info(fastDfsFile.getGroupName(), fastDfsFile.getFileName()); + } catch (IOException e) { + logger.error("IO Exception: Get File from Fast DFS failed", e); + } catch (Exception e) { + logger.error("Non IO Exception: Get File from Fast DFS failed", e); + } + return null; + } + + public void deleteFile(String groupName, String remoteFileName) throws Exception { + storageClient.delete_file(groupName, remoteFileName); + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileModel.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileModel.java index 82b99513..ec8efe26 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileModel.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/fastdfs/FileModel.java @@ -48,7 +48,7 @@ public FileModel(String namespace, String objectId, String filePath) { fileInputStream.read(file_buff); } this.content = file_buff; - is = getClass().getResourceAsStream("/META-INF/mime.types"); + is = getClass().getResourceAsStream("/config/mime.types"); MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap(is); this.mime = mimetypesFileTypeMap.getContentType(filename); this.key = UUID.randomUUID().toString(); diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/login/ThirdPartyUser.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/login/ThirdPartyUser.java index 69f326ba..b50eaf7d 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/login/ThirdPartyUser.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/login/ThirdPartyUser.java @@ -3,14 +3,14 @@ */ package org.ibase4j.core.support.login; -import java.io.Serializable; +import org.ibase4j.core.base.BaseModel; /** * @author ShenHuaJie * @version 2016年5月20日 下午3:26:23 */ @SuppressWarnings("serial") -public class ThirdPartyUser implements Serializable { +public class ThirdPartyUser extends BaseModel { private String account;// 用户 private String userName;// 用户昵称 diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/JobListener.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/JobListener.java index 06e1fadb..f9af3685 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/JobListener.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/JobListener.java @@ -12,7 +12,7 @@ import org.ibase4j.core.support.mq.QueueSender; import org.ibase4j.core.util.EmailUtil; import org.ibase4j.core.util.NativeUtil; -import org.ibase4j.model.scheduler.TaskFireLog; +import org.ibase4j.model.TaskFireLog; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerManager.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerManager.java index 1f8beb62..3b64c15a 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerManager.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerManager.java @@ -7,11 +7,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ibase4j.core.exception.BusinessException; +import org.ibase4j.core.support.scheduler.TaskScheduled.JobType; +import org.ibase4j.core.support.scheduler.TaskScheduled.TaskType; import org.ibase4j.core.support.scheduler.job.BaseJob; import org.ibase4j.core.support.scheduler.job.StatefulJob; import org.ibase4j.core.util.DataUtil; -import org.ibase4j.model.scheduler.TaskScheduled; -import org.ibase4j.model.scheduler.TaskScheduled.JobType; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.JobBuilder; @@ -87,8 +87,11 @@ public List getAllJobDetail() { job.setNextFireTime(trigger.getNextFireTime()); JobDataMap jobDataMap = trigger.getJobDataMap(); job.setTaskType(jobDataMap.getString("taskType")); + job.setTargetSystem(jobDataMap.getString("targetSystem")); job.setTargetObject(jobDataMap.getString("targetObject")); job.setTargetMethod(jobDataMap.getString("targetMethod")); + job.setContactName(jobDataMap.getString("contactName")); + job.setContactEmail(jobDataMap.getString("contactEmail")); job.setTaskDesc(jobDetail.getDescription()); String jobClass = jobDetail.getJobClass().getSimpleName(); if (jobClass.equals("StatefulJob")) { @@ -137,6 +140,9 @@ public boolean updateTask(TaskScheduled taskScheduled) { String jobType = taskScheduled.getJobType(); String taskType = taskScheduled.getTaskType(); JobDataMap jobDataMap = new JobDataMap(); + if (TaskType.dubbo.equals(taskType)) { + jobDataMap.put("targetSystem", taskScheduled.getTargetSystem()); + } jobDataMap.put("targetObject", targetObject); jobDataMap.put("targetMethod", targetMethod); jobDataMap.put("taskType", taskType); diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerService.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerService.java index b4f0ff50..dd3a55bf 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerService.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/SchedulerService.java @@ -5,12 +5,13 @@ import org.ibase4j.core.base.BaseProviderImpl; import org.ibase4j.core.util.InstanceUtil; -import org.ibase4j.dao.scheduler.TaskFireLogMapper; -import org.ibase4j.model.scheduler.TaskFireLog; -import org.ibase4j.model.scheduler.TaskScheduled; +import org.ibase4j.mapper.TaskFireLogMapper; +import org.ibase4j.model.TaskFireLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.plugins.Page; @@ -19,78 +20,79 @@ * @author ShenHuaJie * @version 2016年7月1日 上午11:34:59 */ -public class SchedulerService { - @Autowired - private TaskFireLogMapper logMapper; - @Autowired - private SchedulerManager schedulerManager; +public class SchedulerService implements ApplicationContextAware { + @Autowired + private TaskFireLogMapper logMapper; + @Autowired + private SchedulerManager schedulerManager; + protected ApplicationContext applicationContext; - // 获取所有作业 - public List getAllTaskDetail() { - return schedulerManager.getAllJobDetail(); - } + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } - // 执行作业 - public void execTask(String taskGroup, String taskName) { - TaskScheduled taskScheduler = new TaskScheduled(); - taskScheduler.setTaskGroup(taskGroup); - taskScheduler.setTaskName(taskName); - schedulerManager.runJob(taskScheduler); - } + // 获取所有作业 + public List getAllTaskDetail() { + return schedulerManager.getAllJobDetail(); + } - // 暂停/恢复作业 - public void openCloseTask(String taskGroup, String taskName, String status) { - TaskScheduled taskScheduler = new TaskScheduled(); - taskScheduler.setTaskGroup(taskGroup); - taskScheduler.setTaskName(taskName); - if ("start".equals(status)) { - schedulerManager.resumeJob(taskScheduler); - } else if ("stop".equals(status)) { - schedulerManager.stopJob(taskScheduler); - } - } + // 执行作业 + public void execTask(String taskGroup, String taskName) { + TaskScheduled taskScheduled = new TaskScheduled(taskGroup, taskName); + schedulerManager.runJob(taskScheduled); + } - // 删除作业 - public void delTask(String taskGroup, String taskName) { - TaskScheduled taskScheduler = new TaskScheduled(); - taskScheduler.setTaskGroup(taskGroup); - taskScheduler.setTaskName(taskName); - schedulerManager.delJob(taskScheduler); - } + // 恢复作业 + public void openTask(String taskGroup, String taskName) { + TaskScheduled taskScheduled = new TaskScheduled(taskGroup, taskName); + schedulerManager.resumeJob(taskScheduled); + } - // 修改任务 - public void updateTask(TaskScheduled taskScheduled) { - schedulerManager.updateTask(taskScheduled); - } + // 暂停作业 + public void closeTask(String taskGroup, String taskName) { + TaskScheduled taskScheduled = new TaskScheduled(taskGroup, taskName); + schedulerManager.stopJob(taskScheduled); + } - @Cacheable("taskFireLog") - public TaskFireLog getFireLogById(Long id) { - return logMapper.selectById(id); - } + // 删除作业 + public void delTask(String taskGroup, String taskName) { + TaskScheduled taskScheduled = new TaskScheduled(taskGroup, taskName); + schedulerManager.delJob(taskScheduled); + } - @Transactional - @CachePut("taskFireLog") - public TaskFireLog updateLog(TaskFireLog record) { - if (record.getId() == null) { - logMapper.insert(record); - } else { - logMapper.updateById(record); - } - return record; - } + // 修改任务 + public void updateTask(TaskScheduled taskScheduled) { + schedulerManager.updateTask(taskScheduled); + } - public Page queryLog(Map params) { - Page ids = BaseProviderImpl.getPage(params); - ids.setRecords(logMapper.selectIdByMap(ids, params)); - Page page = new Page(ids.getCurrent(), ids.getSize()); - page.setTotal(ids.getTotal()); - if (ids != null) { - List records = InstanceUtil.newArrayList(); - for (Long id : ids.getRecords()) { - records.add(InstanceUtil.getBean(getClass()).getFireLogById(id)); - } - page.setRecords(records); - } - return page; - } + @Cacheable("taskFireLog") + public TaskFireLog getFireLogById(Long id) { + return logMapper.selectById(id); + } + + @Transactional + @CachePut("taskFireLog") + public TaskFireLog updateLog(TaskFireLog record) { + if (record.getId() == null) { + logMapper.insert(record); + } else { + logMapper.updateById(record); + } + return record; + } + + public Page queryLog(Map params) { + Page ids = BaseProviderImpl.getPage(params); + ids.setRecords(logMapper.selectIdByMap(ids, params)); + Page page = new Page(ids.getCurrent(), ids.getSize()); + page.setTotal(ids.getTotal()); + if (ids != null) { + List records = InstanceUtil.newArrayList(); + for (Long id : ids.getRecords()) { + records.add(applicationContext.getBean(getClass()).getFireLogById(id)); + } + page.setRecords(records); + } + return page; + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/TaskScheduled.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/TaskScheduled.java new file mode 100644 index 00000000..f09fb19c --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/TaskScheduled.java @@ -0,0 +1,214 @@ +package org.ibase4j.core.support.scheduler; + +import java.util.Date; + +import org.ibase4j.core.base.BaseModel; + +/** + * 计划任务信息 + * + * @author ShenHuaJie + * @version $Id: ScheduleJob.java, v 0.1 2015-1-19 下午7:35:44 ShenHuaJie Exp $ + */ +@SuppressWarnings("serial") +public class TaskScheduled extends BaseModel { + public interface JobType { + String job = "job"; + String statefulJob = "statefulJob"; + } + + public interface TaskType { + String local = "LOCAL"; + String dubbo = "DUBBO"; + } + + public TaskScheduled() { + } + + public TaskScheduled(String taskGroup, String taskName) { + this.taskGroup = taskGroup; + this.taskName = taskName; + } + + /** 任务名称 */ + private String taskName; + /** 任务分组 */ + private String taskGroup; + /** 任务状态 0禁用 1启用 2删除 */ + private String status; + /** 任务运行时间表达式 */ + private String taskCron; + /** 最后一次执行时间 */ + private Date previousFireTime; + /** 下次执行时间 */ + private Date nextFireTime; + /** 任务描述 */ + private String taskDesc; + // 任务类型(是否阻塞) + private String jobType; + // 本地任务/dubbo任务 + private String taskType; + // 运行系统(dubbo任务必须) + private String targetSystem; + // 任务对象 + private String targetObject; + // 任务方法 + private String targetMethod; + // 通知邮箱地址 + private String contactName; + private String contactEmail; + + public String getTaskName() { + return taskName; + } + + public void setTaskName(String taskName) { + this.taskName = taskName; + } + + public String getTaskGroup() { + return taskGroup; + } + + public void setTaskGroup(String taskGroup) { + this.taskGroup = taskGroup; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getTaskCron() { + return taskCron; + } + + public void setTaskCron(String taskCron) { + this.taskCron = taskCron; + } + + public Date getPreviousFireTime() { + return previousFireTime; + } + + public void setPreviousFireTime(Date previousFireTime) { + this.previousFireTime = previousFireTime; + } + + public Date getNextFireTime() { + return nextFireTime; + } + + public void setNextFireTime(Date nextFireTime) { + this.nextFireTime = nextFireTime; + } + + public String getTaskDesc() { + return taskDesc; + } + + public void setTaskDesc(String taskDesc) { + this.taskDesc = taskDesc; + } + + /** + * @return the jobType + */ + public String getJobType() { + return jobType; + } + + /** + * @param jobType + * the jobType to set + */ + public void setJobType(String jobType) { + this.jobType = jobType; + } + + /** + * @return the taskType + */ + public String getTaskType() { + return taskType; + } + + /** + * @param taskType + * the taskType to set + */ + public void setTaskType(String taskType) { + this.taskType = taskType; + } + + /** + * @return the targetSystem + */ + public String getTargetSystem() { + return targetSystem; + } + + /** + * @param targetSystem + * the targetSystem to set + */ + public void setTargetSystem(String targetSystem) { + this.targetSystem = targetSystem; + } + + /** + * @return the targetObject + */ + public String getTargetObject() { + return targetObject; + } + + /** + * @param targetObject + * the targetObject to set + */ + public void setTargetObject(String targetObject) { + this.targetObject = targetObject; + } + + /** + * @return the targetMethod + */ + public String getTargetMethod() { + return targetMethod; + } + + /** + * @param targetMethod + * the targetMethod to set + */ + public void setTargetMethod(String targetMethod) { + this.targetMethod = targetMethod; + } + + public String getContactName() { + return contactName; + } + + public void setContactName(String contactName) { + this.contactName = contactName; + } + + /** + * @return the contactEmail + */ + public String getContactEmail() { + return contactEmail; + } + + /** + * @param contactEmail + * the contactEmail to set + */ + public void setContactEmail(String contactEmail) { + this.contactEmail = contactEmail; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/job/BaseJob.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/job/BaseJob.java index a6d0195d..f681491f 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/job/BaseJob.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/scheduler/job/BaseJob.java @@ -6,7 +6,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.ibase4j.core.support.dubbo.ReferenceUtil; -import org.ibase4j.model.scheduler.TaskScheduled.TaskType; +import org.ibase4j.core.support.scheduler.TaskScheduled.TaskType; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; @@ -15,33 +15,34 @@ /** * 默认调度(非阻塞) + * * @author ShenHuaJie * @version 2016年12月29日 上午11:52:32 */ public class BaseJob implements Job { - private Logger logger = LogManager.getLogger(this.getClass()); - - public void execute(JobExecutionContext context) throws JobExecutionException { - long start = System.currentTimeMillis(); - JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); - String taskType = (String)jobDataMap.get("taskType"); - String targetObject = jobDataMap.getString("targetObject"); - String targetMethod = jobDataMap.getString("targetMethod"); - logger.info("定时任务开始执行: [{}.{}]", targetObject, targetMethod); - try { - ApplicationContext applicationContext = (ApplicationContext)context.getScheduler().getContext() - .get("applicationContext"); - if (TaskType.local.equals(taskType)) { - Object refer = applicationContext.getBean(targetObject); - refer.getClass().getDeclaredMethod(targetMethod).invoke(refer); - } else if (TaskType.dubbo.equals(taskType)) { - Object refer = ReferenceUtil.refer(applicationContext, targetObject); - refer.getClass().getDeclaredMethod(targetMethod).invoke(refer); - } - double time = (System.currentTimeMillis() - start) / 1000.0; - logger.info("定时任务[{}.{}]用时:{}s", targetObject, targetMethod, time); - } catch (Exception e) { - throw new JobExecutionException(e); - } - } + private Logger logger = LogManager.getLogger(this.getClass()); + + public void execute(JobExecutionContext context) throws JobExecutionException { + long start = System.currentTimeMillis(); + JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); + String taskType = jobDataMap.getString("taskType"); + String targetObject = jobDataMap.getString("targetObject"); + String targetMethod = jobDataMap.getString("targetMethod"); + logger.info("定时任务开始执行: [{}.{}]", targetObject, targetMethod); + try { + ApplicationContext applicationContext = (ApplicationContext) context.getScheduler().getContext() + .get("applicationContext"); + if (TaskType.local.equals(taskType)) { + Object refer = applicationContext.getBean(targetObject); + refer.getClass().getDeclaredMethod(targetMethod).invoke(refer); + } else if (TaskType.dubbo.equals(taskType)) { + Object refer = ReferenceUtil.refer(applicationContext, targetObject); + refer.getClass().getDeclaredMethod(targetMethod).invoke(refer); + } + double time = (System.currentTimeMillis() - start) / 1000.0; + logger.info("定时任务[{}.{}]用时:{}s", targetObject, targetMethod, time); + } catch (Exception e) { + throw new JobExecutionException(e); + } + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/decoder/BASE64Decoder.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/security/BASE64Decoder.java similarity index 96% rename from iBase4J-Common/src/main/java/org/ibase4j/core/support/decoder/BASE64Decoder.java rename to iBase4J-Common/src/main/java/org/ibase4j/core/support/security/BASE64Decoder.java index 2e7a2a0d..7f10d0a0 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/decoder/BASE64Decoder.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/security/BASE64Decoder.java @@ -21,7 +21,7 @@ * 22 * or visit www.oracle.com if you need additional information or have any * 23 * questions. * 24 */ -package org.ibase4j.core.support.decoder; +package org.ibase4j.core.support.security; import java.io.OutputStream; import java.io.PushbackInputStream; diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/support/decoder/CharacterDecoder.java b/iBase4J-Common/src/main/java/org/ibase4j/core/support/security/CharacterDecoder.java similarity index 97% rename from iBase4J-Common/src/main/java/org/ibase4j/core/support/decoder/CharacterDecoder.java rename to iBase4J-Common/src/main/java/org/ibase4j/core/support/security/CharacterDecoder.java index cbf6a4fb..650abaac 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/support/decoder/CharacterDecoder.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/support/security/CharacterDecoder.java @@ -22,7 +22,7 @@ * 23 * questions. * 24 */ -package org.ibase4j.core.support.decoder; +package org.ibase4j.core.support.security; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/CacheUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/CacheUtil.java index cd014f11..1c35501d 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/util/CacheUtil.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/CacheUtil.java @@ -2,40 +2,80 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.ibase4j.core.Constants; import org.ibase4j.core.support.cache.CacheManager; +import org.ibase4j.core.support.cache.RedisHelper; import org.ibase4j.core.support.cache.RedissonHelper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; -public final class CacheUtil { +@Configuration +public class CacheUtil { private static Logger logger = LogManager.getLogger(CacheUtil.class); + private static CacheManager cacheManager; + private static RedisHelper redisHelper; - private CacheUtil() { + @Bean + public CacheManager setCache() { + cacheManager = getCache(); + return cacheManager; } public static CacheManager getCache() { - return new RedissonHelper(); + if (cacheManager == null) { + synchronized (CacheUtil.class) { + if (cacheManager == null) { + cacheManager = new RedissonHelper(); + } + } + } + return cacheManager; + } + + @Bean + public RedisHelper setRedisHelper() { + redisHelper = getRedisHelper(); + return redisHelper; + } + + public static RedisHelper getRedisHelper() { + if (redisHelper == null) { + synchronized (CacheUtil.class) { + if (redisHelper == null) { + redisHelper = new RedisHelper(); + } + } + } + return redisHelper; } /** 获取锁 */ public static boolean getLock(String key) { - if (!getCache().exists(key)) { - synchronized (CacheUtil.class) { - if (!getCache().exists(key)) { - if (getCache().setnx(key, String.valueOf(System.currentTimeMillis()))) { - return true; + try { + if (!getRedisHelper().exists(key)) { + synchronized (CacheUtil.class) { + if (!getRedisHelper().exists(key)) { + if (getRedisHelper().setnx(key, String.valueOf(System.currentTimeMillis()))) { + return true; + } } } } + } catch (Exception e) { + logger.error("getLock", e); } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - logger.error(Constants.Exception_Head, e); + int expires = 1000 * 60 * 3; + String currentValue = (String) getRedisHelper().get(key); + if (currentValue != null && Long.parseLong(currentValue) < System.currentTimeMillis() - expires) { + if (getRedisHelper().setnx("UNLOCK_" + key, "0")) { + unlock(key); + getCache().set("UNLOCK_" + key, "0", 1); + } + return getLock(key); } - return getLock(key); + return false; } public static void unlock(String key) { - getCache().unlock(key); + getRedisHelper().unlock(key); } -} \ No newline at end of file +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/DubboUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/DubboUtil.java new file mode 100644 index 00000000..c9049cce --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/DubboUtil.java @@ -0,0 +1,40 @@ +package org.ibase4j.core.util; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.springframework.context.ApplicationContext; + +import com.alibaba.dubbo.config.spring.ReferenceBean; + +/** + * @author ShenHuaJie + * @version 2016年5月27日 下午4:23:06 + */ +public class DubboUtil { + private DubboUtil() { + } + + private static final ConcurrentMap> referenceConfigs = new ConcurrentHashMap>(); + + /** 获取Dubbo服务 */ + public static Object refer(ApplicationContext applicationContext, String interfaceName) { + String key = "/" + interfaceName + ":"; + ReferenceBean referenceConfig = referenceConfigs.get(key); + if (referenceConfig == null) { + referenceConfig = new ReferenceBean(); + referenceConfig.setInterface(interfaceName); + if (applicationContext != null) { + referenceConfig.setApplicationContext(applicationContext); + try { + referenceConfig.afterPropertiesSet(); + } catch (Exception e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + referenceConfigs.putIfAbsent(key, referenceConfig); + referenceConfig = referenceConfigs.get(key); + } + return referenceConfig.get(); + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/InstanceUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/InstanceUtil.java index 2af19d10..3f3da293 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/util/InstanceUtil.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/InstanceUtil.java @@ -26,8 +26,11 @@ import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; +import org.apache.commons.lang3.StringUtils; import org.ibase4j.core.exception.DataParseException; -import org.springframework.web.context.ContextLoader; +import org.ibase4j.core.exception.InstanceException; + +import com.esotericsoftware.reflectasm.MethodAccess; /** * 实例辅助类 @@ -36,399 +39,400 @@ * @since 2012-07-18 */ public final class InstanceUtil { - private InstanceUtil() { - } - - /** 实例化并复制属性 */ - public static final T to(Object orig, Class clazz) { - T bean = null; - try { - bean = clazz.newInstance(); - PropertyUtils.copyProperties(bean, orig); - } catch (Exception e) { - } - return bean; - } - - // Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean - public static void transMap2Bean(Map map, Object obj) { - try { - BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor property : propertyDescriptors) { - String key = property.getName(); - if (map.containsKey(key)) { - Object value = map.get(key); - // 得到property对应的setter方法 - Method setter = property.getWriteMethod(); - setter.invoke(obj, value); - } - } - } catch (Exception e) { - System.out.println("transMap2Bean Error " + e); - } - return; - } - - // Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map - public static Map transBean2Map(Object obj) { - Map map = newHashMap(); - if (obj == null) { - return map; - } - try { - BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor property : propertyDescriptors) { - String key = property.getName(); - // 过滤class属性 - if (!key.equals("class")) { - // 得到property对应的getter方法 - Method getter = property.getReadMethod(); - Object value = getter.invoke(obj); - map.put(key, value); - } - } - } catch (Exception e) { - System.out.println("transBean2Map Error " + e); - } - return map; - } - - /** - * @param oldBean - * @param newBean - * @return - */ - public static T getDiff(T oldBean, T newBean) { - if (oldBean == null && newBean != null) { - return newBean; - } else if (newBean == null) { - return null; - } else { - Class cls1 = oldBean.getClass(); - try { - @SuppressWarnings("unchecked") - T object = (T) cls1.newInstance(); - BeanInfo beanInfo = Introspector.getBeanInfo(cls1); - PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); - for (PropertyDescriptor property : propertyDescriptors) { - String key = property.getName(); - // 过滤class属性 - if (!key.equals("class")) { - // 得到property对应的getter方法 - Method getter = property.getReadMethod(); - // 得到property对应的setter方法 - Method setter = property.getWriteMethod(); - Object oldValue = getter.invoke(oldBean); - Object newValue = getter.invoke(newBean); - if (newValue != null) { - if (oldValue == null) { - setter.invoke(object, newValue); - } else if (oldValue != null && !newValue.equals(oldValue)) { - setter.invoke(object, newValue); - } - } - } - } - return object; - } catch (Exception e) { - throw new DataParseException(e); - } - } - } - - /** - * Return the specified class. Checks the ThreadContext classloader first, - * then uses the System classloader. Should replace all calls to - * Class.forName( claz ) (which only calls the System class - * loader) when the class might be in a different classloader (e.g. in a - * webapp). - * - * @param clazz - * the name of the class to instantiate - * @return the requested Class object - */ - public static final Class getClass(String clazz) { - /** - * Use the Thread context classloader if possible - */ - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - try { - if (loader != null) { - return Class.forName(clazz, true, loader); - } - /** - * Thread context classloader isn't working out, so use system - * loader. - */ - return Class.forName(clazz); - } catch (ClassNotFoundException e) { - throw new InstanceException(e); - } - } - - /** - * 封装实体 - * - * @param cls - * 实体类 - * @param list - * 实体Map集合 - * @return - */ - public static final List getInstanceList(Class cls, List list) { - List resultList = newArrayList(); - E object = null; - for (Iterator iterator = list.iterator(); iterator.hasNext();) { - Map map = (Map) iterator.next(); - object = newInstance(cls, map); - resultList.add(object); - } - return resultList; - } - - /** - * 封装实体 - * - * @param cls - * 实体类 - * @param list - * 数据查询结果集 - * @return - */ - public static final List getInstanceList(Class cls, ResultSet rs) { - List resultList = newArrayList(); - try { - E object = cls.newInstance(); - Field[] fields = cls.getDeclaredFields(); - while (rs.next()) { - object = cls.newInstance(); - for (int i = 0; i < fields.length; i++) { - String fieldName = fields[i].getName(); - PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName)); - } - resultList.add(object); - } - } catch (Exception e) { - throw new InstanceException(e); - } - return resultList; - } - - /** - * 新建实例 - * - * @param cls - * 实体类 - * @param list - * 实体属性Map - * @return - */ - public static final E newInstance(Class cls, Map map) { - E object = null; - try { - object = cls.newInstance(); - BeanUtils.populate(object, map); - } catch (Exception e) { - throw new InstanceException(e); - } - return object; - } - - /** - * Return a new instance of the given class. Checks the ThreadContext - * classloader first, then uses the System classloader. Should replace all - * calls to Class.forName( claz ).newInstance() (which only - * calls the System class loader) when the class might be in a different - * classloader (e.g. in a webapp). - * - * @param clazz - * the name of the class to instantiate - * @return an instance of the specified class - */ - public static final Object newInstance(String clazz) { - try { - return getClass(clazz).newInstance(); - } catch (Exception e) { - throw new InstanceException(e); - } - } - - public static final K newInstance(Class cls, Object... args) { - try { - Class[] argsClass = null; - if (args != null) { - argsClass = new Class[args.length]; - for (int i = 0, j = args.length; i < j; i++) { - argsClass[i] = args[i].getClass(); - } - } - Constructor cons = cls.getConstructor(argsClass); - return cons.newInstance(args); - } catch (Exception e) { - throw new InstanceException(e); - } - } - - /** - * 新建实例 - * - * @param className - * 类名 - * @param args - * 构造函数的参数 - * @return 新建的实例 - */ - public static final Object newInstance(String className, Object... args) { - try { - Class newoneClass = Class.forName(className); - return newInstance(newoneClass, args); - } catch (Exception e) { - throw new InstanceException(e); - } - } - - /** - * 执行某对象方法 - * - * @param owner - * 对象 - * @param methodName - * 方法名 - * @param args - * 参数 - * @return 方法返回值 - */ - public static final Object invokeMethod(Object owner, String methodName, Object[] args) { - Class ownerClass = owner.getClass(); - Class[] argsClass = new Class[args.length]; - for (int i = 0, j = args.length; i < j; i++) { - argsClass[i] = args[i].getClass(); - } - try { - Method method = ownerClass.getMethod(methodName, argsClass); - return method.invoke(owner, args); - } catch (Exception e) { - throw new InstanceException(e); - } - } - - /** */ - public static final K getBean(Class cls) { - return ContextLoader.getCurrentWebApplicationContext().getBean(cls); - } - - /** - * Constructs an empty ArrayList. - */ - public static final ArrayList newArrayList() { - return new ArrayList(); - } - - /** - * Constructs an empty ArrayList. - */ - public static final ArrayList newArrayList(@SuppressWarnings("unchecked") E... e) { - ArrayList list = new ArrayList(); - Collections.addAll(list, e); - return list; - } - - /** - * Constructs an empty HashMap. - */ - public static final HashMap newHashMap() { - return new HashMap(); - } - - /** - * Constructs an empty HashSet. - */ - public static final HashSet newHashSet() { - return new HashSet(); - } - - /** - * Constructs an empty Hashtable. - */ - public static final Hashtable newHashtable() { - return new Hashtable(); - } - - /** - * Constructs an empty LinkedHashMap. - */ - public static final LinkedHashMap newLinkedHashMap() { - return new LinkedHashMap(); - } - - /** - * Constructs an empty LinkedHashSet. - */ - public static final LinkedHashSet newLinkedHashSet() { - return new LinkedHashSet(); - } - - /** - * Constructs an empty LinkedList. - */ - public static final LinkedList newLinkedList() { - return new LinkedList(); - } - - /** - * Constructs an empty TreeMap. - */ - public static final TreeMap newTreeMap() { - return new TreeMap(); - } - - /** - * Constructs an empty TreeSet. - */ - public static final TreeSet newTreeSet() { - return new TreeSet(); - } - - /** - * Constructs an empty Vector. - */ - public static final Vector newVector() { - return new Vector(); - } - - /** - * Constructs an empty WeakHashMap. - */ - public static final WeakHashMap newWeakHashMap() { - return new WeakHashMap(); - } - - /** - * Constructs an empty HashMap. - */ - public static final Map newHashMap(k key, v value) { - Map map = newHashMap(); - map.put(key, value); - return map; - } - - /** - * Constructs an empty ConcurrentHashMap. - */ - public static final ConcurrentHashMap newConcurrentHashMap() { - return new ConcurrentHashMap(); - } -} - -@SuppressWarnings("serial") -class InstanceException extends RuntimeException { - public InstanceException() { - super(); - } - - public InstanceException(Throwable t) { - super(t); - } + private InstanceUtil() { + } + + /** 实例化并复制属性 */ + public static final T to(Object orig, Class clazz) { + T bean = null; + try { + bean = clazz.newInstance(); + PropertyUtils.copyProperties(bean, orig); + } catch (Exception e) { + } + return bean; + } + + // Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean + public static void transMap2Bean(Map map, Object obj) { + try { + BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor property : propertyDescriptors) { + String key = property.getName(); + if (map.containsKey(key)) { + Object value = map.get(key); + // 得到property对应的setter方法 + Method setter = property.getWriteMethod(); + setter.invoke(obj, value); + } + } + } catch (Exception e) { + System.out.println("transMap2Bean Error " + e); + } + return; + } + + // Bean --> Map 1: 利用Introspector和PropertyDescriptor 将Bean --> Map + public static Map transBean2Map(Object obj) { + Map map = newHashMap(); + if (obj == null) { + return map; + } + try { + BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor property : propertyDescriptors) { + String key = property.getName(); + // 过滤class属性 + if (!key.equals("class")) { + // 得到property对应的getter方法 + Method getter = property.getReadMethod(); + Object value = getter.invoke(obj); + map.put(key, value); + } + } + } catch (Exception e) { + System.out.println("transBean2Map Error " + e); + } + return map; + } + + /** + * @param oldBean + * @param newBean + * @return + */ + public static T getDiff(T oldBean, T newBean) { + if (oldBean == null && newBean != null) { + return newBean; + } else if (newBean == null) { + return null; + } else { + Class cls1 = oldBean.getClass(); + try { + @SuppressWarnings("unchecked") + T object = (T)cls1.newInstance(); + BeanInfo beanInfo = Introspector.getBeanInfo(cls1); + PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); + for (PropertyDescriptor property : propertyDescriptors) { + String key = property.getName(); + // 过滤class属性 + if (!key.equals("class")) { + // 得到property对应的getter方法 + Method getter = property.getReadMethod(); + // 得到property对应的setter方法 + Method setter = property.getWriteMethod(); + Object oldValue = getter.invoke(oldBean); + Object newValue = getter.invoke(newBean); + if (newValue != null) { + if (oldValue == null) { + setter.invoke(object, newValue); + } else if (oldValue != null && !newValue.equals(oldValue)) { + setter.invoke(object, newValue); + } + } + } + } + return object; + } catch (Exception e) { + throw new DataParseException(e); + } + } + } + + /** + * Return the specified class. Checks the ThreadContext classloader first, + * then uses the System classloader. Should replace all calls to + * Class.forName( claz ) (which only calls the System class + * loader) when the class might be in a different classloader (e.g. in a + * webapp). + * + * @param clazz + * the name of the class to instantiate + * @return the requested Class object + */ + public static final Class getClass(String clazz) { + /** + * Use the Thread context classloader if possible + */ + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + try { + if (loader != null) { + return Class.forName(clazz, true, loader); + } + /** + * Thread context classloader isn't working out, so use system + * loader. + */ + return Class.forName(clazz); + } catch (ClassNotFoundException e) { + throw new InstanceException(e); + } + } + + /** + * 封装实体 + * + * @param cls + * 实体类 + * @param list + * 实体Map集合 + * @return + */ + public static final List getInstanceList(Class cls, List list) { + List resultList = newArrayList(); + E object = null; + for (Iterator iterator = list.iterator(); iterator.hasNext();) { + Map map = (Map)iterator.next(); + object = newInstance(cls, map); + resultList.add(object); + } + return resultList; + } + + /** + * 封装实体 + * + * @param cls + * 实体类 + * @param list + * 数据查询结果集 + * @return + */ + public static final List getInstanceList(Class cls, ResultSet rs) { + List resultList = newArrayList(); + try { + E object = cls.newInstance(); + Field[] fields = cls.getDeclaredFields(); + while (rs.next()) { + object = cls.newInstance(); + for (int i = 0; i < fields.length; i++) { + String fieldName = fields[i].getName(); + PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName)); + } + resultList.add(object); + } + } catch (Exception e) { + throw new InstanceException(e); + } + return resultList; + } + + /** + * 新建实例 + * + * @param cls + * 实体类 + * @param list + * 实体属性Map + * @return + */ + public static final E newInstance(Class cls, Map map) { + E object = null; + try { + object = cls.newInstance(); + BeanUtils.populate(object, map); + } catch (Exception e) { + throw new InstanceException(e); + } + return object; + } + + /** + * Return a new instance of the given class. Checks the ThreadContext + * classloader first, then uses the System classloader. Should replace all + * calls to Class.forName( claz ).newInstance() (which only + * calls the System class loader) when the class might be in a different + * classloader (e.g. in a webapp). + * + * @param clazz + * the name of the class to instantiate + * @return an instance of the specified class + */ + public static final Object newInstance(String clazz) { + try { + return getClass(clazz).newInstance(); + } catch (Exception e) { + throw new InstanceException(e); + } + } + + public static final K newInstance(Class cls, Object... args) { + try { + Class[] argsClass = null; + if (args != null) { + argsClass = new Class[args.length]; + for (int i = 0, j = args.length; i < j; i++) { + argsClass[i] = args[i].getClass(); + } + } + Constructor cons = cls.getConstructor(argsClass); + return cons.newInstance(args); + } catch (Exception e) { + throw new InstanceException(e); + } + } + + public static Map> clazzMap = new HashMap>(); + + /** + * 新建实例 + * + * @param className + * 类名 + * @param args + * 构造函数的参数 + * @return 新建的实例 + */ + public static final Object newInstance(String className, Object... args) { + try { + Class newoneClass = clazzMap.get(className); + if (newoneClass == null) { + newoneClass = Class.forName(className); + clazzMap.put(className, newoneClass); // 缓存class对象 + } + return newInstance(newoneClass, args); + } catch (Exception e) { + throw new InstanceException(e); + } + } + + public static Map methodMap = new HashMap(); + + /** + * 执行某对象方法 + * + * @param owner + * 对象 + * @param methodName + * 方法名 + * @param args + * 参数 + * @return 方法返回值 + */ + public static final Object invokeMethod(Object owner, String methodName, Object... args) { + Class ownerClass = owner.getClass(); + String key = null; + if (args != null) { + Class[] argsClass = new Class[args.length]; + for (int i = 0, j = args.length; i < j; i++) { + if (args[i] != null) { + argsClass[i] = args[i].getClass(); + } + } + key = ownerClass + "_" + methodName + "_" + StringUtils.join(argsClass, ","); // 用于区分重载的方法 + } else { + key = ownerClass + "_" + methodName; // 用于区分重载的方法 + } + MethodAccess methodAccess = methodMap.get(key); + if (methodAccess == null) { + methodAccess = MethodAccess.get(ownerClass); + methodMap.put(key, methodAccess); // 缓存Method对象 + } + return methodAccess.invoke(owner, methodName, args); + } + + /** + * Constructs an empty ArrayList. + */ + public static final ArrayList newArrayList() { + return new ArrayList(); + } + + /** + * Constructs an empty ArrayList. + */ + @SuppressWarnings("unchecked") + public static final ArrayList newArrayList(E... e) { + ArrayList list = new ArrayList(); + Collections.addAll(list, e); + return list; + } + + /** + * Constructs an empty HashMap. + */ + public static final HashMap newHashMap() { + return new HashMap(); + } + + /** + * Constructs an empty HashSet. + */ + public static final HashSet newHashSet() { + return new HashSet(); + } + + /** + * Constructs an empty Hashtable. + */ + public static final Hashtable newHashtable() { + return new Hashtable(); + } + + /** + * Constructs an empty LinkedHashMap. + */ + public static final LinkedHashMap newLinkedHashMap() { + return new LinkedHashMap(); + } + + /** + * Constructs an empty LinkedHashSet. + */ + public static final LinkedHashSet newLinkedHashSet() { + return new LinkedHashSet(); + } + + /** + * Constructs an empty LinkedList. + */ + public static final LinkedList newLinkedList() { + return new LinkedList(); + } + + /** + * Constructs an empty TreeMap. + */ + public static final TreeMap newTreeMap() { + return new TreeMap(); + } + + /** + * Constructs an empty TreeSet. + */ + public static final TreeSet newTreeSet() { + return new TreeSet(); + } + + /** + * Constructs an empty Vector. + */ + public static final Vector newVector() { + return new Vector(); + } + + /** + * Constructs an empty WeakHashMap. + */ + public static final WeakHashMap newWeakHashMap() { + return new WeakHashMap(); + } + + /** + * Constructs an empty HashMap. + */ + public static final Map newHashMap(k key, v value) { + Map map = newHashMap(); + map.put(key, value); + return map; + } + + /** + * Constructs an empty ConcurrentHashMap. + */ + public static final ConcurrentHashMap newConcurrentHashMap() { + return new ConcurrentHashMap(); + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/QrcodeUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/QrcodeUtil.java new file mode 100644 index 00000000..013e5356 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/QrcodeUtil.java @@ -0,0 +1,73 @@ +package org.ibase4j.core.util; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileInputStream; +import java.util.HashMap; +import java.util.UUID; + +import javax.imageio.ImageIO; + +import com.google.zxing.BarcodeFormat; +import com.google.zxing.Binarizer; +import com.google.zxing.BinaryBitmap; +import com.google.zxing.DecodeHintType; +import com.google.zxing.EncodeHintType; +import com.google.zxing.LuminanceSource; +import com.google.zxing.MultiFormatReader; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.Result; +import com.google.zxing.client.j2se.BufferedImageLuminanceSource; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.common.HybridBinarizer; + +/** + * 二维码工具类 + * + * @author ShenHuaJie + * @since 2017年2月21日 下午1:30:29 + */ +public class QrcodeUtil { + public static String createQrcode(String url, String dir, String _text) { + String qrcodeFilePath = ""; + try { + int qrcodeWidth = 300; + int qrcodeHeight = 300; + String qrcodeFormat = "png"; + HashMap hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, + hints); + + BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB); + File qrcodeFile = new File(dir + "/" + UUID.randomUUID().toString() + "." + qrcodeFormat); + ImageIO.write(image, qrcodeFormat, qrcodeFile); + MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, qrcodeFile.toPath()); + qrcodeFilePath = qrcodeFile.getAbsolutePath(); + } catch (Exception e) { + e.printStackTrace(); + } + return qrcodeFilePath; + } + + public static String decodeQr(String filePath) { + String retStr = ""; + if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) { + return "图片路径为空!"; + } + try { + BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath)); + LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage); + Binarizer binarizer = new HybridBinarizer(source); + BinaryBitmap bitmap = new BinaryBitmap(binarizer); + HashMap hintTypeObjectHashMap = new HashMap<>(); + hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8"); + Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap); + retStr = result.getText(); + } catch (Exception e) { + e.printStackTrace(); + } + return retStr; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/SecurityUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/SecurityUtil.java index 79f7ff8b..2c2818d1 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/util/SecurityUtil.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/SecurityUtil.java @@ -59,7 +59,8 @@ public static final String encryptBASE64(byte[] key) { /** * 数据解密,算法(DES) * - * @param cryptData 加密数据 + * @param cryptData + * 加密数据 * @return 解密后的数据 */ public static final String decryptDes(String cryptData) { @@ -69,7 +70,8 @@ public static final String decryptDes(String cryptData) { /** * 数据加密,算法(DES) * - * @param data 要进行加密的数据 + * @param data + * 要进行加密的数据 * @return 加密后的数据 */ public static final String encryptDes(String data) { @@ -79,7 +81,8 @@ public static final String encryptDes(String data) { /** * 基于MD5算法的单向加密 * - * @param strSrc 明文 + * @param strSrc + * 明文 * @return 返回密文 */ public static final String encryptMd5(String strSrc) { @@ -121,7 +124,8 @@ public static final String encryptHMAC(String data) { /** * 数据解密,算法(DES) * - * @param cryptData 加密数据 + * @param cryptData + * 加密数据 * @return 解密后的数据 */ public static final String decryptDes(String cryptData, byte[] key) { @@ -138,7 +142,8 @@ public static final String decryptDes(String cryptData, byte[] key) { /** * 数据加密,算法(DES) * - * @param data 要进行加密的数据 + * @param data + * 要进行加密的数据 * @return 加密后的数据 */ public static final String encryptDes(String data, byte[] key) { @@ -170,7 +175,8 @@ public static final String encryptHMAC(String data, byte[] key) { /** * RSA签名 * - * @param data 原数据 + * @param data + * 原数据 * @return */ public static final String signRSA(String data, String privateKey) { @@ -184,7 +190,8 @@ public static final String signRSA(String data, String privateKey) { /** * RSA验签 * - * @param data 原数据 + * @param data + * 原数据 * @return */ public static final boolean verifyRSA(String data, String publicKey, String sign) { @@ -198,7 +205,8 @@ public static final boolean verifyRSA(String data, String publicKey, String sign /** * 数据加密,算法(RSA) * - * @param data 数据 + * @param data + * 数据 * @return 加密后的数据 */ public static final String encryptRSAPrivate(String data, String privateKey) { @@ -212,7 +220,8 @@ public static final String encryptRSAPrivate(String data, String privateKey) { /** * 数据解密,算法(RSA) * - * @param cryptData 加密数据 + * @param cryptData + * 加密数据 * @return 解密后的数据 */ public static final String decryptRSAPublic(String cryptData, String publicKey) { @@ -224,6 +233,10 @@ public static final String decryptRSAPublic(String cryptData, String publicKey) } } + public static String encryptPassword(String password) { + return encryptMd5(SecurityUtil.encryptSHA(password)); + } + public static void main(String[] args) throws Exception { System.out.println(encryptDes("SHJR")); System.out.println(decryptDes("INzvw/3Qc4q=")); diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/TokenUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/TokenUtil.java new file mode 100644 index 00000000..f846fa07 --- /dev/null +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/TokenUtil.java @@ -0,0 +1,33 @@ +package org.ibase4j.core.util; + +import org.ibase4j.core.Constants; +import org.ibase4j.core.support.Token; + +import com.alibaba.fastjson.JSON; + +public class TokenUtil { + public static void setTokenInfo(String token, String value) { + try { + Token tokenInfo = new Token(); + tokenInfo.setTime(System.currentTimeMillis()); + tokenInfo.setValue(value); + CacheUtil.getCache().hset(Constants.TOKEN_KEY, token, JSON.toJSONString(tokenInfo)); + } catch (Exception e) { + throw new RuntimeException("保存token失败,错误信息:", e); + } + } + + public static void delToken(String token) { + try { + CacheUtil.getCache().hdel(Constants.TOKEN_KEY, token); + } catch (Exception e) { + throw new RuntimeException("删除token失败,错误信息:", e); + } + } + + public static Token getTokenInfo(String token) { + String value = (String) CacheUtil.getCache().hget(Constants.TOKEN_KEY, token); + Token tokenInfo = JSON.parseObject(value, Token.class); + return tokenInfo; + } +} diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/UploadUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/UploadUtil.java index 3548b630..3264ce77 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/util/UploadUtil.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/UploadUtil.java @@ -2,6 +2,9 @@ import java.awt.image.BufferedImage; import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStream; +import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.UUID; @@ -21,6 +24,7 @@ import org.ibase4j.core.support.fastdfs.FileManager; import org.ibase4j.core.support.fastdfs.FileModel; import org.ibase4j.core.support.ftp.SftpClient; +import org.ibase4j.core.support.security.BASE64Decoder; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @@ -31,76 +35,72 @@ * @author ShenHuaJie */ public final class UploadUtil { - private UploadUtil() { - } + private UploadUtil() { + } - private static final Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); - /** 上传文件缓存大小限制 */ - private static int fileSizeThreshold = 1024 * 1024 * 1; - /** 上传文件临时目录 */ - private static final String uploadFileDir = "/WEB-INF/upload/"; + /** 上传文件缓存大小限制 */ + private static int fileSizeThreshold = 1024 * 1024 * 1; + /** 上传文件临时目录 */ + private static final String uploadFileDir = "/WEB-INF/upload/"; - /** 获取所有文本域 */ - public static final List getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException { - if (!saveDir.isDirectory()) { - saveDir.mkdir(); - } - List fileItems = null; - RequestContext requestContext = new ServletRequestContext(request); - if (FileUpload.isMultipartContent(requestContext)) { - DiskFileItemFactory factory = new DiskFileItemFactory(); - factory.setRepository(saveDir); - factory.setSizeThreshold(fileSizeThreshold); - ServletFileUpload upload = new ServletFileUpload(factory); - fileItems = upload.parseRequest(request); - } - return fileItems; - } + /** 获取所有文本域 */ + public static final List getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException { + if (!saveDir.isDirectory()) { + saveDir.mkdir(); + } + List fileItems = null; + RequestContext requestContext = new ServletRequestContext(request); + if (FileUpload.isMultipartContent(requestContext)) { + DiskFileItemFactory factory = new DiskFileItemFactory(); + factory.setRepository(saveDir); + factory.setSizeThreshold(fileSizeThreshold); + ServletFileUpload upload = new ServletFileUpload(factory); + fileItems = upload.parseRequest(request); + } + return fileItems; + } - /** 获取文本域 */ - public static final FileItem[] getFileItem(HttpServletRequest request, File saveDir, String... fieldName) - throws FileUploadException { - if (fieldName == null || saveDir == null) { - return null; - } - List fileItemList = getFileItemList(request, saveDir); - FileItem fileItem = null; - FileItem[] fileItems = new FileItem[fieldName.length]; - for (int i = 0; i < fieldName.length; i++) { - for (Iterator iterator = fileItemList.iterator(); iterator.hasNext();) { - fileItem = (FileItem)iterator.next(); - // 根据名字获得文本域 - if (fieldName[i] != null && fieldName[i].equals(fileItem.getFieldName())) { - fileItems[i] = fileItem; - break; - } - } - } - return fileItems; - } + /** 获取文本域 */ + public static final FileItem[] getFileItem(HttpServletRequest request, File saveDir, String... fieldName) + throws FileUploadException { + if (fieldName == null || saveDir == null) { + return null; + } + List fileItemList = getFileItemList(request, saveDir); + FileItem fileItem = null; + FileItem[] fileItems = new FileItem[fieldName.length]; + for (int i = 0; i < fieldName.length; i++) { + for (Iterator iterator = fileItemList.iterator(); iterator.hasNext();) { + fileItem = (FileItem) iterator.next(); + // 根据名字获得文本域 + if (fieldName[i] != null && fieldName[i].equals(fileItem.getFieldName())) { + fileItems[i] = fileItem; + break; + } + } + } + return fileItems; + } /** 上传文件处理(支持批量) */ - public static List uploadImage(HttpServletRequest request) { + public static List uploadFile(HttpServletRequest request) { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( - request.getSession().getServletContext()); + request.getSession().getServletContext()); List fileNames = InstanceUtil.newArrayList(); if (multipartResolver.isMultipart(request)) { - MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; - Iterator iterator = multiRequest.getFileNames(); - String pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtil.getDate()); + MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; + String pathDir = getUploadDir(request); File dirFile = new File(pathDir); if (!dirFile.isDirectory()) { dirFile.mkdirs(); } - while (iterator.hasNext()) { + for (Iterator iterator = multiRequest.getFileNames(); iterator.hasNext();) { String key = iterator.next(); MultipartFile multipartFile = multiRequest.getFile(key); if (multipartFile != null) { String name = multipartFile.getOriginalFilename(); - if (name.indexOf(".") == -1 && "blob".equals(name)) { - name = name + ".png"; - } String uuid = UUID.randomUUID().toString(); String postFix = name.substring(name.lastIndexOf(".")).toLowerCase(); String fileName = uuid + postFix; @@ -113,49 +113,131 @@ public static List uploadImage(HttpServletRequest request) { } catch (Exception e) { logger.error(name + "保存失败", e); } - try { // 缩放 - BufferedImage bufferedImg = ImageIO.read(file); - int orgwidth = bufferedImg.getWidth();// 原始宽度 - ImageUtil.scaleWidth(file, 100); - if (orgwidth > 300) { - ImageUtil.scaleWidth(file, 300); - } - if (orgwidth > 500) { - ImageUtil.scaleWidth(file, 500); - } - } catch (Exception e) { - } } } } return fileNames; } - /** 获取上传文件临时目录 */ - public static String getUploadDir(HttpServletRequest request) { - return request.getServletContext().getRealPath(uploadFileDir) + File.separator; - } + /** 上传文件处理(支持批量) */ + public static List uploadImage(HttpServletRequest request, boolean lessen) { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( + request.getSession().getServletContext()); + List fileNames = InstanceUtil.newArrayList(); + if (multipartResolver.isMultipart(request)) { + MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; + String pathDir = getUploadDir(request); + File dirFile = new File(pathDir); + if (!dirFile.isDirectory()) { + dirFile.mkdirs(); + } + for (Iterator iterator = multiRequest.getFileNames(); iterator.hasNext();) { + String key = iterator.next(); + MultipartFile multipartFile = multiRequest.getFile(key); + if (multipartFile != null) { + String name = multipartFile.getOriginalFilename(); + if (name.indexOf(".") == -1 && "blob".equals(name)) { + name = name + ".png"; + } + String uuid = UUID.randomUUID().toString(); + String postFix = name.substring(name.lastIndexOf(".")).toLowerCase(); + String fileName = uuid + postFix; + String filePath = pathDir + File.separator + fileName; + File file = new File(filePath); + file.setWritable(true, false); + try { + multipartFile.transferTo(file); + fileNames.add(fileName); + } catch (Exception e) { + logger.error(name + "保存失败", e); + } + if (lessen) { + try { // 缩放 + BufferedImage bufferedImg = ImageIO.read(file); + int orgwidth = bufferedImg.getWidth();// 原始宽度 + ImageUtil.scaleWidth(file, 100); + if (orgwidth > 300) { + ImageUtil.scaleWidth(file, 300); + } + if (orgwidth > 500) { + ImageUtil.scaleWidth(file, 500); + } + } catch (Exception e) { + logger.error(name + "缩放失败", e); + } + } + } + } + } + return fileNames; + } - /** 移动文件到fastDFS */ - public static FileModel remove2DFS(String namespace, String objectId, String fileName) { - FileModel fastDFSFile = new FileModel(namespace, objectId, fileName); - if (fastDFSFile.getKey() != null) { - FileManager.upload(fastDFSFile); - } - return fastDFSFile; - } + public static List uploadImageData(HttpServletRequest request) { + List fileNames = InstanceUtil.newArrayList(); + Enumeration params = request.getParameterNames(); + String pathDir = getUploadDir(request); + File dir = new File(pathDir); + if (!dir.exists()) { + dir.mkdirs(); + } + while (params.hasMoreElements()) { + String key = params.nextElement(); + String fileStr = request.getParameter(key); + if (fileStr != null && !"".equals(fileStr)) { + int index = fileStr.indexOf("base64"); + if (index > 0) { + try { + String fileName = UUID.randomUUID().toString(); + String preStr = fileStr.substring(0, index + 7); + String prefix = preStr.substring(preStr.indexOf("/") + 1, preStr.indexOf(";")).toLowerCase(); + fileStr = fileStr.substring(fileStr.indexOf(",") + 1); + BASE64Decoder decoder = new BASE64Decoder(); + byte[] bb = decoder.decodeBuffer(fileStr); + for (int j = 0; j < bb.length; ++j) { + if (bb[j] < 0) {// 调整异常数据 + bb[j] += 256; + } + } + String distPath = pathDir + fileName + "." + prefix; + OutputStream out = new FileOutputStream(distPath); + out.write(bb); + out.flush(); + out.close(); + fileNames.add(fileName + "." + prefix); + } catch (Exception e) { + logger.error("上传文件异常:", e); + } + } + } + } + return fileNames; + } - /** 移动文件到SFTP */ - public static String remove2Sftp(String filePath, String namespace) { - File file = new File(filePath); - if (!file.exists()) { - throw new RuntimeException("文件" + filePath + "不存在"); - } - SftpClient client = SftpClient.connect(); - String dir = PropertiesUtil.getString("sftp.baseDir"); - String fileName = namespace + File.separator + file.getName(); - client.put(filePath, dir + fileName); - client.disconnect(); - return PropertiesUtil.getString("sftp.nginx.path") + fileName; - } + /** 获取上传文件临时目录 */ + public static String getUploadDir(HttpServletRequest request) { + return request.getServletContext().getRealPath(uploadFileDir) + File.separator; + } + + /** 移动文件到fastDFS */ + public static FileModel remove2DFS(String namespace, String objectId, String fileName) { + FileModel fastDFSFile = new FileModel(namespace, objectId, fileName); + if (fastDFSFile.getKey() != null) { + FileManager.getInstance().upload(fastDFSFile); + } + return fastDFSFile; + } + + /** 移动文件到SFTP */ + public static String remove2Sftp(String filePath, String namespace) { + File file = new File(filePath); + if (!file.exists()) { + throw new RuntimeException("文件" + filePath + "不存在"); + } + SftpClient client = SftpClient.connect(); + String dir = PropertiesUtil.getString("sftp.baseDir"); + String fileName = namespace + File.separator + file.getName(); + client.put(filePath, dir + fileName); + client.disconnect(); + return PropertiesUtil.getString("sftp.nginx.path") + fileName; + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/core/util/WebUtil.java b/iBase4J-Common/src/main/java/org/ibase4j/core/util/WebUtil.java index b7c1c2b8..bd638ee9 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/core/util/WebUtil.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/core/util/WebUtil.java @@ -7,6 +7,7 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; @@ -25,119 +26,150 @@ * @version 2016年4月2日 下午4:19:28 */ public final class WebUtil { - private WebUtil() { - } + private WebUtil() { + } + private static Logger logger = LogManager.getLogger(); - /** - * 获取指定Cookie的值 - * - * @param cookies cookie集合 - * @param cookieName cookie名字 - * @param defaultValue 缺省值 - * @return - */ - public static final String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue) { - Cookie cookie = WebUtils.getCookie(request, cookieName); - if (cookie == null) { - return defaultValue; - } - return cookie.getValue(); - } - - /** 保存当前用户 */ - public static final void saveCurrentUser(Object user) { - setSession(Constants.CURRENT_USER, user); - } - - /** 获取当前用户 */ - public static final Long getCurrentUser() { - Subject currentUser = SecurityUtils.getSubject(); - if (null != currentUser) { - try { + /** + * 获取指定Cookie的值 + * + * @param cookies cookie集合 + * @param cookieName cookie名字 + * @param defaultValue 缺省值 + * @return + */ + public static final String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue) { + Cookie cookie = WebUtils.getCookie(request, cookieName); + if (cookie == null) { + return defaultValue; + } + return cookie.getValue(); + } + + /** 保存当前用户 */ + public static final void saveCurrentUser(Object user) { + setSession(Constants.CURRENT_USER, user); + } + + /** 保存当前用户 */ + public static final void saveCurrentUser(HttpServletRequest request, Object user) { + setSession(request, Constants.CURRENT_USER, user); + } + + /** 获取当前用户 */ + public static final Long getCurrentUser() { + Subject currentUser = SecurityUtils.getSubject(); + if (null != currentUser) { + try { Session session = currentUser.getSession(); if (null != session) { - return (Long) session.getAttribute(Constants.CURRENT_USER); + return (Long)session.getAttribute(Constants.CURRENT_USER); } } catch (InvalidSessionException e) { logger.error(e); } - } - return null; - } - - /** - * 将一些数据放到ShiroSession中,以便于其它地方使用 - * - * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 - */ - public static final void setSession(Object key, Object value) { - Subject currentUser = SecurityUtils.getSubject(); - if (null != currentUser) { - Session session = currentUser.getSession(); - if (null != session) { - session.setAttribute(key, value); - } - } - } - - /** 移除当前用户 */ - public static final void removeCurrentUser(HttpServletRequest request) { - request.getSession().removeAttribute(Constants.CURRENT_USER); - } - - /** - * 获得国际化信息 - * - * @param key 键 - * @param request - * @return - */ - public static final String getApplicationResource(String key, HttpServletRequest request) { - ResourceBundle resourceBundle = ResourceBundle.getBundle("ApplicationResources", request.getLocale()); - return resourceBundle.getString(key); - } - - /** - * 获得参数Map - * - * @param request - * @return - */ - public static final Map getParameterMap(HttpServletRequest request) { - return WebUtils.getParametersStartingWith(request, null); - } - - /** 获取客户端IP */ - public static final String getHost(HttpServletRequest request) { - String ip = request.getHeader("X-Forwarded-For"); - if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("Proxy-Client-IP"); - } - if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("WL-Proxy-Client-IP"); - } - if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getHeader("X-Real-IP"); - } - if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { - ip = request.getRemoteAddr(); - } - if ("127.0.0.1".equals(ip)) { - InetAddress inet = null; - try { // 根据网卡取本机配置的IP - inet = InetAddress.getLocalHost(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - ip = inet.getHostAddress(); - } - // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 - if (ip != null && ip.length() > 15) { - if (ip.indexOf(",") > 0) { - ip = ip.substring(0, ip.indexOf(",")); - } - } - return ip; - } + } + return null; + } + + /** 获取当前用户 */ + public static final Object getCurrentUser(HttpServletRequest request) { + try { + HttpSession session = request.getSession(); + if (null != session) { + return session.getAttribute(Constants.CURRENT_USER); + } + } catch (InvalidSessionException e) { + logger.error(e); + } + return null; + } + + /** + * 将一些数据放到ShiroSession中,以便于其它地方使用 + * + * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 + */ + public static final void setSession(Object key, Object value) { + Subject currentUser = SecurityUtils.getSubject(); + if (null != currentUser) { + Session session = currentUser.getSession(); + if (null != session) { + session.setAttribute(key, value); + } + } + } + + /** + * 将一些数据放到ShiroSession中,以便于其它地方使用 + * + * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 + */ + public static final void setSession(HttpServletRequest request, String key, Object value) { + HttpSession session = request.getSession(); + if (null != session) { + session.setAttribute(key, value); + } + } + + /** 移除当前用户 */ + public static final void removeCurrentUser(HttpServletRequest request) { + request.getSession().removeAttribute(Constants.CURRENT_USER); + } + + /** + * 获得国际化信息 + * + * @param key 键 + * @param request + * @return + */ + public static final String getApplicationResource(String key, HttpServletRequest request) { + ResourceBundle resourceBundle = ResourceBundle.getBundle("ApplicationResources", request.getLocale()); + return resourceBundle.getString(key); + } + + /** + * 获得参数Map + * + * @param request + * @return + */ + public static final Map getParameterMap(HttpServletRequest request) { + return WebUtils.getParametersStartingWith(request, null); + } + + /** 获取客户端IP */ + public static final String getHost(HttpServletRequest request) { + String ip = request.getHeader("X-Forwarded-For"); + if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + } + if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + if ("127.0.0.1".equals(ip)) { + InetAddress inet = null; + try { // 根据网卡取本机配置的IP + inet = InetAddress.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + ip = inet.getHostAddress(); + } + // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 + if (ip != null && ip.length() > 15) { + if (ip.indexOf(",") > 0) { + ip = ip.substring(0, ip.indexOf(",")); + } + } + return ip; + } } diff --git a/iBase4J-Common/src/main/java/org/ibase4j/dao/scheduler/TaskFireLogMapper.java b/iBase4J-Common/src/main/java/org/ibase4j/mapper/TaskFireLogMapper.java similarity index 78% rename from iBase4J-Common/src/main/java/org/ibase4j/dao/scheduler/TaskFireLogMapper.java rename to iBase4J-Common/src/main/java/org/ibase4j/mapper/TaskFireLogMapper.java index 25c3ec8d..b0cef046 100644 --- a/iBase4J-Common/src/main/java/org/ibase4j/dao/scheduler/TaskFireLogMapper.java +++ b/iBase4J-Common/src/main/java/org/ibase4j/mapper/TaskFireLogMapper.java @@ -1,11 +1,11 @@ -package org.ibase4j.dao.scheduler; +package org.ibase4j.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; -import org.ibase4j.model.scheduler.TaskFireLog; +import org.ibase4j.model.TaskFireLog; import com.baomidou.mybatisplus.mapper.BaseMapper; diff --git a/iBase4J-Common/src/main/resources/mappers/TaskFireLogMapper.xml b/iBase4J-Common/src/main/java/org/ibase4j/mapper/xml/TaskFireLogMapper.xml similarity index 85% rename from iBase4J-Common/src/main/resources/mappers/TaskFireLogMapper.xml rename to iBase4J-Common/src/main/java/org/ibase4j/mapper/xml/TaskFireLogMapper.xml index 3be24363..e4bba422 100644 --- a/iBase4J-Common/src/main/resources/mappers/TaskFireLogMapper.xml +++ b/iBase4J-Common/src/main/java/org/ibase4j/mapper/xml/TaskFireLogMapper.xml @@ -1,6 +1,6 @@ - + select id_ from sys_dept diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysDicIndexMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysDicIndexMapper.xml similarity index 85% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysDicIndexMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysDicIndexMapper.xml index 5a6eb01d..da511064 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysDicIndexMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysDicIndexMapper.xml @@ -1,6 +1,6 @@ - + select id_ from sys_dic diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysEmailConfigMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysEmailConfigMapper.xml similarity index 84% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysEmailConfigMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysEmailConfigMapper.xml index eb219e7a..48caf99e 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysEmailConfigMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysEmailConfigMapper.xml @@ -1,6 +1,6 @@ - + select id_ from sys_email diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysEmailTemplateMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysEmailTemplateMapper.xml similarity index 84% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysEmailTemplateMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysEmailTemplateMapper.xml index 60ed807f..b3d0e15d 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysEmailTemplateMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysEmailTemplateMapper.xml @@ -1,6 +1,6 @@ - + select e.id_ from sys_event e left join sys_user u on e.create_by = u.id_ diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysMenuMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysMenuMapper.xml similarity index 91% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysMenuMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysMenuMapper.xml index 6ef466b4..4113b277 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysMenuMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysMenuMapper.xml @@ -1,6 +1,6 @@ - + select id_ from sys_news diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysNoticeMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysNoticeMapper.xml similarity index 86% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysNoticeMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysNoticeMapper.xml index 1bb0f083..2278e0bc 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysNoticeMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysNoticeMapper.xml @@ -1,6 +1,6 @@ - + select id_ from sys_param diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysRoleMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysRoleMapper.xml similarity index 86% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysRoleMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysRoleMapper.xml index 13b4b962..ccf4ace0 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysRoleMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysRoleMapper.xml @@ -1,6 +1,6 @@ - + select distinct menu_id from sys_role_menu where role_id=#{roleId} and permission_='read' diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysSessionMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysSessionMapper.xml similarity index 91% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysSessionMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysSessionMapper.xml index a106b2ec..8ba2c0f4 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysSessionMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysSessionMapper.xml @@ -1,6 +1,6 @@ - + select id_ from sys_unit diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysUserMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserMapper.xml similarity index 95% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysUserMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserMapper.xml index 13f87209..e425ffdc 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysUserMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserMapper.xml @@ -1,6 +1,6 @@ - + select distinct menu_id from sys_user_menu where user_id=#{userId} and permission_='read' diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysUserRoleMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserRoleMapper.xml similarity index 72% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysUserRoleMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserRoleMapper.xml index efc844dd..bae2905f 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysUserRoleMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserRoleMapper.xml @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/iBase4J-SYS-Service/src/main/resources/mappers/SysUserThirdpartyMapper.xml b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserThirdpartyMapper.xml similarity index 80% rename from iBase4J-SYS-Service/src/main/resources/mappers/SysUserThirdpartyMapper.xml rename to iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserThirdpartyMapper.xml index 9235d92c..cfe50f75 100644 --- a/iBase4J-SYS-Service/src/main/resources/mappers/SysUserThirdpartyMapper.xml +++ b/iBase4J-SYS-Service/src/main/java/org/ibase4j/mapper/mappers/SysUserThirdpartyMapper.xml @@ -1,6 +1,6 @@ - +