Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
F
foc_manage
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
首航-临时账号
foc_manage
Commits
89564d2b
Commit
89564d2b
authored
Sep 07, 2020
by
java-李谡
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
代码规范
parent
f07cde2a
Show whitespace changes
Inline
Side-by-side
Showing
14 changed files
with
468 additions
and
662 deletions
+468
-662
PathFormat.java
src/com/baidu/ueditor/core/PathFormat.java
+44
-58
GConstants.java
src/com/ejweb/core/conf/GConstants.java
+0
-5
HCFetcher.java
src/com/ejweb/core/fetcher/HCFetcher.java
+62
-148
SQLHelper.java
src/com/ejweb/core/persistence/interceptor/SQLHelper.java
+4
-4
JedisSessionDAO.java
src/com/ejweb/core/security/shiro/session/JedisSessionDAO.java
+45
-49
IdGen.java
src/com/ejweb/core/utils/IdGen.java
+4
-16
JedisUtils.java
src/com/ejweb/core/utils/JedisUtils.java
+77
-46
PathFormatUtils.java
src/com/ejweb/core/utils/PathFormatUtils.java
+44
-75
StringUtils.java
src/com/ejweb/core/utils/StringUtils.java
+56
-58
ImportExcel.java
src/com/ejweb/core/utils/excel/ImportExcel.java
+107
-130
VerifyService.java
src/com/ejweb/modules/airline/service/VerifyService.java
+12
-10
GroupChatService.java
src/com/ejweb/modules/chat/service/GroupChatService.java
+12
-13
AirportBaseController.java
src/com/ejweb/modules/contact/web/AirportBaseController.java
+1
-2
LoginController.java
src/com/ejweb/modules/sys/web/LoginController.java
+0
-48
No files found.
src/com/baidu/ueditor/core/PathFormat.java
View file @
89564d2b
...
@@ -6,7 +6,7 @@ import java.util.regex.Matcher;
...
@@ -6,7 +6,7 @@ import java.util.regex.Matcher;
import
java.util.regex.Pattern
;
import
java.util.regex.Pattern
;
public
class
PathFormat
{
public
class
PathFormat
{
private
static
final
Pattern
pattern
=
Pattern
.
compile
(
"\\{([^\\}]+)\\}"
,
Pattern
.
CASE_INSENSITIVE
);
private
static
final
String
TIME
=
"time"
;
private
static
final
String
TIME
=
"time"
;
private
static
final
String
FULL_YEAR
=
"yyyy"
;
private
static
final
String
FULL_YEAR
=
"yyyy"
;
private
static
final
String
YEAR
=
"yy"
;
private
static
final
String
YEAR
=
"yy"
;
...
@@ -19,18 +19,16 @@ public class PathFormat {
...
@@ -19,18 +19,16 @@ public class PathFormat {
private
static
Date
currentDate
=
null
;
private
static
Date
currentDate
=
null
;
public
static
String
parse
(
String
input
)
{
public
static
String
parse
(
String
input
)
{
Pattern
pattern
=
Pattern
.
compile
(
"\\{([^\\}]+)\\}"
,
Pattern
.
CASE_INSENSITIVE
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
PathFormat
.
currentDate
=
new
Date
();
PathFormat
.
currentDate
=
new
Date
();
StringBuffer
sb
=
new
StringBuffer
();
StringBuffer
sb
=
new
StringBuffer
();
while
(
matcher
.
find
()
)
{
while
(
matcher
.
find
()
)
{
matcher
.
appendReplacement
(
sb
,
PathFormat
.
getString
(
matcher
.
group
(
1
)
)
);
matcher
.
appendReplacement
(
sb
,
PathFormat
.
getString
(
matcher
.
group
(
1
))
);
}
}
...
@@ -41,111 +39,99 @@ public class PathFormat {
...
@@ -41,111 +39,99 @@ public class PathFormat {
/**
/**
* 格式化路径, 把windows路径替换成标准路径
* 格式化路径, 把windows路径替换成标准路径
*
* @param input 待格式化的路径
* @param input 待格式化的路径
* @return 格式化后的路径
* @return 格式化后的路径
*/
*/
public
static
String
format
(
String
input
)
{
public
static
String
format
(
String
input
)
{
return
input
.
replace
(
"\\"
,
"/"
);
return
input
.
replace
(
"\\"
,
"/"
);
}
}
public
static
String
parse
(
String
input
,
String
filename
)
{
public
static
String
parse
(
String
input
,
String
filename
)
{
Pattern
pattern
=
Pattern
.
compile
(
"\\{([^\\}]+)\\}"
,
Pattern
.
CASE_INSENSITIVE
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
String
matchStr
=
null
;
String
matchStr
=
null
;
PathFormat
.
currentDate
=
new
Date
();
PathFormat
.
currentDate
=
new
Date
();
StringBuffer
sb
=
new
StringBuffer
();
StringBuffer
sb
=
new
StringBuffer
();
while
(
matcher
.
find
())
{
while
(
matcher
.
find
()
)
{
matchStr
=
matcher
.
group
(
1
);
if
(
matchStr
.
indexOf
(
"filename"
)
!=
-
1
)
{
matchStr
=
matcher
.
group
(
1
);
filename
=
filename
.
replace
(
"$"
,
"\\$"
).
replaceAll
(
"[\\/:*?\"<>|]"
,
""
);
if
(
matchStr
.
indexOf
(
"filename"
)
!=
-
1
)
{
matcher
.
appendReplacement
(
sb
,
filename
);
filename
=
filename
.
replace
(
"$"
,
"\\$"
).
replaceAll
(
"[\\/:*?\"<>|]"
,
""
);
matcher
.
appendReplacement
(
sb
,
filename
);
}
else
{
}
else
{
matcher
.
appendReplacement
(
sb
,
PathFormat
.
getString
(
matchStr
)
);
matcher
.
appendReplacement
(
sb
,
PathFormat
.
getString
(
matchStr
)
);
}
}
}
}
matcher
.
appendTail
(
sb
);
matcher
.
appendTail
(
sb
);
return
sb
.
toString
();
return
sb
.
toString
();
}
}
private
static
String
getString
(
String
pattern
)
{
private
static
String
getString
(
String
pattern
)
{
pattern
=
pattern
.
toLowerCase
();
pattern
=
pattern
.
toLowerCase
();
// time 处理
// time 处理
if
(
pattern
.
indexOf
(
PathFormat
.
TIME
)
!=
-
1
)
{
if
(
pattern
.
indexOf
(
PathFormat
.
TIME
)
!=
-
1
)
{
return
PathFormat
.
getTimestamp
();
return
PathFormat
.
getTimestamp
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
FULL_YEAR
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
FULL_YEAR
)
!=
-
1
)
{
return
PathFormat
.
getFullYear
();
return
PathFormat
.
getFullYear
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
YEAR
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
YEAR
)
!=
-
1
)
{
return
PathFormat
.
getYear
();
return
PathFormat
.
getYear
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
MONTH
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
MONTH
)
!=
-
1
)
{
return
PathFormat
.
getMonth
();
return
PathFormat
.
getMonth
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
DAY
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
DAY
)
!=
-
1
)
{
return
PathFormat
.
getDay
();
return
PathFormat
.
getDay
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
HOUR
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
HOUR
)
!=
-
1
)
{
return
PathFormat
.
getHour
();
return
PathFormat
.
getHour
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
MINUTE
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
MINUTE
)
!=
-
1
)
{
return
PathFormat
.
getMinute
();
return
PathFormat
.
getMinute
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
SECOND
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
SECOND
)
!=
-
1
)
{
return
PathFormat
.
getSecond
();
return
PathFormat
.
getSecond
();
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
RAND
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormat
.
RAND
)
!=
-
1
)
{
return
PathFormat
.
getRandom
(
pattern
);
return
PathFormat
.
getRandom
(
pattern
);
}
}
return
pattern
;
return
pattern
;
}
}
private
static
String
getTimestamp
()
{
private
static
String
getTimestamp
()
{
return
System
.
currentTimeMillis
()
+
""
;
return
System
.
currentTimeMillis
()
+
""
;
}
}
private
static
String
getFullYear
()
{
private
static
String
getFullYear
()
{
return
new
SimpleDateFormat
(
"yyyy"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"yyyy"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getYear
()
{
private
static
String
getYear
()
{
return
new
SimpleDateFormat
(
"yy"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"yy"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getMonth
()
{
private
static
String
getMonth
()
{
return
new
SimpleDateFormat
(
"MM"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"MM"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getDay
()
{
private
static
String
getDay
()
{
return
new
SimpleDateFormat
(
"dd"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"dd"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getHour
()
{
private
static
String
getHour
()
{
return
new
SimpleDateFormat
(
"HH"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"HH"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getMinute
()
{
private
static
String
getMinute
()
{
return
new
SimpleDateFormat
(
"mm"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"mm"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getSecond
()
{
private
static
String
getSecond
()
{
return
new
SimpleDateFormat
(
"ss"
).
format
(
PathFormat
.
currentDate
);
return
new
SimpleDateFormat
(
"ss"
).
format
(
PathFormat
.
currentDate
);
}
}
private
static
String
getRandom
(
String
pattern
)
{
private
static
String
getRandom
(
String
pattern
)
{
int
length
=
0
;
int
length
=
0
;
pattern
=
pattern
.
split
(
":"
)[
1
].
trim
();
pattern
=
pattern
.
split
(
":"
)[
1
].
trim
();
length
=
Integer
.
parseInt
(
pattern
);
length
=
Integer
.
parseInt
(
pattern
);
return
(
Math
.
random
()
+
""
).
replace
(
"."
,
""
).
substring
(
0
,
length
);
return
(
Math
.
random
()
+
""
).
replace
(
"."
,
""
).
substring
(
0
,
length
);
}
}
...
...
src/com/ejweb/core/conf/GConstants.java
View file @
89564d2b
...
@@ -432,13 +432,8 @@ public class GConstants {
...
@@ -432,13 +432,8 @@ public class GConstants {
if
(!
dir
.
endsWith
(
"/"
))
{
if
(!
dir
.
endsWith
(
"/"
))
{
dir
+=
"/"
;
dir
+=
"/"
;
}
}
// System.out.println("file.upload.dir: " + dir);
return
dir
;
return
dir
;
}
}
// public static String getBaseUrl(HttpServletRequest req){
//
// return IMAGE_BASE_URL;
// }
/**
/**
* 获取工程路径
* 获取工程路径
* @return
* @return
...
...
src/com/ejweb/core/fetcher/HCFetcher.java
View file @
89564d2b
package
com
.
ejweb
.
core
.
fetcher
;
package
com
.
ejweb
.
core
.
fetcher
;
import
java.io.IOException
;
import
org.apache.http.*
;
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.client.config.CookieSpecs
;
import
org.apache.http.client.config.CookieSpecs
;
import
org.apache.http.client.config.RequestConfig
;
import
org.apache.http.client.config.RequestConfig
;
import
org.apache.http.client.entity.GzipDecompressingEntity
;
import
org.apache.http.client.entity.GzipDecompressingEntity
;
...
@@ -44,6 +26,13 @@ import org.apache.http.ssl.TrustStrategy;
...
@@ -44,6 +26,13 @@ import org.apache.http.ssl.TrustStrategy;
import
org.apache.http.util.EntityUtils
;
import
org.apache.http.util.EntityUtils
;
import
org.apache.log4j.Logger
;
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
{
public
class
HCFetcher
{
private
final
Logger
LOG
=
Logger
.
getLogger
(
HCFetcher
.
class
);
private
final
Logger
LOG
=
Logger
.
getLogger
(
HCFetcher
.
class
);
...
@@ -52,11 +41,11 @@ public class HCFetcher {
...
@@ -52,11 +41,11 @@ public class HCFetcher {
private
CloseableHttpClient
httpclient
=
null
;
private
CloseableHttpClient
httpclient
=
null
;
private
final
Object
mutex
=
new
Object
();
private
final
Object
mutex
=
new
Object
();
private
long
getLastFetchTime
=
0
;
// 删除GET请求时间
private
long
getLastFetchTime
=
0
;
private
long
postLastFetchTime
=
0
;
// 上次POST请求时间
private
long
postLastFetchTime
=
0
;
private
long
politenessDelay
=
120L
;
// 两次请求默认最小间隔
private
long
politenessDelay
=
120L
;
private
final
static
HCFetcher
C
=
new
HCFetcher
();
// 单体类
private
final
static
HCFetcher
C
=
new
HCFetcher
();
private
ClientConnectionMonitor
connectionMonitor
=
null
;
private
ClientConnectionMonitor
connectionMonitor
=
null
;
public
static
HCFetcher
getInstance
()
{
public
static
HCFetcher
getInstance
()
{
...
@@ -66,7 +55,7 @@ public class HCFetcher {
...
@@ -66,7 +55,7 @@ public class HCFetcher {
private
HCFetcher
()
{
private
HCFetcher
()
{
try
{
try
{
SSLContext
sslcontext
=
SSLContexts
.
custom
()
SSLContext
sslcontext
=
SSLContexts
.
custom
()
.
loadTrustMaterial
(
new
TrustStrategy
(){
.
loadTrustMaterial
(
new
TrustStrategy
()
{
@Override
@Override
public
boolean
isTrusted
(
final
X509Certificate
[]
chain
,
final
String
authType
)
public
boolean
isTrusted
(
final
X509Certificate
[]
chain
,
final
String
authType
)
throws
CertificateException
{
throws
CertificateException
{
...
@@ -74,23 +63,10 @@ public class HCFetcher {
...
@@ -74,23 +63,10 @@ public class HCFetcher {
}
}
}).
build
();
}).
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());
SSLConnectionSocketFactory
sslsf
=
new
SSLConnectionSocketFactory
(
SSLConnectionSocketFactory
sslsf
=
new
SSLConnectionSocketFactory
(
sslcontext
,
SSLConnectionSocketFactory
.
getDefaultHostnameVerifier
());
sslcontext
,
SSLConnectionSocketFactory
.
getDefaultHostnameVerifier
());
// Create a registry of custom connection socket factories for
// supported
// protocol schemes.
Registry
<
ConnectionSocketFactory
>
socketFactoryRegistry
=
RegistryBuilder
Registry
<
ConnectionSocketFactory
>
socketFactoryRegistry
=
RegistryBuilder
.<
ConnectionSocketFactory
>
create
()
.<
ConnectionSocketFactory
>
create
()
.
register
(
"http"
,
PlainConnectionSocketFactory
.
INSTANCE
)
.
register
(
"http"
,
PlainConnectionSocketFactory
.
INSTANCE
)
.
register
(
"https"
,
sslsf
).
build
();
.
register
(
"https"
,
sslsf
).
build
();
...
@@ -98,30 +74,19 @@ public class HCFetcher {
...
@@ -98,30 +74,19 @@ public class HCFetcher {
socketFactoryRegistry
);
socketFactoryRegistry
);
connManager
.
setMaxTotal
(
100
);
connManager
.
setMaxTotal
(
100
);
// Create message constraints
MessageConstraints
messageConstraints
=
MessageConstraints
.
custom
()
MessageConstraints
messageConstraints
=
MessageConstraints
.
custom
()
.
setMaxHeaderCount
(
200
)
.
setMaxHeaderCount
(
200
)
.
setMaxLineLength
(
2000
)
.
setMaxLineLength
(
2000
)
.
build
();
.
build
();
// Create connection configuration
ConnectionConfig
connectionConfig
=
ConnectionConfig
.
custom
()
ConnectionConfig
connectionConfig
=
ConnectionConfig
.
custom
()
.
setMalformedInputAction
(
CodingErrorAction
.
IGNORE
)
.
setMalformedInputAction
(
CodingErrorAction
.
IGNORE
)
.
setUnmappableInputAction
(
CodingErrorAction
.
IGNORE
)
.
setUnmappableInputAction
(
CodingErrorAction
.
IGNORE
)
.
setCharset
(
Consts
.
UTF_8
)
.
setCharset
(
Consts
.
UTF_8
)
.
setMessageConstraints
(
messageConstraints
)
.
setMessageConstraints
(
messageConstraints
)
.
build
();
.
build
();
// Configure the connection manager to use connection configuration
// either
// by default or for a specific host.
connManager
.
setDefaultConnectionConfig
(
connectionConfig
);
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
.
setMaxTotal
(
100
);
connManager
.
setDefaultMaxPerRoute
(
30
);
connManager
.
setDefaultMaxPerRoute
(
30
);
// Create global request configuration
RequestConfig
defaultRequestConfig
=
RequestConfig
.
custom
()
RequestConfig
defaultRequestConfig
=
RequestConfig
.
custom
()
.
setCookieSpec
(
CookieSpecs
.
DEFAULT
)
.
setCookieSpec
(
CookieSpecs
.
DEFAULT
)
.
setExpectContinueEnabled
(
true
)
.
setExpectContinueEnabled
(
true
)
...
@@ -133,11 +98,10 @@ public class HCFetcher {
...
@@ -133,11 +98,10 @@ public class HCFetcher {
connectionMonitor
=
new
ClientConnectionMonitor
(
connectionMonitor
=
new
ClientConnectionMonitor
(
connManager
);
connManager
);
connectionMonitor
.
start
();
connectionMonitor
.
start
();
httpclient
=
HttpClients
.
custom
()
httpclient
=
HttpClients
.
custom
()
.
setConnectionManager
(
connManager
)
.
setConnectionManager
(
connManager
)
.
setDefaultRequestConfig
(
defaultRequestConfig
)
.
setDefaultRequestConfig
(
defaultRequestConfig
)
.
addInterceptorFirst
(
new
HttpRequestInterceptor
()
{
// 请求
.
addInterceptorFirst
(
new
HttpRequestInterceptor
()
{
@Override
@Override
public
void
process
(
final
HttpRequest
request
,
final
HttpContext
context
)
public
void
process
(
final
HttpRequest
request
,
final
HttpContext
context
)
throws
HttpException
,
IOException
{
throws
HttpException
,
IOException
{
...
@@ -155,7 +119,7 @@ public class HCFetcher {
...
@@ -155,7 +119,7 @@ public class HCFetcher {
request
.
addHeader
(
"Accept-Charset"
,
"utf-8"
);
request
.
addHeader
(
"Accept-Charset"
,
"utf-8"
);
request
.
addHeader
(
"Accept-Encoding"
,
"gzip"
);
request
.
addHeader
(
"Accept-Encoding"
,
"gzip"
);
}
}
}).
addInterceptorFirst
(
new
HttpResponseInterceptor
()
{
// 响应
}).
addInterceptorFirst
(
new
HttpResponseInterceptor
()
{
@Override
@Override
public
void
process
(
final
HttpResponse
response
,
final
HttpContext
context
)
public
void
process
(
final
HttpResponse
response
,
final
HttpContext
context
)
throws
HttpException
,
IOException
{
throws
HttpException
,
IOException
{
...
@@ -166,8 +130,8 @@ public class HCFetcher {
...
@@ -166,8 +130,8 @@ public class HCFetcher {
HeaderElement
[]
codecs
=
ceheader
.
getElements
();
HeaderElement
[]
codecs
=
ceheader
.
getElements
();
for
(
int
i
=
0
;
i
<
codecs
.
length
;
i
++)
{
for
(
int
i
=
0
;
i
<
codecs
.
length
;
i
++)
{
if
(
codecs
[
i
].
getName
().
equalsIgnoreCase
(
"gzip"
))
{
if
(
codecs
[
i
].
getName
().
equalsIgnoreCase
(
"gzip"
))
{
response
.
setEntity
(
new
GzipDecompressingEntity
(
response
.
getEntity
())
);
response
.
setEntity
(
new
GzipDecompressingEntity
(
response
.
getEntity
())
);
return
;
return
;
}
}
}
}
}
}
...
@@ -176,12 +140,13 @@ public class HCFetcher {
...
@@ -176,12 +140,13 @@ public class HCFetcher {
})
})
.
build
();
.
build
();
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
// TODO: handle exception
}
}
}
}
/**
/**
* 发送给请求
* 发送给请求
*
* @param url
* @param url
* @return
* @return
*/
*/
...
@@ -191,7 +156,8 @@ public class HCFetcher {
...
@@ -191,7 +156,8 @@ public class HCFetcher {
if
(
currentTimeMillis
-
getLastFetchTime
<
politenessDelay
)
{
if
(
currentTimeMillis
-
getLastFetchTime
<
politenessDelay
)
{
try
{
try
{
Thread
.
sleep
(
politenessDelay
-
(
currentTimeMillis
-
getLastFetchTime
));
Thread
.
sleep
(
politenessDelay
-
(
currentTimeMillis
-
getLastFetchTime
));
}
catch
(
Exception
e
)
{}
}
catch
(
Exception
e
)
{
}
}
}
getLastFetchTime
=
System
.
currentTimeMillis
();
getLastFetchTime
=
System
.
currentTimeMillis
();
...
@@ -204,26 +170,27 @@ public class HCFetcher {
...
@@ -204,26 +170,27 @@ public class HCFetcher {
entity
.
setLocation
(
url
);
entity
.
setLocation
(
url
);
try
{
try
{
if
(
httpclient
==
null
||
url
==
null
)
if
(
httpclient
==
null
||
url
==
null
)
{
return
entity
;
return
entity
;
}
LOG
.
debug
(
"----------------------------------------"
);
LOG
.
debug
(
"----------------------------------------"
);
LOG
.
debug
(
"请求网址: "
+
url
);
LOG
.
debug
(
"请求网址: "
+
url
);
LOG
.
debug
(
"请求方法: GET"
);
LOG
.
debug
(
"请求方法: GET"
);
httpget
=
new
HttpGet
(
url
);
httpget
=
new
HttpGet
(
url
);
response
=
httpclient
.
execute
(
httpget
);
response
=
httpclient
.
execute
(
httpget
);
StatusLine
statusLine
=
response
.
getStatusLine
();
StatusLine
statusLine
=
response
.
getStatusLine
();
LOG
.
debug
(
"版本状态: "
+
statusLine
);
LOG
.
debug
(
"版本状态: "
+
statusLine
);
entity
.
setStatus
(
statusLine
.
getStatusCode
());
entity
.
setStatus
(
statusLine
.
getStatusCode
());
if
(
response
.
getLastHeader
(
"Content-Encoding"
)
==
null
)
{
if
(
response
.
getLastHeader
(
"Content-Encoding"
)
==
null
)
{
LOG
.
debug
(
"Content-Encoding: NULL"
);
LOG
.
debug
(
"Content-Encoding: NULL"
);
}
else
{
}
else
{
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Encoding"
));
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Encoding"
));
}
}
if
(
response
.
getLastHeader
(
"Content-Length"
)
==
null
)
{
if
(
response
.
getLastHeader
(
"Content-Length"
)
==
null
)
{
LOG
.
debug
(
"Content-Length: NULL"
);
LOG
.
debug
(
"Content-Length: NULL"
);
}
else
{
}
else
{
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Length"
));
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Length"
));
...
@@ -232,89 +199,77 @@ public class HCFetcher {
...
@@ -232,89 +199,77 @@ public class HCFetcher {
if
(
entity
.
getStatus
()
==
HttpStatus
.
SC_OK
)
{
if
(
entity
.
getStatus
()
==
HttpStatus
.
SC_OK
)
{
HttpEntity
httpEntity
=
response
.
getEntity
();
HttpEntity
httpEntity
=
response
.
getEntity
();
// byte[] buf = EntityUtils.toByteArray(httpEntity);
entity
.
setData
(
EntityUtils
.
toByteArray
(
httpEntity
));
entity
.
setData
(
EntityUtils
.
toByteArray
(
httpEntity
));
Header
contentTypeHeader
=
httpEntity
.
getContentType
();
Header
contentTypeHeader
=
httpEntity
.
getContentType
();
if
(
contentTypeHeader
!=
null
)
{
if
(
contentTypeHeader
!=
null
)
{
entity
.
setContentType
(
contentTypeHeader
.
getValue
());
entity
.
setContentType
(
contentTypeHeader
.
getValue
());
}
}
Header
contentEncodingHeader
=
httpEntity
.
getContentEncoding
();
Header
contentEncodingHeader
=
httpEntity
.
getContentEncoding
();
if
(
contentEncodingHeader
!=
null
)
{
if
(
contentEncodingHeader
!=
null
)
{
entity
.
setContentEncoding
(
contentEncodingHeader
.
getValue
());
entity
.
setContentEncoding
(
contentEncodingHeader
.
getValue
());
}
}
entity
.
setSuccess
(
true
);
entity
.
setSuccess
(
true
);
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils
.
consume
(
httpEntity
);
EntityUtils
.
consume
(
httpEntity
);
}
}
}
catch
(
IOException
e
)
{
}
catch
(
IOException
e
)
{
// TODO Auto-generated catch block
e
.
printStackTrace
();
e
.
printStackTrace
();
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
// TODO Auto-generated catch block
e
.
printStackTrace
();
e
.
printStackTrace
();
}
finally
{
}
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
{
try
{
if
(
response
!=
null
)
{
if
(
response
!=
null
)
{
response
.
close
();
response
.
close
();
}
}
}
catch
(
Exception
e
)
{}
}
catch
(
Exception
e
)
{
}
}
}
return
entity
;
return
entity
;
}
}
}
}
public
FetchEntity
post
(
final
String
url
,
final
byte
[]
data
)
{
public
FetchEntity
post
(
final
String
url
,
final
byte
[]
data
)
{
synchronized
(
mutex
)
{
synchronized
(
mutex
)
{
long
currentTimeMillis
=
System
.
currentTimeMillis
();
long
currentTimeMillis
=
System
.
currentTimeMillis
();
if
(
currentTimeMillis
-
postLastFetchTime
<
politenessDelay
)
{
if
(
currentTimeMillis
-
postLastFetchTime
<
politenessDelay
)
{
try
{
try
{
Thread
.
sleep
(
politenessDelay
-
(
currentTimeMillis
-
postLastFetchTime
));
Thread
.
sleep
(
politenessDelay
-
(
currentTimeMillis
-
postLastFetchTime
));
}
catch
(
Exception
e
)
{}
}
catch
(
Exception
e
)
{
}
}
}
postLastFetchTime
=
System
.
currentTimeMillis
();
postLastFetchTime
=
System
.
currentTimeMillis
();
FetchEntity
entity
=
null
;
FetchEntity
entity
=
null
;
HttpPost
httppost
=
null
;
HttpPost
httppost
=
null
;
CloseableHttpResponse
response
=
null
;
CloseableHttpResponse
response
=
null
;
entity
=
new
FetchEntity
();
entity
=
new
FetchEntity
();
entity
.
setSuccess
(
false
);
entity
.
setSuccess
(
false
);
entity
.
setLocation
(
url
);
entity
.
setLocation
(
url
);
try
{
try
{
if
(
httpclient
==
null
||
url
==
null
)
if
(
httpclient
==
null
||
url
==
null
)
{
return
entity
;
return
entity
;
}
LOG
.
debug
(
"----------------------------------------"
);
LOG
.
debug
(
"----------------------------------------"
);
LOG
.
debug
(
"请求网址: "
+
url
);
LOG
.
debug
(
"请求网址: "
+
url
);
LOG
.
debug
(
"请求方法: POST"
);
LOG
.
debug
(
"请求方法: POST"
);
httppost
=
new
HttpPost
(
url
);
httppost
=
new
HttpPost
(
url
);
if
(
data
!=
null
)
{
if
(
data
!=
null
)
{
httppost
.
setEntity
(
new
ByteArrayEntity
(
data
));
httppost
.
setEntity
(
new
ByteArrayEntity
(
data
));
}
}
response
=
httpclient
.
execute
(
httppost
);
response
=
httpclient
.
execute
(
httppost
);
StatusLine
statusLine
=
response
.
getStatusLine
();
StatusLine
statusLine
=
response
.
getStatusLine
();
LOG
.
debug
(
"版本状态: "
+
statusLine
);
LOG
.
debug
(
"版本状态: "
+
statusLine
);
entity
.
setStatus
(
statusLine
.
getStatusCode
());
entity
.
setStatus
(
statusLine
.
getStatusCode
());
if
(
response
.
getLastHeader
(
"Content-Encoding"
)
==
null
)
{
if
(
response
.
getLastHeader
(
"Content-Encoding"
)
==
null
)
{
LOG
.
debug
(
"Content-Encoding: NULL"
);
LOG
.
debug
(
"Content-Encoding: NULL"
);
}
else
{
}
else
{
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Encoding"
));
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Encoding"
));
}
}
if
(
response
.
getLastHeader
(
"Content-Length"
)
==
null
)
{
if
(
response
.
getLastHeader
(
"Content-Length"
)
==
null
)
{
LOG
.
debug
(
"Content-Length: NULL"
);
LOG
.
debug
(
"Content-Length: NULL"
);
}
else
{
}
else
{
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Length"
));
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Length"
));
...
@@ -323,21 +278,16 @@ public class HCFetcher {
...
@@ -323,21 +278,16 @@ public class HCFetcher {
if
(
entity
.
getStatus
()
==
HttpStatus
.
SC_OK
)
{
if
(
entity
.
getStatus
()
==
HttpStatus
.
SC_OK
)
{
HttpEntity
httpEntity
=
response
.
getEntity
();
HttpEntity
httpEntity
=
response
.
getEntity
();
// byte[] buf = EntityUtils.toByteArray(httpEntity);
entity
.
setData
(
EntityUtils
.
toByteArray
(
httpEntity
));
entity
.
setData
(
EntityUtils
.
toByteArray
(
httpEntity
));
Header
contentTypeHeader
=
httpEntity
.
getContentType
();
Header
contentTypeHeader
=
httpEntity
.
getContentType
();
if
(
contentTypeHeader
!=
null
)
{
if
(
contentTypeHeader
!=
null
)
{
entity
.
setContentType
(
contentTypeHeader
.
getValue
());
entity
.
setContentType
(
contentTypeHeader
.
getValue
());
}
}
Header
contentEncodingHeader
=
httpEntity
.
getContentEncoding
();
Header
contentEncodingHeader
=
httpEntity
.
getContentEncoding
();
if
(
contentEncodingHeader
!=
null
)
{
if
(
contentEncodingHeader
!=
null
)
{
entity
.
setContentEncoding
(
contentEncodingHeader
.
getValue
());
entity
.
setContentEncoding
(
contentEncodingHeader
.
getValue
());
}
}
entity
.
setSuccess
(
true
);
entity
.
setSuccess
(
true
);
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils
.
consume
(
httpEntity
);
EntityUtils
.
consume
(
httpEntity
);
}
}
}
catch
(
IOException
e
)
{
}
catch
(
IOException
e
)
{
...
@@ -347,29 +297,25 @@ public class HCFetcher {
...
@@ -347,29 +297,25 @@ public class HCFetcher {
// TODO Auto-generated catch block
// TODO Auto-generated catch block
e
.
printStackTrace
();
e
.
printStackTrace
();
}
finally
{
}
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
{
try
{
if
(
response
!=
null
)
{
if
(
response
!=
null
)
{
response
.
close
();
response
.
close
();
}
}
}
catch
(
Exception
e
)
{}
}
catch
(
Exception
e
)
{
}
}
}
return
entity
;
return
entity
;
}
}
}
}
public
FetchEntity
post
(
final
String
url
,
List
<
BasicNameValuePair
>
params
,
final
byte
[]
data
)
{
public
FetchEntity
post
(
final
String
url
,
List
<
BasicNameValuePair
>
params
,
final
byte
[]
data
)
{
synchronized
(
mutex
)
{
synchronized
(
mutex
)
{
long
currentTimeMillis
=
System
.
currentTimeMillis
();
long
currentTimeMillis
=
System
.
currentTimeMillis
();
if
(
currentTimeMillis
-
postLastFetchTime
<
politenessDelay
)
{
if
(
currentTimeMillis
-
postLastFetchTime
<
politenessDelay
)
{
try
{
try
{
Thread
.
sleep
(
politenessDelay
-
(
currentTimeMillis
-
postLastFetchTime
));
Thread
.
sleep
(
politenessDelay
-
(
currentTimeMillis
-
postLastFetchTime
));
}
catch
(
Exception
e
)
{}
}
catch
(
Exception
e
)
{
}
}
}
postLastFetchTime
=
System
.
currentTimeMillis
();
postLastFetchTime
=
System
.
currentTimeMillis
();
...
@@ -382,31 +328,30 @@ public class HCFetcher {
...
@@ -382,31 +328,30 @@ public class HCFetcher {
entity
.
setLocation
(
url
);
entity
.
setLocation
(
url
);
try
{
try
{
if
(
httpclient
==
null
||
url
==
null
)
if
(
httpclient
==
null
||
url
==
null
)
{
return
entity
;
return
entity
;
}
LOG
.
debug
(
"----------------------------------------"
);
LOG
.
debug
(
"----------------------------------------"
);
LOG
.
debug
(
"请求网址: "
+
url
);
LOG
.
debug
(
"请求网址: "
+
url
);
LOG
.
debug
(
"请求方法: POST"
);
LOG
.
debug
(
"请求方法: POST"
);
httppost
=
new
HttpPost
(
url
);
httppost
=
new
HttpPost
(
url
);
if
(
params
!=
null
){
if
(
params
!=
null
)
{
httppost
.
setEntity
(
new
UrlEncodedFormEntity
(
params
,
"UTF-8"
));
httppost
.
setEntity
(
new
UrlEncodedFormEntity
(
params
,
"UTF-8"
));
// httppost.setEntity(new ByteArrayEntity(data));
}
}
response
=
httpclient
.
execute
(
httppost
);
response
=
httpclient
.
execute
(
httppost
);
StatusLine
statusLine
=
response
.
getStatusLine
();
StatusLine
statusLine
=
response
.
getStatusLine
();
LOG
.
debug
(
"版本状态: "
+
statusLine
);
LOG
.
debug
(
"版本状态: "
+
statusLine
);
entity
.
setStatus
(
statusLine
.
getStatusCode
());
entity
.
setStatus
(
statusLine
.
getStatusCode
());
if
(
response
.
getLastHeader
(
"Content-Encoding"
)
==
null
)
{
if
(
response
.
getLastHeader
(
"Content-Encoding"
)
==
null
)
{
LOG
.
debug
(
"Content-Encoding: NULL"
);
LOG
.
debug
(
"Content-Encoding: NULL"
);
}
else
{
}
else
{
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Encoding"
));
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Encoding"
));
}
}
if
(
response
.
getLastHeader
(
"Content-Length"
)
==
null
)
{
if
(
response
.
getLastHeader
(
"Content-Length"
)
==
null
)
{
LOG
.
debug
(
"Content-Length: NULL"
);
LOG
.
debug
(
"Content-Length: NULL"
);
}
else
{
}
else
{
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Length"
));
LOG
.
debug
(
response
.
getLastHeader
(
"Content-Length"
));
...
@@ -415,46 +360,34 @@ public class HCFetcher {
...
@@ -415,46 +360,34 @@ public class HCFetcher {
if
(
entity
.
getStatus
()
==
HttpStatus
.
SC_OK
)
{
if
(
entity
.
getStatus
()
==
HttpStatus
.
SC_OK
)
{
HttpEntity
httpEntity
=
response
.
getEntity
();
HttpEntity
httpEntity
=
response
.
getEntity
();
// byte[] buf = EntityUtils.toByteArray(httpEntity);
entity
.
setData
(
EntityUtils
.
toByteArray
(
httpEntity
));
entity
.
setData
(
EntityUtils
.
toByteArray
(
httpEntity
));
Header
contentTypeHeader
=
httpEntity
.
getContentType
();
Header
contentTypeHeader
=
httpEntity
.
getContentType
();
if
(
contentTypeHeader
!=
null
)
{
if
(
contentTypeHeader
!=
null
)
{
entity
.
setContentType
(
contentTypeHeader
.
getValue
());
entity
.
setContentType
(
contentTypeHeader
.
getValue
());
}
}
Header
contentEncodingHeader
=
httpEntity
.
getContentEncoding
();
Header
contentEncodingHeader
=
httpEntity
.
getContentEncoding
();
if
(
contentEncodingHeader
!=
null
)
{
if
(
contentEncodingHeader
!=
null
)
{
entity
.
setContentEncoding
(
contentEncodingHeader
.
getValue
());
entity
.
setContentEncoding
(
contentEncodingHeader
.
getValue
());
}
}
entity
.
setSuccess
(
true
);
entity
.
setSuccess
(
true
);
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils
.
consume
(
httpEntity
);
EntityUtils
.
consume
(
httpEntity
);
}
}
}
catch
(
IOException
e
)
{
}
catch
(
IOException
e
)
{
// TODO Auto-generated catch block
e
.
printStackTrace
();
e
.
printStackTrace
();
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
// TODO Auto-generated catch block
e
.
printStackTrace
();
e
.
printStackTrace
();
}
finally
{
}
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
{
try
{
if
(
response
!=
null
)
{
if
(
response
!=
null
)
{
response
.
close
();
response
.
close
();
}
}
}
catch
(
Exception
e
)
{}
}
catch
(
Exception
e
)
{
}
}
}
return
entity
;
return
entity
;
}
}
}
}
/**
/**
* 关闭资源
* 关闭资源
*/
*/
...
@@ -480,23 +413,4 @@ public class HCFetcher {
...
@@ -480,23 +413,4 @@ public class HCFetcher {
public
void
setPolitenessDelay
(
long
politenessDelay
)
{
public
void
setPolitenessDelay
(
long
politenessDelay
)
{
this
.
politenessDelay
=
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;
}
}
*/
}
}
src/com/ejweb/core/persistence/interceptor/SQLHelper.java
View file @
89564d2b
...
@@ -33,10 +33,12 @@ import java.util.regex.Pattern;
...
@@ -33,10 +33,12 @@ import java.util.regex.Pattern;
/**
/**
* SQL工具类
* SQL工具类
*
* @author poplar.yfyang / thinkgem
* @author poplar.yfyang / thinkgem
* @version 2013-8-28
* @version 2013-8-28
*/
*/
public
class
SQLHelper
{
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
* 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
...
@@ -107,7 +109,6 @@ public class SQLHelper {
...
@@ -107,7 +109,6 @@ public class SQLHelper {
countSql
=
"select count(1) from ("
+
sql
+
") tmp_count"
;
countSql
=
"select count(1) from ("
+
sql
+
") tmp_count"
;
}
else
{
}
else
{
countSql
=
"select count(1) from ("
+
removeOrders
(
sql
)
+
") tmp_count"
;
countSql
=
"select count(1) from ("
+
removeOrders
(
sql
)
+
") tmp_count"
;
// countSql = "select count(1) " + removeSelect(removeOrders(sql));
}
}
Connection
conn
=
connection
;
Connection
conn
=
connection
;
PreparedStatement
ps
=
null
;
PreparedStatement
ps
=
null
;
...
@@ -166,7 +167,7 @@ public class SQLHelper {
...
@@ -166,7 +167,7 @@ public class SQLHelper {
/**
/**
* 去除qlString的select子句。
* 去除qlString的select子句。
* @param
hql
* @param
qlString
* @return
* @return
*/
*/
@SuppressWarnings
(
"unused"
)
@SuppressWarnings
(
"unused"
)
...
@@ -177,11 +178,10 @@ public class SQLHelper {
...
@@ -177,11 +178,10 @@ public class SQLHelper {
/**
/**
* 去除hql的orderBy子句。
* 去除hql的orderBy子句。
* @param
hql
* @param
qlString
* @return
* @return
*/
*/
private
static
String
removeOrders
(
String
qlString
)
{
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
);
Matcher
m
=
p
.
matcher
(
qlString
);
StringBuffer
sb
=
new
StringBuffer
();
StringBuffer
sb
=
new
StringBuffer
();
while
(
m
.
find
())
{
while
(
m
.
find
())
{
...
...
src/com/ejweb/core/security/shiro/session/JedisSessionDAO.java
View file @
89564d2b
...
@@ -3,14 +3,12 @@
...
@@ -3,14 +3,12 @@
*/
*/
package
com
.
ejweb
.
core
.
security
.
shiro
.
session
;
package
com
.
ejweb
.
core
.
security
.
shiro
.
session
;
import
java.io.Serializable
;
import
com.ejweb.core.conf.GConstants
;
import
java.util.Collection
;
import
com.ejweb.core.utils.DateUtils
;
import
java.util.Date
;
import
com.ejweb.core.utils.JedisUtils
;
import
java.util.Map
;
import
com.ejweb.core.utils.StringUtils
;
import
java.util.Set
;
import
com.ejweb.core.web.Servlets
;
import
com.google.common.collect.Sets
;
import
javax.servlet.http.HttpServletRequest
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.UnknownSessionException
;
import
org.apache.shiro.session.UnknownSessionException
;
import
org.apache.shiro.session.mgt.SimpleSession
;
import
org.apache.shiro.session.mgt.SimpleSession
;
...
@@ -19,18 +17,18 @@ import org.apache.shiro.subject.PrincipalCollection;
...
@@ -19,18 +17,18 @@ import org.apache.shiro.subject.PrincipalCollection;
import
org.apache.shiro.subject.support.DefaultSubjectContext
;
import
org.apache.shiro.subject.support.DefaultSubjectContext
;
import
org.slf4j.Logger
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.slf4j.LoggerFactory
;
import
redis.clients.jedis.Jedis
;
import
redis.clients.jedis.Jedis
;
import
com.google.common.collect.Sets
;
import
javax.servlet.http.HttpServletRequest
;
import
com.ejweb.core.conf.GConstants
;
import
java.io.Serializable
;
import
com.ejweb.core.utils.DateUtils
;
import
java.util.Collection
;
import
com.ejweb.core.utils.JedisUtils
;
import
java.util.Date
;
import
com.ejweb.core.utils.StringUtils
;
import
java.util.Map
;
import
com.ejweb.core.web.Servlets
;
import
java.util.Set
;
/**
/**
* 自定义授权会话管理类
* 自定义授权会话管理类
*
* @author ThinkGem
* @author ThinkGem
* @version 2014-7-20
* @version 2014-7-20
*/
*/
...
@@ -47,19 +45,19 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -47,19 +45,19 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
}
}
HttpServletRequest
request
=
Servlets
.
getRequest
();
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
if
(
request
!=
null
)
{
String
uri
=
request
.
getServletPath
();
String
uri
=
request
.
getServletPath
();
// 如果是静态文件,则不更新SESSION
// 如果是静态文件,则不更新SESSION
if
(
Servlets
.
isStaticFile
(
uri
)){
if
(
Servlets
.
isStaticFile
(
uri
))
{
return
;
return
;
}
}
// 如果是视图文件,则不更新SESSION
// 如果是视图文件,则不更新SESSION
if
(
StringUtils
.
startsWith
(
uri
,
GConstants
.
getValue
(
"web.view.prefix"
))
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
;
return
;
}
}
// 手动控制不更新SESSION
// 手动控制不更新SESSION
if
(
GConstants
.
NO
.
equals
(
request
.
getParameter
(
"updateSession"
))){
if
(
GConstants
.
NO
.
equals
(
request
.
getParameter
(
"updateSession"
)))
{
return
;
return
;
}
}
}
}
...
@@ -70,14 +68,14 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -70,14 +68,14 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
jedis
=
JedisUtils
.
getResource
();
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
;
String
principalId
=
pc
!=
null
?
pc
.
getPrimaryPrincipal
().
toString
()
:
StringUtils
.
EMPTY
;
jedis
.
hset
(
sessionKeyPrefix
,
session
.
getId
().
toString
(),
principalId
+
"|"
+
session
.
getTimeout
()
+
"|"
+
session
.
getLastAccessTime
().
getTime
());
jedis
.
hset
(
sessionKeyPrefix
,
session
.
getId
().
toString
(),
principalId
+
"|"
+
session
.
getTimeout
()
+
"|"
+
session
.
getLastAccessTime
().
getTime
());
jedis
.
set
(
JedisUtils
.
getBytesKey
(
sessionKeyPrefix
+
session
.
getId
()),
JedisUtils
.
toBytes
(
session
));
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
);
jedis
.
expire
((
sessionKeyPrefix
+
session
.
getId
()),
timeoutSeconds
);
logger
.
debug
(
"update {} {}"
,
session
.
getId
(),
request
!=
null
?
request
.
getRequestURI
()
:
""
);
logger
.
debug
(
"update {} {}"
,
session
.
getId
(),
request
!=
null
?
request
.
getRequestURI
()
:
""
);
...
@@ -116,6 +114,7 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -116,6 +114,7 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
/**
/**
* 获取活动会话
* 获取活动会话
*
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
* @return
*/
*/
...
@@ -126,51 +125,51 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -126,51 +125,51 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
/**
/**
* 获取活动会话
* 获取活动会话
*
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
* @return
*/
*/
@Override
@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
();
Set
<
Session
>
sessions
=
Sets
.
newHashSet
();
Jedis
jedis
=
null
;
Jedis
jedis
=
null
;
try
{
try
{
jedis
=
JedisUtils
.
getResource
();
jedis
=
JedisUtils
.
getResource
();
Map
<
String
,
String
>
map
=
jedis
.
hgetAll
(
sessionKeyPrefix
);
Map
<
String
,
String
>
map
=
jedis
.
hgetAll
(
sessionKeyPrefix
);
for
(
Map
.
Entry
<
String
,
String
>
e
:
map
.
entrySet
()){
for
(
Map
.
Entry
<
String
,
String
>
e
:
map
.
entrySet
())
{
if
(
StringUtils
.
isNotBlank
(
e
.
getKey
())
&&
StringUtils
.
isNotBlank
(
e
.
getValue
())){
if
(
StringUtils
.
isNotBlank
(
e
.
getKey
())
&&
StringUtils
.
isNotBlank
(
e
.
getValue
()))
{
String
[]
ss
=
StringUtils
.
split
(
e
.
getValue
(),
"|"
);
String
[]
ss
=
StringUtils
.
split
(
e
.
getValue
(),
"|"
);
if
(
ss
!=
null
&&
ss
.
length
==
3
){
// jedis.exists(sessionKeyPrefix + e.getKey())){
if
(
ss
!=
null
&&
ss
.
length
==
3
)
{
// Session session = (Session)JedisUtils.toObject(jedis.get(JedisUtils.getBytesKey(sessionKeyPrefix + e.getKey())));
SimpleSession
session
=
new
SimpleSession
();
SimpleSession
session
=
new
SimpleSession
();
session
.
setId
(
e
.
getKey
());
session
.
setId
(
e
.
getKey
());
session
.
setAttribute
(
"principalId"
,
ss
[
0
]);
session
.
setAttribute
(
"principalId"
,
ss
[
0
]);
session
.
setTimeout
(
Long
.
valueOf
(
ss
[
1
]));
session
.
setTimeout
(
Long
.
valueOf
(
ss
[
1
]));
session
.
setLastAccessTime
(
new
Date
(
Long
.
valueOf
(
ss
[
2
])));
session
.
setLastAccessTime
(
new
Date
(
Long
.
valueOf
(
ss
[
2
])));
try
{
try
{
// 验证SESSION
// 验证SESSION
session
.
validate
();
session
.
validate
();
boolean
isActiveSession
=
false
;
boolean
isActiveSession
=
false
;
// 不包括离线并符合最后访问时间小于等于3分钟条件。
// 不包括离线并符合最后访问时间小于等于3分钟条件。
if
(
includeLeave
||
DateUtils
.
pastMinutes
(
session
.
getLastAccessTime
())
<=
3
){
if
(
includeLeave
||
DateUtils
.
pastMinutes
(
session
.
getLastAccessTime
())
<=
3
)
{
isActiveSession
=
true
;
isActiveSession
=
true
;
}
}
// 符合登陆者条件。
// 符合登陆者条件。
if
(
principal
!=
null
){
if
(
principal
!=
null
)
{
PrincipalCollection
pc
=
(
PrincipalCollection
)
session
.
getAttribute
(
DefaultSubjectContext
.
PRINCIPALS_SESSION_KEY
);
PrincipalCollection
pc
=
(
PrincipalCollection
)
session
.
getAttribute
(
DefaultSubjectContext
.
PRINCIPALS_SESSION_KEY
);
if
(
principal
.
toString
().
equals
(
pc
!=
null
?
pc
.
getPrimaryPrincipal
().
toString
()
:
StringUtils
.
EMPTY
)){
if
(
principal
.
toString
().
equals
(
pc
!=
null
?
pc
.
getPrimaryPrincipal
().
toString
()
:
StringUtils
.
EMPTY
))
{
isActiveSession
=
true
;
isActiveSession
=
true
;
}
}
}
}
// 过滤掉的SESSION
// 过滤掉的SESSION
if
(
filterSession
!=
null
&&
filterSession
.
getId
().
equals
(
session
.
getId
())){
if
(
filterSession
!=
null
&&
filterSession
.
getId
().
equals
(
session
.
getId
()))
{
isActiveSession
=
false
;
isActiveSession
=
false
;
}
}
if
(
isActiveSession
){
if
(
isActiveSession
)
{
sessions
.
add
(
session
);
sessions
.
add
(
session
);
}
}
...
@@ -181,12 +180,12 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -181,12 +180,12 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
}
}
}
}
// 存储的SESSION不符合规则
// 存储的SESSION不符合规则
else
{
else
{
jedis
.
hdel
(
sessionKeyPrefix
,
e
.
getKey
());
jedis
.
hdel
(
sessionKeyPrefix
,
e
.
getKey
());
}
}
}
}
// 存储的SESSION无Value
// 存储的SESSION无Value
else
if
(
StringUtils
.
isNotBlank
(
e
.
getKey
())){
else
if
(
StringUtils
.
isNotBlank
(
e
.
getKey
()))
{
jedis
.
hdel
(
sessionKeyPrefix
,
e
.
getKey
());
jedis
.
hdel
(
sessionKeyPrefix
,
e
.
getKey
());
}
}
}
}
...
@@ -202,10 +201,10 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -202,10 +201,10 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
@Override
@Override
protected
Serializable
doCreate
(
Session
session
)
{
protected
Serializable
doCreate
(
Session
session
)
{
HttpServletRequest
request
=
Servlets
.
getRequest
();
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
if
(
request
!=
null
)
{
String
uri
=
request
.
getServletPath
();
String
uri
=
request
.
getServletPath
();
// 如果是静态文件,则不创建SESSION
// 如果是静态文件,则不创建SESSION
if
(
Servlets
.
isStaticFile
(
uri
)){
if
(
Servlets
.
isStaticFile
(
uri
))
{
return
null
;
return
null
;
}
}
}
}
...
@@ -220,15 +219,15 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -220,15 +219,15 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
Session
s
=
null
;
Session
s
=
null
;
HttpServletRequest
request
=
Servlets
.
getRequest
();
HttpServletRequest
request
=
Servlets
.
getRequest
();
if
(
request
!=
null
){
if
(
request
!=
null
)
{
String
uri
=
request
.
getServletPath
();
String
uri
=
request
.
getServletPath
();
// 如果是静态文件,则不获取SESSION
// 如果是静态文件,则不获取SESSION
if
(
Servlets
.
isStaticFile
(
uri
)){
if
(
Servlets
.
isStaticFile
(
uri
))
{
return
null
;
return
null
;
}
}
s
=
(
Session
)
request
.
getAttribute
(
"session_"
+
sessionId
);
s
=
(
Session
)
request
.
getAttribute
(
"session_"
+
sessionId
);
}
}
if
(
s
!=
null
){
if
(
s
!=
null
)
{
return
s
;
return
s
;
}
}
...
@@ -236,19 +235,16 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -236,19 +235,16 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
Jedis
jedis
=
null
;
Jedis
jedis
=
null
;
try
{
try
{
jedis
=
JedisUtils
.
getResource
();
jedis
=
JedisUtils
.
getResource
();
// if (jedis.exists(sessionKeyPrefix + sessionId)){
session
=
(
Session
)
JedisUtils
.
toObject
(
jedis
.
get
(
session
=
(
Session
)
JedisUtils
.
toObject
(
jedis
.
get
(
JedisUtils
.
getBytesKey
(
sessionKeyPrefix
+
sessionId
)));
JedisUtils
.
getBytesKey
(
sessionKeyPrefix
+
sessionId
)));
// }
logger
.
debug
(
"doReadSession {} {}"
,
sessionId
,
request
!=
null
?
request
.
getRequestURI
()
:
""
);
logger
.
debug
(
"doReadSession {} {}"
,
sessionId
,
request
!=
null
?
request
.
getRequestURI
()
:
""
);
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
logger
.
error
(
"doReadSession {} {}"
,
sessionId
,
request
!=
null
?
request
.
getRequestURI
()
:
""
,
e
);
logger
.
error
(
"doReadSession {} {}"
,
sessionId
,
request
!=
null
?
request
.
getRequestURI
()
:
""
,
e
);
}
finally
{
}
finally
{
JedisUtils
.
returnResource
(
jedis
);
JedisUtils
.
returnResource
(
jedis
);
}
}
if
(
request
!=
null
&&
session
!=
null
)
{
if
(
request
!=
null
&&
session
!=
null
){
request
.
setAttribute
(
"session_"
+
sessionId
,
session
);
request
.
setAttribute
(
"session_"
+
sessionId
,
session
);
}
}
return
session
;
return
session
;
...
@@ -256,9 +252,9 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
...
@@ -256,9 +252,9 @@ public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
@Override
@Override
public
Session
readSession
(
Serializable
sessionId
)
throws
UnknownSessionException
{
public
Session
readSession
(
Serializable
sessionId
)
throws
UnknownSessionException
{
try
{
try
{
return
super
.
readSession
(
sessionId
);
return
super
.
readSession
(
sessionId
);
}
catch
(
UnknownSessionException
e
)
{
}
catch
(
UnknownSessionException
e
)
{
return
null
;
return
null
;
}
}
}
}
...
...
src/com/ejweb/core/utils/IdGen.java
View file @
89564d2b
...
@@ -3,18 +3,18 @@
...
@@ -3,18 +3,18 @@
*/
*/
package
com
.
ejweb
.
core
.
utils
;
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.activiti.engine.impl.cfg.IdGenerator
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.mgt.eis.SessionIdGenerator
;
import
org.apache.shiro.session.mgt.eis.SessionIdGenerator
;
import
org.springframework.context.annotation.Lazy
;
import
org.springframework.context.annotation.Lazy
;
import
org.springframework.stereotype.Service
;
import
org.springframework.stereotype.Service
;
import
java.io.Serializable
;
import
java.security.SecureRandom
;
/**
/**
* 封装各种生成唯一性ID算法的工具类.
* 封装各种生成唯一性ID算法的工具类.
*
* @author ThinkGem
* @author ThinkGem
* @version 2013-01-15
* @version 2013-01-15
*/
*/
...
@@ -29,7 +29,6 @@ public class IdGen implements IdGenerator, SessionIdGenerator {
...
@@ -29,7 +29,6 @@ public class IdGen implements IdGenerator, SessionIdGenerator {
*/
*/
public
static
String
uuid
()
{
public
static
String
uuid
()
{
return
IdWorker
.
getNextId
();
return
IdWorker
.
getNextId
();
// return UUID.randomUUID().toString().replaceAll("-", "");
}
}
/**
/**
...
@@ -54,22 +53,11 @@ public class IdGen implements IdGenerator, SessionIdGenerator {
...
@@ -54,22 +53,11 @@ public class IdGen implements IdGenerator, SessionIdGenerator {
@Override
@Override
public
String
getNextId
()
{
public
String
getNextId
()
{
return
IdWorker
.
getNextId
();
return
IdWorker
.
getNextId
();
// return IdGen.uuid();
}
}
@Override
@Override
public
Serializable
generateId
(
Session
session
)
{
public
Serializable
generateId
(
Session
session
)
{
return
IdWorker
.
getNextId
();
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));
// }
// }
}
}
src/com/ejweb/core/utils/JedisUtils.java
View file @
89564d2b
...
@@ -3,22 +3,20 @@
...
@@ -3,22 +3,20 @@
*/
*/
package
com
.
ejweb
.
core
.
utils
;
package
com
.
ejweb
.
core
.
utils
;
import
java.util.List
;
import
com.ejweb.core.conf.GConstants
;
import
java.util.Map
;
import
java.util.Set
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.google.common.collect.Lists
;
import
com.google.common.collect.Lists
;
import
com.google.common.collect.Maps
;
import
com.google.common.collect.Maps
;
import
com.google.common.collect.Sets
;
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.Jedis
;
import
redis.clients.jedis.JedisPool
;
import
redis.clients.jedis.JedisPool
;
import
redis.clients.jedis.exceptions.JedisException
;
import
redis.clients.jedis.exceptions.JedisException
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.Set
;
/**
/**
* Jedis Cache 工具类
* Jedis Cache 工具类
*
*
...
@@ -35,6 +33,7 @@ public class JedisUtils {
...
@@ -35,6 +33,7 @@ public class JedisUtils {
/**
/**
* 获取缓存
* 获取缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -58,6 +57,7 @@ public class JedisUtils {
...
@@ -58,6 +57,7 @@ public class JedisUtils {
/**
/**
* 获取缓存
* 获取缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -80,6 +80,7 @@ public class JedisUtils {
...
@@ -80,6 +80,7 @@ public class JedisUtils {
/**
/**
* 设置缓存
* 设置缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -105,6 +106,7 @@ public class JedisUtils {
...
@@ -105,6 +106,7 @@ public class JedisUtils {
/**
/**
* 设置缓存
* 设置缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -130,6 +132,7 @@ public class JedisUtils {
...
@@ -130,6 +132,7 @@ public class JedisUtils {
/**
/**
* 获取List缓存
* 获取List缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -152,6 +155,7 @@ public class JedisUtils {
...
@@ -152,6 +155,7 @@ public class JedisUtils {
/**
/**
* 获取List缓存
* 获取List缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -163,7 +167,7 @@ public class JedisUtils {
...
@@ -163,7 +167,7 @@ public class JedisUtils {
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
List
<
byte
[]>
list
=
jedis
.
lrange
(
getBytesKey
(
key
),
0
,
-
1
);
List
<
byte
[]>
list
=
jedis
.
lrange
(
getBytesKey
(
key
),
0
,
-
1
);
value
=
Lists
.
newArrayList
();
value
=
Lists
.
newArrayList
();
for
(
byte
[]
bs
:
list
){
for
(
byte
[]
bs
:
list
)
{
value
.
add
(
toObject
(
bs
));
value
.
add
(
toObject
(
bs
));
}
}
logger
.
debug
(
"getObjectList {} = {}"
,
key
,
value
);
logger
.
debug
(
"getObjectList {} = {}"
,
key
,
value
);
...
@@ -178,6 +182,7 @@ public class JedisUtils {
...
@@ -178,6 +182,7 @@ public class JedisUtils {
/**
/**
* 设置List缓存
* 设置List缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -191,7 +196,7 @@ public class JedisUtils {
...
@@ -191,7 +196,7 @@ public class JedisUtils {
if
(
jedis
.
exists
(
key
))
{
if
(
jedis
.
exists
(
key
))
{
jedis
.
del
(
key
);
jedis
.
del
(
key
);
}
}
result
=
jedis
.
rpush
(
key
,
(
String
[])
value
.
toArray
());
result
=
jedis
.
rpush
(
key
,
(
String
[])
value
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
jedis
.
expire
(
key
,
cacheSeconds
);
}
}
...
@@ -206,6 +211,7 @@ public class JedisUtils {
...
@@ -206,6 +211,7 @@ public class JedisUtils {
/**
/**
* 设置List缓存
* 设置List缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -220,10 +226,10 @@ public class JedisUtils {
...
@@ -220,10 +226,10 @@ public class JedisUtils {
jedis
.
del
(
key
);
jedis
.
del
(
key
);
}
}
List
<
byte
[]>
list
=
Lists
.
newArrayList
();
List
<
byte
[]>
list
=
Lists
.
newArrayList
();
for
(
Object
o
:
value
){
for
(
Object
o
:
value
)
{
list
.
add
(
toBytes
(
o
));
list
.
add
(
toBytes
(
o
));
}
}
result
=
jedis
.
rpush
(
getBytesKey
(
key
),
(
byte
[][])
list
.
toArray
());
result
=
jedis
.
rpush
(
getBytesKey
(
key
),
(
byte
[][])
list
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
jedis
.
expire
(
key
,
cacheSeconds
);
}
}
...
@@ -238,6 +244,7 @@ public class JedisUtils {
...
@@ -238,6 +244,7 @@ public class JedisUtils {
/**
/**
* 向List缓存中添加值
* 向List缓存中添加值
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @return
* @return
...
@@ -259,6 +266,7 @@ public class JedisUtils {
...
@@ -259,6 +266,7 @@ public class JedisUtils {
/**
/**
* 向List缓存中添加值
* 向List缓存中添加值
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @return
* @return
...
@@ -269,10 +277,10 @@ public class JedisUtils {
...
@@ -269,10 +277,10 @@ public class JedisUtils {
try
{
try
{
jedis
=
getResource
();
jedis
=
getResource
();
List
<
byte
[]>
list
=
Lists
.
newArrayList
();
List
<
byte
[]>
list
=
Lists
.
newArrayList
();
for
(
Object
o
:
value
){
for
(
Object
o
:
value
)
{
list
.
add
(
toBytes
(
o
));
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
);
logger
.
debug
(
"listObjectAdd {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
logger
.
warn
(
"listObjectAdd {} = {}"
,
key
,
value
,
e
);
logger
.
warn
(
"listObjectAdd {} = {}"
,
key
,
value
,
e
);
...
@@ -284,6 +292,7 @@ public class JedisUtils {
...
@@ -284,6 +292,7 @@ public class JedisUtils {
/**
/**
* 获取缓存
* 获取缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -306,6 +315,7 @@ public class JedisUtils {
...
@@ -306,6 +315,7 @@ public class JedisUtils {
/**
/**
* 获取缓存
* 获取缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -317,7 +327,7 @@ public class JedisUtils {
...
@@ -317,7 +327,7 @@ public class JedisUtils {
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
value
=
Sets
.
newHashSet
();
value
=
Sets
.
newHashSet
();
Set
<
byte
[]>
set
=
jedis
.
smembers
(
getBytesKey
(
key
));
Set
<
byte
[]>
set
=
jedis
.
smembers
(
getBytesKey
(
key
));
for
(
byte
[]
bs
:
set
){
for
(
byte
[]
bs
:
set
)
{
value
.
add
(
toObject
(
bs
));
value
.
add
(
toObject
(
bs
));
}
}
logger
.
debug
(
"getObjectSet {} = {}"
,
key
,
value
);
logger
.
debug
(
"getObjectSet {} = {}"
,
key
,
value
);
...
@@ -332,6 +342,7 @@ public class JedisUtils {
...
@@ -332,6 +342,7 @@ public class JedisUtils {
/**
/**
* 设置Set缓存
* 设置Set缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -345,7 +356,7 @@ public class JedisUtils {
...
@@ -345,7 +356,7 @@ public class JedisUtils {
if
(
jedis
.
exists
(
key
))
{
if
(
jedis
.
exists
(
key
))
{
jedis
.
del
(
key
);
jedis
.
del
(
key
);
}
}
result
=
jedis
.
sadd
(
key
,
(
String
[])
value
.
toArray
());
result
=
jedis
.
sadd
(
key
,
(
String
[])
value
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
jedis
.
expire
(
key
,
cacheSeconds
);
}
}
...
@@ -360,6 +371,7 @@ public class JedisUtils {
...
@@ -360,6 +371,7 @@ public class JedisUtils {
/**
/**
* 设置Set缓存
* 设置Set缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -374,10 +386,10 @@ public class JedisUtils {
...
@@ -374,10 +386,10 @@ public class JedisUtils {
jedis
.
del
(
key
);
jedis
.
del
(
key
);
}
}
Set
<
byte
[]>
set
=
Sets
.
newHashSet
();
Set
<
byte
[]>
set
=
Sets
.
newHashSet
();
for
(
Object
o
:
value
){
for
(
Object
o
:
value
)
{
set
.
add
(
toBytes
(
o
));
set
.
add
(
toBytes
(
o
));
}
}
result
=
jedis
.
sadd
(
getBytesKey
(
key
),
(
byte
[][])
set
.
toArray
());
result
=
jedis
.
sadd
(
getBytesKey
(
key
),
(
byte
[][])
set
.
toArray
());
if
(
cacheSeconds
!=
0
)
{
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
jedis
.
expire
(
key
,
cacheSeconds
);
}
}
...
@@ -392,6 +404,7 @@ public class JedisUtils {
...
@@ -392,6 +404,7 @@ public class JedisUtils {
/**
/**
* 向Set缓存中添加值
* 向Set缓存中添加值
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @return
* @return
...
@@ -413,6 +426,7 @@ public class JedisUtils {
...
@@ -413,6 +426,7 @@ public class JedisUtils {
/**
/**
* 向Set缓存中添加值
* 向Set缓存中添加值
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @return
* @return
...
@@ -423,10 +437,10 @@ public class JedisUtils {
...
@@ -423,10 +437,10 @@ public class JedisUtils {
try
{
try
{
jedis
=
getResource
();
jedis
=
getResource
();
Set
<
byte
[]>
set
=
Sets
.
newHashSet
();
Set
<
byte
[]>
set
=
Sets
.
newHashSet
();
for
(
Object
o
:
value
){
for
(
Object
o
:
value
)
{
set
.
add
(
toBytes
(
o
));
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
);
logger
.
debug
(
"setSetObjectAdd {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
logger
.
warn
(
"setSetObjectAdd {} = {}"
,
key
,
value
,
e
);
logger
.
warn
(
"setSetObjectAdd {} = {}"
,
key
,
value
,
e
);
...
@@ -438,6 +452,7 @@ public class JedisUtils {
...
@@ -438,6 +452,7 @@ public class JedisUtils {
/**
/**
* 获取Map缓存
* 获取Map缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -460,6 +475,7 @@ public class JedisUtils {
...
@@ -460,6 +475,7 @@ public class JedisUtils {
/**
/**
* 获取Map缓存
* 获取Map缓存
*
* @param key 键
* @param key 键
* @return 值
* @return 值
*/
*/
...
@@ -471,7 +487,7 @@ public class JedisUtils {
...
@@ -471,7 +487,7 @@ public class JedisUtils {
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
value
=
Maps
.
newHashMap
();
value
=
Maps
.
newHashMap
();
Map
<
byte
[],
byte
[]>
map
=
jedis
.
hgetAll
(
getBytesKey
(
key
));
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
()));
value
.
put
(
StringUtils
.
toString
(
e
.
getKey
()),
toObject
(
e
.
getValue
()));
}
}
logger
.
debug
(
"getObjectMap {} = {}"
,
key
,
value
);
logger
.
debug
(
"getObjectMap {} = {}"
,
key
,
value
);
...
@@ -486,6 +502,7 @@ public class JedisUtils {
...
@@ -486,6 +502,7 @@ public class JedisUtils {
/**
/**
* 设置Map缓存
* 设置Map缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -514,6 +531,7 @@ public class JedisUtils {
...
@@ -514,6 +531,7 @@ public class JedisUtils {
/**
/**
* 设置Map缓存
* 设置Map缓存
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @param cacheSeconds 超时时间,0为不超时
...
@@ -528,10 +546,10 @@ public class JedisUtils {
...
@@ -528,10 +546,10 @@ public class JedisUtils {
jedis
.
del
(
key
);
jedis
.
del
(
key
);
}
}
Map
<
byte
[],
byte
[]>
map
=
Maps
.
newHashMap
();
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
()));
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
)
{
if
(
cacheSeconds
!=
0
)
{
jedis
.
expire
(
key
,
cacheSeconds
);
jedis
.
expire
(
key
,
cacheSeconds
);
}
}
...
@@ -546,6 +564,7 @@ public class JedisUtils {
...
@@ -546,6 +564,7 @@ public class JedisUtils {
/**
/**
* 向Map缓存中添加值
* 向Map缓存中添加值
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @return
* @return
...
@@ -567,6 +586,7 @@ public class JedisUtils {
...
@@ -567,6 +586,7 @@ public class JedisUtils {
/**
/**
* 向Map缓存中添加值
* 向Map缓存中添加值
*
* @param key 键
* @param key 键
* @param value 值
* @param value 值
* @return
* @return
...
@@ -577,10 +597,10 @@ public class JedisUtils {
...
@@ -577,10 +597,10 @@ public class JedisUtils {
try
{
try
{
jedis
=
getResource
();
jedis
=
getResource
();
Map
<
byte
[],
byte
[]>
map
=
Maps
.
newHashMap
();
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
()));
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
);
logger
.
debug
(
"mapObjectPut {} = {}"
,
key
,
value
);
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
logger
.
warn
(
"mapObjectPut {} = {}"
,
key
,
value
,
e
);
logger
.
warn
(
"mapObjectPut {} = {}"
,
key
,
value
,
e
);
...
@@ -592,8 +612,9 @@ public class JedisUtils {
...
@@ -592,8 +612,9 @@ public class JedisUtils {
/**
/**
* 移除Map缓存中的值
* 移除Map缓存中的值
*
* @param key 键
* @param key 键
* @param
value
值
* @param
mapKey
值
* @return
* @return
*/
*/
public
static
long
mapRemove
(
String
key
,
String
mapKey
)
{
public
static
long
mapRemove
(
String
key
,
String
mapKey
)
{
...
@@ -613,8 +634,9 @@ public class JedisUtils {
...
@@ -613,8 +634,9 @@ public class JedisUtils {
/**
/**
* 移除Map缓存中的值
* 移除Map缓存中的值
*
* @param key 键
* @param key 键
* @param
value
值
* @param
mapKey
值
* @return
* @return
*/
*/
public
static
long
mapObjectRemove
(
String
key
,
String
mapKey
)
{
public
static
long
mapObjectRemove
(
String
key
,
String
mapKey
)
{
...
@@ -634,8 +656,9 @@ public class JedisUtils {
...
@@ -634,8 +656,9 @@ public class JedisUtils {
/**
/**
* 判断Map缓存中的Key是否存在
* 判断Map缓存中的Key是否存在
*
* @param key 键
* @param key 键
* @param
value
值
* @param
mapKey
值
* @return
* @return
*/
*/
public
static
boolean
mapExists
(
String
key
,
String
mapKey
)
{
public
static
boolean
mapExists
(
String
key
,
String
mapKey
)
{
...
@@ -655,8 +678,9 @@ public class JedisUtils {
...
@@ -655,8 +678,9 @@ public class JedisUtils {
/**
/**
* 判断Map缓存中的Key是否存在
* 判断Map缓存中的Key是否存在
*
* @param key 键
* @param key 键
* @param
value
值
* @param
mapKey
值
* @return
* @return
*/
*/
public
static
boolean
mapObjectExists
(
String
key
,
String
mapKey
)
{
public
static
boolean
mapObjectExists
(
String
key
,
String
mapKey
)
{
...
@@ -676,6 +700,7 @@ public class JedisUtils {
...
@@ -676,6 +700,7 @@ public class JedisUtils {
/**
/**
* 删除缓存
* 删除缓存
*
* @param key 键
* @param key 键
* @return
* @return
*/
*/
...
@@ -684,10 +709,10 @@ public class JedisUtils {
...
@@ -684,10 +709,10 @@ public class JedisUtils {
Jedis
jedis
=
null
;
Jedis
jedis
=
null
;
try
{
try
{
jedis
=
getResource
();
jedis
=
getResource
();
if
(
jedis
.
exists
(
key
)){
if
(
jedis
.
exists
(
key
))
{
result
=
jedis
.
del
(
key
);
result
=
jedis
.
del
(
key
);
logger
.
debug
(
"del {}"
,
key
);
logger
.
debug
(
"del {}"
,
key
);
}
else
{
}
else
{
logger
.
debug
(
"del {} not exists"
,
key
);
logger
.
debug
(
"del {} not exists"
,
key
);
}
}
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
...
@@ -700,6 +725,7 @@ public class JedisUtils {
...
@@ -700,6 +725,7 @@ public class JedisUtils {
/**
/**
* 删除缓存
* 删除缓存
*
* @param key 键
* @param key 键
* @return
* @return
*/
*/
...
@@ -708,10 +734,10 @@ public class JedisUtils {
...
@@ -708,10 +734,10 @@ public class JedisUtils {
Jedis
jedis
=
null
;
Jedis
jedis
=
null
;
try
{
try
{
jedis
=
getResource
();
jedis
=
getResource
();
if
(
jedis
.
exists
(
getBytesKey
(
key
))){
if
(
jedis
.
exists
(
getBytesKey
(
key
)))
{
result
=
jedis
.
del
(
getBytesKey
(
key
));
result
=
jedis
.
del
(
getBytesKey
(
key
));
logger
.
debug
(
"delObject {}"
,
key
);
logger
.
debug
(
"delObject {}"
,
key
);
}
else
{
}
else
{
logger
.
debug
(
"delObject {} not exists"
,
key
);
logger
.
debug
(
"delObject {} not exists"
,
key
);
}
}
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
...
@@ -724,6 +750,7 @@ public class JedisUtils {
...
@@ -724,6 +750,7 @@ public class JedisUtils {
/**
/**
* 缓存是否存在
* 缓存是否存在
*
* @param key 键
* @param key 键
* @return
* @return
*/
*/
...
@@ -744,6 +771,7 @@ public class JedisUtils {
...
@@ -744,6 +771,7 @@ public class JedisUtils {
/**
/**
* 缓存是否存在
* 缓存是否存在
*
* @param key 键
* @param key 键
* @return
* @return
*/
*/
...
@@ -764,6 +792,7 @@ public class JedisUtils {
...
@@ -764,6 +792,7 @@ public class JedisUtils {
/**
/**
* 获取资源
* 获取资源
*
* @return
* @return
* @throws JedisException
* @throws JedisException
*/
*/
...
@@ -771,7 +800,6 @@ public class JedisUtils {
...
@@ -771,7 +800,6 @@ public class JedisUtils {
Jedis
jedis
=
null
;
Jedis
jedis
=
null
;
try
{
try
{
jedis
=
jedisPool
.
getResource
();
jedis
=
jedisPool
.
getResource
();
// logger.debug("getResource.", jedis);
}
catch
(
JedisException
e
)
{
}
catch
(
JedisException
e
)
{
logger
.
warn
(
"getResource."
,
e
);
logger
.
warn
(
"getResource."
,
e
);
returnBrokenResource
(
jedis
);
returnBrokenResource
(
jedis
);
...
@@ -782,8 +810,8 @@ public class JedisUtils {
...
@@ -782,8 +810,8 @@ public class JedisUtils {
/**
/**
* 归还资源
* 归还资源
*
* @param jedis
* @param jedis
* @param isBroken
*/
*/
public
static
void
returnBrokenResource
(
Jedis
jedis
)
{
public
static
void
returnBrokenResource
(
Jedis
jedis
)
{
if
(
jedis
!=
null
)
{
if
(
jedis
!=
null
)
{
...
@@ -793,8 +821,8 @@ public class JedisUtils {
...
@@ -793,8 +821,8 @@ public class JedisUtils {
/**
/**
* 释放资源
* 释放资源
*
* @param jedis
* @param jedis
* @param isBroken
*/
*/
public
static
void
returnResource
(
Jedis
jedis
)
{
public
static
void
returnResource
(
Jedis
jedis
)
{
if
(
jedis
!=
null
)
{
if
(
jedis
!=
null
)
{
...
@@ -804,32 +832,35 @@ public class JedisUtils {
...
@@ -804,32 +832,35 @@ public class JedisUtils {
/**
/**
* 获取byte[]类型Key
* 获取byte[]类型Key
* @param key
*
* @param object
* @return
* @return
*/
*/
public
static
byte
[]
getBytesKey
(
Object
object
){
public
static
byte
[]
getBytesKey
(
Object
object
)
{
if
(
object
instanceof
String
)
{
if
(
object
instanceof
String
)
{
return
StringUtils
.
getBytes
((
String
)
object
);
return
StringUtils
.
getBytes
((
String
)
object
);
}
else
{
}
else
{
return
ObjectUtils
.
serialize
(
object
);
return
ObjectUtils
.
serialize
(
object
);
}
}
}
}
/**
/**
* Object转换byte[]类型
* Object转换byte[]类型
* @param key
*
* @param object
* @return
* @return
*/
*/
public
static
byte
[]
toBytes
(
Object
object
){
public
static
byte
[]
toBytes
(
Object
object
)
{
return
ObjectUtils
.
serialize
(
object
);
return
ObjectUtils
.
serialize
(
object
);
}
}
/**
/**
* byte[]型转换Object
* byte[]型转换Object
* @param key
*
* @param bytes
* @return
* @return
*/
*/
public
static
Object
toObject
(
byte
[]
bytes
){
public
static
Object
toObject
(
byte
[]
bytes
)
{
return
ObjectUtils
.
unserialize
(
bytes
);
return
ObjectUtils
.
unserialize
(
bytes
);
}
}
...
...
src/com/ejweb/core/utils/PathFormatUtils.java
View file @
89564d2b
...
@@ -6,7 +6,7 @@ import java.util.regex.Matcher;
...
@@ -6,7 +6,7 @@ import java.util.regex.Matcher;
import
java.util.regex.Pattern
;
import
java.util.regex.Pattern
;
public
class
PathFormatUtils
{
public
class
PathFormatUtils
{
private
static
final
Pattern
pattern
=
Pattern
.
compile
(
"\\{([^\\}]+)\\}"
,
Pattern
.
CASE_INSENSITIVE
);
private
static
final
String
TIME
=
"time"
;
private
static
final
String
TIME
=
"time"
;
private
static
final
String
FULL_YEAR
=
"yyyy"
;
private
static
final
String
FULL_YEAR
=
"yyyy"
;
private
static
final
String
YEAR
=
"yy"
;
private
static
final
String
YEAR
=
"yy"
;
...
@@ -19,139 +19,108 @@ public class PathFormatUtils {
...
@@ -19,139 +19,108 @@ public class PathFormatUtils {
private
static
Date
currentDate
=
null
;
private
static
Date
currentDate
=
null
;
public
static
String
parse
(
String
input
)
{
public
static
String
parse
(
String
input
)
{
Pattern
pattern
=
Pattern
.
compile
(
"\\{([^\\}]+)\\}"
,
Pattern
.
CASE_INSENSITIVE
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
PathFormatUtils
.
currentDate
=
new
Date
();
PathFormatUtils
.
currentDate
=
new
Date
();
StringBuffer
sb
=
new
StringBuffer
();
StringBuffer
sb
=
new
StringBuffer
();
while
(
matcher
.
find
())
{
while
(
matcher
.
find
()
)
{
matcher
.
appendReplacement
(
sb
,
PathFormatUtils
.
getString
(
matcher
.
group
(
1
)));
matcher
.
appendReplacement
(
sb
,
PathFormatUtils
.
getString
(
matcher
.
group
(
1
)
)
);
}
}
matcher
.
appendTail
(
sb
);
matcher
.
appendTail
(
sb
);
return
sb
.
toString
();
return
sb
.
toString
();
}
}
/**
/**
* 格式化路径, 把windows路径替换成标准路径
* 格式化路径, 把windows路径替换成标准路径
*
* @param input 待格式化的路径
* @param input 待格式化的路径
* @return 格式化后的路径
* @return 格式化后的路径
*/
*/
public
static
String
format
(
String
input
)
{
public
static
String
format
(
String
input
)
{
return
input
.
replace
(
"\\"
,
"/"
);
return
input
.
replace
(
"\\"
,
"/"
);
}
}
public
static
String
parse
(
String
input
,
String
filename
)
{
public
static
String
parse
(
String
input
,
String
filename
)
{
Pattern
pattern
=
Pattern
.
compile
(
"\\{([^\\}]+)\\}"
,
Pattern
.
CASE_INSENSITIVE
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
Matcher
matcher
=
pattern
.
matcher
(
input
);
String
matchStr
=
null
;
String
matchStr
=
null
;
PathFormatUtils
.
currentDate
=
new
Date
();
PathFormatUtils
.
currentDate
=
new
Date
();
StringBuffer
sb
=
new
StringBuffer
();
StringBuffer
sb
=
new
StringBuffer
();
while
(
matcher
.
find
())
{
while
(
matcher
.
find
()
)
{
matchStr
=
matcher
.
group
(
1
);
if
(
matchStr
.
indexOf
(
"filename"
)
!=
-
1
)
{
matchStr
=
matcher
.
group
(
1
);
filename
=
filename
.
replace
(
"$"
,
"\\$"
).
replaceAll
(
"[\\/:*?\"<>|]"
,
""
);
if
(
matchStr
.
indexOf
(
"filename"
)
!=
-
1
)
{
matcher
.
appendReplacement
(
sb
,
filename
);
filename
=
filename
.
replace
(
"$"
,
"\\$"
).
replaceAll
(
"[\\/:*?\"<>|]"
,
""
);
matcher
.
appendReplacement
(
sb
,
filename
);
}
else
{
}
else
{
matcher
.
appendReplacement
(
sb
,
PathFormatUtils
.
getString
(
matchStr
)
);
matcher
.
appendReplacement
(
sb
,
PathFormatUtils
.
getString
(
matchStr
)
);
}
}
}
}
matcher
.
appendTail
(
sb
);
matcher
.
appendTail
(
sb
);
return
sb
.
toString
();
return
sb
.
toString
();
}
}
private
static
String
getString
(
String
pattern
)
{
private
static
String
getString
(
String
pattern
)
{
pattern
=
pattern
.
toLowerCase
();
pattern
=
pattern
.
toLowerCase
();
// time 处理
// time 处理
if
(
pattern
.
indexOf
(
PathFormatUtils
.
TIME
)
!=
-
1
)
{
if
(
pattern
.
indexOf
(
PathFormatUtils
.
TIME
)
!=
-
1
)
{
return
PathFormatUtils
.
getTimestamp
();
return
PathFormatUtils
.
getTimestamp
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
FULL_YEAR
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
FULL_YEAR
)
!=
-
1
)
{
return
PathFormatUtils
.
getFullYear
();
return
PathFormatUtils
.
getFullYear
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
YEAR
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
YEAR
)
!=
-
1
)
{
return
PathFormatUtils
.
getYear
();
return
PathFormatUtils
.
getYear
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
MONTH
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
MONTH
)
!=
-
1
)
{
return
PathFormatUtils
.
getMonth
();
return
PathFormatUtils
.
getMonth
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
DAY
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
DAY
)
!=
-
1
)
{
return
PathFormatUtils
.
getDay
();
return
PathFormatUtils
.
getDay
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
HOUR
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
HOUR
)
!=
-
1
)
{
return
PathFormatUtils
.
getHour
();
return
PathFormatUtils
.
getHour
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
MINUTE
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
MINUTE
)
!=
-
1
)
{
return
PathFormatUtils
.
getMinute
();
return
PathFormatUtils
.
getMinute
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
SECOND
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
SECOND
)
!=
-
1
)
{
return
PathFormatUtils
.
getSecond
();
return
PathFormatUtils
.
getSecond
();
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
RAND
)
!=
-
1
)
{
}
else
if
(
pattern
.
indexOf
(
PathFormatUtils
.
RAND
)
!=
-
1
)
{
return
PathFormatUtils
.
getRandom
(
pattern
);
return
PathFormatUtils
.
getRandom
(
pattern
);
}
}
return
pattern
;
return
pattern
;
}
}
private
static
String
getTimestamp
()
{
private
static
String
getTimestamp
()
{
return
System
.
currentTimeMillis
()
+
""
;
return
System
.
currentTimeMillis
()
+
""
;
}
}
private
static
String
getFullYear
()
{
private
static
String
getFullYear
()
{
return
new
SimpleDateFormat
(
"yyyy"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"yyyy"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getYear
()
{
private
static
String
getYear
()
{
return
new
SimpleDateFormat
(
"yy"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"yy"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getMonth
()
{
private
static
String
getMonth
()
{
return
new
SimpleDateFormat
(
"MM"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"MM"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getDay
()
{
private
static
String
getDay
()
{
return
new
SimpleDateFormat
(
"dd"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"dd"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getHour
()
{
private
static
String
getHour
()
{
return
new
SimpleDateFormat
(
"HH"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"HH"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getMinute
()
{
private
static
String
getMinute
()
{
return
new
SimpleDateFormat
(
"mm"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"mm"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getSecond
()
{
private
static
String
getSecond
()
{
return
new
SimpleDateFormat
(
"ss"
).
format
(
PathFormatUtils
.
currentDate
);
return
new
SimpleDateFormat
(
"ss"
).
format
(
PathFormatUtils
.
currentDate
);
}
}
private
static
String
getRandom
(
String
pattern
)
{
private
static
String
getRandom
(
String
pattern
)
{
int
length
=
0
;
int
length
=
0
;
pattern
=
pattern
.
split
(
":"
)[
1
].
trim
();
pattern
=
pattern
.
split
(
":"
)[
1
].
trim
();
length
=
Integer
.
parseInt
(
pattern
);
length
=
Integer
.
parseInt
(
pattern
);
return
(
Math
.
random
()
+
""
).
replace
(
"."
,
""
).
substring
(
0
,
length
);
return
(
Math
.
random
()
+
""
).
replace
(
"."
,
""
).
substring
(
0
,
length
);
}
public
static
void
main
(
String
[]
args
)
{
// TODO Auto-generated method stub
}
}
}
}
src/com/ejweb/core/utils/StringUtils.java
View file @
89564d2b
...
@@ -3,54 +3,55 @@
...
@@ -3,54 +3,55 @@
*/
*/
package
com
.
ejweb
.
core
.
utils
;
package
com
.
ejweb
.
core
.
utils
;
import
java.io.UnsupportedEncodingException
;
import
com.google.common.collect.Lists
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.regex.Matcher
;
import
java.util.regex.Pattern
;
import
javax.servlet.http.HttpServletRequest
;
import
org.apache.commons.lang3.StringEscapeUtils
;
import
org.apache.commons.lang3.StringEscapeUtils
;
import
org.springframework.web.context.request.RequestContextHolder
;
import
org.springframework.web.context.request.RequestContextHolder
;
import
org.springframework.web.context.request.ServletRequestAttributes
;
import
org.springframework.web.context.request.ServletRequestAttributes
;
import
org.springframework.web.servlet.LocaleResolver
;
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类
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
*
* @author ThinkGem
* @author ThinkGem
* @version 2013-05-22
* @version 2013-05-22
*/
*/
public
class
StringUtils
extends
org
.
apache
.
commons
.
lang3
.
StringUtils
{
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
char
SEPARATOR
=
'_'
;
private
static
final
String
CHARSET_NAME
=
"UTF-8"
;
private
static
final
String
CHARSET_NAME
=
"UTF-8"
;
/**
/**
* 转换为字节数组
* 转换为字节数组
*
* @param str
* @param str
* @return
* @return
*/
*/
public
static
byte
[]
getBytes
(
String
str
){
public
static
byte
[]
getBytes
(
String
str
)
{
if
(
str
!=
null
){
if
(
str
!=
null
)
{
try
{
try
{
return
str
.
getBytes
(
CHARSET_NAME
);
return
str
.
getBytes
(
CHARSET_NAME
);
}
catch
(
UnsupportedEncodingException
e
)
{
}
catch
(
UnsupportedEncodingException
e
)
{
return
null
;
return
null
;
}
}
}
else
{
}
else
{
return
null
;
return
null
;
}
}
}
}
/**
/**
* 转换为字节数组
* 转换为字节数组
* @param str
*
* @param bytes
* @return
* @return
*/
*/
public
static
String
toString
(
byte
[]
bytes
){
public
static
String
toString
(
byte
[]
bytes
)
{
try
{
try
{
return
new
String
(
bytes
,
CHARSET_NAME
);
return
new
String
(
bytes
,
CHARSET_NAME
);
}
catch
(
UnsupportedEncodingException
e
)
{
}
catch
(
UnsupportedEncodingException
e
)
{
...
@@ -60,14 +61,15 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -60,14 +61,15 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 是否包含字符串
* 是否包含字符串
*
* @param str 验证字符串
* @param str 验证字符串
* @param strs 字符串组
* @param strs 字符串组
* @return 包含返回true
* @return 包含返回true
*/
*/
public
static
boolean
inString
(
String
str
,
String
...
strs
){
public
static
boolean
inString
(
String
str
,
String
...
strs
)
{
if
(
str
!=
null
){
if
(
str
!=
null
)
{
for
(
String
s
:
strs
){
for
(
String
s
:
strs
)
{
if
(
str
.
equals
(
trim
(
s
))){
if
(
str
.
equals
(
trim
(
s
)))
{
return
true
;
return
true
;
}
}
}
}
...
@@ -79,7 +81,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -79,7 +81,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* 替换掉HTML标签方法
* 替换掉HTML标签方法
*/
*/
public
static
String
replaceHtml
(
String
html
)
{
public
static
String
replaceHtml
(
String
html
)
{
if
(
isBlank
(
html
)){
if
(
isBlank
(
html
))
{
return
""
;
return
""
;
}
}
String
regEx
=
"<.+?>"
;
String
regEx
=
"<.+?>"
;
...
@@ -91,11 +93,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -91,11 +93,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param html
* @param html
* @return
* @return
*/
*/
public
static
String
replaceMobileHtml
(
String
html
){
public
static
String
replaceMobileHtml
(
String
html
)
{
if
(
html
==
null
){
if
(
html
==
null
)
{
return
""
;
return
""
;
}
}
return
html
.
replaceAll
(
"<([a-z]+?)\\s+?.*?>"
,
"<$1>"
);
return
html
.
replaceAll
(
"<([a-z]+?)\\s+?.*?>"
,
"<$1>"
);
...
@@ -103,11 +106,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -103,11 +106,12 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
*
* @param txt
* @param txt
* @return
* @return
*/
*/
public
static
String
toHtml
(
String
txt
){
public
static
String
toHtml
(
String
txt
)
{
if
(
txt
==
null
){
if
(
txt
==
null
)
{
return
""
;
return
""
;
}
}
return
replace
(
replace
(
Encodes
.
escapeHtml
(
txt
),
"\n"
,
"<br/>"
),
"\t"
,
" "
);
return
replace
(
replace
(
Encodes
.
escapeHtml
(
txt
),
"\n"
,
"<br/>"
),
"\t"
,
" "
);
...
@@ -115,6 +119,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -115,6 +119,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 缩略字符串(不区分中英文字符)
* 缩略字符串(不区分中英文字符)
*
* @param str 目标字符串
* @param str 目标字符串
* @param length 截取长度
* @param length 截取长度
* @return
* @return
...
@@ -190,7 +195,6 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -190,7 +195,6 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
temp_result
=
temp_result
.
replaceAll
(
"<([a-zA-Z]+)[^<>]*>(.*?)</\\1>"
,
temp_result
=
temp_result
.
replaceAll
(
"<([a-zA-Z]+)[^<>]*>(.*?)</\\1>"
,
"$2"
);
"$2"
);
// 用正则表达式取出标记
// 用正则表达式取出标记
Pattern
p
=
Pattern
.
compile
(
"<([a-zA-Z]+)[^<>]*>"
);
Matcher
m
=
p
.
matcher
(
temp_result
);
Matcher
m
=
p
.
matcher
(
temp_result
);
List
<
String
>
endHTML
=
Lists
.
newArrayList
();
List
<
String
>
endHTML
=
Lists
.
newArrayList
();
while
(
m
.
find
())
{
while
(
m
.
find
())
{
...
@@ -208,8 +212,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -208,8 +212,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 转换为Double类型
* 转换为Double类型
*/
*/
public
static
Double
toDouble
(
Object
val
){
public
static
Double
toDouble
(
Object
val
)
{
if
(
val
==
null
){
if
(
val
==
null
)
{
return
0
D
;
return
0
D
;
}
}
try
{
try
{
...
@@ -222,21 +226,21 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -222,21 +226,21 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 转换为Float类型
* 转换为Float类型
*/
*/
public
static
Float
toFloat
(
Object
val
){
public
static
Float
toFloat
(
Object
val
)
{
return
toDouble
(
val
).
floatValue
();
return
toDouble
(
val
).
floatValue
();
}
}
/**
/**
* 转换为Long类型
* 转换为Long类型
*/
*/
public
static
Long
toLong
(
Object
val
){
public
static
Long
toLong
(
Object
val
)
{
return
toDouble
(
val
).
longValue
();
return
toDouble
(
val
).
longValue
();
}
}
/**
/**
* 转换为Integer类型
* 转换为Integer类型
*/
*/
public
static
Integer
toInteger
(
Object
val
){
public
static
Integer
toInteger
(
Object
val
)
{
return
toLong
(
val
).
intValue
();
return
toLong
(
val
).
intValue
();
}
}
...
@@ -245,7 +249,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -245,7 +249,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
*/
*/
public
static
String
getMessage
(
String
code
,
Object
[]
args
)
{
public
static
String
getMessage
(
String
code
,
Object
[]
args
)
{
LocaleResolver
localLocaleResolver
=
(
LocaleResolver
)
SpringContextHolder
.
getBean
(
LocaleResolver
.
class
);
LocaleResolver
localLocaleResolver
=
(
LocaleResolver
)
SpringContextHolder
.
getBean
(
LocaleResolver
.
class
);
HttpServletRequest
request
=
((
ServletRequestAttributes
)
RequestContextHolder
.
getRequestAttributes
()).
getRequest
();
HttpServletRequest
request
=
((
ServletRequestAttributes
)
RequestContextHolder
.
getRequestAttributes
()).
getRequest
();
Locale
localLocale
=
localLocaleResolver
.
resolveLocale
(
request
);
Locale
localLocale
=
localLocaleResolver
.
resolveLocale
(
request
);
return
SpringContextHolder
.
getApplicationContext
().
getMessage
(
code
,
args
,
localLocale
);
return
SpringContextHolder
.
getApplicationContext
().
getMessage
(
code
,
args
,
localLocale
);
}
}
...
@@ -253,43 +257,35 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -253,43 +257,35 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 获得用户远程地址
* 获得用户远程地址
*/
*/
public
static
String
getRemoteAddr
(
HttpServletRequest
request
){
public
static
String
getRemoteAddr
(
HttpServletRequest
request
)
{
// String remoteAddr = request.getHeader("X-Real-IP");
if
(
request
==
null
)
{
// 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
)
return
"Unknown"
;
return
"Unknown"
;
}
String
ip
=
request
.
getHeader
(
"X-Real-IP"
);
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"
);
ip
=
request
.
getHeader
(
"x-forwarded-for"
);
if
(
StringUtils
.
isBlank
(
ip
)
||
"Unknown"
.
equalsIgnoreCase
(
ip
))
{
if
(
StringUtils
.
isBlank
(
ip
)
||
"Unknown"
.
equalsIgnoreCase
(
ip
))
{
//获取HTTP_CLIENT_IP
//获取HTTP_CLIENT_IP
ip
=
request
.
getHeader
(
"Proxy-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
//HTTP_X_FORWARDED_FOR
ip
=
request
.
getHeader
(
"WL-Proxy-Client-IP"
);
ip
=
request
.
getHeader
(
"WL-Proxy-Client-IP"
);
if
(
StringUtils
.
isBlank
(
ip
)
||
"Unknown"
.
equalsIgnoreCase
(
ip
))
{
if
(
StringUtils
.
isBlank
(
ip
)
||
"Unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getRemoteAddr
();
ip
=
request
.
getRemoteAddr
();
}
}
}
}
}
}
}
}
if
(
StringUtils
.
isBlank
(
ip
))
if
(
StringUtils
.
isBlank
(
ip
))
{
return
"Unknown"
;
return
"Unknown"
;
}
return
ip
.
split
(
","
)[
0
];
return
ip
.
split
(
","
)[
0
];
}
}
/**
/**
* 驼峰命名法工具
* 驼峰命名法工具
*
@return
*
*
toCamelCase("hello_world") == "helloWorld"
*
@return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
*/
...
@@ -320,8 +316,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -320,8 +316,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 驼峰命名法工具
* 驼峰命名法工具
*
@return
*
*
toCamelCase("hello_world") == "helloWorld"
*
@return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
*/
...
@@ -335,8 +331,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -335,8 +331,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 驼峰命名法工具
* 驼峰命名法工具
*
@return
*
*
toCamelCase("hello_world") == "helloWorld"
*
@return toCamelCase(" hello_world ") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
*/
...
@@ -373,28 +369,30 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
...
@@ -373,28 +369,30 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/**
/**
* 如果不为空,则设置值
* 如果不为空,则设置值
*
* @param target
* @param target
* @param source
* @param source
*/
*/
public
static
void
setValueIfNotBlank
(
String
target
,
String
source
)
{
public
static
void
setValueIfNotBlank
(
String
target
,
String
source
)
{
if
(
isNotBlank
(
source
)){
if
(
isNotBlank
(
source
))
{
target
=
source
;
target
=
source
;
}
}
}
}
/**
/**
* 转换为JS获取对象值,生成三目运算返回结果
* 转换为JS获取对象值,生成三目运算返回结果
*
* @param objectString 对象串
* @param objectString 对象串
* 例如:row.user.id
* 例如:row.user.id
* 返回:!row?'':!row.user?'':!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
result
=
new
StringBuilder
();
StringBuilder
val
=
new
StringBuilder
();
StringBuilder
val
=
new
StringBuilder
();
String
[]
vals
=
split
(
objectString
,
"."
);
String
[]
vals
=
split
(
objectString
,
"."
);
for
(
int
i
=
0
;
i
<
vals
.
length
;
i
++)
{
for
(
int
i
=
0
;
i
<
vals
.
length
;
i
++)
{
val
.
append
(
"."
+
vals
[
i
]);
val
.
append
(
"."
+
vals
[
i
]);
result
.
append
(
"!"
+(
val
.
substring
(
1
))+
"?'':"
);
result
.
append
(
"!"
+
(
val
.
substring
(
1
))
+
"?'':"
);
}
}
result
.
append
(
val
.
substring
(
1
));
result
.
append
(
val
.
substring
(
1
));
return
result
.
toString
();
return
result
.
toString
();
...
...
src/com/ejweb/core/utils/excel/ImportExcel.java
View file @
89564d2b
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package
com
.
ejweb
.
core
.
utils
.
excel
;
package
com
.
ejweb
.
core
.
utils
.
excel
;
import
java.io.File
;
import
com.ejweb.core.utils.Reflections
;
import
java.io.FileInputStream
;
import
com.ejweb.core.utils.excel.annotation.ExcelField
;
import
java.io.IOException
;
import
com.ejweb.modules.sys.utils.DictUtils
;
import
java.io.InputStream
;
import
com.google.common.collect.Lists
;
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
org.apache.commons.lang3.StringUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.poi.hssf.usermodel.HSSFWorkbook
;
import
org.apache.poi.hssf.usermodel.HSSFWorkbook
;
import
org.apache.poi.openxml4j.exceptions.InvalidFormatException
;
import
org.apache.poi.openxml4j.exceptions.InvalidFormatException
;
import
org.apache.poi.ss.usermodel.Cell
;
import
org.apache.poi.ss.usermodel.*
;
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.xssf.usermodel.XSSFWorkbook
;
import
org.apache.poi.xssf.usermodel.XSSFWorkbook
;
import
org.slf4j.Logger
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.web.multipart.MultipartFile
;
import
org.springframework.web.multipart.MultipartFile
;
import
com.google.common.collect.Lists
;
import
java.io.File
;
import
com.ejweb.core.utils.Reflections
;
import
java.io.FileInputStream
;
import
com.ejweb.core.utils.excel.annotation.ExcelField
;
import
java.io.IOException
;
import
com.ejweb.modules.sys.utils.DictUtils
;
import
java.io.InputStream
;
import
java.lang.reflect.Field
;
import
java.lang.reflect.Method
;
import
java.util.*
;
/**
/**
* 导入Excel文件(支持“XLS”和“XLSX”格式)
* 导入Excel文件(支持“XLS”和“XLSX”格式)
* @author ThinkGem
* @version 2013-03-10
*/
*/
public
class
ImportExcel
{
public
class
ImportExcel
{
...
@@ -60,7 +45,8 @@ public class ImportExcel {
...
@@ -60,7 +45,8 @@ public class ImportExcel {
/**
/**
* 构造函数
* 构造函数
* @param path 导入文件,读取第一个工作表
*
* @param fileName 导入文件,读取第一个工作表
* @param headerNum 标题行号,数据行号=标题行号+1
* @param headerNum 标题行号,数据行号=标题行号+1
* @throws InvalidFormatException
* @throws InvalidFormatException
* @throws IOException
* @throws IOException
...
@@ -72,7 +58,8 @@ public class ImportExcel {
...
@@ -72,7 +58,8 @@ public class ImportExcel {
/**
/**
* 构造函数
* 构造函数
* @param path 导入文件对象,读取第一个工作表
*
* @param file 导入文件对象,读取第一个工作表
* @param headerNum 标题行号,数据行号=标题行号+1
* @param headerNum 标题行号,数据行号=标题行号+1
* @throws InvalidFormatException
* @throws InvalidFormatException
* @throws IOException
* @throws IOException
...
@@ -84,7 +71,8 @@ public class ImportExcel {
...
@@ -84,7 +71,8 @@ public class ImportExcel {
/**
/**
* 构造函数
* 构造函数
* @param path 导入文件
*
* @param fileName 导入文件
* @param headerNum 标题行号,数据行号=标题行号+1
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws InvalidFormatException
...
@@ -97,7 +85,8 @@ public class ImportExcel {
...
@@ -97,7 +85,8 @@ public class ImportExcel {
/**
/**
* 构造函数
* 构造函数
* @param path 导入文件对象
*
* @param file 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws InvalidFormatException
...
@@ -110,7 +99,8 @@ public class ImportExcel {
...
@@ -110,7 +99,8 @@ public class ImportExcel {
/**
/**
* 构造函数
* 构造函数
* @param file 导入文件对象
*
* @param multipartFile 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws InvalidFormatException
...
@@ -123,7 +113,8 @@ public class ImportExcel {
...
@@ -123,7 +113,8 @@ public class ImportExcel {
/**
/**
* 构造函数
* 构造函数
* @param path 导入文件对象
*
* @param fileName 导入文件对象
* @param headerNum 标题行号,数据行号=标题行号+1
* @param headerNum 标题行号,数据行号=标题行号+1
* @param sheetIndex 工作表编号
* @param sheetIndex 工作表编号
* @throws InvalidFormatException
* @throws InvalidFormatException
...
@@ -131,16 +122,16 @@ public class ImportExcel {
...
@@ -131,16 +122,16 @@ public class ImportExcel {
*/
*/
public
ImportExcel
(
String
fileName
,
InputStream
is
,
int
headerNum
,
int
sheetIndex
)
public
ImportExcel
(
String
fileName
,
InputStream
is
,
int
headerNum
,
int
sheetIndex
)
throws
InvalidFormatException
,
IOException
{
throws
InvalidFormatException
,
IOException
{
if
(
StringUtils
.
isBlank
(
fileName
)){
if
(
StringUtils
.
isBlank
(
fileName
))
{
throw
new
RuntimeException
(
"导入文档为空!"
);
throw
new
RuntimeException
(
"导入文档为空!"
);
}
else
if
(
fileName
.
toLowerCase
().
endsWith
(
"xls"
)){
}
else
if
(
fileName
.
toLowerCase
().
endsWith
(
"xls"
))
{
this
.
wb
=
new
HSSFWorkbook
(
is
);
this
.
wb
=
new
HSSFWorkbook
(
is
);
}
else
if
(
fileName
.
toLowerCase
().
endsWith
(
"xlsx"
)){
}
else
if
(
fileName
.
toLowerCase
().
endsWith
(
"xlsx"
))
{
this
.
wb
=
new
XSSFWorkbook
(
is
);
this
.
wb
=
new
XSSFWorkbook
(
is
);
}
else
{
}
else
{
throw
new
RuntimeException
(
"文档格式不正确!"
);
throw
new
RuntimeException
(
"文档格式不正确!"
);
}
}
if
(
this
.
wb
.
getNumberOfSheets
()
<
sheetIndex
)
{
if
(
this
.
wb
.
getNumberOfSheets
()
<
sheetIndex
)
{
throw
new
RuntimeException
(
"文档中没有工作表!"
);
throw
new
RuntimeException
(
"文档中没有工作表!"
);
}
}
this
.
sheet
=
this
.
wb
.
getSheetAt
(
sheetIndex
);
this
.
sheet
=
this
.
wb
.
getSheetAt
(
sheetIndex
);
...
@@ -150,61 +141,66 @@ public class ImportExcel {
...
@@ -150,61 +141,66 @@ public class ImportExcel {
/**
/**
* 获取行对象
* 获取行对象
*
* @param rownum
* @param rownum
* @return
* @return
*/
*/
public
Row
getRow
(
int
rownum
){
public
Row
getRow
(
int
rownum
)
{
return
this
.
sheet
.
getRow
(
rownum
);
return
this
.
sheet
.
getRow
(
rownum
);
}
}
/**
/**
* 获取数据行号
* 获取数据行号
*
* @return
* @return
*/
*/
public
int
getDataRowNum
(){
public
int
getDataRowNum
()
{
return
headerNum
+
1
;
return
headerNum
+
1
;
}
}
/**
/**
* 获取最后一个数据行号
* 获取最后一个数据行号
*
* @return
* @return
*/
*/
public
int
getLastDataRowNum
(){
public
int
getLastDataRowNum
()
{
return
this
.
sheet
.
getLastRowNum
()
+
headerNum
;
return
this
.
sheet
.
getLastRowNum
()
+
headerNum
;
}
}
/**
/**
* 获取最后一个列号
* 获取最后一个列号
*
* @return
* @return
*/
*/
public
int
getLastCellNum
(){
public
int
getLastCellNum
()
{
return
this
.
getRow
(
headerNum
).
getLastCellNum
();
return
this
.
getRow
(
headerNum
).
getLastCellNum
();
}
}
/**
/**
* 获取单元格值
* 获取单元格值
*
* @param row 获取的行
* @param row 获取的行
* @param column 获取单元格列号
* @param column 获取单元格列号
* @return 单元格值
* @return 单元格值
*/
*/
public
Object
getCellValue
(
Row
row
,
int
column
){
public
Object
getCellValue
(
Row
row
,
int
column
)
{
Object
val
=
""
;
Object
val
=
""
;
try
{
try
{
Cell
cell
=
row
.
getCell
(
column
);
Cell
cell
=
row
.
getCell
(
column
);
if
(
cell
!=
null
){
if
(
cell
!=
null
)
{
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_NUMERIC
){
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_NUMERIC
)
{
val
=
cell
.
getNumericCellValue
();
val
=
cell
.
getNumericCellValue
();
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_STRING
)
{
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_STRING
)
{
val
=
cell
.
getStringCellValue
();
val
=
cell
.
getStringCellValue
();
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_FORMULA
)
{
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_FORMULA
)
{
val
=
cell
.
getCellFormula
();
val
=
cell
.
getCellFormula
();
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_BOOLEAN
)
{
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_BOOLEAN
)
{
val
=
cell
.
getBooleanCellValue
();
val
=
cell
.
getBooleanCellValue
();
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_ERROR
)
{
}
else
if
(
cell
.
getCellType
()
==
Cell
.
CELL_TYPE_ERROR
)
{
val
=
cell
.
getErrorCellValue
();
val
=
cell
.
getErrorCellValue
();
}
}
}
}
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
return
val
;
return
val
;
}
}
return
val
;
return
val
;
...
@@ -212,55 +208,56 @@ public class ImportExcel {
...
@@ -212,55 +208,56 @@ public class ImportExcel {
/**
/**
* 获取导入数据列表
* 获取导入数据列表
*
* @param cls 导入对象类型
* @param cls 导入对象类型
* @param groups 导入分组
* @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
();
List
<
Object
[]>
annotationList
=
Lists
.
newArrayList
();
// Get annotation field
// Get annotation field
Field
[]
fs
=
cls
.
getDeclaredFields
();
Field
[]
fs
=
cls
.
getDeclaredFields
();
for
(
Field
f
:
fs
){
for
(
Field
f
:
fs
)
{
ExcelField
ef
=
f
.
getAnnotation
(
ExcelField
.
class
);
ExcelField
ef
=
f
.
getAnnotation
(
ExcelField
.
class
);
if
(
ef
!=
null
&&
(
ef
.
type
()
==
0
||
ef
.
type
()==
2
))
{
if
(
ef
!=
null
&&
(
ef
.
type
()
==
0
||
ef
.
type
()
==
2
))
{
if
(
groups
!=
null
&&
groups
.
length
>
0
)
{
if
(
groups
!=
null
&&
groups
.
length
>
0
)
{
boolean
inGroup
=
false
;
boolean
inGroup
=
false
;
for
(
int
g
:
groups
){
for
(
int
g
:
groups
)
{
if
(
inGroup
){
if
(
inGroup
)
{
break
;
break
;
}
}
for
(
int
efg
:
ef
.
groups
()){
for
(
int
efg
:
ef
.
groups
())
{
if
(
g
==
efg
){
if
(
g
==
efg
)
{
inGroup
=
true
;
inGroup
=
true
;
annotationList
.
add
(
new
Object
[]{
ef
,
f
});
annotationList
.
add
(
new
Object
[]{
ef
,
f
});
break
;
break
;
}
}
}
}
}
}
}
else
{
}
else
{
annotationList
.
add
(
new
Object
[]{
ef
,
f
});
annotationList
.
add
(
new
Object
[]{
ef
,
f
});
}
}
}
}
}
}
// Get annotation method
// Get annotation method
Method
[]
ms
=
cls
.
getDeclaredMethods
();
Method
[]
ms
=
cls
.
getDeclaredMethods
();
for
(
Method
m
:
ms
){
for
(
Method
m
:
ms
)
{
ExcelField
ef
=
m
.
getAnnotation
(
ExcelField
.
class
);
ExcelField
ef
=
m
.
getAnnotation
(
ExcelField
.
class
);
if
(
ef
!=
null
&&
(
ef
.
type
()
==
0
||
ef
.
type
()==
2
))
{
if
(
ef
!=
null
&&
(
ef
.
type
()
==
0
||
ef
.
type
()
==
2
))
{
if
(
groups
!=
null
&&
groups
.
length
>
0
)
{
if
(
groups
!=
null
&&
groups
.
length
>
0
)
{
boolean
inGroup
=
false
;
boolean
inGroup
=
false
;
for
(
int
g
:
groups
){
for
(
int
g
:
groups
)
{
if
(
inGroup
){
if
(
inGroup
)
{
break
;
break
;
}
}
for
(
int
efg
:
ef
.
groups
()){
for
(
int
efg
:
ef
.
groups
())
{
if
(
g
==
efg
){
if
(
g
==
efg
)
{
inGroup
=
true
;
inGroup
=
true
;
annotationList
.
add
(
new
Object
[]{
ef
,
m
});
annotationList
.
add
(
new
Object
[]{
ef
,
m
});
break
;
break
;
}
}
}
}
}
}
}
else
{
}
else
{
annotationList
.
add
(
new
Object
[]{
ef
,
m
});
annotationList
.
add
(
new
Object
[]{
ef
,
m
});
}
}
}
}
...
@@ -268,106 +265,86 @@ public class ImportExcel {
...
@@ -268,106 +265,86 @@ public class ImportExcel {
// Field sorting
// Field sorting
Collections
.
sort
(
annotationList
,
new
Comparator
<
Object
[]>()
{
Collections
.
sort
(
annotationList
,
new
Comparator
<
Object
[]>()
{
public
int
compare
(
Object
[]
o1
,
Object
[]
o2
)
{
public
int
compare
(
Object
[]
o1
,
Object
[]
o2
)
{
return
new
Integer
(((
ExcelField
)
o1
[
0
]).
sort
()).
compareTo
(
return
new
Integer
(((
ExcelField
)
o1
[
0
]).
sort
()).
compareTo
(
new
Integer
(((
ExcelField
)
o2
[
0
]).
sort
()));
new
Integer
(((
ExcelField
)
o2
[
0
]).
sort
()));
};
}
;
});
});
//log.debug("Import column count:"+annotationList.size());
// Get excel data
List
<
E
>
dataList
=
Lists
.
newArrayList
();
List
<
E
>
dataList
=
Lists
.
newArrayList
();
for
(
int
i
=
this
.
getDataRowNum
();
i
<
this
.
getLastDataRowNum
();
i
++)
{
for
(
int
i
=
this
.
getDataRowNum
();
i
<
this
.
getLastDataRowNum
();
i
++)
{
E
e
=
(
E
)
cls
.
newInstance
();
E
e
=
(
E
)
cls
.
newInstance
();
int
column
=
0
;
int
column
=
0
;
Row
row
=
this
.
getRow
(
i
);
Row
row
=
this
.
getRow
(
i
);
StringBuilder
sb
=
new
StringBuilder
();
StringBuilder
sb
=
new
StringBuilder
();
for
(
Object
[]
os
:
annotationList
){
for
(
Object
[]
os
:
annotationList
)
{
Object
val
=
this
.
getCellValue
(
row
,
column
++);
Object
val
=
this
.
getCellValue
(
row
,
column
++);
if
(
val
!=
null
){
if
(
val
!=
null
)
{
ExcelField
ef
=
(
ExcelField
)
os
[
0
];
ExcelField
ef
=
(
ExcelField
)
os
[
0
];
// If is dict type, get dict value
// If is dict type, get dict value
if
(
StringUtils
.
isNotBlank
(
ef
.
dictType
())){
if
(
StringUtils
.
isNotBlank
(
ef
.
dictType
()))
{
val
=
DictUtils
.
getDictValue
(
val
.
toString
(),
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
;
Class
<?>
valType
=
Class
.
class
;
if
(
os
[
1
]
instanceof
Field
){
if
(
os
[
1
]
instanceof
Field
)
{
valType
=
((
Field
)
os
[
1
]).
getType
();
valType
=
((
Field
)
os
[
1
]).
getType
();
}
else
if
(
os
[
1
]
instanceof
Method
)
{
}
else
if
(
os
[
1
]
instanceof
Method
)
{
Method
method
=
((
Method
)
os
[
1
]);
Method
method
=
((
Method
)
os
[
1
]);
if
(
"get"
.
equals
(
method
.
getName
().
substring
(
0
,
3
))){
if
(
"get"
.
equals
(
method
.
getName
().
substring
(
0
,
3
)))
{
valType
=
method
.
getReturnType
();
valType
=
method
.
getReturnType
();
}
else
if
(
"set"
.
equals
(
method
.
getName
().
substring
(
0
,
3
)))
{
}
else
if
(
"set"
.
equals
(
method
.
getName
().
substring
(
0
,
3
)))
{
valType
=
((
Method
)
os
[
1
]).
getParameterTypes
()[
0
];
valType
=
((
Method
)
os
[
1
]).
getParameterTypes
()[
0
];
}
}
}
}
//log.debug("Import value type: ["+i+","+column+"] " + valType);
try
{
try
{
if
(
valType
==
String
.
class
){
if
(
valType
==
String
.
class
)
{
String
s
=
String
.
valueOf
(
val
.
toString
());
String
s
=
String
.
valueOf
(
val
.
toString
());
if
(
StringUtils
.
endsWith
(
s
,
".0"
))
{
if
(
StringUtils
.
endsWith
(
s
,
".0"
))
{
val
=
StringUtils
.
substringBefore
(
s
,
".0"
);
val
=
StringUtils
.
substringBefore
(
s
,
".0"
);
}
else
{
}
else
{
val
=
String
.
valueOf
(
val
.
toString
());
val
=
String
.
valueOf
(
val
.
toString
());
}
}
}
else
if
(
valType
==
Integer
.
class
)
{
}
else
if
(
valType
==
Integer
.
class
)
{
val
=
Double
.
valueOf
(
val
.
toString
()).
intValue
();
val
=
Double
.
valueOf
(
val
.
toString
()).
intValue
();
}
else
if
(
valType
==
Long
.
class
)
{
}
else
if
(
valType
==
Long
.
class
)
{
val
=
Double
.
valueOf
(
val
.
toString
()).
longValue
();
val
=
Double
.
valueOf
(
val
.
toString
()).
longValue
();
}
else
if
(
valType
==
Double
.
class
)
{
}
else
if
(
valType
==
Double
.
class
)
{
val
=
Double
.
valueOf
(
val
.
toString
());
val
=
Double
.
valueOf
(
val
.
toString
());
}
else
if
(
valType
==
Float
.
class
)
{
}
else
if
(
valType
==
Float
.
class
)
{
val
=
Float
.
valueOf
(
val
.
toString
());
val
=
Float
.
valueOf
(
val
.
toString
());
}
else
if
(
valType
==
Date
.
class
)
{
}
else
if
(
valType
==
Date
.
class
)
{
val
=
DateUtil
.
getJavaDate
((
Double
)
val
);
val
=
DateUtil
.
getJavaDate
((
Double
)
val
);
}
else
{
}
else
{
if
(
ef
.
fieldType
()
!=
Class
.
class
){
if
(
ef
.
fieldType
()
!=
Class
.
class
)
{
val
=
ef
.
fieldType
().
getMethod
(
"getValue"
,
String
.
class
).
invoke
(
null
,
val
.
toString
());
val
=
ef
.
fieldType
().
getMethod
(
"getValue"
,
String
.
class
).
invoke
(
null
,
val
.
toString
());
}
else
{
}
else
{
val
=
Class
.
forName
(
this
.
getClass
().
getName
().
replaceAll
(
this
.
getClass
().
getSimpleName
(),
val
=
Class
.
forName
(
this
.
getClass
().
getName
().
replaceAll
(
this
.
getClass
().
getSimpleName
(),
"fieldtype."
+
valType
.
getSimpleName
()+
"Type"
)).
getMethod
(
"getValue"
,
String
.
class
).
invoke
(
null
,
val
.
toString
());
"fieldtype."
+
valType
.
getSimpleName
()
+
"Type"
)).
getMethod
(
"getValue"
,
String
.
class
).
invoke
(
null
,
val
.
toString
());
}
}
}
}
}
catch
(
Exception
ex
)
{
}
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
;
val
=
null
;
}
}
// set entity value
// set entity value
if
(
os
[
1
]
instanceof
Field
){
if
(
os
[
1
]
instanceof
Field
)
{
Reflections
.
invokeSetter
(
e
,
((
Field
)
os
[
1
]).
getName
(),
val
);
Reflections
.
invokeSetter
(
e
,
((
Field
)
os
[
1
]).
getName
(),
val
);
}
else
if
(
os
[
1
]
instanceof
Method
)
{
}
else
if
(
os
[
1
]
instanceof
Method
)
{
String
mthodName
=
((
Method
)
os
[
1
]).
getName
();
String
mthodName
=
((
Method
)
os
[
1
]).
getName
();
if
(
"get"
.
equals
(
mthodName
.
substring
(
0
,
3
))){
if
(
"get"
.
equals
(
mthodName
.
substring
(
0
,
3
)))
{
mthodName
=
"set"
+
StringUtils
.
substringAfter
(
mthodName
,
"get"
);
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
);
dataList
.
add
(
e
);
log
.
debug
(
"Read success: ["
+
i
+
"] "
+
sb
.
toString
());
log
.
debug
(
"Read success: ["
+
i
+
"] "
+
sb
.
toString
());
}
}
return
dataList
;
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
)
{
public
static
List
<
Map
<
String
,
String
>>
getImportFileContent
(
InputStream
inputStream
)
{
...
...
src/com/ejweb/modules/airline/service/VerifyService.java
View file @
89564d2b
...
@@ -31,6 +31,8 @@ import java.util.regex.Pattern;
...
@@ -31,6 +31,8 @@ import java.util.regex.Pattern;
@Service
@Service
@Transactional
(
readOnly
=
true
)
@Transactional
(
readOnly
=
true
)
public
class
VerifyService
extends
CrudService
<
VerifyDao
,
VerifyEntity
>
{
public
class
VerifyService
extends
CrudService
<
VerifyDao
,
VerifyEntity
>
{
private
static
final
Pattern
pattern
=
Pattern
.
compile
(
"[0-9]*"
);
@Autowired
@Autowired
private
VerifyDao
verifyDao
;
private
VerifyDao
verifyDao
;
@Autowired
@Autowired
...
@@ -71,7 +73,9 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
...
@@ -71,7 +73,9 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
}
else
{
}
else
{
Integer
day
=
verifyDao
.
getDay
(
entity
);
Integer
day
=
verifyDao
.
getDay
(
entity
);
if
(
day
!=
null
)
{
if
(
day
!=
null
)
{
if
(
day
<=
0
)
day
=
0
;
if
(
day
<=
0
)
{
day
=
0
;
}
day
=
90
-
day
;
day
=
90
-
day
;
if
(
day
<
0
)
{
if
(
day
<
0
)
{
entity
.
setExpiryDate
(
"0"
);
entity
.
setExpiryDate
(
"0"
);
...
@@ -113,7 +117,6 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
...
@@ -113,7 +117,6 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
}
}
public
boolean
isNumeric
(
String
str
)
{
public
boolean
isNumeric
(
String
str
)
{
Pattern
pattern
=
Pattern
.
compile
(
"[0-9]*"
);
Matcher
isNum
=
pattern
.
matcher
(
str
);
Matcher
isNum
=
pattern
.
matcher
(
str
);
if
(!
isNum
.
matches
())
{
if
(!
isNum
.
matches
())
{
return
false
;
return
false
;
...
@@ -124,15 +127,15 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
...
@@ -124,15 +127,15 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
@Transactional
(
readOnly
=
false
)
@Transactional
(
readOnly
=
false
)
public
String
saveVerify
(
VerifyEntity
verifyEntity
)
{
public
String
saveVerify
(
VerifyEntity
verifyEntity
)
{
String
verifNo
=
verifyEntity
.
getVerifNo
();
String
verifNo
=
verifyEntity
.
getVerifNo
();
if
(
null
!=
verifNo
&&
""
!=
verifNo
)
{
if
(
null
!=
verifNo
&&
""
!=
verifNo
)
{
List
<
VerifyEntity
>
validator
=
verifyDao
.
findverifNo
(
verifyEntity
);
List
<
VerifyEntity
>
validator
=
verifyDao
.
findverifNo
(
verifyEntity
);
if
(
validator
.
size
()
!=
0
)
{
if
(
validator
.
size
()
!=
0
)
{
return
"1"
;
return
"1"
;
}
}
}
}
VerifyUpdateUserEntity
vue
=
new
VerifyUpdateUserEntity
();
VerifyUpdateUserEntity
vue
=
new
VerifyUpdateUserEntity
();
VerifyEntity
verifyDao2
=
verifyDao
.
get2
(
verifyEntity
.
getId
());
VerifyEntity
verifyDao2
=
verifyDao
.
get2
(
verifyEntity
.
getId
());
if
(
verifyDao2
!=
null
)
{
if
(
verifyDao2
!=
null
)
{
vue
.
setId
(
verifyEntity
.
getId
());
vue
.
setId
(
verifyEntity
.
getId
());
vue
.
setOperateUser
(
verifyEntity
.
getOperateUser
());
vue
.
setOperateUser
(
verifyEntity
.
getOperateUser
());
vue
.
setReason
(
verifyEntity
.
getReason
());
vue
.
setReason
(
verifyEntity
.
getReason
());
...
@@ -155,7 +158,7 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
...
@@ -155,7 +158,7 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
// 如果不是航线则结束
// 如果不是航线则结束
if
(
"06"
.
equals
(
verifyEntity
.
getVerifType
())
||
"07"
.
equals
(
verifyEntity
.
getVerifType
())
if
(
"06"
.
equals
(
verifyEntity
.
getVerifType
())
||
"07"
.
equals
(
verifyEntity
.
getVerifType
())
||
"08"
.
equals
(
verifyEntity
.
getVerifType
()))
{
||
"08"
.
equals
(
verifyEntity
.
getVerifType
()))
{
return
""
;
return
""
;
}
}
ConnectEntity
connect
=
new
ConnectEntity
();
ConnectEntity
connect
=
new
ConnectEntity
();
connect
.
preInsert
();
// 生成id
connect
.
preInsert
();
// 生成id
...
@@ -189,7 +192,7 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
...
@@ -189,7 +192,7 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
verif
.
setAreaSt
(
verifyEntity
.
getAreaSt
());
verif
.
setAreaSt
(
verifyEntity
.
getAreaSt
());
verif
.
setFlightNo
(
verifyEntity
.
getFlightNo
());
verif
.
setFlightNo
(
verifyEntity
.
getFlightNo
());
verifyDao
.
update
(
verifyEntity
);
verifyDao
.
update
(
verifyEntity
);
return
""
;
return
""
;
}
}
// 判断是否主数据
// 判断是否主数据
else
if
(
"1"
.
equals
(
verifyEntity
.
getConnect
().
getIsMain
()))
{
else
if
(
"1"
.
equals
(
verifyEntity
.
getConnect
().
getIsMain
()))
{
...
@@ -206,11 +209,10 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
...
@@ -206,11 +209,10 @@ public class VerifyService extends CrudService<VerifyDao, VerifyEntity> {
connect
.
setFlightNo
(
verifyEntity
.
getFlightNo
());
connect
.
setFlightNo
(
verifyEntity
.
getFlightNo
());
connectDao
.
update
(
verifyEntity
.
getConnect
());
connectDao
.
update
(
verifyEntity
.
getConnect
());
}
}
return
""
;
return
""
;
}
}
public
List
<
VerifyEntity
>
CheckValidator
(
VerifyEntity
verifyEntity
)
{
public
List
<
VerifyEntity
>
CheckValidator
(
VerifyEntity
verifyEntity
)
{
return
verifyDao
.
findValidator
(
verifyEntity
);
return
verifyDao
.
findValidator
(
verifyEntity
);
}
}
...
...
src/com/ejweb/modules/chat/service/GroupChatService.java
View file @
89564d2b
...
@@ -16,47 +16,46 @@ import java.util.List;
...
@@ -16,47 +16,46 @@ import java.util.List;
@Service
@Service
@Transactional
(
readOnly
=
true
)
@Transactional
(
readOnly
=
true
)
public
class
GroupChatService
extends
CrudService
<
GroupChatDao
,
GroupChatEntity
>
{
public
class
GroupChatService
extends
CrudService
<
GroupChatDao
,
GroupChatEntity
>
{
@Autowired
@Autowired
private
GroupChatDao
dao
;
private
GroupChatDao
dao
;
public
Page
<
GroupChatEntity
>
findList
(
Page
<
GroupChatEntity
>
page
,
GroupChatEntity
groupSeatEntity
)
{
public
Page
<
GroupChatEntity
>
findList
(
Page
<
GroupChatEntity
>
page
,
GroupChatEntity
groupSeatEntity
)
{
groupSeatEntity
.
setPage
(
page
);
groupSeatEntity
.
setPage
(
page
);
PageHelper
.
startPage
(
page
.
getPageNo
(),
page
.
getPageSize
());
PageHelper
.
startPage
(
page
.
getPageNo
(),
page
.
getPageSize
());
List
<
GroupChatEntity
>
list
=
dao
.
findList
(
groupSeatEntity
);
List
<
GroupChatEntity
>
list
=
dao
.
findList
(
groupSeatEntity
);
page
.
setList
(
list
);
page
.
setList
(
list
);
return
page
;
return
page
;
}
}
public
List
<
GroupMemberEntity
>
getMemberList
(
GroupChatEntity
entity
)
{
public
List
<
GroupMemberEntity
>
getMemberList
(
GroupChatEntity
entity
)
{
List
<
GroupMemberEntity
>
list
=
dao
.
getMemberList
(
entity
);
List
<
GroupMemberEntity
>
list
=
dao
.
getMemberList
(
entity
);
/* for(GroupMemberEntity e:list){
GroupMemberEntity user=dao.getMember(e.getId());
}*/
return
list
;
return
list
;
}
}
public
GroupMemberEntity
getSeatMember
(
GroupChatEntity
entity
)
{
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
);
groupChatEntity
.
setPage
(
page
);
PageHelper
.
startPage
(
page
.
getPageNo
(),
page
.
getPageSize
());
PageHelper
.
startPage
(
page
.
getPageNo
(),
page
.
getPageSize
());
List
<
GroupMemberEntity
>
list
=
dao
.
findChatList
(
groupChatEntity
);
List
<
GroupMemberEntity
>
list
=
dao
.
findChatList
(
groupChatEntity
);
for
(
GroupMemberEntity
e:
list
)
{
for
(
GroupMemberEntity
e
:
list
)
{
if
(
"TXT"
.
equals
(
e
.
getMessageType
()))
{
if
(
"TXT"
.
equals
(
e
.
getMessageType
()))
{
continue
;
continue
;
}
}
switch
(
e
.
getMessageType
())
{
switch
(
e
.
getMessageType
())
{
case
"PIC"
:
case
"PIC"
:
case
"FILE"
:
case
"FILE"
:
case
"VOICE"
:
case
"VOICE"
:
case
"VIDEO"
:
case
"VIDEO"
:
String
content
=
e
.
getContent
();
String
content
=
e
.
getContent
();
content
=
content
.
substring
(
11
);
content
=
content
.
substring
(
11
);
ContentEntity
data
=
JSON
.
parseObject
(
content
,
ContentEntity
.
class
);
ContentEntity
data
=
JSON
.
parseObject
(
content
,
ContentEntity
.
class
);
e
.
setData
(
data
);
e
.
setData
(
data
);
break
;
break
;
default
:
default
:
...
...
src/com/ejweb/modules/contact/web/AirportBaseController.java
View file @
89564d2b
...
@@ -55,6 +55,7 @@ import com.ejweb.modules.sys.utils.UserUtils;
...
@@ -55,6 +55,7 @@ import com.ejweb.modules.sys.utils.UserUtils;
@Controller
@Controller
@RequestMapping
(
value
=
"${adminPath}/contact/airportBase"
)
@RequestMapping
(
value
=
"${adminPath}/contact/airportBase"
)
public
class
AirportBaseController
extends
BaseController
{
public
class
AirportBaseController
extends
BaseController
{
private
static
final
Pattern
pattern
=
Pattern
.
compile
(
"\\d+\\.\\d+$|-\\d+\\.\\d+$"
);
@Autowired
@Autowired
private
AirportBaseService
airportBaseService
;
private
AirportBaseService
airportBaseService
;
@Autowired
@Autowired
...
@@ -290,8 +291,6 @@ public class AirportBaseController extends BaseController{
...
@@ -290,8 +291,6 @@ public class AirportBaseController extends BaseController{
}
}
private
Map
<
String
,
Integer
>
getDate
(
String
time
){
private
Map
<
String
,
Integer
>
getDate
(
String
time
){
Map
<
String
,
Integer
>
map
=
new
HashMap
<>();
Map
<
String
,
Integer
>
map
=
new
HashMap
<>();
Pattern
pattern
=
Pattern
.
compile
(
"\\d+\\.\\d+$|-\\d+\\.\\d+$"
);
Matcher
isNum
=
pattern
.
matcher
(
time
);
Matcher
isNum
=
pattern
.
matcher
(
time
);
if
(
isNum
.
matches
()
){
if
(
isNum
.
matches
()
){
Double
d18
=
Double
.
parseDouble
(
time
);
Double
d18
=
Double
.
parseDouble
(
time
);
...
...
src/com/ejweb/modules/sys/web/LoginController.java
View file @
89564d2b
...
@@ -33,8 +33,6 @@ import com.google.common.collect.Maps;
...
@@ -33,8 +33,6 @@ import com.google.common.collect.Maps;
/**
/**
* 登录Controller
* 登录Controller
* @author ThinkGem
* @version 2013-5-31
*/
*/
@Controller
@Controller
public
class
LoginController
extends
BaseController
{
public
class
LoginController
extends
BaseController
{
...
@@ -49,12 +47,6 @@ public class LoginController extends BaseController{
...
@@ -49,12 +47,6 @@ public class LoginController extends BaseController{
public
String
login
(
HttpServletRequest
request
,
HttpServletResponse
response
,
Model
model
)
{
public
String
login
(
HttpServletRequest
request
,
HttpServletResponse
response
,
Model
model
)
{
Principal
principal
=
UserUtils
.
getPrincipal
();
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"
));
CookieUtils
.
setCookie
(
response
,
"tabmode"
,
GConstants
.
getValue
(
"tabmode"
,
"1"
));
if
(
logger
.
isDebugEnabled
()){
if
(
logger
.
isDebugEnabled
()){
...
@@ -70,12 +62,6 @@ public class LoginController extends BaseController{
...
@@ -70,12 +62,6 @@ public class LoginController extends BaseController{
if
(
principal
!=
null
&&
!
principal
.
isMobileLogin
()){
if
(
principal
!=
null
&&
!
principal
.
isMobileLogin
()){
return
"redirect:"
+
adminPath
;
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"
;
return
"modules/sys/sysLogin"
;
}
}
...
@@ -111,20 +97,16 @@ public class LoginController extends BaseController{
...
@@ -111,20 +97,16 @@ public class LoginController extends BaseController{
logger
.
debug
(
"login fail, active session size: {}, message: {}, exception: {}"
,
logger
.
debug
(
"login fail, active session size: {}, message: {}, exception: {}"
,
sessionDAO
.
getActiveSessions
(
false
).
size
(),
message
,
exception
);
sessionDAO
.
getActiveSessions
(
false
).
size
(),
message
,
exception
);
}
}
// 非授权异常,登录失败,验证码加1。
// 非授权异常,登录失败,验证码加1。
if
(!
UnauthorizedException
.
class
.
getName
().
equals
(
exception
)){
if
(!
UnauthorizedException
.
class
.
getName
().
equals
(
exception
)){
model
.
addAttribute
(
"isValidateCodeLogin"
,
isValidateCodeLogin
(
username
,
true
,
false
));
model
.
addAttribute
(
"isValidateCodeLogin"
,
isValidateCodeLogin
(
username
,
true
,
false
));
}
}
// 验证失败清空验证码
// 验证失败清空验证码
request
.
getSession
().
setAttribute
(
ValidateCodeServlet
.
VALIDATE_CODE
,
IdGen
.
uuid
());
request
.
getSession
().
setAttribute
(
ValidateCodeServlet
.
VALIDATE_CODE
,
IdGen
.
uuid
());
// 如果是手机登录,则返回JSON字符串
// 如果是手机登录,则返回JSON字符串
if
(
mobile
){
if
(
mobile
){
return
renderString
(
response
,
model
);
return
renderString
(
response
,
model
);
}
}
return
"modules/sys/sysLogin"
;
return
"modules/sys/sysLogin"
;
}
}
...
@@ -165,40 +147,10 @@ public class LoginController extends BaseController{
...
@@ -165,40 +147,10 @@ public class LoginController extends BaseController{
return
"redirect:"
+
adminPath
+
"/login"
;
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"
;
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 useruame 用户名
* @param isFail 计数加1
* @param isFail 计数加1
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment