Commit 89564d2b by java-李谡

代码规范

parent f07cde2a
......@@ -6,7 +6,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathFormat {
private static final Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE);
private static final String TIME = "time";
private static final String FULL_YEAR = "yyyy";
private static final String YEAR = "yy";
......@@ -16,137 +16,123 @@ public class PathFormat {
private static final String MINUTE = "ii";
private static final String SECOND = "ss";
private static final String RAND = "rand";
private static Date currentDate = null;
public static String parse ( String input ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
public static String parse(String input) {
Matcher matcher = pattern.matcher(input);
PathFormat.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matcher.appendReplacement(sb, PathFormat.getString( matcher.group( 1 ) ) );
while (matcher.find()) {
matcher.appendReplacement(sb, PathFormat.getString(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 格式化路径, 把windows路径替换成标准路径
*
* @param input 待格式化的路径
* @return 格式化后的路径
*/
public static String format ( String input ) {
return input.replace( "\\", "/" );
public static String format(String input) {
return input.replace("\\", "/");
}
public static String parse ( String input, String filename ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
public static String parse(String input, String filename) {
Matcher matcher = pattern.matcher(input);
String matchStr = null;
PathFormat.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matchStr = matcher.group( 1 );
if ( matchStr.indexOf( "filename" ) != -1 ) {
filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" );
matcher.appendReplacement(sb, filename );
while (matcher.find()) {
matchStr = matcher.group(1);
if (matchStr.indexOf("filename") != -1) {
filename = filename.replace("$", "\\$").replaceAll("[\\/:*?\"<>|]", "");
matcher.appendReplacement(sb, filename);
} else {
matcher.appendReplacement(sb, PathFormat.getString( matchStr ) );
matcher.appendReplacement(sb, PathFormat.getString(matchStr));
}
}
matcher.appendTail(sb);
return sb.toString();
}
private static String getString ( String pattern ) {
private static String getString(String pattern) {
pattern = pattern.toLowerCase();
// time 处理
if ( pattern.indexOf( PathFormat.TIME ) != -1 ) {
if (pattern.indexOf(PathFormat.TIME) != -1) {
return PathFormat.getTimestamp();
} else if ( pattern.indexOf( PathFormat.FULL_YEAR ) != -1 ) {
} else if (pattern.indexOf(PathFormat.FULL_YEAR) != -1) {
return PathFormat.getFullYear();
} else if ( pattern.indexOf( PathFormat.YEAR ) != -1 ) {
} else if (pattern.indexOf(PathFormat.YEAR) != -1) {
return PathFormat.getYear();
} else if ( pattern.indexOf( PathFormat.MONTH ) != -1 ) {
} else if (pattern.indexOf(PathFormat.MONTH) != -1) {
return PathFormat.getMonth();
} else if ( pattern.indexOf( PathFormat.DAY ) != -1 ) {
} else if (pattern.indexOf(PathFormat.DAY) != -1) {
return PathFormat.getDay();
} else if ( pattern.indexOf( PathFormat.HOUR ) != -1 ) {
} else if (pattern.indexOf(PathFormat.HOUR) != -1) {
return PathFormat.getHour();
} else if ( pattern.indexOf( PathFormat.MINUTE ) != -1 ) {
} else if (pattern.indexOf(PathFormat.MINUTE) != -1) {
return PathFormat.getMinute();
} else if ( pattern.indexOf( PathFormat.SECOND ) != -1 ) {
} else if (pattern.indexOf(PathFormat.SECOND) != -1) {
return PathFormat.getSecond();
} else if ( pattern.indexOf( PathFormat.RAND ) != -1 ) {
return PathFormat.getRandom( pattern );
} else if (pattern.indexOf(PathFormat.RAND) != -1) {
return PathFormat.getRandom(pattern);
}
return pattern;
}
private static String getTimestamp () {
private static String getTimestamp() {
return System.currentTimeMillis() + "";
}
private static String getFullYear () {
return new SimpleDateFormat( "yyyy" ).format( PathFormat.currentDate );
private static String getFullYear() {
return new SimpleDateFormat("yyyy").format(PathFormat.currentDate);
}
private static String getYear () {
return new SimpleDateFormat( "yy" ).format( PathFormat.currentDate );
private static String getYear() {
return new SimpleDateFormat("yy").format(PathFormat.currentDate);
}
private static String getMonth () {
return new SimpleDateFormat( "MM" ).format( PathFormat.currentDate );
private static String getMonth() {
return new SimpleDateFormat("MM").format(PathFormat.currentDate);
}
private static String getDay () {
return new SimpleDateFormat( "dd" ).format( PathFormat.currentDate );
private static String getDay() {
return new SimpleDateFormat("dd").format(PathFormat.currentDate);
}
private static String getHour () {
return new SimpleDateFormat( "HH" ).format( PathFormat.currentDate );
private static String getHour() {
return new SimpleDateFormat("HH").format(PathFormat.currentDate);
}
private static String getMinute () {
return new SimpleDateFormat( "mm" ).format( PathFormat.currentDate );
private static String getMinute() {
return new SimpleDateFormat("mm").format(PathFormat.currentDate);
}
private static String getSecond () {
return new SimpleDateFormat( "ss" ).format( PathFormat.currentDate );
private static String getSecond() {
return new SimpleDateFormat("ss").format(PathFormat.currentDate);
}
private static String getRandom ( String pattern ) {
private static String getRandom(String pattern) {
int length = 0;
pattern = pattern.split( ":" )[ 1 ].trim();
length = Integer.parseInt( pattern );
return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length );
pattern = pattern.split(":")[1].trim();
length = Integer.parseInt(pattern);
return (Math.random() + "").replace(".", "").substring(0, length);
}
public static void main(String[] args) {
......
......@@ -432,13 +432,8 @@ public class GConstants {
if(!dir.endsWith("/")) {
dir += "/";
}
// System.out.println("file.upload.dir: " + dir);
return dir;
}
// public static String getBaseUrl(HttpServletRequest req){
//
// return IMAGE_BASE_URL;
// }
/**
* 获取工程路径
* @return
......
package com.ejweb.core.fetcher;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.*;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
......@@ -44,19 +26,26 @@ import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.CodingErrorAction;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
public class HCFetcher {
private final Logger LOG = Logger.getLogger(HCFetcher.class);
private PoolingHttpClientConnectionManager connManager = null;
private CloseableHttpClient httpclient = null;
private final Object mutex = new Object();
private long getLastFetchTime = 0;// 删除GET请求时间
private long postLastFetchTime = 0;// 上次POST请求时间
private long politenessDelay = 120L;// 两次请求默认最小间隔
private final static HCFetcher C = new HCFetcher();// 单体类
private long getLastFetchTime = 0;
private long postLastFetchTime = 0;
private long politenessDelay = 120L;
private final static HCFetcher C = new HCFetcher();
private ClientConnectionMonitor connectionMonitor = null;
public static HCFetcher getInstance() {
......@@ -66,31 +55,18 @@ public class HCFetcher {
private HCFetcher() {
try {
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new TrustStrategy(){
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
return true;
}
}).build();
// SSLContext sslcontext = SSLContext.getInstance("TLS");
// sslcontext.init(null, new TrustManager[] { trustAllManager },
// new java.security.SecureRandom());
// Allow TLSv1 protocol only
// SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
// sslcontext, new String[] { "TLSv1" }, null,
// SSLConnectionSocketFactory.getDefaultHostnameVerifier());
.loadTrustMaterial(new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
// Create a registry of custom connection socket factories for
// supported
// protocol schemes.
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create()
.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslsf).build();
......@@ -98,30 +74,19 @@ public class HCFetcher {
socketFactoryRegistry);
connManager.setMaxTotal(100);
// Create message constraints
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
// Configure the connection manager to use connection configuration
// either
// by default or for a specific host.
connManager.setDefaultConnectionConfig(connectionConfig);
// Configure total max or per route limits for persistent
// connections
// that can be kept in the pool or leased by the connection manager.
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(30);
// Create global request configuration
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setCookieSpec(CookieSpecs.DEFAULT)
.setExpectContinueEnabled(true)
......@@ -133,13 +98,12 @@ public class HCFetcher {
connectionMonitor = new ClientConnectionMonitor(
connManager);
connectionMonitor.start();
httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.addInterceptorFirst(new HttpRequestInterceptor() {// 请求
.addInterceptorFirst(new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context)
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
if (request.containsHeader("Accept-Encoding") == false) {
request.addHeader("Accept-Encoding", "gzip");
......@@ -155,7 +119,7 @@ public class HCFetcher {
request.addHeader("Accept-Charset", "utf-8");
request.addHeader("Accept-Encoding", "gzip");
}
}).addInterceptorFirst(new HttpResponseInterceptor() {// 响应
}).addInterceptorFirst(new HttpResponseInterceptor() {
@Override
public void process(final HttpResponse response, final HttpContext context)
throws HttpException, IOException {
......@@ -166,8 +130,8 @@ public class HCFetcher {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity( new GzipDecompressingEntity(response.getEntity()) );
return ;
response.setEntity(new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
......@@ -176,12 +140,13 @@ public class HCFetcher {
})
.build();
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* 发送给请求
*
* @param url
* @return
*/
......@@ -191,153 +156,138 @@ public class HCFetcher {
if (currentTimeMillis - getLastFetchTime < politenessDelay) {
try {
Thread.sleep(politenessDelay - (currentTimeMillis - getLastFetchTime));
} catch (Exception e) {}
} catch (Exception e) {
}
}
getLastFetchTime = System.currentTimeMillis();
FetchEntity entity = null;
HttpGet httpget = null;
CloseableHttpResponse response = null;
entity = new FetchEntity();
entity.setSuccess(false);
entity.setLocation(url);
try {
if (httpclient == null || url == null)
if (httpclient == null || url == null) {
return entity;
}
LOG.debug("----------------------------------------");
LOG.debug("请求网址: "+url);
LOG.debug("请求网址: " + url);
LOG.debug("请求方法: GET");
httpget = new HttpGet(url);
httpget = new HttpGet(url);
response = httpclient.execute(httpget);
StatusLine statusLine = response.getStatusLine();
LOG.debug("版本状态: "+statusLine);
LOG.debug("版本状态: " + statusLine);
entity.setStatus(statusLine.getStatusCode());
if(response.getLastHeader("Content-Encoding") == null){
if (response.getLastHeader("Content-Encoding") == null) {
LOG.debug("Content-Encoding: NULL");
} else {
LOG.debug(response.getLastHeader("Content-Encoding"));
}
if(response.getLastHeader("Content-Length") == null){
if (response.getLastHeader("Content-Length") == null) {
LOG.debug("Content-Length: NULL");
} else {
LOG.debug(response.getLastHeader("Content-Length"));
}
LOG.debug("----------------------------------------");
if (entity.getStatus() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
// byte[] buf = EntityUtils.toByteArray(httpEntity);
entity.setData(EntityUtils.toByteArray(httpEntity));
Header contentTypeHeader = httpEntity.getContentType();
if(contentTypeHeader != null){
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader.getValue());
}
Header contentEncodingHeader = httpEntity.getContentEncoding();
if(contentEncodingHeader != null){
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader.getValue());
}
entity.setSuccess(true);
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(httpEntity);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
if (response != null) {
response.close();
}
} catch (Exception e) {}
} catch (Exception e) {
}
}
return entity;
}
}
public FetchEntity post(final String url, final byte[] data) {
synchronized (mutex) {
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - postLastFetchTime < politenessDelay) {
try {
Thread.sleep(politenessDelay - (currentTimeMillis - postLastFetchTime));
} catch (Exception e) {}
} catch (Exception e) {
}
}
postLastFetchTime = System.currentTimeMillis();
FetchEntity entity = null;
HttpPost httppost = null;
CloseableHttpResponse response = null;
entity = new FetchEntity();
entity.setSuccess(false);
entity.setLocation(url);
try {
if (httpclient == null || url == null)
if (httpclient == null || url == null) {
return entity;
}
LOG.debug("----------------------------------------");
LOG.debug("请求网址: "+url);
LOG.debug("请求网址: " + url);
LOG.debug("请求方法: POST");
httppost = new HttpPost(url);
if(data != null){
httppost = new HttpPost(url);
if (data != null) {
httppost.setEntity(new ByteArrayEntity(data));
}
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
LOG.debug("版本状态: "+statusLine);
LOG.debug("版本状态: " + statusLine);
entity.setStatus(statusLine.getStatusCode());
if(response.getLastHeader("Content-Encoding") == null){
if (response.getLastHeader("Content-Encoding") == null) {
LOG.debug("Content-Encoding: NULL");
} else {
LOG.debug(response.getLastHeader("Content-Encoding"));
}
if(response.getLastHeader("Content-Length") == null){
if (response.getLastHeader("Content-Length") == null) {
LOG.debug("Content-Length: NULL");
} else {
LOG.debug(response.getLastHeader("Content-Length"));
}
LOG.debug("----------------------------------------");
if (entity.getStatus() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
// byte[] buf = EntityUtils.toByteArray(httpEntity);
entity.setData(EntityUtils.toByteArray(httpEntity));
Header contentTypeHeader = httpEntity.getContentType();
if(contentTypeHeader != null){
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader.getValue());
}
Header contentEncodingHeader = httpEntity.getContentEncoding();
if(contentEncodingHeader != null){
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader.getValue());
}
entity.setSuccess(true);
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(httpEntity);
}
} catch (IOException e) {
......@@ -347,114 +297,97 @@ public class HCFetcher {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
if (response != null) {
response.close();
}
} catch (Exception e) {}
} catch (Exception e) {
}
}
return entity;
}
}
public FetchEntity post(final String url, List<BasicNameValuePair> params, final byte[] data) {
synchronized (mutex) {
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis - postLastFetchTime < politenessDelay) {
try {
Thread.sleep(politenessDelay - (currentTimeMillis - postLastFetchTime));
} catch (Exception e) {}
} catch (Exception e) {
}
}
postLastFetchTime = System.currentTimeMillis();
FetchEntity entity = null;
HttpPost httppost = null;
CloseableHttpResponse response = null;
entity = new FetchEntity();
entity.setSuccess(false);
entity.setLocation(url);
try {
if (httpclient == null || url == null)
if (httpclient == null || url == null) {
return entity;
}
LOG.debug("----------------------------------------");
LOG.debug("请求网址: "+url);
LOG.debug("请求网址: " + url);
LOG.debug("请求方法: POST");
httppost = new HttpPost(url);
if(params != null){
httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
// httppost.setEntity(new ByteArrayEntity(data));
httppost = new HttpPost(url);
if (params != null) {
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
}
response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
LOG.debug("版本状态: "+statusLine);
LOG.debug("版本状态: " + statusLine);
entity.setStatus(statusLine.getStatusCode());
if(response.getLastHeader("Content-Encoding") == null){
if (response.getLastHeader("Content-Encoding") == null) {
LOG.debug("Content-Encoding: NULL");
} else {
LOG.debug(response.getLastHeader("Content-Encoding"));
}
if(response.getLastHeader("Content-Length") == null){
if (response.getLastHeader("Content-Length") == null) {
LOG.debug("Content-Length: NULL");
} else {
LOG.debug(response.getLastHeader("Content-Length"));
}
LOG.debug("----------------------------------------");
if (entity.getStatus() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
// byte[] buf = EntityUtils.toByteArray(httpEntity);
entity.setData(EntityUtils.toByteArray(httpEntity));
Header contentTypeHeader = httpEntity.getContentType();
if(contentTypeHeader != null){
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader.getValue());
}
Header contentEncodingHeader = httpEntity.getContentEncoding();
if(contentEncodingHeader != null){
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader.getValue());
}
entity.setSuccess(true);
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(httpEntity);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
if (response != null) {
response.close();
}
} catch (Exception e) {}
} catch (Exception e) {
}
}
return entity;
}
}
/**
* 关闭资源
*/
......@@ -472,7 +405,7 @@ public class HCFetcher {
}
}
}
public long getPolitenessDelay() {
return politenessDelay;
}
......@@ -480,23 +413,4 @@ public class HCFetcher {
public void setPolitenessDelay(long politenessDelay) {
this.politenessDelay = politenessDelay;
}
/*
private class AllTrustManager implements X509TrustManager{
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
*/
}
......@@ -33,11 +33,13 @@ import java.util.regex.Pattern;
/**
* SQL工具类
*
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
*/
public class SQLHelper {
private static final Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
/**
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
*
......@@ -107,7 +109,6 @@ public class SQLHelper {
countSql = "select count(1) from (" + sql + ") tmp_count";
}else{
countSql = "select count(1) from (" + removeOrders(sql) + ") tmp_count";
// countSql = "select count(1) " + removeSelect(removeOrders(sql));
}
Connection conn = connection;
PreparedStatement ps = null;
......@@ -163,26 +164,25 @@ public class SQLHelper {
return sql;
}
}
/**
/**
* 去除qlString的select子句。
* @param hql
* @return
* @param qlString
* @return
*/
@SuppressWarnings("unused")
private static String removeSelect(String qlString){
int beginPos = qlString.toLowerCase().indexOf("from");
return qlString.substring(beginPos);
}
/**
}
/**
* 去除hql的orderBy子句。
* @param hql
* @return
* @param qlString
* @return
*/
private static String removeOrders(String qlString) {
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(qlString);
private static String removeOrders(String qlString) {
Matcher m = p.matcher(qlString);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "");
......
......@@ -3,14 +3,12 @@
*/
package com.ejweb.core.security.shiro.session;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.DateUtils;
import com.ejweb.core.utils.JedisUtils;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.core.web.Servlets;
import com.google.common.collect.Sets;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
......@@ -19,65 +17,65 @@ import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import com.google.common.collect.Sets;
import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.DateUtils;
import com.ejweb.core.utils.JedisUtils;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.core.web.Servlets;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Set;
/**
* 自定义授权会话管理类
*
* @author ThinkGem
* @version 2014-7-20
*/
public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
private Logger logger = LoggerFactory.getLogger(getClass());
private String sessionKeyPrefix = "shiro_session_";
@Override
public void update(Session session) throws UnknownSessionException {
if (session == null || session.getId() == null) {
if (session == null || session.getId() == null) {
return;
}
HttpServletRequest request = Servlets.getRequest();
if (request != null){
if (request != null) {
String uri = request.getServletPath();
// 如果是静态文件,则不更新SESSION
if (Servlets.isStaticFile(uri)){
if (Servlets.isStaticFile(uri)) {
return;
}
// 如果是视图文件,则不更新SESSION
if (StringUtils.startsWith(uri, GConstants.getValue("web.view.prefix"))
&& StringUtils.endsWith(uri, GConstants.getValue("web.view.suffix"))){
&& StringUtils.endsWith(uri, GConstants.getValue("web.view.suffix"))) {
return;
}
// 手动控制不更新SESSION
if (GConstants.NO.equals(request.getParameter("updateSession"))){
if (GConstants.NO.equals(request.getParameter("updateSession"))) {
return;
}
}
Jedis jedis = null;
try {
jedis = JedisUtils.getResource();
// 获取登录者编号
PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
PrincipalCollection pc = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;
jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));
// 设置超期时间
int timeoutSeconds = (int)(session.getTimeout() / 1000);
int timeoutSeconds = (int) (session.getTimeout() / 1000);
jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);
logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
......@@ -93,11 +91,11 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
if (session == null || session.getId() == null) {
return;
}
Jedis jedis = null;
try {
jedis = JedisUtils.getResource();
jedis.hdel(JedisUtils.getBytesKey(sessionKeyPrefix), JedisUtils.getBytesKey(session.getId().toString()));
jedis.del(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()));
......@@ -108,14 +106,15 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
JedisUtils.returnResource(jedis);
}
}
@Override
public Collection<Session> getActiveSessions() {
return getActiveSessions(true);
}
/**
* 获取活动会话
*
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
*/
......@@ -123,57 +122,57 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
public Collection<Session> getActiveSessions(boolean includeLeave) {
return getActiveSessions(includeLeave, null, null);
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
*
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
*/
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession){
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession) {
Set<Session> sessions = Sets.newHashSet();
Jedis jedis = null;
try {
jedis = JedisUtils.getResource();
Map<String, String> map = jedis.hgetAll(sessionKeyPrefix);
for (Map.Entry<String, String> e : map.entrySet()){
if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())){
for (Map.Entry<String, String> e : map.entrySet()) {
if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())) {
String[] ss = StringUtils.split(e.getValue(), "|");
if (ss != null && ss.length == 3){// jedis.exists(sessionKeyPrefix + e.getKey())){
// Session session = (Session)JedisUtils.toObject(jedis.get(JedisUtils.getBytesKey(sessionKeyPrefix + e.getKey())));
if (ss != null && ss.length == 3) {
SimpleSession session = new SimpleSession();
session.setId(e.getKey());
session.setAttribute("principalId", ss[0]);
session.setTimeout(Long.valueOf(ss[1]));
session.setLastAccessTime(new Date(Long.valueOf(ss[2])));
try{
try {
// 验证SESSION
session.validate();
boolean isActiveSession = false;
// 不包括离线并符合最后访问时间小于等于3分钟条件。
if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3) {
isActiveSession = true;
}
// 符合登陆者条件。
if (principal != null){
PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
if (principal != null) {
PrincipalCollection pc = (PrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)) {
isActiveSession = true;
}
}
// 过滤掉的SESSION
if (filterSession != null && filterSession.getId().equals(session.getId())){
if (filterSession != null && filterSession.getId().equals(session.getId())) {
isActiveSession = false;
}
if (isActiveSession){
if (isActiveSession) {
sessions.add(session);
}
}
// SESSION验证失败
catch (Exception e2) {
......@@ -181,12 +180,12 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
}
}
// 存储的SESSION不符合规则
else{
else {
jedis.hdel(sessionKeyPrefix, e.getKey());
}
}
// 存储的SESSION无Value
else if (StringUtils.isNotBlank(e.getKey())){
else if (StringUtils.isNotBlank(e.getKey())) {
jedis.hdel(sessionKeyPrefix, e.getKey());
}
}
......@@ -202,10 +201,10 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
@Override
protected Serializable doCreate(Session session) {
HttpServletRequest request = Servlets.getRequest();
if (request != null){
if (request != null) {
String uri = request.getServletPath();
// 如果是静态文件,则不创建SESSION
if (Servlets.isStaticFile(uri)){
if (Servlets.isStaticFile(uri)) {
return null;
}
}
......@@ -220,15 +219,15 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
Session s = null;
HttpServletRequest request = Servlets.getRequest();
if (request != null){
if (request != null) {
String uri = request.getServletPath();
// 如果是静态文件,则不获取SESSION
if (Servlets.isStaticFile(uri)){
if (Servlets.isStaticFile(uri)) {
return null;
}
s = (Session)request.getAttribute("session_"+sessionId);
s = (Session) request.getAttribute("session_" + sessionId);
}
if (s != null){
if (s != null) {
return s;
}
......@@ -236,29 +235,26 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
Jedis jedis = null;
try {
jedis = JedisUtils.getResource();
// if (jedis.exists(sessionKeyPrefix + sessionId)){
session = (Session)JedisUtils.toObject(jedis.get(
JedisUtils.getBytesKey(sessionKeyPrefix + sessionId)));
// }
session = (Session) JedisUtils.toObject(jedis.get(
JedisUtils.getBytesKey(sessionKeyPrefix + sessionId)));
logger.debug("doReadSession {} {}", sessionId, request != null ? request.getRequestURI() : "");
} catch (Exception e) {
logger.error("doReadSession {} {}", sessionId, request != null ? request.getRequestURI() : "", e);
} finally {
JedisUtils.returnResource(jedis);
}
if (request != null && session != null){
request.setAttribute("session_"+sessionId, session);
if (request != null && session != null) {
request.setAttribute("session_" + sessionId, session);
}
return session;
}
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
try{
try {
return super.readSession(sessionId);
}catch (UnknownSessionException e) {
} catch (UnknownSessionException e) {
return null;
}
}
......
......@@ -3,18 +3,18 @@
*/
package com.ejweb.core.utils;
import java.io.Serializable;
import java.security.SecureRandom;
//import java.util.UUID;
import org.activiti.engine.impl.cfg.IdGenerator;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionIdGenerator;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.security.SecureRandom;
/**
* 封装各种生成唯一性ID算法的工具类.
*
* @author ThinkGem
* @version 2013-01-15
*/
......@@ -23,17 +23,16 @@ import org.springframework.stereotype.Service;
public class IdGen implements IdGenerator, SessionIdGenerator {
private static SecureRandom random = new SecureRandom();
/**
* 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
*/
public static String uuid() {
return IdWorker.getNextId();
// return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* 使用SecureRandom随机生成Long.
* 使用SecureRandom随机生成Long.
*/
public static long randomLong() {
return Math.abs(random.nextLong());
......@@ -47,29 +46,18 @@ public class IdGen implements IdGenerator, SessionIdGenerator {
random.nextBytes(randomBytes);
return Encodes.encodeBase62(randomBytes);
}
/**
* Activiti ID 生成
*/
@Override
public String getNextId() {
return IdWorker.getNextId();
// return IdGen.uuid();
}
@Override
public Serializable generateId(Session session) {
return IdWorker.getNextId();
// return IdGen.uuid();
}
// public static void main(String[] args) {
// System.out.println(IdGen.uuid());
// System.out.println(IdGen.uuid().length());
// System.out.println(new IdGen().getNextId());
// for (int i=0; i<1000; i++){
// System.out.println(IdGen.randomLong() + " " + IdGen.randomBase62(5));
// }
// }
}
......@@ -3,38 +3,37 @@
*/
package com.ejweb.core.utils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ejweb.core.conf.GConstants;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ejweb.core.conf.GConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Jedis Cache 工具类
*
*
* @author ThinkGem
* @version 2014-6-29
*/
public class JedisUtils {
private static Logger logger = LoggerFactory.getLogger(JedisUtils.class);
private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class);
public static final String KEY_PREFIX = GConstants.getValue("redis.keyPrefix");
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
......@@ -55,9 +54,10 @@ public class JedisUtils {
}
return value;
}
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
......@@ -77,11 +77,12 @@ public class JedisUtils {
}
return value;
}
/**
* 设置缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -102,11 +103,12 @@ public class JedisUtils {
}
return result;
}
/**
* 设置缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -127,9 +129,10 @@ public class JedisUtils {
}
return result;
}
/**
* 获取List缓存
*
* @param key 键
* @return 值
*/
......@@ -149,9 +152,10 @@ public class JedisUtils {
}
return value;
}
/**
* 获取List缓存
*
* @param key 键
* @return 值
*/
......@@ -163,7 +167,7 @@ public class JedisUtils {
if (jedis.exists(getBytesKey(key))) {
List<byte[]> list = jedis.lrange(getBytesKey(key), 0, -1);
value = Lists.newArrayList();
for (byte[] bs : list){
for (byte[] bs : list) {
value.add(toObject(bs));
}
logger.debug("getObjectList {} = {}", key, value);
......@@ -175,11 +179,12 @@ public class JedisUtils {
}
return value;
}
/**
* 设置List缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -191,7 +196,7 @@ public class JedisUtils {
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.rpush(key, (String[])value.toArray());
result = jedis.rpush(key, (String[]) value.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
......@@ -203,11 +208,12 @@ public class JedisUtils {
}
return result;
}
/**
* 设置List缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -220,10 +226,10 @@ public class JedisUtils {
jedis.del(key);
}
List<byte[]> list = Lists.newArrayList();
for (Object o : value){
for (Object o : value) {
list.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray());
result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
......@@ -235,10 +241,11 @@ public class JedisUtils {
}
return result;
}
/**
* 向List缓存中添加值
* @param key 键
*
* @param key 键
* @param value 值
* @return
*/
......@@ -256,10 +263,11 @@ public class JedisUtils {
}
return result;
}
/**
* 向List缓存中添加值
* @param key 键
*
* @param key 键
* @param value 值
* @return
*/
......@@ -269,10 +277,10 @@ public class JedisUtils {
try {
jedis = getResource();
List<byte[]> list = Lists.newArrayList();
for (Object o : value){
for (Object o : value) {
list.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray());
result = jedis.rpush(getBytesKey(key), (byte[][]) list.toArray());
logger.debug("listObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listObjectAdd {} = {}", key, value, e);
......@@ -284,6 +292,7 @@ public class JedisUtils {
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
......@@ -303,9 +312,10 @@ public class JedisUtils {
}
return value;
}
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
......@@ -317,7 +327,7 @@ public class JedisUtils {
if (jedis.exists(getBytesKey(key))) {
value = Sets.newHashSet();
Set<byte[]> set = jedis.smembers(getBytesKey(key));
for (byte[] bs : set){
for (byte[] bs : set) {
value.add(toObject(bs));
}
logger.debug("getObjectSet {} = {}", key, value);
......@@ -329,11 +339,12 @@ public class JedisUtils {
}
return value;
}
/**
* 设置Set缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -345,7 +356,7 @@ public class JedisUtils {
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.sadd(key, (String[])value.toArray());
result = jedis.sadd(key, (String[]) value.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
......@@ -357,11 +368,12 @@ public class JedisUtils {
}
return result;
}
/**
* 设置Set缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -374,10 +386,10 @@ public class JedisUtils {
jedis.del(key);
}
Set<byte[]> set = Sets.newHashSet();
for (Object o : value){
for (Object o : value) {
set.add(toBytes(o));
}
result = jedis.sadd(getBytesKey(key), (byte[][])set.toArray());
result = jedis.sadd(getBytesKey(key), (byte[][]) set.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
......@@ -389,10 +401,11 @@ public class JedisUtils {
}
return result;
}
/**
* 向Set缓存中添加值
* @param key 键
*
* @param key 键
* @param value 值
* @return
*/
......@@ -413,7 +426,8 @@ public class JedisUtils {
/**
* 向Set缓存中添加值
* @param key 键
*
* @param key 键
* @param value 值
* @return
*/
......@@ -423,10 +437,10 @@ public class JedisUtils {
try {
jedis = getResource();
Set<byte[]> set = Sets.newHashSet();
for (Object o : value){
for (Object o : value) {
set.add(toBytes(o));
}
result = jedis.rpush(getBytesKey(key), (byte[][])set.toArray());
result = jedis.rpush(getBytesKey(key), (byte[][]) set.toArray());
logger.debug("setSetObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetObjectAdd {} = {}", key, value, e);
......@@ -435,9 +449,10 @@ public class JedisUtils {
}
return result;
}
/**
* 获取Map缓存
*
* @param key 键
* @return 值
*/
......@@ -457,9 +472,10 @@ public class JedisUtils {
}
return value;
}
/**
* 获取Map缓存
*
* @param key 键
* @return 值
*/
......@@ -471,7 +487,7 @@ public class JedisUtils {
if (jedis.exists(getBytesKey(key))) {
value = Maps.newHashMap();
Map<byte[], byte[]> map = jedis.hgetAll(getBytesKey(key));
for (Map.Entry<byte[], byte[]> e : map.entrySet()){
for (Map.Entry<byte[], byte[]> e : map.entrySet()) {
value.put(StringUtils.toString(e.getKey()), toObject(e.getValue()));
}
logger.debug("getObjectMap {} = {}", key, value);
......@@ -483,11 +499,12 @@ public class JedisUtils {
}
return value;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -511,11 +528,12 @@ public class JedisUtils {
}
return result;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
......@@ -528,10 +546,10 @@ public class JedisUtils {
jedis.del(key);
}
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()){
for (Map.Entry<String, Object> e : value.entrySet()) {
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>) map);
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
......@@ -543,10 +561,11 @@ public class JedisUtils {
}
return result;
}
/**
* 向Map缓存中添加值
* @param key 键
*
* @param key 键
* @param value 值
* @return
*/
......@@ -564,10 +583,11 @@ public class JedisUtils {
}
return result;
}
/**
* 向Map缓存中添加值
* @param key 键
*
* @param key 键
* @param value 值
* @return
*/
......@@ -577,10 +597,10 @@ public class JedisUtils {
try {
jedis = getResource();
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()){
for (Map.Entry<String, Object> e : value.entrySet()) {
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>) map);
logger.debug("mapObjectPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapObjectPut {} = {}", key, value, e);
......@@ -589,11 +609,12 @@ public class JedisUtils {
}
return result;
}
/**
* 移除Map缓存中的值
* @param key 键
* @param value 值
*
* @param key 键
* @param mapKey 值
* @return
*/
public static long mapRemove(String key, String mapKey) {
......@@ -610,11 +631,12 @@ public class JedisUtils {
}
return result;
}
/**
* 移除Map缓存中的值
* @param key 键
* @param value 值
*
* @param key 键
* @param mapKey 值
* @return
*/
public static long mapObjectRemove(String key, String mapKey) {
......@@ -631,11 +653,12 @@ public class JedisUtils {
}
return result;
}
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @param value 值
*
* @param key 键
* @param mapKey 值
* @return
*/
public static boolean mapExists(String key, String mapKey) {
......@@ -652,11 +675,12 @@ public class JedisUtils {
}
return result;
}
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @param value 值
*
* @param key 键
* @param mapKey 值
* @return
*/
public static boolean mapObjectExists(String key, String mapKey) {
......@@ -673,9 +697,10 @@ public class JedisUtils {
}
return result;
}
/**
* 删除缓存
*
* @param key 键
* @return
*/
......@@ -684,10 +709,10 @@ public class JedisUtils {
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)){
if (jedis.exists(key)) {
result = jedis.del(key);
logger.debug("del {}", key);
}else{
} else {
logger.debug("del {} not exists", key);
}
} catch (Exception e) {
......@@ -700,6 +725,7 @@ public class JedisUtils {
/**
* 删除缓存
*
* @param key 键
* @return
*/
......@@ -708,10 +734,10 @@ public class JedisUtils {
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))){
if (jedis.exists(getBytesKey(key))) {
result = jedis.del(getBytesKey(key));
logger.debug("delObject {}", key);
}else{
} else {
logger.debug("delObject {} not exists", key);
}
} catch (Exception e) {
......@@ -721,9 +747,10 @@ public class JedisUtils {
}
return result;
}
/**
* 缓存是否存在
*
* @param key 键
* @return
*/
......@@ -741,9 +768,10 @@ public class JedisUtils {
}
return result;
}
/**
* 缓存是否存在
*
* @param key 键
* @return
*/
......@@ -764,6 +792,7 @@ public class JedisUtils {
/**
* 获取资源
*
* @return
* @throws JedisException
*/
......@@ -771,7 +800,6 @@ public class JedisUtils {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
// logger.debug("getResource.", jedis);
} catch (JedisException e) {
logger.warn("getResource.", e);
returnBrokenResource(jedis);
......@@ -782,19 +810,19 @@ public class JedisUtils {
/**
* 归还资源
*
* @param jedis
* @param isBroken
*/
public static void returnBrokenResource(Jedis jedis) {
if (jedis != null) {
jedisPool.returnBrokenResource(jedis);
}
}
/**
* 释放资源
*
* @param jedis
* @param isBroken
*/
public static void returnResource(Jedis jedis) {
if (jedis != null) {
......@@ -804,32 +832,35 @@ public class JedisUtils {
/**
* 获取byte[]类型Key
* @param key
*
* @param object
* @return
*/
public static byte[] getBytesKey(Object object){
if(object instanceof String){
return StringUtils.getBytes((String)object);
}else{
public static byte[] getBytesKey(Object object) {
if (object instanceof String) {
return StringUtils.getBytes((String) object);
} else {
return ObjectUtils.serialize(object);
}
}
/**
* Object转换byte[]类型
* @param key
*
* @param object
* @return
*/
public static byte[] toBytes(Object object){
public static byte[] toBytes(Object object) {
return ObjectUtils.serialize(object);
}
/**
* byte[]型转换Object
* @param key
*
* @param bytes
* @return
*/
public static Object toObject(byte[] bytes){
public static Object toObject(byte[] bytes) {
return ObjectUtils.unserialize(bytes);
}
......
......@@ -6,7 +6,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathFormatUtils {
private static final Pattern pattern = Pattern.compile("\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE);
private static final String TIME = "time";
private static final String FULL_YEAR = "yyyy";
private static final String YEAR = "yy";
......@@ -16,142 +16,111 @@ public class PathFormatUtils {
private static final String MINUTE = "ii";
private static final String SECOND = "ss";
private static final String RAND = "rand";
private static Date currentDate = null;
public static String parse ( String input ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
public static String parse(String input) {
Matcher matcher = pattern.matcher(input);
PathFormatUtils.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matcher.appendReplacement(sb, PathFormatUtils.getString( matcher.group( 1 ) ) );
while (matcher.find()) {
matcher.appendReplacement(sb, PathFormatUtils.getString(matcher.group(1)));
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 格式化路径, 把windows路径替换成标准路径
*
* @param input 待格式化的路径
* @return 格式化后的路径
*/
public static String format ( String input ) {
return input.replace( "\\", "/" );
public static String format(String input) {
return input.replace("\\", "/");
}
public static String parse ( String input, String filename ) {
Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE );
public static String parse(String input, String filename) {
Matcher matcher = pattern.matcher(input);
String matchStr = null;
PathFormatUtils.currentDate = new Date();
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
matchStr = matcher.group( 1 );
if ( matchStr.indexOf( "filename" ) != -1 ) {
filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" );
matcher.appendReplacement(sb, filename );
while (matcher.find()) {
matchStr = matcher.group(1);
if (matchStr.indexOf("filename") != -1) {
filename = filename.replace("$", "\\$").replaceAll("[\\/:*?\"<>|]", "");
matcher.appendReplacement(sb, filename);
} else {
matcher.appendReplacement(sb, PathFormatUtils.getString( matchStr ) );
matcher.appendReplacement(sb, PathFormatUtils.getString(matchStr));
}
}
matcher.appendTail(sb);
return sb.toString();
}
private static String getString ( String pattern ) {
private static String getString(String pattern) {
pattern = pattern.toLowerCase();
// time 处理
if ( pattern.indexOf( PathFormatUtils.TIME ) != -1 ) {
if (pattern.indexOf(PathFormatUtils.TIME) != -1) {
return PathFormatUtils.getTimestamp();
} else if ( pattern.indexOf( PathFormatUtils.FULL_YEAR ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.FULL_YEAR) != -1) {
return PathFormatUtils.getFullYear();
} else if ( pattern.indexOf( PathFormatUtils.YEAR ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.YEAR) != -1) {
return PathFormatUtils.getYear();
} else if ( pattern.indexOf( PathFormatUtils.MONTH ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.MONTH) != -1) {
return PathFormatUtils.getMonth();
} else if ( pattern.indexOf( PathFormatUtils.DAY ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.DAY) != -1) {
return PathFormatUtils.getDay();
} else if ( pattern.indexOf( PathFormatUtils.HOUR ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.HOUR) != -1) {
return PathFormatUtils.getHour();
} else if ( pattern.indexOf( PathFormatUtils.MINUTE ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.MINUTE) != -1) {
return PathFormatUtils.getMinute();
} else if ( pattern.indexOf( PathFormatUtils.SECOND ) != -1 ) {
} else if (pattern.indexOf(PathFormatUtils.SECOND) != -1) {
return PathFormatUtils.getSecond();
} else if ( pattern.indexOf( PathFormatUtils.RAND ) != -1 ) {
return PathFormatUtils.getRandom( pattern );
} else if (pattern.indexOf(PathFormatUtils.RAND) != -1) {
return PathFormatUtils.getRandom(pattern);
}
return pattern;
}
private static String getTimestamp () {
private static String getTimestamp() {
return System.currentTimeMillis() + "";
}
private static String getFullYear () {
return new SimpleDateFormat( "yyyy" ).format( PathFormatUtils.currentDate );
}
private static String getYear () {
return new SimpleDateFormat( "yy" ).format( PathFormatUtils.currentDate );
}
private static String getMonth () {
return new SimpleDateFormat( "MM" ).format( PathFormatUtils.currentDate );
private static String getFullYear() {
return new SimpleDateFormat("yyyy").format(PathFormatUtils.currentDate);
}
private static String getDay () {
return new SimpleDateFormat( "dd" ).format( PathFormatUtils.currentDate );
private static String getYear() {
return new SimpleDateFormat("yy").format(PathFormatUtils.currentDate);
}
private static String getHour () {
return new SimpleDateFormat( "HH" ).format( PathFormatUtils.currentDate );
private static String getMonth() {
return new SimpleDateFormat("MM").format(PathFormatUtils.currentDate);
}
private static String getMinute () {
return new SimpleDateFormat( "mm" ).format( PathFormatUtils.currentDate );
private static String getDay() {
return new SimpleDateFormat("dd").format(PathFormatUtils.currentDate);
}
private static String getSecond () {
return new SimpleDateFormat( "ss" ).format( PathFormatUtils.currentDate );
private static String getHour() {
return new SimpleDateFormat("HH").format(PathFormatUtils.currentDate);
}
private static String getRandom ( String pattern ) {
int length = 0;
pattern = pattern.split( ":" )[ 1 ].trim();
length = Integer.parseInt( pattern );
return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length );
private static String getMinute() {
return new SimpleDateFormat("mm").format(PathFormatUtils.currentDate);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
private static String getSecond() {
return new SimpleDateFormat("ss").format(PathFormatUtils.currentDate);
}
private static String getRandom(String pattern) {
int length = 0;
pattern = pattern.split(":")[1].trim();
length = Integer.parseInt(pattern);
return (Math.random() + "").replace(".", "").substring(0, length);
}
}
......@@ -3,83 +3,85 @@
*/
package com.ejweb.core.utils;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import com.google.common.collect.Lists;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
*
* @author ThinkGem
* @version 2013-05-22
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 转换为字节数组
*
* @param str
* @return
*/
public static byte[] getBytes(String str){
if (str != null){
public static byte[] getBytes(String str) {
if (str != null) {
try {
return str.getBytes(CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return null;
}
}else{
} else {
return null;
}
}
/**
* 转换为字节数组
* @param str
*
* @param bytes
* @return
*/
public static String toString(byte[] bytes){
public static String toString(byte[] bytes) {
try {
return new String(bytes, CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return EMPTY;
}
}
/**
* 是否包含字符串
* @param str 验证字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs){
if (str != null){
for (String s : strs){
if (str.equals(trim(s))){
public static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}
/**
* 替换掉HTML标签方法
*/
public static String replaceHtml(String html) {
if (isBlank(html)){
if (isBlank(html)) {
return "";
}
String regEx = "<.+?>";
......@@ -88,26 +90,28 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
String s = m.replaceAll("");
return s;
}
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param html
* @return
*/
public static String replaceMobileHtml(String html){
if (html == null){
public static String replaceMobileHtml(String html) {
if (html == null) {
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param txt
* @return
*/
public static String toHtml(String txt){
if (txt == null){
public static String toHtml(String txt) {
if (txt == null) {
return "";
}
return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", "&nbsp; &nbsp; ");
......@@ -115,7 +119,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* 缩略字符串(不区分中英文字符)
* @param str 目标字符串
*
* @param str 目标字符串
* @param length 截取长度
* @return
*/
......@@ -141,7 +146,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
}
return "";
}
public static String abbr2(String param, int length) {
if (param == null) {
return "";
......@@ -190,7 +195,6 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>",
"$2");
// 用正则表达式取出标记
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
List<String> endHTML = Lists.newArrayList();
while (m.find()) {
......@@ -204,12 +208,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
}
return result.toString();
}
/**
* 转换为Double类型
*/
public static Double toDouble(Object val){
if (val == null){
public static Double toDouble(Object val) {
if (val == null) {
return 0D;
}
try {
......@@ -222,76 +226,68 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* 转换为Float类型
*/
public static Float toFloat(Object val){
public static Float toFloat(Object val) {
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(Object val){
public static Long toLong(Object val) {
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(Object val){
public static Integer toInteger(Object val) {
return toLong(val).intValue();
}
/**
* 获得i18n字符串
*/
public static String getMessage(String code, Object[] args) {
LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class);
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
Locale localLocale = localLocaleResolver.resolveLocale(request);
return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
}
/**
* 获得用户远程地址
*/
public static String getRemoteAddr(HttpServletRequest request){
// String remoteAddr = request.getHeader("X-Real-IP");
// if (isNotBlank(remoteAddr)) {
// remoteAddr = request.getHeader("X-Forwarded-For");
// }else if (isNotBlank(remoteAddr)) {
// remoteAddr = request.getHeader("Proxy-Client-IP");
// }else if (isNotBlank(remoteAddr)) {
// remoteAddr = request.getHeader("WL-Proxy-Client-IP");
// }
// return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
if(request == null)
public static String getRemoteAddr(HttpServletRequest request) {
if (request == null) {
return "Unknown";
}
String ip = request.getHeader("X-Real-IP");
if(StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)){
if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("x-forwarded-for");
if(StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)){
if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
//获取HTTP_CLIENT_IP
ip = request.getHeader("Proxy-Client-IP");
if(StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)){
if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
//HTTP_X_FORWARDED_FOR
ip = request.getHeader("WL-Proxy-Client-IP");
if(StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)){
if (StringUtils.isBlank(ip) || "Unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
}
}
}
if(StringUtils.isBlank(ip))
if (StringUtils.isBlank(ip)) {
return "Unknown";
}
return ip.split(",")[0];
}
/**
* 驼峰命名法工具
* @return
* toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*
* @return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCamelCase(String s) {
if (s == null) {
......@@ -320,10 +316,10 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
* 驼峰命名法工具
* @return
* toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*
* @return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
......@@ -332,13 +328,13 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
* @return
* toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*
* @return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
if (s == null) {
......@@ -370,34 +366,36 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
return sb.toString();
}
/**
* 如果不为空,则设置值
*
* @param target
* @param source
*/
public static void setValueIfNotBlank(String target, String source) {
if (isNotBlank(source)){
if (isNotBlank(source)) {
target = source;
}
}
/**
* 转换为JS获取对象值,生成三目运算返回结果
*
* @param objectString 对象串
* 例如:row.user.id
* 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
* 例如:row.user.id
* 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
*/
public static String jsGetVal(String objectString){
public static String jsGetVal(String objectString) {
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = split(objectString, ".");
for (int i=0; i<vals.length; i++){
for (int i = 0; i < vals.length; i++) {
val.append("." + vals[i]);
result.append("!"+(val.substring(1))+"?'':");
result.append("!" + (val.substring(1)) + "?'':");
}
result.append(val.substring(1));
return result.toString();
}
}
/**
* Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.ejweb.core.utils.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ejweb.core.utils.Reflections;
import com.ejweb.core.utils.excel.annotation.ExcelField;
import com.ejweb.modules.sys.utils.DictUtils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.collect.Lists;
import com.ejweb.core.utils.Reflections;
import com.ejweb.core.utils.excel.annotation.ExcelField;
import com.ejweb.modules.sys.utils.DictUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* 导入Excel文件(支持“XLS”和“XLSX”格式)
* @author ThinkGem
* @version 2013-03-10
*/
public class ImportExcel {
private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 标题行号
*/
private int headerNum;
/**
* 构造函数
* @param path 导入文件,读取第一个工作表
*
* @param fileName 导入文件,读取第一个工作表
* @param headerNum 标题行号,数据行号=标题行号+1
* @throws InvalidFormatException
* @throws IOException
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, int headerNum)
public ImportExcel(String fileName, int headerNum)
throws InvalidFormatException, IOException {
this(new File(fileName), headerNum);
}
/**
* 构造函数
* @param path 导入文件对象,读取第一个工作表
*
* @param file 导入文件对象,读取第一个工作表
* @param headerNum 标题行号,数据行号=标题行号+1
* @throws InvalidFormatException
* @throws IOException
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(File file, int headerNum)
public ImportExcel(File file, int headerNum)
throws InvalidFormatException, IOException {
this(file, headerNum, 0);
}
/**
* 构造函数
* @param path 导入文件
* @param headerNum 标题行号,数据行号=标题行号+1
*
* @param fileName 导入文件
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, int headerNum, int sheetIndex)
public ImportExcel(String fileName, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(new File(fileName), headerNum, sheetIndex);
}
/**
* 构造函数
* @param path 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
*
* @param file 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(File file, int headerNum, int sheetIndex)
public ImportExcel(File file, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
}
/**
* 构造函数
* @param file 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*
* @param multipartFile 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
}
/**
* 构造函数
* @param path 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
*
* @param fileName 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws IOException
* @throws InvalidFormatException
* @throws IOException
*/
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
throws InvalidFormatException, IOException {
if (StringUtils.isBlank(fileName)){
if (StringUtils.isBlank(fileName)) {
throw new RuntimeException("导入文档为空!");
}else if(fileName.toLowerCase().endsWith("xls")){
this.wb = new HSSFWorkbook(is);
}else if(fileName.toLowerCase().endsWith("xlsx")){
} else if (fileName.toLowerCase().endsWith("xls")) {
this.wb = new HSSFWorkbook(is);
} else if (fileName.toLowerCase().endsWith("xlsx")) {
this.wb = new XSSFWorkbook(is);
}else{
} else {
throw new RuntimeException("文档格式不正确!");
}
if (this.wb.getNumberOfSheets()<sheetIndex){
}
if (this.wb.getNumberOfSheets() < sheetIndex) {
throw new RuntimeException("文档中没有工作表!");
}
this.sheet = this.wb.getSheetAt(sheetIndex);
this.headerNum = headerNum;
log.debug("Initialize success.");
}
/**
* 获取行对象
*
* @param rownum
* @return
*/
public Row getRow(int rownum){
public Row getRow(int rownum) {
return this.sheet.getRow(rownum);
}
/**
* 获取数据行号
*
* @return
*/
public int getDataRowNum(){
return headerNum+1;
public int getDataRowNum() {
return headerNum + 1;
}
/**
* 获取最后一个数据行号
*
* @return
*/
public int getLastDataRowNum(){
return this.sheet.getLastRowNum()+headerNum;
public int getLastDataRowNum() {
return this.sheet.getLastRowNum() + headerNum;
}
/**
* 获取最后一个列号
*
* @return
*/
public int getLastCellNum(){
public int getLastCellNum() {
return this.getRow(headerNum).getLastCellNum();
}
/**
* 获取单元格值
* @param row 获取的行
*
* @param row 获取的行
* @param column 获取单元格列号
* @return 单元格值
*/
public Object getCellValue(Row row, int column){
public Object getCellValue(Row row, int column) {
Object val = "";
try{
try {
Cell cell = row.getCell(column);
if (cell != null){
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
if (cell != null) {
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
val = cell.getNumericCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
val = cell.getStringCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
val = cell.getCellFormula();
}else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
val = cell.getBooleanCellValue();
}else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
} else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
val = cell.getErrorCellValue();
}
}
}catch (Exception e) {
} catch (Exception e) {
return val;
}
return val;
}
/**
* 获取导入数据列表
* @param cls 导入对象类型
*
* @param cls 导入对象类型
* @param groups 导入分组
*/
public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException {
List<Object[]> annotationList = Lists.newArrayList();
// Get annotation field
Field[] fs = cls.getDeclaredFields();
for (Field f : fs){
for (Field f : fs) {
ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==2)){
if (groups!=null && groups.length>0){
if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
if (groups != null && groups.length > 0) {
boolean inGroup = false;
for (int g : groups){
if (inGroup){
for (int g : groups) {
if (inGroup) {
break;
}
for (int efg : ef.groups()){
if (g == efg){
for (int efg : ef.groups()) {
if (g == efg) {
inGroup = true;
annotationList.add(new Object[]{ef, f});
break;
}
}
}
}else{
} else {
annotationList.add(new Object[]{ef, f});
}
}
}
// Get annotation method
Method[] ms = cls.getDeclaredMethods();
for (Method m : ms){
for (Method m : ms) {
ExcelField ef = m.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==2)){
if (groups!=null && groups.length>0){
if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
if (groups != null && groups.length > 0) {
boolean inGroup = false;
for (int g : groups){
if (inGroup){
for (int g : groups) {
if (inGroup) {
break;
}
for (int efg : ef.groups()){
if (g == efg){
for (int efg : ef.groups()) {
if (g == efg) {
inGroup = true;
annotationList.add(new Object[]{ef, m});
break;
}
}
}
}else{
} else {
annotationList.add(new Object[]{ef, m});
}
}
......@@ -268,106 +265,86 @@ public class ImportExcel {
// Field sorting
Collections.sort(annotationList, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
new Integer(((ExcelField)o2[0]).sort()));
};
return new Integer(((ExcelField) o1[0]).sort()).compareTo(
new Integer(((ExcelField) o2[0]).sort()));
}
;
});
//log.debug("Import column count:"+annotationList.size());
// Get excel data
List<E> dataList = Lists.newArrayList();
for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
E e = (E)cls.newInstance();
E e = (E) cls.newInstance();
int column = 0;
Row row = this.getRow(i);
StringBuilder sb = new StringBuilder();
for (Object[] os : annotationList){
for (Object[] os : annotationList) {
Object val = this.getCellValue(row, column++);
if (val != null){
ExcelField ef = (ExcelField)os[0];
if (val != null) {
ExcelField ef = (ExcelField) os[0];
// If is dict type, get dict value
if (StringUtils.isNotBlank(ef.dictType())){
if (StringUtils.isNotBlank(ef.dictType())) {
val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
//log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
}
// Get param type and type cast
Class<?> valType = Class.class;
if (os[1] instanceof Field){
valType = ((Field)os[1]).getType();
}else if (os[1] instanceof Method){
Method method = ((Method)os[1]);
if ("get".equals(method.getName().substring(0, 3))){
if (os[1] instanceof Field) {
valType = ((Field) os[1]).getType();
} else if (os[1] instanceof Method) {
Method method = ((Method) os[1]);
if ("get".equals(method.getName().substring(0, 3))) {
valType = method.getReturnType();
}else if("set".equals(method.getName().substring(0, 3))){
valType = ((Method)os[1]).getParameterTypes()[0];
} else if ("set".equals(method.getName().substring(0, 3))) {
valType = ((Method) os[1]).getParameterTypes()[0];
}
}
//log.debug("Import value type: ["+i+","+column+"] " + valType);
try {
if (valType == String.class){
if (valType == String.class) {
String s = String.valueOf(val.toString());
if(StringUtils.endsWith(s, ".0")){
if (StringUtils.endsWith(s, ".0")) {
val = StringUtils.substringBefore(s, ".0");
}else{
} else {
val = String.valueOf(val.toString());
}
}else if (valType == Integer.class){
} else if (valType == Integer.class) {
val = Double.valueOf(val.toString()).intValue();
}else if (valType == Long.class){
} else if (valType == Long.class) {
val = Double.valueOf(val.toString()).longValue();
}else if (valType == Double.class){
} else if (valType == Double.class) {
val = Double.valueOf(val.toString());
}else if (valType == Float.class){
} else if (valType == Float.class) {
val = Float.valueOf(val.toString());
}else if (valType == Date.class){
val = DateUtil.getJavaDate((Double)val);
}else{
if (ef.fieldType() != Class.class){
} else if (valType == Date.class) {
val = DateUtil.getJavaDate((Double) val);
} else {
if (ef.fieldType() != Class.class) {
val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
}else{
val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
"fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
} else {
val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
"fieldtype." + valType.getSimpleName() + "Type")).getMethod("getValue", String.class).invoke(null, val.toString());
}
}
} catch (Exception ex) {
log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
val = null;
}
// set entity value
if (os[1] instanceof Field){
Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
}else if (os[1] instanceof Method){
String mthodName = ((Method)os[1]).getName();
if ("get".equals(mthodName.substring(0, 3))){
mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
if (os[1] instanceof Field) {
Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
} else if (os[1] instanceof Method) {
String mthodName = ((Method) os[1]).getName();
if ("get".equals(mthodName.substring(0, 3))) {
mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
}
Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
Reflections.invokeMethod(e, mthodName, new Class[]{valType}, new Object[]{val});
}
}
sb.append(val+", ");
sb.append(val + ", ");
}
dataList.add(e);
log.debug("Read success: ["+i+"] "+sb.toString());
log.debug("Read success: [" + i + "] " + sb.toString());
}
return dataList;
}
// /**
// * 导入测试
// */
// public static void main(String[] args) throws Throwable {
//
// ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
//
// for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
// Row row = ei.getRow(i);
// for (int j = 0; j < ei.getLastCellNum(); j++) {
// Object val = ei.getCellValue(row, j);
// System.out.print(val+", ");
// }
// System.out.print("\n");
// }
//
// }
public static List<Map<String, String>> getImportFileContent(InputStream inputStream) {
......@@ -406,7 +383,7 @@ public class ImportExcel {
} finally {
try {
inputStream.close();
/* if (null != workbook) workbook.close();*/
/* if (null != workbook) workbook.close();*/
} catch (IOException ex) {
throw new RuntimeException(ex);
}
......
......@@ -31,6 +31,8 @@ import java.util.regex.Pattern;
@Service
@Transactional(readOnly = true)
public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
private static final Pattern pattern = Pattern.compile("[0-9]*");
@Autowired
private VerifyDao verifyDao;
@Autowired
......@@ -71,7 +73,9 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
} else {
Integer day = verifyDao.getDay(entity);
if (day != null) {
if (day <= 0) day = 0;
if (day <= 0) {
day = 0;
}
day = 90 - day;
if (day < 0) {
entity.setExpiryDate("0");
......@@ -113,7 +117,6 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
}
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
......@@ -124,15 +127,15 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
@Transactional(readOnly = false)
public String saveVerify(VerifyEntity verifyEntity) {
String verifNo = verifyEntity.getVerifNo();
if (null!=verifNo&& ""!=verifNo){
if (null != verifNo && "" != verifNo) {
List<VerifyEntity> validator = verifyDao.findverifNo(verifyEntity);
if (validator.size()!=0){
if (validator.size() != 0) {
return "1";
}
}
VerifyUpdateUserEntity vue=new VerifyUpdateUserEntity();
VerifyUpdateUserEntity vue = new VerifyUpdateUserEntity();
VerifyEntity verifyDao2 = verifyDao.get2(verifyEntity.getId());
if (verifyDao2!=null){
if (verifyDao2 != null) {
vue.setId(verifyEntity.getId());
vue.setOperateUser(verifyEntity.getOperateUser());
vue.setReason(verifyEntity.getReason());
......@@ -155,7 +158,7 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
// 如果不是航线则结束
if ("06".equals(verifyEntity.getVerifType()) || "07".equals(verifyEntity.getVerifType())
|| "08".equals(verifyEntity.getVerifType())) {
return"";
return "";
}
ConnectEntity connect = new ConnectEntity();
connect.preInsert(); // 生成id
......@@ -189,7 +192,7 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
verif.setAreaSt(verifyEntity.getAreaSt());
verif.setFlightNo(verifyEntity.getFlightNo());
verifyDao.update(verifyEntity);
return"";
return "";
}
// 判断是否主数据
else if ("1".equals(verifyEntity.getConnect().getIsMain())) {
......@@ -206,11 +209,10 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
connect.setFlightNo(verifyEntity.getFlightNo());
connectDao.update(verifyEntity.getConnect());
}
return"";
return "";
}
public List<VerifyEntity> CheckValidator(VerifyEntity verifyEntity) {
return verifyDao.findValidator(verifyEntity);
}
......
......@@ -16,47 +16,46 @@ import java.util.List;
@Service
@Transactional(readOnly = true)
public class GroupChatService extends CrudService<GroupChatDao,GroupChatEntity> {
public class GroupChatService extends CrudService<GroupChatDao, GroupChatEntity> {
@Autowired
private GroupChatDao dao;
public Page<GroupChatEntity> findList(Page<GroupChatEntity> page, GroupChatEntity groupSeatEntity) {
groupSeatEntity.setPage(page);
PageHelper.startPage(page.getPageNo(), page.getPageSize());
List<GroupChatEntity> list=dao.findList(groupSeatEntity);
List<GroupChatEntity> list = dao.findList(groupSeatEntity);
page.setList(list);
return page;
}
public List<GroupMemberEntity> getMemberList(GroupChatEntity entity) {
List<GroupMemberEntity> list = dao.getMemberList(entity);
/* for(GroupMemberEntity e:list){
GroupMemberEntity user=dao.getMember(e.getId());
}*/
List<GroupMemberEntity> list = dao.getMemberList(entity);
return list;
}
public GroupMemberEntity getSeatMember(GroupChatEntity entity) {
return dao.getSeatMember(entity);
return dao.getSeatMember(entity);
}
public Page<GroupMemberEntity> findChatList(Page<GroupChatEntity> page,Page<GroupMemberEntity> pages, GroupChatEntity groupChatEntity) {
public Page<GroupMemberEntity> findChatList(Page<GroupChatEntity> page, Page<GroupMemberEntity> pages, GroupChatEntity groupChatEntity) {
groupChatEntity.setPage(page);
PageHelper.startPage(page.getPageNo(), page.getPageSize());
List<GroupMemberEntity> list=dao.findChatList(groupChatEntity);
List<GroupMemberEntity> list = dao.findChatList(groupChatEntity);
for(GroupMemberEntity e:list){
if("TXT".equals(e.getMessageType())){
for (GroupMemberEntity e : list) {
if ("TXT".equals(e.getMessageType())) {
continue;
}
switch(e.getMessageType()){
switch (e.getMessageType()) {
case "PIC":
case "FILE":
case "VOICE":
case "VIDEO":
String content=e.getContent();
content=content.substring(11);
ContentEntity data= JSON.parseObject(content,ContentEntity.class);
String content = e.getContent();
content = content.substring(11);
ContentEntity data = JSON.parseObject(content, ContentEntity.class);
e.setData(data);
break;
default:
......
......@@ -55,6 +55,7 @@ import com.ejweb.modules.sys.utils.UserUtils;
@Controller
@RequestMapping(value = "${adminPath}/contact/airportBase")
public class AirportBaseController extends BaseController{
private static final Pattern pattern = Pattern.compile("\\d+\\.\\d+$|-\\d+\\.\\d+$");
@Autowired
private AirportBaseService airportBaseService;
@Autowired
......@@ -290,8 +291,6 @@ public class AirportBaseController extends BaseController{
}
private Map<String,Integer> getDate(String time){
Map<String,Integer> map = new HashMap<>();
Pattern pattern = Pattern.compile("\\d+\\.\\d+$|-\\d+\\.\\d+$");
Matcher isNum = pattern.matcher(time);
if( isNum.matches() ){
Double d18=Double.parseDouble(time);
......
......@@ -33,8 +33,6 @@ import com.google.common.collect.Maps;
/**
* 登录Controller
* @author ThinkGem
* @version 2013-5-31
*/
@Controller
public class LoginController extends BaseController{
......@@ -49,12 +47,6 @@ public class LoginController extends BaseController{
public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
Principal principal = UserUtils.getPrincipal();
// // 默认页签模式
// String tabmode = CookieUtils.getCookie(request, "tabmode");
// if (tabmode == null){
// CookieUtils.setCookie(response, "tabmode", "1");
// }
CookieUtils.setCookie(response, "tabmode", GConstants.getValue("tabmode", "1"));
if (logger.isDebugEnabled()){
......@@ -70,12 +62,6 @@ public class LoginController extends BaseController{
if(principal != null && !principal.isMobileLogin()){
return "redirect:" + adminPath;
}
// String view;
// view = "/WEB-INF/views/modules/sys/sysLogin.jsp";
// view = "classpath:";
// view += "jar:file:/D:/GitHub/jeesite/src/main/webapp/WEB-INF/lib/jeesite.jar!";
// view += "/"+getClass().getName().replaceAll("\\.", "/").replace(getClass().getSimpleName(), "")+"view/sysLogin";
// view += ".jsp";
return "modules/sys/sysLogin";
}
......@@ -111,20 +97,16 @@ public class LoginController extends BaseController{
logger.debug("login fail, active session size: {}, message: {}, exception: {}",
sessionDAO.getActiveSessions(false).size(), message, exception);
}
// 非授权异常,登录失败,验证码加1。
if (!UnauthorizedException.class.getName().equals(exception)){
model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
}
// 验证失败清空验证码
request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
// 如果是手机登录,则返回JSON字符串
if (mobile){
return renderString(response, model);
}
return "modules/sys/sysLogin";
}
......@@ -165,40 +147,10 @@ public class LoginController extends BaseController{
return "redirect:" + adminPath + "/login";
}
// // 登录成功后,获取上次登录的当前站点ID
// UserUtils.putCache("siteId", StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));
// System.out.println("==========================a");
// try {
// byte[] bytes = com.ejweb.core.utils.FileUtils.readFileToByteArray(
// com.ejweb.core.utils.FileUtils.getFile("c:\\sxt.dmp"));
// UserUtils.getSession().setAttribute("kkk", bytes);
// UserUtils.getSession().setAttribute("kkk2", bytes);
// } catch (Exception e) {
// e.printStackTrace();
// }
//// for (int i=0; i<1000000; i++){
//// //UserUtils.getSession().setAttribute("a", "a");
//// request.getSession().setAttribute("aaa", "aa");
//// }
// System.out.println("==========================b");
return "modules/sys/sysIndex";
}
/**
* 获取主题方案
*/
// @RequestMapping(value = "/theme/{theme}")
// public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
// if (StringUtils.isNotBlank(theme)){
// CookieUtils.setCookie(response, "theme", theme);
// }else{
// theme = CookieUtils.getCookie(request, "theme");
// }
// return "redirect:"+request.getParameter("url");
// }
/**
* 是否是验证码登录
* @param useruame 用户名
* @param isFail 计数加1
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment