Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
jinli gu
JeeSpringCloud
Commits
d3ad3768
Commit
d3ad3768
authored
Nov 12, 2018
by
Huang
Browse files
no commit message
parent
b6becbcd
Changes
393
Hide whitespace changes
Inline
Side-by-side
Too many changes to show.
To preserve performance only
20 of 393+
files are displayed.
Plain diff
Email patch
JeeSpringCloud/src/main/java/com/jeespring/common/utils/FreeMarkers.java
deleted
100644 → 0
View file @
b6becbcd
/**
* * Copyright © 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package
com.jeespring.common.utils
;
import
java.io.IOException
;
import
java.io.StringReader
;
import
java.io.StringWriter
;
import
java.util.Map
;
import
org.springframework.core.io.DefaultResourceLoader
;
import
org.springframework.core.io.Resource
;
import
freemarker.template.Configuration
;
import
freemarker.template.Template
;
/**
* FreeMarkers工具类
* @author 黄炳桂 516821420@qq.com
* @version 2013-01-15
*/
public
class
FreeMarkers
{
public
static
String
renderString
(
String
name
,
String
templateString
,
Map
<
String
,
?>
model
)
{
try
{
StringWriter
result
=
new
StringWriter
();
Template
t
=
new
Template
(
"name"
,
new
StringReader
(
templateString
),
new
Configuration
());
t
.
process
(
model
,
result
);
return
result
.
toString
();
}
catch
(
Exception
e
)
{
System
.
out
.
println
(
"代码生成执行:"
+
name
+
"文件时异常!"
);
throw
Exceptions
.
unchecked
(
e
);
}
}
public
static
String
renderTemplate
(
Template
template
,
Object
model
)
{
try
{
StringWriter
result
=
new
StringWriter
();
template
.
process
(
model
,
result
);
return
result
.
toString
();
}
catch
(
Exception
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
public
static
Configuration
buildConfiguration
(
String
directory
)
throws
IOException
{
Configuration
cfg
=
new
Configuration
();
Resource
path
=
new
DefaultResourceLoader
().
getResource
(
directory
);
cfg
.
setDirectoryForTemplateLoading
(
path
.
getFile
());
return
cfg
;
}
public
static
void
main
(
String
[]
args
)
throws
IOException
{
// // renderString
// Map<String, String> model = com.google.common.collect.Maps.newHashMap();
// model.put("userName", "calvin");
// String result = FreeMarkers.renderString("hello ${userName}", model);
// System.out.println(result);
// // renderTemplate
// Configuration cfg = FreeMarkers.buildConfiguration("classpath:/");
// Template template = cfg.getTemplate("testTemplate.ftl");
// String result2 = FreeMarkers.renderTemplate(template, model);
// System.out.println(result2);
// Map<String, String> model = com.google.common.collect.Maps.newHashMap();
// model.put("userName", "calvin");
// String result = FreeMarkers.renderString("hello ${userName} ${r'${userName}'}", model);
// System.out.println(result);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/GsonUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
com.google.gson.Gson
;
import
com.google.gson.GsonBuilder
;
import
com.google.gson.JsonParseException
;
import
java.lang.reflect.Type
;
/**
* Json工具类.
*/
public
class
GsonUtils
{
private
static
Gson
gson
=
new
GsonBuilder
().
create
();
public
static
String
toJson
(
Object
value
)
{
return
gson
.
toJson
(
value
);
}
public
static
<
T
>
T
fromJson
(
String
json
,
Class
<
T
>
classOfT
)
throws
JsonParseException
{
return
gson
.
fromJson
(
json
,
classOfT
);
}
public
static
<
T
>
T
fromJson
(
String
json
,
Type
typeOfT
)
throws
JsonParseException
{
return
(
T
)
gson
.
fromJson
(
json
,
typeOfT
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/HttpRequest.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
javax.servlet.http.HttpServletRequest
;
import
java.io.BufferedReader
;
import
java.io.IOException
;
import
java.io.InputStreamReader
;
import
java.io.PrintWriter
;
import
java.net.URL
;
import
java.net.URLConnection
;
import
java.util.List
;
import
java.util.Map
;
public
class
HttpRequest
{
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public
static
String
sendGet
(
String
url
,
String
param
)
{
String
result
=
""
;
BufferedReader
in
=
null
;
try
{
String
urlNameString
=
url
+
"?"
+
param
;
URL
realUrl
=
new
URL
(
urlNameString
);
// 打开和URL之间的连接
URLConnection
connection
=
realUrl
.
openConnection
();
// 设置通用的请求属性
connection
.
setRequestProperty
(
"accept"
,
"*/*"
);
connection
.
setRequestProperty
(
"connection"
,
"Keep-Alive"
);
connection
.
setRequestProperty
(
"user-agent"
,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"
);
// 建立实际的连接
connection
.
connect
();
// 获取所有响应头字段
//Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
//for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
//}
// 定义 BufferedReader输入流来读取URL的响应
in
=
new
BufferedReader
(
new
InputStreamReader
(
connection
.
getInputStream
()));
String
line
;
while
((
line
=
in
.
readLine
())
!=
null
)
{
result
+=
line
;
}
}
catch
(
Exception
e
)
{
System
.
out
.
println
(
"发送GET请求出现异常!"
+
e
.
toString
());
result
=
"Down"
;
//e.printStackTrace();
}
// 使用finally块来关闭输入流
finally
{
try
{
if
(
in
!=
null
)
{
in
.
close
();
}
}
catch
(
Exception
e2
)
{
e2
.
printStackTrace
();
}
}
return
result
;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public
static
String
sendPost
(
String
url
,
String
param
)
{
PrintWriter
out
=
null
;
BufferedReader
in
=
null
;
String
result
=
""
;
try
{
URL
realUrl
=
new
URL
(
url
);
// 打开和URL之间的连接
URLConnection
conn
=
realUrl
.
openConnection
();
// 设置通用的请求属性
conn
.
setRequestProperty
(
"accept"
,
"*/*"
);
conn
.
setRequestProperty
(
"connection"
,
"Keep-Alive"
);
conn
.
setRequestProperty
(
"user-agent"
,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"
);
// 发送POST请求必须设置如下两行
conn
.
setDoOutput
(
true
);
conn
.
setDoInput
(
true
);
// 获取URLConnection对象对应的输出流
out
=
new
PrintWriter
(
conn
.
getOutputStream
());
// 发送请求参数
out
.
print
(
param
);
// flush输出流的缓冲
out
.
flush
();
// 定义BufferedReader输入流来读取URL的响应
in
=
new
BufferedReader
(
new
InputStreamReader
(
conn
.
getInputStream
()));
String
line
;
while
((
line
=
in
.
readLine
())
!=
null
)
{
result
+=
line
;
}
}
catch
(
Exception
e
)
{
System
.
out
.
println
(
"发送 POST 请求出现异常!"
+
e
.
toString
());
//e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally
{
try
{
if
(
out
!=
null
){
out
.
close
();
}
if
(
in
!=
null
){
in
.
close
();
}
}
catch
(
IOException
ex
){
ex
.
printStackTrace
();
}
}
return
result
;
}
public
static
String
getParameterMapString
(
HttpServletRequest
request
){
if
(
request
.
getQueryString
()!=
null
){
if
(
request
.
getQueryString
().
length
()>
0
){
return
request
.
getQueryString
();
}
}
Map
map
=
request
.
getParameterMap
();
java
.
util
.
Enumeration
enumx
=
request
.
getParameterNames
();
String
result
=
""
;
while
(
enumx
.
hasMoreElements
()){
String
paramName
=(
String
)
enumx
.
nextElement
();
String
[]
values
=
request
.
getParameterValues
(
paramName
);
for
(
int
i
=
0
;
i
<
values
.
length
;
i
++){
result
+=
paramName
+
"="
+
values
[
i
]+
"&"
;
}
}
return
result
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/utils/HttpUtil.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.io.BufferedReader
;
import
java.io.DataOutputStream
;
import
java.io.InputStreamReader
;
import
java.net.HttpURLConnection
;
import
java.net.URL
;
import
java.util.List
;
import
java.util.Map
;
/**
* http 工具类
*/
public
class
HttpUtil
{
public
static
String
post
(
String
requestUrl
,
String
accessToken
,
String
params
)
throws
Exception
{
String
contentType
=
"application/x-www-form-urlencoded"
;
return
HttpUtil
.
post
(
requestUrl
,
accessToken
,
contentType
,
params
);
}
public
static
String
post
(
String
requestUrl
,
String
accessToken
,
String
contentType
,
String
params
)
throws
Exception
{
String
encoding
=
"UTF-8"
;
if
(
requestUrl
.
contains
(
"nlp"
))
{
encoding
=
"GBK"
;
}
return
HttpUtil
.
post
(
requestUrl
,
accessToken
,
contentType
,
params
,
encoding
);
}
public
static
String
post
(
String
requestUrl
,
String
accessToken
,
String
contentType
,
String
params
,
String
encoding
)
throws
Exception
{
String
url
=
requestUrl
+
"?access_token="
+
accessToken
;
return
HttpUtil
.
postGeneralUrl
(
url
,
contentType
,
params
,
encoding
);
}
public
static
String
postGeneralUrl
(
String
generalUrl
,
String
contentType
,
String
params
,
String
encoding
)
throws
Exception
{
URL
url
=
new
URL
(
generalUrl
);
// 打开和URL之间的连接
HttpURLConnection
connection
=
(
HttpURLConnection
)
url
.
openConnection
();
connection
.
setRequestMethod
(
"POST"
);
// 设置通用的请求属性
connection
.
setRequestProperty
(
"Content-Type"
,
contentType
);
connection
.
setRequestProperty
(
"Connection"
,
"Keep-Alive"
);
connection
.
setUseCaches
(
false
);
connection
.
setDoOutput
(
true
);
connection
.
setDoInput
(
true
);
// 得到请求的输出流对象
DataOutputStream
out
=
new
DataOutputStream
(
connection
.
getOutputStream
());
out
.
write
(
params
.
getBytes
(
encoding
));
out
.
flush
();
out
.
close
();
// 建立实际的连接
connection
.
connect
();
// 获取所有响应头字段
Map
<
String
,
List
<
String
>>
headers
=
connection
.
getHeaderFields
();
// 遍历所有的响应头字段
for
(
String
key
:
headers
.
keySet
())
{
System
.
err
.
println
(
key
+
"--->"
+
headers
.
get
(
key
));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader
in
=
null
;
in
=
new
BufferedReader
(
new
InputStreamReader
(
connection
.
getInputStream
(),
encoding
));
String
result
=
""
;
String
getLine
;
while
((
getLine
=
in
.
readLine
())
!=
null
)
{
result
+=
getLine
;
}
in
.
close
();
System
.
err
.
println
(
"result:"
+
result
);
return
result
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/utils/IdGen.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.utils
;
import
org.activiti.engine.impl.cfg.IdGenerator
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.session.mgt.eis.SessionIdGenerator
;
import
org.springframework.context.annotation.Lazy
;
import
org.springframework.stereotype.Service
;
import
java.io.Serializable
;
import
java.security.SecureRandom
;
import
java.util.UUID
;
/**
* 封装各种生成唯一性ID算法的工具类.
*
* @author 黄炳桂 516821420@qq.com
* @version 2013-01-15
*/
@Service
@Lazy
(
false
)
public
class
IdGen
implements
IdGenerator
,
SessionIdGenerator
{
private
static
SecureRandom
random
=
new
SecureRandom
();
/**
* 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
*/
public
static
String
uuid
()
{
return
UUID
.
randomUUID
().
toString
().
replaceAll
(
"-"
,
""
);
}
/**
* 使用SecureRandom随机生成Long.
*/
public
static
long
randomLong
()
{
return
Math
.
abs
(
random
.
nextLong
());
}
/**
* 基于Base62编码的SecureRandom随机生成bytes.
*/
public
static
String
randomBase62
(
int
length
)
{
byte
[]
randomBytes
=
new
byte
[
length
];
random
.
nextBytes
(
randomBytes
);
return
Encodes
.
encodeBase62
(
randomBytes
);
}
/**
* Activiti ID 生成
*/
//@Override
@Override
public
String
getNextId
()
{
return
IdGen
.
uuid
();
}
@Override
public
Serializable
generateId
(
Session
session
)
{
return
IdGen
.
uuid
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/IdcardUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.text.ParseException
;
import
java.text.SimpleDateFormat
;
import
java.util.Calendar
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.Map
;
import
org.apache.commons.lang3.StringUtils
;
/**
* 身份证工具类
*
* @author June
* @version 1.0, 2010-06-17
*/
public
class
IdcardUtils
extends
StringUtils
{
/** 中国公民身份证号码最小长度。 */
public
static
final
int
CHINA_ID_MIN_LENGTH
=
15
;
/** 中国公民身份证号码最大长度。 */
public
static
final
int
CHINA_ID_MAX_LENGTH
=
18
;
/**
* 省、直辖市代码表
*/
public
static
final
String
[]
cityCode
=
{
"11"
,
"12"
,
"13"
,
"14"
,
"15"
,
"21"
,
"22"
,
"23"
,
"31"
,
"32"
,
"33"
,
"34"
,
"35"
,
"36"
,
"37"
,
"41"
,
"42"
,
"43"
,
"44"
,
"45"
,
"46"
,
"50"
,
"51"
,
"52"
,
"53"
,
"54"
,
"61"
,
"62"
,
"63"
,
"64"
,
"65"
,
"71"
,
"81"
,
"82"
,
"91"
};
/**
* 每位加权因子
*/
public
static
final
int
[]
power
=
{
7
,
9
,
10
,
5
,
8
,
4
,
2
,
1
,
6
,
3
,
7
,
9
,
10
,
5
,
8
,
4
,
2
};
/**
* 第18位校检码
*/
public
static
final
String
[]
verifyCode
=
{
"1"
,
"0"
,
"X"
,
"9"
,
"8"
,
"7"
,
"6"
,
"5"
,
"4"
,
"3"
,
"2"
};
/** 最低年限 */
public
static
final
int
MIN
=
1930
;
public
static
Map
<
String
,
String
>
cityCodes
=
new
HashMap
<
String
,
String
>();
/** 台湾身份首字母对应数字 */
public
static
Map
<
String
,
Integer
>
twFirstCode
=
new
HashMap
<
String
,
Integer
>();
/** 香港身份首字母对应数字 */
public
static
Map
<
String
,
Integer
>
hkFirstCode
=
new
HashMap
<
String
,
Integer
>();
static
{
cityCodes
.
put
(
"11"
,
"北京"
);
cityCodes
.
put
(
"12"
,
"天津"
);
cityCodes
.
put
(
"13"
,
"河北"
);
cityCodes
.
put
(
"14"
,
"山西"
);
cityCodes
.
put
(
"15"
,
"内蒙古"
);
cityCodes
.
put
(
"21"
,
"辽宁"
);
cityCodes
.
put
(
"22"
,
"吉林"
);
cityCodes
.
put
(
"23"
,
"黑龙江"
);
cityCodes
.
put
(
"31"
,
"上海"
);
cityCodes
.
put
(
"32"
,
"江苏"
);
cityCodes
.
put
(
"33"
,
"浙江"
);
cityCodes
.
put
(
"34"
,
"安徽"
);
cityCodes
.
put
(
"35"
,
"福建"
);
cityCodes
.
put
(
"36"
,
"江西"
);
cityCodes
.
put
(
"37"
,
"山东"
);
cityCodes
.
put
(
"41"
,
"河南"
);
cityCodes
.
put
(
"42"
,
"湖北"
);
cityCodes
.
put
(
"43"
,
"湖南"
);
cityCodes
.
put
(
"44"
,
"广东"
);
cityCodes
.
put
(
"45"
,
"广西"
);
cityCodes
.
put
(
"46"
,
"海南"
);
cityCodes
.
put
(
"50"
,
"重庆"
);
cityCodes
.
put
(
"51"
,
"四川"
);
cityCodes
.
put
(
"52"
,
"贵州"
);
cityCodes
.
put
(
"53"
,
"云南"
);
cityCodes
.
put
(
"54"
,
"西藏"
);
cityCodes
.
put
(
"61"
,
"陕西"
);
cityCodes
.
put
(
"62"
,
"甘肃"
);
cityCodes
.
put
(
"63"
,
"青海"
);
cityCodes
.
put
(
"64"
,
"宁夏"
);
cityCodes
.
put
(
"65"
,
"新疆"
);
cityCodes
.
put
(
"71"
,
"台湾"
);
cityCodes
.
put
(
"81"
,
"香港"
);
cityCodes
.
put
(
"82"
,
"澳门"
);
cityCodes
.
put
(
"91"
,
"国外"
);
twFirstCode
.
put
(
"A"
,
10
);
twFirstCode
.
put
(
"B"
,
11
);
twFirstCode
.
put
(
"C"
,
12
);
twFirstCode
.
put
(
"D"
,
13
);
twFirstCode
.
put
(
"E"
,
14
);
twFirstCode
.
put
(
"F"
,
15
);
twFirstCode
.
put
(
"G"
,
16
);
twFirstCode
.
put
(
"H"
,
17
);
twFirstCode
.
put
(
"J"
,
18
);
twFirstCode
.
put
(
"K"
,
19
);
twFirstCode
.
put
(
"L"
,
20
);
twFirstCode
.
put
(
"M"
,
21
);
twFirstCode
.
put
(
"N"
,
22
);
twFirstCode
.
put
(
"P"
,
23
);
twFirstCode
.
put
(
"Q"
,
24
);
twFirstCode
.
put
(
"R"
,
25
);
twFirstCode
.
put
(
"S"
,
26
);
twFirstCode
.
put
(
"T"
,
27
);
twFirstCode
.
put
(
"U"
,
28
);
twFirstCode
.
put
(
"V"
,
29
);
twFirstCode
.
put
(
"X"
,
30
);
twFirstCode
.
put
(
"Y"
,
31
);
twFirstCode
.
put
(
"W"
,
32
);
twFirstCode
.
put
(
"Z"
,
33
);
twFirstCode
.
put
(
"I"
,
34
);
twFirstCode
.
put
(
"O"
,
35
);
hkFirstCode
.
put
(
"A"
,
1
);
hkFirstCode
.
put
(
"B"
,
2
);
hkFirstCode
.
put
(
"C"
,
3
);
hkFirstCode
.
put
(
"R"
,
18
);
hkFirstCode
.
put
(
"U"
,
21
);
hkFirstCode
.
put
(
"Z"
,
26
);
hkFirstCode
.
put
(
"X"
,
24
);
hkFirstCode
.
put
(
"W"
,
23
);
hkFirstCode
.
put
(
"O"
,
15
);
hkFirstCode
.
put
(
"N"
,
14
);
}
/**
* 将15位身份证号码转换为18位
*
* @param idCard
* 15位身份编码
* @return 18位身份编码
*/
public
static
String
conver15CardTo18
(
String
idCard
)
{
String
idCard18
=
""
;
if
(
idCard
.
length
()
!=
CHINA_ID_MIN_LENGTH
)
{
return
null
;
}
if
(
isNum
(
idCard
))
{
// 获取出生年月日
String
birthday
=
idCard
.
substring
(
6
,
12
);
Date
birthDate
=
null
;
try
{
birthDate
=
new
SimpleDateFormat
(
"yyMMdd"
).
parse
(
birthday
);
}
catch
(
ParseException
e
)
{
e
.
printStackTrace
();
}
Calendar
cal
=
Calendar
.
getInstance
();
if
(
birthDate
!=
null
)
{
cal
.
setTime
(
birthDate
);
}
// 获取出生年(完全表现形式,如:2010)
String
sYear
=
String
.
valueOf
(
cal
.
get
(
Calendar
.
YEAR
));
idCard18
=
idCard
.
substring
(
0
,
6
)
+
sYear
+
idCard
.
substring
(
8
);
// 转换字符数组
char
[]
cArr
=
idCard18
.
toCharArray
();
if
(
cArr
!=
null
)
{
int
[]
iCard
=
converCharToInt
(
cArr
);
int
iSum17
=
getPowerSum
(
iCard
);
// 获取校验位
String
sVal
=
getCheckCode18
(
iSum17
);
if
(
sVal
.
length
()
>
0
)
{
idCard18
+=
sVal
;
}
else
{
return
null
;
}
}
}
else
{
return
null
;
}
return
idCard18
;
}
/**
* 验证身份证是否合法
*/
public
static
boolean
validateCard
(
String
idCard
)
{
String
card
=
idCard
.
trim
();
if
(
validateIdCard18
(
card
))
{
return
true
;
}
if
(
validateIdCard15
(
card
))
{
return
true
;
}
String
[]
cardval
=
validateIdCard10
(
card
);
if
(
cardval
!=
null
)
{
if
(
"true"
.
equals
(
cardval
[
2
]))
{
return
true
;
}
}
return
false
;
}
/**
* 验证18位身份编码是否合法
*
* @param idCard
* 身份编码
* @return 是否合法
*/
public
static
boolean
validateIdCard18
(
String
idCard
)
{
boolean
bTrue
=
false
;
if
(
idCard
.
length
()
==
CHINA_ID_MAX_LENGTH
)
{
// 前17位
String
code17
=
idCard
.
substring
(
0
,
17
);
// 第18位
String
code18
=
idCard
.
substring
(
17
,
CHINA_ID_MAX_LENGTH
);
if
(
isNum
(
code17
))
{
char
[]
cArr
=
code17
.
toCharArray
();
if
(
cArr
!=
null
)
{
int
[]
iCard
=
converCharToInt
(
cArr
);
int
iSum17
=
getPowerSum
(
iCard
);
// 获取校验位
String
val
=
getCheckCode18
(
iSum17
);
if
(
val
.
length
()
>
0
)
{
if
(
val
.
equalsIgnoreCase
(
code18
))
{
bTrue
=
true
;
}
}
}
}
}
return
bTrue
;
}
/**
* 验证15位身份编码是否合法
*
* @param idCard
* 身份编码
* @return 是否合法
*/
public
static
boolean
validateIdCard15
(
String
idCard
)
{
if
(
idCard
.
length
()
!=
CHINA_ID_MIN_LENGTH
)
{
return
false
;
}
if
(
isNum
(
idCard
))
{
String
proCode
=
idCard
.
substring
(
0
,
2
);
if
(
cityCodes
.
get
(
proCode
)
==
null
)
{
return
false
;
}
String
birthCode
=
idCard
.
substring
(
6
,
12
);
Date
birthDate
=
null
;
try
{
birthDate
=
new
SimpleDateFormat
(
"yy"
).
parse
(
birthCode
.
substring
(
0
,
2
));
}
catch
(
ParseException
e
)
{
e
.
printStackTrace
();
}
Calendar
cal
=
Calendar
.
getInstance
();
if
(
birthDate
!=
null
)
{
cal
.
setTime
(
birthDate
);
}
if
(!
valiDate
(
cal
.
get
(
Calendar
.
YEAR
),
Integer
.
valueOf
(
birthCode
.
substring
(
2
,
4
)),
Integer
.
valueOf
(
birthCode
.
substring
(
4
,
6
))))
{
return
false
;
}
}
else
{
return
false
;
}
return
true
;
}
/**
* 验证10位身份编码是否合法
*
* @param idCard
* 身份编码
* @return 身份证信息数组
* <p>
* [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false)
* 若不是身份证件号码则返回null
* </p>
*/
public
static
String
[]
validateIdCard10
(
String
idCard
)
{
String
[]
info
=
new
String
[
3
];
String
card
=
idCard
.
replaceAll
(
"[\\(|\\)]"
,
""
);
if
(
card
.
length
()
!=
8
&&
card
.
length
()
!=
9
&&
idCard
.
length
()
!=
10
)
{
return
null
;
}
if
(
idCard
.
matches
(
"^[a-zA-Z][0-9]{9}$"
))
{
// 台湾
info
[
0
]
=
"台湾"
;
System
.
out
.
println
(
"11111"
);
String
char2
=
idCard
.
substring
(
1
,
2
);
if
(
"1"
.
equals
(
char2
))
{
info
[
1
]
=
"M"
;
System
.
out
.
println
(
"MMMMMMM"
);
}
else
if
(
"2"
.
equals
(
char2
))
{
info
[
1
]
=
"F"
;
System
.
out
.
println
(
"FFFFFFF"
);
}
else
{
info
[
1
]
=
"N"
;
info
[
2
]
=
"false"
;
System
.
out
.
println
(
"NNNN"
);
return
info
;
}
info
[
2
]
=
validateTWCard
(
idCard
)
?
"true"
:
"false"
;
}
else
if
(
idCard
.
matches
(
"^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$"
))
{
// 澳门
info
[
0
]
=
"澳门"
;
info
[
1
]
=
"N"
;
}
else
if
(
idCard
.
matches
(
"^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$"
))
{
// 香港
info
[
0
]
=
"香港"
;
info
[
1
]
=
"N"
;
info
[
2
]
=
validateHKCard
(
idCard
)
?
"true"
:
"false"
;
}
else
{
return
null
;
}
return
info
;
}
/**
* 验证台湾身份证号码
*
* @param idCard
* 身份证号码
* @return 验证码是否符合
*/
public
static
boolean
validateTWCard
(
String
idCard
)
{
String
start
=
idCard
.
substring
(
0
,
1
);
String
mid
=
idCard
.
substring
(
1
,
9
);
String
end
=
idCard
.
substring
(
9
,
10
);
Integer
iStart
=
twFirstCode
.
get
(
start
);
Integer
sum
=
iStart
/
10
+
(
iStart
%
10
)
*
9
;
char
[]
chars
=
mid
.
toCharArray
();
Integer
iflag
=
8
;
for
(
char
c
:
chars
)
{
sum
=
sum
+
Integer
.
valueOf
(
c
+
""
)
*
iflag
;
iflag
--;
}
return
(
sum
%
10
==
0
?
0
:
(
10
-
sum
%
10
))
==
Integer
.
valueOf
(
end
)
?
true
:
false
;
}
/**
* 验证香港身份证号码(存在Bug,部份特殊身份证无法检查)
* <p>
* 身份证前2位为英文字符,如果只出现一个英文字符则表示第一位是空格,对应数字58 前2位英文字符A-Z分别对应数字10-35
* 最后一位校验码为0-9的数字加上字符"A","A"代表10
* </p>
* <p>
* 将身份证号码全部转换为数字,分别对应乘9-1相加的总和,整除11则证件号码有效
* </p>
*
* @param idCard
* 身份证号码
* @return 验证码是否符合
*/
public
static
boolean
validateHKCard
(
String
idCard
)
{
String
card
=
idCard
.
replaceAll
(
"[\\(|\\)]"
,
""
);
Integer
sum
=
0
;
if
(
card
.
length
()
==
9
)
{
sum
=
(
Integer
.
valueOf
(
card
.
substring
(
0
,
1
).
toUpperCase
()
.
toCharArray
()[
0
])
-
55
)
*
9
+
(
Integer
.
valueOf
(
card
.
substring
(
1
,
2
).
toUpperCase
()
.
toCharArray
()[
0
])
-
55
)
*
8
;
card
=
card
.
substring
(
1
,
9
);
}
else
{
sum
=
522
+
(
Integer
.
valueOf
(
card
.
substring
(
0
,
1
).
toUpperCase
()
.
toCharArray
()[
0
])
-
55
)
*
8
;
}
String
mid
=
card
.
substring
(
1
,
7
);
String
end
=
card
.
substring
(
7
,
8
);
char
[]
chars
=
mid
.
toCharArray
();
Integer
iflag
=
7
;
for
(
char
c
:
chars
)
{
sum
=
sum
+
Integer
.
valueOf
(
c
+
""
)
*
iflag
;
iflag
--;
}
if
(
"A"
.
equals
(
end
.
toUpperCase
()))
{
sum
=
sum
+
10
;
}
else
{
sum
=
sum
+
Integer
.
valueOf
(
end
);
}
return
(
sum
%
11
==
0
)
?
true
:
false
;
}
/**
* 将字符数组转换成数字数组
*
* @param ca
* 字符数组
* @return 数字数组
*/
public
static
int
[]
converCharToInt
(
char
[]
ca
)
{
int
len
=
ca
.
length
;
int
[]
iArr
=
new
int
[
len
];
try
{
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
iArr
[
i
]
=
Integer
.
parseInt
(
String
.
valueOf
(
ca
[
i
]));
}
}
catch
(
NumberFormatException
e
)
{
e
.
printStackTrace
();
}
return
iArr
;
}
/**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值
*
* @param iArr
* @return 身份证编码。
*/
public
static
int
getPowerSum
(
int
[]
iArr
)
{
int
iSum
=
0
;
if
(
power
.
length
==
iArr
.
length
)
{
for
(
int
i
=
0
;
i
<
iArr
.
length
;
i
++)
{
for
(
int
j
=
0
;
j
<
power
.
length
;
j
++)
{
if
(
i
==
j
)
{
iSum
=
iSum
+
iArr
[
i
]
*
power
[
j
];
}
}
}
}
return
iSum
;
}
/**
* 将power和值与11取模获得余数进行校验码判断
*
* @param iSum
* @return 校验位
*/
public
static
String
getCheckCode18
(
int
iSum
)
{
String
sCode
=
""
;
switch
(
iSum
%
11
)
{
case
10
:
sCode
=
"2"
;
break
;
case
9
:
sCode
=
"3"
;
break
;
case
8
:
sCode
=
"4"
;
break
;
case
7
:
sCode
=
"5"
;
break
;
case
6
:
sCode
=
"6"
;
break
;
case
5
:
sCode
=
"7"
;
break
;
case
4
:
sCode
=
"8"
;
break
;
case
3
:
sCode
=
"9"
;
break
;
case
2
:
sCode
=
"x"
;
break
;
case
1
:
sCode
=
"0"
;
break
;
case
0
:
sCode
=
"1"
;
break
;
}
return
sCode
;
}
/**
* 根据身份编号获取年龄
*
* @param idCard
* 身份编号
* @return 年龄
*/
public
static
int
getAgeByIdCard
(
String
idCard
)
{
int
iAge
=
0
;
if
(
idCard
.
length
()
==
CHINA_ID_MIN_LENGTH
)
{
idCard
=
conver15CardTo18
(
idCard
);
}
String
year
=
idCard
.
substring
(
6
,
10
);
Calendar
cal
=
Calendar
.
getInstance
();
int
iCurrYear
=
cal
.
get
(
Calendar
.
YEAR
);
iAge
=
iCurrYear
-
Integer
.
valueOf
(
year
);
return
iAge
;
}
/**
* 根据身份编号获取生日
*
* @param idCard
* 身份编号
* @return 生日(yyyyMMdd)
*/
public
static
String
getBirthByIdCard
(
String
idCard
)
{
Integer
len
=
idCard
.
length
();
if
(
len
<
CHINA_ID_MIN_LENGTH
)
{
return
null
;
}
else
if
(
len
==
CHINA_ID_MIN_LENGTH
)
{
idCard
=
conver15CardTo18
(
idCard
);
}
return
idCard
.
substring
(
6
,
14
);
}
/**
* 根据身份编号获取生日年
*
* @param idCard
* 身份编号
* @return 生日(yyyy)
*/
public
static
Short
getYearByIdCard
(
String
idCard
)
{
Integer
len
=
idCard
.
length
();
if
(
len
<
CHINA_ID_MIN_LENGTH
)
{
return
null
;
}
else
if
(
len
==
CHINA_ID_MIN_LENGTH
)
{
idCard
=
conver15CardTo18
(
idCard
);
}
return
Short
.
valueOf
(
idCard
.
substring
(
6
,
10
));
}
/**
* 根据身份编号获取生日月
*
* @param idCard
* 身份编号
* @return 生日(MM)
*/
public
static
Short
getMonthByIdCard
(
String
idCard
)
{
Integer
len
=
idCard
.
length
();
if
(
len
<
CHINA_ID_MIN_LENGTH
)
{
return
null
;
}
else
if
(
len
==
CHINA_ID_MIN_LENGTH
)
{
idCard
=
conver15CardTo18
(
idCard
);
}
return
Short
.
valueOf
(
idCard
.
substring
(
10
,
12
));
}
/**
* 根据身份编号获取生日天
*
* @param idCard
* 身份编号
* @return 生日(dd)
*/
public
static
Short
getDateByIdCard
(
String
idCard
)
{
Integer
len
=
idCard
.
length
();
if
(
len
<
CHINA_ID_MIN_LENGTH
)
{
return
null
;
}
else
if
(
len
==
CHINA_ID_MIN_LENGTH
)
{
idCard
=
conver15CardTo18
(
idCard
);
}
return
Short
.
valueOf
(
idCard
.
substring
(
12
,
14
));
}
/**
* 根据身份编号获取性别
*
* @param idCard
* 身份编号
* @return 性别(M-男,F-女,N-未知)
*/
public
static
String
getGenderByIdCard
(
String
idCard
)
{
String
sGender
=
"N"
;
if
(
idCard
.
length
()
==
CHINA_ID_MIN_LENGTH
)
{
idCard
=
conver15CardTo18
(
idCard
);
}
String
sCardNum
=
idCard
.
substring
(
16
,
17
);
if
(
Integer
.
parseInt
(
sCardNum
)
%
2
!=
0
)
{
sGender
=
"M"
;
}
else
{
sGender
=
"F"
;
}
return
sGender
;
}
/**
* 根据身份编号获取户籍省份
*
* @param idCard
* 身份编码
* @return 省级编码。
*/
public
static
String
getProvinceByIdCard
(
String
idCard
)
{
int
len
=
idCard
.
length
();
String
sProvince
=
null
;
String
sProvinNum
=
""
;
if
(
len
==
CHINA_ID_MIN_LENGTH
||
len
==
CHINA_ID_MAX_LENGTH
)
{
sProvinNum
=
idCard
.
substring
(
0
,
2
);
}
sProvince
=
cityCodes
.
get
(
sProvinNum
);
return
sProvince
;
}
/**
* 数字验证
*
* @param val
* @return 提取的数字。
*/
public
static
boolean
isNum
(
String
val
)
{
return
val
==
null
||
""
.
equals
(
val
)
?
false
:
val
.
matches
(
"^[0-9]*$"
);
}
/**
* 验证小于当前日期 是否有效
*
* @param iYear
* 待验证日期(年)
* @param iMonth
* 待验证日期(月 1-12)
* @param iDate
* 待验证日期(日)
* @return 是否有效
*/
public
static
boolean
valiDate
(
int
iYear
,
int
iMonth
,
int
iDate
)
{
Calendar
cal
=
Calendar
.
getInstance
();
int
year
=
cal
.
get
(
Calendar
.
YEAR
);
int
datePerMonth
;
if
(
iYear
<
MIN
||
iYear
>=
year
)
{
return
false
;
}
if
(
iMonth
<
1
||
iMonth
>
12
)
{
return
false
;
}
switch
(
iMonth
)
{
case
4
:
case
6
:
case
9
:
case
11
:
datePerMonth
=
30
;
break
;
case
2
:
boolean
dm
=
((
iYear
%
4
==
0
&&
iYear
%
100
!=
0
)
||
(
iYear
%
400
==
0
))
&&
(
iYear
>
MIN
&&
iYear
<
year
);
datePerMonth
=
dm
?
29
:
28
;
break
;
default
:
datePerMonth
=
31
;
}
return
(
iDate
>=
1
)
&&
(
iDate
<=
datePerMonth
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/ImageGeo.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
com.drew.metadata.*
;
import
com.drew.metadata.exif.*
;
import
com.drew.imaging.jpeg.*
;
import
com.drew.lang.*
;
import
java.io.*
;
public
class
ImageGeo
{
public
double
lat
=
0.0
;
public
double
lon
=
0.0
;
public
double
alt
=
0.0
;
public
boolean
error
=
false
;
public
ImageGeo
(
String
filename
)
{
try
{
error
=
false
;
File
jpegFile
=
new
File
(
filename
);
Metadata
metadata
=
JpegMetadataReader
.
readMetadata
(
jpegFile
);
GpsDirectory
gpsdir
=
(
GpsDirectory
)
metadata
.
getDirectory
(
GpsDirectory
.
class
);
Rational
[]
latpart
=
gpsdir
.
getRationalArray
(
GpsDirectory
.
TAG_GPS_LATITUDE
);
Rational
[]
lonpart
=
gpsdir
.
getRationalArray
(
GpsDirectory
.
TAG_GPS_LONGITUDE
);
String
northing
=
gpsdir
.
getString
(
GpsDirectory
.
TAG_GPS_LATITUDE_REF
);
String
easting
=
gpsdir
.
getString
(
GpsDirectory
.
TAG_GPS_LONGITUDE_REF
);
try
{
alt
=
gpsdir
.
getDouble
(
GpsDirectory
.
TAG_GPS_ALTITUDE
);
}
catch
(
Exception
ex
)
{
}
double
latsign
=
1.0d
;
if
(
"S"
.
equalsIgnoreCase
(
northing
))
{
latsign
=
-
1.0d
;
}
double
lonsign
=
1.0d
;
if
(
"W"
.
equalsIgnoreCase
(
easting
))
{
lonsign
=
-
1.0d
;
}
lat
=
(
Math
.
abs
(
latpart
[
0
].
doubleValue
())
+
latpart
[
1
].
doubleValue
()
/
60.0d
+
latpart
[
2
]
.
doubleValue
()
/
3600.0d
)
*
latsign
;
lon
=
(
Math
.
abs
(
lonpart
[
0
].
doubleValue
())
+
lonpart
[
1
].
doubleValue
()
/
60.0d
+
lonpart
[
2
]
.
doubleValue
()
/
3600.0d
)
*
lonsign
;
if
(
Double
.
isNaN
(
lat
)
||
Double
.
isNaN
(
lon
))
{
error
=
true
;
}
}
catch
(
Exception
ex
)
{
error
=
true
;
}
System
.
out
.
println
(
filename
+
": ("
+
lat
+
", "
+
lon
+
")"
);
}
public
static
void
main
(
String
[]
args
)
{
ImageGeo
imageGeo
=
new
ImageGeo
(
ImageGeo
.
class
.
getResource
(
"IMAG0068.jpg"
).
getFile
());
System
.
out
.
println
(
imageGeo
.
lon
+
","
+
imageGeo
.
lat
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/IpUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
javax.servlet.http.HttpServletRequest
;
/**
* 获取IP方法
*
* @author JeeSpring
*/
public
class
IpUtils
{
public
static
String
getIpAddr
(
HttpServletRequest
request
)
{
if
(
request
==
null
)
{
return
"unknown"
;
}
String
ip
=
request
.
getHeader
(
"x-forwarded-for"
);
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"Proxy-Client-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"X-Forwarded-For"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"WL-Proxy-Client-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"X-Real-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getRemoteAddr
();
}
return
"0:0:0:0:0:0:0:1"
.
equals
(
ip
)
?
"127.0.0.1"
:
ip
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/MacUtils.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.utils
;
import
java.io.BufferedReader
;
import
java.io.IOException
;
import
java.io.InputStreamReader
;
/**
* MAC地址工具
*
* @author 黄炳桂 516821420@qq.com
* @version 2013-12-21
*/
public
class
MacUtils
{
/**
* 获取当前操作系统名称. return 操作系统名称 例如:windows,Linux,Unix等.
*/
public
static
String
getOSName
()
{
return
System
.
getProperty
(
"os.name"
).
toLowerCase
();
}
/**
* 获取Unix网卡的mac地址.
*
* @return mac地址
*/
public
static
String
getUnixMACAddress
()
{
String
mac
=
null
;
BufferedReader
bufferedReader
=
null
;
Process
process
=
null
;
try
{
/**
* Unix下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
*/
process
=
Runtime
.
getRuntime
().
exec
(
"ifconfig eth0"
);
bufferedReader
=
new
BufferedReader
(
new
InputStreamReader
(
process
.
getInputStream
()));
String
line
=
null
;
int
index
=
-
1
;
while
((
line
=
bufferedReader
.
readLine
())
!=
null
)
{
/**
* 寻找标示字符串[hwaddr]
*/
index
=
line
.
toLowerCase
().
indexOf
(
"hwaddr"
);
/**
* 找到了
*/
if
(
index
!=
-
1
)
{
/**
* 取出mac地址并去除2边空格
*/
mac
=
line
.
substring
(
index
+
"hwaddr"
.
length
()
+
1
).
trim
();
break
;
}
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
finally
{
try
{
if
(
bufferedReader
!=
null
)
{
bufferedReader
.
close
();
}
}
catch
(
IOException
e1
)
{
e1
.
printStackTrace
();
}
bufferedReader
=
null
;
process
=
null
;
}
return
mac
;
}
/**
* 获取Linux网卡的mac地址.
*
* @return mac地址
*/
public
static
String
getLinuxMACAddress
()
{
String
mac
=
null
;
BufferedReader
bufferedReader
=
null
;
Process
process
=
null
;
try
{
/**
* linux下的命令,一般取eth0作为本地主网卡 显示信息中包含有mac地址信息
*/
process
=
Runtime
.
getRuntime
().
exec
(
"ifconfig eth0"
);
bufferedReader
=
new
BufferedReader
(
new
InputStreamReader
(
process
.
getInputStream
()));
String
line
=
null
;
int
index
=
-
1
;
while
((
line
=
bufferedReader
.
readLine
())
!=
null
)
{
index
=
line
.
toLowerCase
().
indexOf
(
"硬件地址"
);
/**
* 找到了
*/
if
(
index
!=
-
1
)
{
/**
* 取出mac地址并去除2边空格
*/
mac
=
line
.
substring
(
index
+
4
).
trim
();
break
;
}
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
finally
{
try
{
if
(
bufferedReader
!=
null
)
{
bufferedReader
.
close
();
}
}
catch
(
IOException
e1
)
{
e1
.
printStackTrace
();
}
bufferedReader
=
null
;
process
=
null
;
}
// 取不到,试下Unix取发
if
(
mac
==
null
){
return
getUnixMACAddress
();
}
return
mac
;
}
/**
* 获取widnows网卡的mac地址.
*
* @return mac地址
*/
public
static
String
getWindowsMACAddress
()
{
String
mac
=
null
;
BufferedReader
bufferedReader
=
null
;
Process
process
=
null
;
try
{
/**
* windows下的命令,显示信息中包含有mac地址信息
*/
process
=
Runtime
.
getRuntime
().
exec
(
"ipconfig /all"
);
bufferedReader
=
new
BufferedReader
(
new
InputStreamReader
(
process
.
getInputStream
()));
String
line
=
null
;
int
index
=
-
1
;
while
((
line
=
bufferedReader
.
readLine
())
!=
null
)
{
/**
* 寻找标示字符串[physical address]
*/
// index = line.toLowerCase().indexOf("physical address");
// if (index != -1) {
if
(
line
.
split
(
"-"
).
length
==
6
){
index
=
line
.
indexOf
(
":"
);
if
(
index
!=
-
1
)
{
/**
* 取出mac地址并去除2边空格
*/
mac
=
line
.
substring
(
index
+
1
).
trim
();
}
break
;
}
index
=
line
.
toLowerCase
().
indexOf
(
"物理地址"
);
if
(
index
!=
-
1
)
{
index
=
line
.
indexOf
(
":"
);
if
(
index
!=
-
1
)
{
/**
* 取出mac地址并去除2边空格
*/
mac
=
line
.
substring
(
index
+
1
).
trim
();
}
break
;
}
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
finally
{
try
{
if
(
bufferedReader
!=
null
)
{
bufferedReader
.
close
();
}
}
catch
(
IOException
e1
)
{
e1
.
printStackTrace
();
}
bufferedReader
=
null
;
process
=
null
;
}
return
mac
;
}
public
static
String
getMac
(){
String
os
=
getOSName
();
String
mac
;
if
(
os
.
startsWith
(
"windows"
))
{
mac
=
getWindowsMACAddress
();
}
else
if
(
os
.
startsWith
(
"linux"
))
{
mac
=
getLinuxMACAddress
();
}
else
{
mac
=
getUnixMACAddress
();
}
return
mac
==
null
?
""
:
mac
;
}
/**
* 测试用的main方法.
*
* @param argc 运行参数.
*/
public
static
void
main
(
String
[]
argc
)
{
String
os
=
getOSName
();
System
.
out
.
println
(
"os: "
+
os
);
if
(
os
.
startsWith
(
"windows"
))
{
String
mac
=
getWindowsMACAddress
();
System
.
out
.
println
(
"mac: "
+
mac
);
}
else
if
(
os
.
startsWith
(
"linux"
))
{
String
mac
=
getLinuxMACAddress
();
System
.
out
.
println
(
"mac: "
+
mac
);
}
else
{
String
mac
=
getUnixMACAddress
();
System
.
out
.
println
(
"mac: "
+
mac
);
}
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/utils/MyBeanUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.beans.PropertyDescriptor
;
import
java.lang.reflect.InvocationTargetException
;
import
java.util.Iterator
;
import
java.util.Map
;
import
org.apache.commons.beanutils.DynaBean
;
import
org.apache.commons.beanutils.DynaProperty
;
import
org.apache.commons.beanutils.PropertyUtils
;
import
org.apache.commons.beanutils.PropertyUtilsBean
;
/**
* <p>Title: </p>
* <p>Description: </p>
* @author 刘高峰
* @version 2.0
*/
public
class
MyBeanUtils
extends
PropertyUtilsBean
{
private
static
void
convert
(
Object
dest
,
Object
orig
)
throws
IllegalAccessException
,
InvocationTargetException
{
// Validate existence of the specified beans
if
(
dest
==
null
)
{
throw
new
IllegalArgumentException
(
"No destination bean specified"
);
}
if
(
orig
==
null
)
{
throw
new
IllegalArgumentException
(
"No origin bean specified"
);
}
// Copy the properties, converting as necessary
if
(
orig
instanceof
DynaBean
)
{
DynaProperty
[]
origDescriptors
=
((
DynaBean
)
orig
).
getDynaClass
().
getDynaProperties
();
for
(
int
i
=
0
;
i
<
origDescriptors
.
length
;
i
++)
{
String
name
=
origDescriptors
[
i
].
getName
();
if
(
PropertyUtils
.
isWriteable
(
dest
,
name
))
{
Object
value
=
(
(
DynaBean
)
orig
).
get
(
name
);
try
{
getInstance
().
setSimpleProperty
(
dest
,
name
,
value
);
}
catch
(
Exception
e
)
{
;
// Should not happen
}
}
}
}
else
if
(
orig
instanceof
Map
)
{
Iterator
names
=
(
(
Map
)
orig
).
keySet
().
iterator
();
while
(
names
.
hasNext
())
{
String
name
=
(
String
)
names
.
next
();
if
(
PropertyUtils
.
isWriteable
(
dest
,
name
))
{
Object
value
=
(
(
Map
)
orig
).
get
(
name
);
try
{
getInstance
().
setSimpleProperty
(
dest
,
name
,
value
);
}
catch
(
Exception
e
)
{
;
// Should not happen
}
}
}
}
else
/* if (orig is a standard JavaBean) */
{
PropertyDescriptor
[]
origDescriptors
=
PropertyUtils
.
getPropertyDescriptors
(
orig
);
for
(
int
i
=
0
;
i
<
origDescriptors
.
length
;
i
++)
{
String
name
=
origDescriptors
[
i
].
getName
();
// String type = origDescriptors[i].getPropertyType().toString();
if
(
"class"
.
equals
(
name
))
{
continue
;
// No point in trying to set an object's class
}
if
(
PropertyUtils
.
isReadable
(
orig
,
name
)
&&
PropertyUtils
.
isWriteable
(
dest
,
name
))
{
try
{
Object
value
=
PropertyUtils
.
getSimpleProperty
(
orig
,
name
);
getInstance
().
setSimpleProperty
(
dest
,
name
,
value
);
}
catch
(
IllegalArgumentException
ie
)
{
;
// Should not happen
}
catch
(
Exception
e
)
{
;
// Should not happen
}
}
}
}
}
/**
* 对象拷贝
* 数据对象空值不拷贝到目标对象
*
* @param dataObject
* @param toObject
* @throws NoSuchMethodException
* copy
*/
public
static
void
copyBeanNotNull2Bean
(
Object
databean
,
Object
tobean
)
throws
Exception
{
PropertyDescriptor
[]
origDescriptors
=
PropertyUtils
.
getPropertyDescriptors
(
databean
);
for
(
int
i
=
0
;
i
<
origDescriptors
.
length
;
i
++)
{
String
name
=
origDescriptors
[
i
].
getName
();
// String type = origDescriptors[i].getPropertyType().toString();
if
(
"class"
.
equals
(
name
))
{
continue
;
// No point in trying to set an object's class
}
if
(
PropertyUtils
.
isReadable
(
databean
,
name
)
&&
PropertyUtils
.
isWriteable
(
tobean
,
name
))
{
try
{
Object
value
=
PropertyUtils
.
getSimpleProperty
(
databean
,
name
);
if
(
value
!=
null
){
getInstance
().
setSimpleProperty
(
tobean
,
name
,
value
);
}
}
catch
(
IllegalArgumentException
ie
)
{
;
// Should not happen
}
catch
(
Exception
e
)
{
;
// Should not happen
}
}
}
}
/**
* 把orig和dest相同属性的value复制到dest中
* @param dest
* @param orig
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public
static
void
copyBean2Bean
(
Object
dest
,
Object
orig
)
throws
Exception
{
convert
(
dest
,
orig
);
}
public
static
void
copyBean2Map
(
Map
map
,
Object
bean
){
PropertyDescriptor
[]
pds
=
PropertyUtils
.
getPropertyDescriptors
(
bean
);
for
(
int
i
=
0
;
i
<
pds
.
length
;
i
++)
{
PropertyDescriptor
pd
=
pds
[
i
];
String
propname
=
pd
.
getName
();
try
{
Object
propvalue
=
PropertyUtils
.
getSimpleProperty
(
bean
,
propname
);
map
.
put
(
propname
,
propvalue
);
}
catch
(
IllegalAccessException
e
)
{
//e.printStackTrace();
}
catch
(
InvocationTargetException
e
)
{
//e.printStackTrace();
}
catch
(
NoSuchMethodException
e
)
{
//e.printStackTrace();
}
}
}
/**
* 将Map内的key与Bean中属性相同的内容复制到BEAN中
* @param bean Object
* @param properties Map
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public
static
void
copyMap2Bean
(
Object
bean
,
Map
properties
)
throws
IllegalAccessException
,
InvocationTargetException
{
// Do nothing unless both arguments have been specified
if
(
(
bean
==
null
)
||
(
properties
==
null
))
{
return
;
}
// Loop through the property name/value pairs to be set
Iterator
names
=
properties
.
keySet
().
iterator
();
while
(
names
.
hasNext
())
{
String
name
=
(
String
)
names
.
next
();
// Identify the property name and value(s) to be assigned
if
(
name
==
null
)
{
continue
;
}
Object
value
=
properties
.
get
(
name
);
try
{
Class
clazz
=
PropertyUtils
.
getPropertyType
(
bean
,
name
);
if
(
null
==
clazz
)
{
continue
;
}
String
className
=
clazz
.
getName
();
if
(
"java.sql.Timestamp"
.
equalsIgnoreCase
(
className
))
{
if
(
value
==
null
||
""
.
equals
(
value
))
{
continue
;
}
}
getInstance
().
setSimpleProperty
(
bean
,
name
,
value
);
}
catch
(
NoSuchMethodException
e
)
{
continue
;
}
}
}
/**
* 自动转Map key值大写
* 将Map内的key与Bean中属性相同的内容复制到BEAN中
* @param bean Object
* @param properties Map
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public
static
void
copyMap2Bean_Nobig
(
Object
bean
,
Map
properties
)
throws
IllegalAccessException
,
InvocationTargetException
{
// Do nothing unless both arguments have been specified
if
(
(
bean
==
null
)
||
(
properties
==
null
))
{
return
;
}
// Loop through the property name/value pairs to be set
Iterator
names
=
properties
.
keySet
().
iterator
();
while
(
names
.
hasNext
())
{
String
name
=
(
String
)
names
.
next
();
// Identify the property name and value(s) to be assigned
if
(
name
==
null
)
{
continue
;
}
Object
value
=
properties
.
get
(
name
);
// 命名应该大小写应该敏感(否则取不到对象的属性)
//name = name.toLowerCase();
try
{
if
(
value
==
null
)
{
// 不光Date类型,好多类型在null时会出错
continue
;
// 如果为null不用设 (对象如果有特殊初始值也可以保留?)
}
Class
clazz
=
PropertyUtils
.
getPropertyType
(
bean
,
name
);
if
(
null
==
clazz
)
{
// 在bean中这个属性不存在
continue
;
}
String
className
=
clazz
.
getName
();
// 临时对策(如果不处理默认的类型转换时会出错)
if
(
"java.util.Date"
.
equalsIgnoreCase
(
className
))
{
value
=
new
java
.
util
.
Date
(((
java
.
sql
.
Timestamp
)
value
).
getTime
());
// wait to do:貌似有时区问题, 待进一步确认
}
// if (className.equalsIgnoreCase("java.sql.Timestamp")) {
// if (value == null || value.equals("")) {
// continue;
// }
// }
getInstance
().
setSimpleProperty
(
bean
,
name
,
value
);
}
catch
(
NoSuchMethodException
e
)
{
continue
;
}
}
}
/**
* Map内的key与Bean中属性相同的内容复制到BEAN中
* 对于存在空值的取默认值
* @param bean Object
* @param properties Map
* @param defaultValue String
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public
static
void
copyMap2Bean
(
Object
bean
,
Map
properties
,
String
defaultValue
)
throws
IllegalAccessException
,
InvocationTargetException
{
// Do nothing unless both arguments have been specified
if
(
(
bean
==
null
)
||
(
properties
==
null
))
{
return
;
}
// Loop through the property name/value pairs to be set
Iterator
names
=
properties
.
keySet
().
iterator
();
while
(
names
.
hasNext
())
{
String
name
=
(
String
)
names
.
next
();
// Identify the property name and value(s) to be assigned
if
(
name
==
null
)
{
continue
;
}
Object
value
=
properties
.
get
(
name
);
try
{
Class
clazz
=
PropertyUtils
.
getPropertyType
(
bean
,
name
);
if
(
null
==
clazz
)
{
continue
;
}
String
className
=
clazz
.
getName
();
if
(
"java.sql.Timestamp"
.
equalsIgnoreCase
(
className
))
{
if
(
value
==
null
||
""
.
equals
(
value
))
{
continue
;
}
}
if
(
"java.lang.String"
.
equalsIgnoreCase
(
className
))
{
if
(
value
==
null
)
{
value
=
defaultValue
;
}
}
getInstance
().
setSimpleProperty
(
bean
,
name
,
value
);
}
catch
(
NoSuchMethodException
e
)
{
continue
;
}
}
}
public
MyBeanUtils
()
{
super
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/ObjectFieldUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.lang.reflect.Field
;
public
class
ObjectFieldUtils
{
/**
*
* 获取对象属性赋值
*
* @param dObject
* @param fieldName
* 字段别名
* @return
*/
public
static
Object
getFieldValue
(
Object
dObject
,
String
fieldName
)
{
Object
result
=
null
;
try
{
Field
fu
=
dObject
.
getClass
().
getDeclaredField
(
fieldName
);
// 获取对象的属性域
try
{
fu
.
setAccessible
(
true
);
// 设置对象属性域的访问属性
result
=
fu
.
get
(
dObject
);
// 获取对象属性域的属性值
}
catch
(
IllegalAccessException
e
)
{
e
.
printStackTrace
();
}
}
catch
(
NoSuchFieldException
e
)
{
e
.
printStackTrace
();
}
return
result
;
}
/**
* 给对象属性赋值
*
* @param dObject
* @param fieldName
* @param val
* @return
*/
public
static
Object
setFieldValue
(
Object
dObject
,
String
fieldName
,
Object
val
)
{
Object
result
=
null
;
try
{
Field
fu
=
dObject
.
getClass
().
getDeclaredField
(
fieldName
);
// 获取对象的属性域
try
{
fu
.
setAccessible
(
true
);
// 设置对象属性域的访问属性
fu
.
set
(
dObject
,
val
);
// 设置对象属性域的属性值
result
=
fu
.
get
(
dObject
);
// 获取对象属性域的属性值
}
catch
(
IllegalAccessException
e
)
{
e
.
printStackTrace
();
}
}
catch
(
NoSuchFieldException
e
)
{
e
.
printStackTrace
();
}
return
result
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/ObjectUtils.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.utils
;
import
java.io.ByteArrayInputStream
;
import
java.io.ByteArrayOutputStream
;
import
java.io.ObjectInputStream
;
import
java.io.ObjectOutputStream
;
import
java.lang.reflect.Method
;
import
java.math.BigDecimal
;
import
java.util.Collection
;
import
java.util.Map
;
import
org.apache.commons.lang3.StringUtils
;
/**
* 对象操作工具类, 继承org.apache.commons.lang3.ObjectUtils类
* @author 黄炳桂 516821420@qq.com
* @version 2014-6-29
*/
public
class
ObjectUtils
extends
org
.
apache
.
commons
.
lang3
.
ObjectUtils
{
/**
* 注解到对象复制,只复制能匹配上的方法。
* @param annotation
* @param object
*/
public
static
void
annotationToObject
(
Object
annotation
,
Object
object
){
if
(
annotation
!=
null
){
Class
<?>
annotationClass
=
annotation
.
getClass
();
Class
<?>
objectClass
=
object
.
getClass
();
for
(
Method
m
:
objectClass
.
getMethods
()){
if
(
StringUtils
.
startsWith
(
m
.
getName
(),
"set"
)){
try
{
String
s
=
StringUtils
.
uncapitalize
(
StringUtils
.
substring
(
m
.
getName
(),
3
));
Object
obj
=
annotationClass
.
getMethod
(
s
).
invoke
(
annotation
);
if
(
obj
!=
null
&&
!
""
.
equals
(
obj
.
toString
())){
if
(
object
==
null
){
object
=
objectClass
.
newInstance
();
}
m
.
invoke
(
object
,
obj
);
}
}
catch
(
Exception
e
)
{
// 忽略所有设置失败方法
}
}
}
}
}
/**
* 序列化对象
* @param object
* @return
*/
public
static
byte
[]
serialize
(
Object
object
)
{
ObjectOutputStream
oos
=
null
;
ByteArrayOutputStream
baos
=
null
;
try
{
if
(
object
!=
null
){
baos
=
new
ByteArrayOutputStream
();
oos
=
new
ObjectOutputStream
(
baos
);
oos
.
writeObject
(
object
);
return
baos
.
toByteArray
();
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
null
;
}
/**
* 反序列化对象
* @param bytes
* @return
*/
public
static
Object
unserialize
(
byte
[]
bytes
)
{
ByteArrayInputStream
bais
=
null
;
try
{
if
(
bytes
!=
null
&&
bytes
.
length
>
0
){
bais
=
new
ByteArrayInputStream
(
bytes
);
ObjectInputStream
ois
=
new
ObjectInputStream
(
bais
);
return
ois
.
readObject
();
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
null
;
}
private
static
final
int
ErrorRe
=-
1
;
private
static
final
String
NullStringRe
=
""
;
public
static
boolean
isEmpty
(
Object
o
)
{
return
o
==
null
||
o
.
toString
().
length
()
<=
0
;
}
public
static
BigDecimal
convertObjectToBigDecimal
(
Object
o
)
{
return
o
==
null
?
null
:
BigDecimal
.
valueOf
(
Double
.
parseDouble
(
o
.
toString
()));
}
public
static
Integer
convertObjectToInteger
(
Object
o
)
{
return
o
==
null
?
null
:
Integer
.
parseInt
(
o
.
toString
());
}
public
static
String
convertObjectToString
(
Object
o
)
{
return
o
==
null
?
null
:
o
.
toString
();
}
public
static
Integer
convertObjectToInteger2
(
Object
o
)
{
return
o
==
null
?
ErrorRe
:
Integer
.
parseInt
(
o
.
toString
());
}
public
static
String
convertObjectToString2
(
Object
o
)
{
return
o
==
null
?
NullStringRe
:
o
.
toString
();
}
@SuppressWarnings
(
"unchecked"
)
private
static
<
T
>
T
getMapValue
(
Map
<?,
?>
params
,
Object
key
)
{
return
(
T
)
(
null
==
params
?
null
:
params
.
get
(
key
));
}
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
T
getMapValue
(
Map
<?,
?>
params
,
Object
key
,
Class
<
T
>
t
)
{
return
(
T
)
getMapValue
(
params
,
key
);
}
public
static
String
getMapNotNullStrValue
(
Map
<?,
?>
params
,
Object
key
)
{
Object
value
=
getMapValue
(
params
,
key
);
if
(
null
==
value
)
{
return
NullStringRe
;
}
return
String
.
valueOf
(
value
);
}
public
static
int
getMapNotNullIntValue
(
Map
<?,
?>
params
,
Object
key
)
{
Object
value
=
getMapValue
(
params
,
key
);
if
(
null
==
value
)
{
return
0
;
}
int
v
=
0
;
if
(
value
instanceof
Integer
)
{
v
=
((
Integer
)
value
).
intValue
();
}
else
{
try
{
v
=
Integer
.
parseInt
(
String
.
valueOf
(
value
));
}
catch
(
Exception
e
)
{
}
}
return
v
;
}
public
static
Integer
getMapIntegerValue
(
Map
<?,
?>
params
,
Object
key
)
{
Object
value
=
getMapValue
(
params
,
key
);
if
(
null
==
value
)
{
return
null
;
}
Integer
v
=
0
;
if
(
value
instanceof
Integer
)
{
v
=
((
Integer
)
value
).
intValue
();
}
else
{
try
{
v
=
Integer
.
parseInt
(
String
.
valueOf
(
value
));
}
catch
(
Exception
e
)
{
v
=
null
;
}
}
return
v
;
}
public
static
boolean
isEmpty
(
Collection
<?>
c
)
{
return
c
==
null
||
c
.
isEmpty
();
}
public
static
boolean
isNotEmpty
(
Collection
<?>
c
)
{
return
!
isEmpty
(
c
);
}
public
static
boolean
isEmpty
(
Map
<?,
?>
c
)
{
return
c
==
null
||
c
.
isEmpty
();
}
public
static
boolean
isNotEmpty
(
Map
<?,
?>
c
)
{
return
!
isEmpty
(
c
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/OrderProperties.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.io.BufferedReader
;
import
java.io.BufferedWriter
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.io.InputStreamReader
;
import
java.io.OutputStream
;
import
java.io.OutputStreamWriter
;
import
java.util.List
;
import
java.util.Properties
;
import
com.google.common.base.Objects
;
import
com.google.common.collect.Lists
;
/**
* <p>
* 有序的properties的工具类,由于JDK自身的写会乱序,所以采用这个工具类来保证读写次序正常.
* </p>
*
* @author poplar.yfyang
* @version 1.0 2013-01-02 12:57 PM
* @since JDK 1.5
*/
public
class
OrderProperties
extends
Properties
{
/** 序列化ID */
private
static
final
long
serialVersionUID
=
-
762117852594617585L
;
private
static
final
String
keyValueSeparators
=
"=: \t\r\n\f"
;
private
static
final
String
strictKeyValueSeparators
=
"=:"
;
private
static
final
String
specialSaveChars
=
"=: \t\r\n\f#!"
;
private
static
final
String
whiteSpaceChars
=
" \t\r\n\f"
;
/** A table of hex digits */
private
static
final
char
[]
hexDigit
=
{
'0'
,
'1'
,
'2'
,
'3'
,
'4'
,
'5'
,
'6'
,
'7'
,
'8'
,
'9'
,
'A'
,
'B'
,
'C'
,
'D'
,
'E'
,
'F'
};
private
PropertiesContext
context
=
new
PropertiesContext
();
private
static
void
writeln
(
BufferedWriter
bw
,
String
s
)
throws
IOException
{
bw
.
write
(
s
);
bw
.
newLine
();
}
/**
* Convert a nibble to a hex character
*
* @param nibble the nibble to convert.
*/
private
static
char
toHex
(
int
nibble
)
{
return
hexDigit
[(
nibble
&
0xF
)];
}
public
PropertiesContext
getContext
()
{
return
context
;
}
@Override
public
synchronized
void
load
(
InputStream
inStream
)
throws
IOException
{
BufferedReader
in
;
in
=
new
BufferedReader
(
new
InputStreamReader
(
inStream
,
"8859_1"
));
while
(
true
)
{
// Get next line
String
line
=
in
.
readLine
();
// intract property/comment string
String
intactLine
=
line
;
if
(
line
==
null
)
{
return
;
}
if
(
line
.
length
()
>
0
)
{
// Find start of key
int
len
=
line
.
length
();
int
keyStart
;
for
(
keyStart
=
0
;
keyStart
<
len
;
keyStart
++)
{
if
(
whiteSpaceChars
.
indexOf
(
line
.
charAt
(
keyStart
))
==
-
1
)
{
break
;
}
}
// Blank lines are ignored
if
(
keyStart
==
len
)
{
continue
;
}
// Continue lines that end in slashes if they are not comments
char
firstChar
=
line
.
charAt
(
keyStart
);
if
((
firstChar
!=
'#'
)
&&
(
firstChar
!=
'!'
))
{
while
(
continueLine
(
line
))
{
String
nextLine
=
in
.
readLine
();
intactLine
=
intactLine
+
"\n"
+
nextLine
;
if
(
nextLine
==
null
)
{
nextLine
=
""
;
}
String
loppedLine
=
line
.
substring
(
0
,
len
-
1
);
// Advance beyond whitespace on new line
int
startIndex
;
for
(
startIndex
=
0
;
startIndex
<
nextLine
.
length
();
startIndex
++)
{
if
(
whiteSpaceChars
.
indexOf
(
nextLine
.
charAt
(
startIndex
))
==
-
1
)
{
break
;
}
}
nextLine
=
nextLine
.
substring
(
startIndex
,
nextLine
.
length
());
line
=
loppedLine
+
nextLine
;
len
=
line
.
length
();
}
// Find separation between key and value
int
separatorIndex
;
for
(
separatorIndex
=
keyStart
;
separatorIndex
<
len
;
separatorIndex
++)
{
char
currentChar
=
line
.
charAt
(
separatorIndex
);
if
(
currentChar
==
'\\'
)
{
separatorIndex
++;
}
else
if
(
keyValueSeparators
.
indexOf
(
currentChar
)
!=
-
1
)
{
break
;
}
}
// Skip over whitespace after key if any
int
valueIndex
;
for
(
valueIndex
=
separatorIndex
;
valueIndex
<
len
;
valueIndex
++)
{
if
(
whiteSpaceChars
.
indexOf
(
line
.
charAt
(
valueIndex
))
==
-
1
)
{
break
;
}
}
// Skip over one non whitespace key value separators if any
if
(
valueIndex
<
len
)
{
if
(
strictKeyValueSeparators
.
indexOf
(
line
.
charAt
(
valueIndex
))
!=
-
1
)
{
valueIndex
++;
}
}
// Skip over white space after other separators if any
while
(
valueIndex
<
len
)
{
if
(
whiteSpaceChars
.
indexOf
(
line
.
charAt
(
valueIndex
))
==
-
1
)
{
break
;
}
valueIndex
++;
}
String
key
=
line
.
substring
(
keyStart
,
separatorIndex
);
String
value
=
(
separatorIndex
<
len
)
?
line
.
substring
(
valueIndex
,
len
)
:
""
;
// Convert then store key and value
key
=
loadConvert
(
key
);
value
=
loadConvert
(
value
);
//memorize the property also with the whold string
put
(
key
,
value
,
intactLine
);
}
else
{
//memorize the comment string
context
.
addCommentLine
(
intactLine
);
}
}
else
{
//memorize the string even the string is empty
context
.
addCommentLine
(
intactLine
);
}
}
}
/*
* Converts encoded \uxxxx to unicode chars and changes special saved
* chars to their original forms
*/
private
String
loadConvert
(
String
theString
)
{
char
aChar
;
int
len
=
theString
.
length
();
StringBuilder
outBuffer
=
new
StringBuilder
(
len
);
for
(
int
x
=
0
;
x
<
len
;
)
{
aChar
=
theString
.
charAt
(
x
++);
if
(
aChar
==
'\\'
)
{
aChar
=
theString
.
charAt
(
x
++);
if
(
aChar
==
'u'
)
{
// Read the xxxx
int
value
=
0
;
for
(
int
i
=
0
;
i
<
4
;
i
++)
{
aChar
=
theString
.
charAt
(
x
++);
switch
(
aChar
)
{
case
'0'
:
case
'1'
:
case
'2'
:
case
'3'
:
case
'4'
:
case
'5'
:
case
'6'
:
case
'7'
:
case
'8'
:
case
'9'
:
value
=
(
value
<<
4
)
+
aChar
-
'0'
;
break
;
case
'a'
:
case
'b'
:
case
'c'
:
case
'd'
:
case
'e'
:
case
'f'
:
value
=
(
value
<<
4
)
+
10
+
aChar
-
'a'
;
break
;
case
'A'
:
case
'B'
:
case
'C'
:
case
'D'
:
case
'E'
:
case
'F'
:
value
=
(
value
<<
4
)
+
10
+
aChar
-
'A'
;
break
;
default
:
throw
new
IllegalArgumentException
(
"Malformed \\uxxxx encoding."
);
}
}
outBuffer
.
append
((
char
)
value
);
}
else
{
if
(
aChar
==
't'
)
{
outBuffer
.
append
(
'\t'
);
/* ibm@7211 */
}
else
if
(
aChar
==
'r'
)
{
outBuffer
.
append
(
'\r'
);
/* ibm@7211 */
}
else
if
(
aChar
==
'n'
)
{
/*
* ibm@8897 do not convert a \n to a line.separator
* because on some platforms line.separator is a String
* of "\r\n". When a Properties class is saved as a file
* (store()) and then restored (load()) the restored
* input MUST be the same as the output (so that
* Properties.equals() works).
*
*/
outBuffer
.
append
(
'\n'
);
/* ibm@8897 ibm@7211 */
}
else
if
(
aChar
==
'f'
)
{
outBuffer
.
append
(
'\f'
);
/* ibm@7211 */
}
else
/* ibm@7211 */
{
outBuffer
.
append
(
aChar
);
/* ibm@7211 */
}
}
}
else
{
outBuffer
.
append
(
aChar
);
}
}
return
outBuffer
.
toString
();
}
@Override
public
synchronized
void
store
(
OutputStream
out
,
String
header
)
throws
IOException
{
BufferedWriter
awriter
;
awriter
=
new
BufferedWriter
(
new
OutputStreamWriter
(
out
,
"8859_1"
));
if
(
header
!=
null
)
{
writeln
(
awriter
,
"#"
+
header
);
}
@SuppressWarnings
(
"rawtypes"
)
List
entrys
=
context
.
getCommentOrEntrys
();
for
(
Object
obj
:
entrys
)
{
if
(
obj
.
toString
()
!=
null
)
{
writeln
(
awriter
,
obj
.
toString
());
}
}
awriter
.
flush
();
}
private
boolean
continueLine
(
String
line
)
{
int
slashCount
=
0
;
int
index
=
line
.
length
()
-
1
;
while
((
index
>=
0
)
&&
(
line
.
charAt
(
index
--)
==
'\\'
))
{
slashCount
++;
}
return
(
slashCount
%
2
==
1
);
}
/*
* Converts unicodes to encoded \uxxxx and writes out any of the
* characters in specialSaveChars with a preceding slash
*/
private
String
saveConvert
(
String
theString
,
boolean
escapeSpace
)
{
int
len
=
theString
.
length
();
StringBuilder
outBuffer
=
new
StringBuilder
(
len
*
2
);
for
(
int
x
=
0
;
x
<
len
;
x
++)
{
char
aChar
=
theString
.
charAt
(
x
);
switch
(
aChar
)
{
case
' '
:
if
(
x
==
0
||
escapeSpace
)
{
outBuffer
.
append
(
'\\'
);
}
outBuffer
.
append
(
' '
);
break
;
case
'\\'
:
outBuffer
.
append
(
'\\'
);
outBuffer
.
append
(
'\\'
);
break
;
case
'\t'
:
outBuffer
.
append
(
'\\'
);
outBuffer
.
append
(
't'
);
break
;
case
'\n'
:
outBuffer
.
append
(
'\\'
);
outBuffer
.
append
(
'n'
);
break
;
case
'\r'
:
outBuffer
.
append
(
'\\'
);
outBuffer
.
append
(
'r'
);
break
;
case
'\f'
:
outBuffer
.
append
(
'\\'
);
outBuffer
.
append
(
'f'
);
break
;
default
:
if
((
aChar
<
0x0020
)
||
(
aChar
>
0x007e
))
{
outBuffer
.
append
(
'\\'
);
outBuffer
.
append
(
'u'
);
outBuffer
.
append
(
toHex
((
aChar
>>
12
)
&
0xF
));
outBuffer
.
append
(
toHex
((
aChar
>>
8
)
&
0xF
));
outBuffer
.
append
(
toHex
((
aChar
>>
4
)
&
0xF
));
outBuffer
.
append
(
toHex
(
aChar
&
0xF
));
}
else
{
if
(
specialSaveChars
.
indexOf
(
aChar
)
!=
-
1
)
{
outBuffer
.
append
(
'\\'
);
}
outBuffer
.
append
(
aChar
);
}
}
}
return
outBuffer
.
toString
();
}
@Override
public
synchronized
Object
put
(
Object
key
,
Object
value
)
{
context
.
putOrUpdate
(
key
.
toString
(),
value
.
toString
());
return
super
.
put
(
key
,
value
);
}
public
synchronized
Object
put
(
Object
key
,
Object
value
,
String
line
)
{
context
.
putOrUpdate
(
key
.
toString
(),
value
.
toString
(),
line
);
return
super
.
put
(
key
,
value
);
}
@Override
public
synchronized
Object
remove
(
Object
key
)
{
context
.
remove
(
key
.
toString
());
return
super
.
remove
(
key
);
}
/** @param comment */
public
void
addComment
(
String
comment
)
{
if
(
comment
!=
null
)
{
context
.
addCommentLine
(
"#"
+
comment
);
}
}
class
PropertiesContext
{
/** 描述信息 */
private
List
<
Object
>
commentOrEntrys
=
Lists
.
newArrayList
();
@SuppressWarnings
(
"rawtypes"
)
public
List
getCommentOrEntrys
()
{
return
commentOrEntrys
;
}
public
void
addCommentLine
(
String
line
)
{
commentOrEntrys
.
add
(
line
);
}
public
void
putOrUpdate
(
PropertyEntry
pe
)
{
remove
(
pe
.
getKey
());
commentOrEntrys
.
add
(
pe
);
}
public
void
putOrUpdate
(
String
key
,
String
value
,
String
line
)
{
PropertyEntry
pe
=
new
PropertyEntry
(
key
,
value
,
line
);
remove
(
key
);
commentOrEntrys
.
add
(
pe
);
}
public
void
putOrUpdate
(
String
key
,
String
value
)
{
PropertyEntry
pe
=
new
PropertyEntry
(
key
,
value
);
int
index
=
remove
(
key
);
commentOrEntrys
.
add
(
index
,
pe
);
}
public
int
remove
(
String
key
)
{
for
(
int
index
=
0
;
index
<
commentOrEntrys
.
size
();
index
++)
{
Object
obj
=
commentOrEntrys
.
get
(
index
);
if
(
obj
instanceof
PropertyEntry
)
{
if
(!
Objects
.
equal
(
obj
,
null
))
{
if
(
key
.
equals
(((
PropertyEntry
)
obj
).
getKey
()))
{
commentOrEntrys
.
remove
(
obj
);
return
index
;
}
}
}
}
return
commentOrEntrys
.
size
();
}
/** 属性描述 */
class
PropertyEntry
{
/** 属性KEY */
private
String
key
;
/** 属性值 */
private
String
value
;
/** 属性行 */
private
String
line
;
public
PropertyEntry
(
String
key
,
String
value
)
{
this
.
key
=
key
;
this
.
value
=
value
;
}
/**
* 构建属性描述
*
* @param key key
* @param value value
* @param line line
*/
public
PropertyEntry
(
String
key
,
String
value
,
String
line
)
{
this
(
key
,
value
);
this
.
line
=
line
;
}
public
String
getLine
()
{
return
line
;
}
public
void
setLine
(
String
line
)
{
this
.
line
=
line
;
}
public
String
getKey
()
{
return
key
;
}
public
void
setKey
(
String
key
)
{
this
.
key
=
key
;
}
public
String
getValue
()
{
return
value
;
}
public
void
setValue
(
String
value
)
{
this
.
value
=
value
;
}
@Override
public
String
toString
()
{
if
(
line
!=
null
)
{
return
line
;
}
if
(
key
!=
null
&&
value
!=
null
)
{
String
k
=
saveConvert
(
key
,
true
);
String
v
=
saveConvert
(
value
,
false
);
return
k
+
"="
+
v
;
}
return
null
;
}
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/PropertiesLoader.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright (c) 2005-2011 springside.org.cn
* <p>
* $Id: PropertiesLoader.java 1690 2012-02-22 13:42:00Z calvinxiu $
*/
package
com.jeespring.common.utils
;
import
java.io.IOException
;
import
java.io.InputStreamReader
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.NoSuchElementException
;
import
java.util.Properties
;
import
org.apache.commons.io.IOUtils
;
import
org.springframework.core.io.DefaultResourceLoader
;
import
org.springframework.core.io.Resource
;
import
org.springframework.core.io.ResourceLoader
;
import
org.yaml.snakeyaml.Yaml
;
/**
* Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先.
*
* @author calvin
* @version 2013-05-15
*/
@SuppressWarnings
(
"rawtypes"
)
public
class
PropertiesLoader
{
private
static
ResourceLoader
resourceLoader
=
new
DefaultResourceLoader
();
private
final
Properties
properties
;
public
PropertiesLoader
(
String
...
resourcesPaths
)
{
properties
=
loadProperties
(
resourcesPaths
);
}
public
Properties
getProperties
()
{
return
properties
;
}
/**
* 取出Property,但以System的Property优先,取不到返回空字符串.
*/
private
String
getValue
(
String
key
)
{
String
systemProperty
=
System
.
getProperty
(
key
);
if
(
systemProperty
!=
null
)
{
return
systemProperty
;
}
if
(
properties
.
containsKey
(
key
))
{
return
properties
.
getProperty
(
key
);
}
return
""
;
}
/**
* 取出String类型的Property,但以System的Property优先,如果都为Null则抛出异常.
*/
public
String
getProperty
(
String
key
)
{
String
value
=
getValue
(
key
);
if
(
value
==
null
)
{
throw
new
NoSuchElementException
();
}
return
value
;
}
/**
* 取出String类型的Property,但以System的Property优先.如果都为Null则返回Default值.
*/
public
String
getProperty
(
String
key
,
String
defaultValue
)
{
String
value
=
getValue
(
key
);
return
value
!=
null
?
value
:
defaultValue
;
}
/**
* 取出Integer类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
*/
public
Integer
getInteger
(
String
key
)
{
String
value
=
getValue
(
key
);
if
(
value
==
null
)
{
throw
new
NoSuchElementException
();
}
return
Integer
.
valueOf
(
value
);
}
/**
* 取出Integer类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
*/
public
Integer
getInteger
(
String
key
,
Integer
defaultValue
)
{
String
value
=
getValue
(
key
);
return
value
!=
null
?
Integer
.
valueOf
(
value
)
:
defaultValue
;
}
/**
* 取出Double类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
*/
public
Double
getDouble
(
String
key
)
{
String
value
=
getValue
(
key
);
if
(
value
==
null
)
{
throw
new
NoSuchElementException
();
}
return
Double
.
valueOf
(
value
);
}
/**
* 取出Double类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
*/
public
Double
getDouble
(
String
key
,
Integer
defaultValue
)
{
String
value
=
getValue
(
key
);
return
value
!=
null
?
Double
.
valueOf
(
value
)
:
defaultValue
;
}
/**
* 取出Boolean类型的Property,但以System的Property优先.如果都为Null抛出异常,如果内容不是true/false则返回false.
*/
public
Boolean
getBoolean
(
String
key
)
{
String
value
=
getValue
(
key
);
if
(
value
==
null
)
{
throw
new
NoSuchElementException
();
}
return
Boolean
.
valueOf
(
value
);
}
/**
* 取出Boolean类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容不为true/false则返回false.
*/
public
Boolean
getBoolean
(
String
key
,
boolean
defaultValue
)
{
String
value
=
getValue
(
key
);
return
value
!=
null
?
Boolean
.
valueOf
(
value
)
:
defaultValue
;
}
/**
* 载入多个文件, 文件路径使用Spring Resource格式.
*/
private
Properties
loadProperties
(
String
...
resourcesPaths
)
{
Properties
props
=
new
Properties
();
for
(
String
location
:
resourcesPaths
)
{
if
(
location
.
endsWith
(
".properties"
))
{
InputStreamReader
reader
=
null
;
try
{
Resource
resource
=
resourceLoader
.
getResource
(
location
);
reader
=
new
InputStreamReader
(
resource
.
getInputStream
(),
"utf-8"
);
props
.
load
(
reader
);
}
catch
(
IOException
ex
)
{
ex
.
printStackTrace
(
System
.
out
);
}
finally
{
IOUtils
.
closeQuietly
(
reader
);
}
}
else
if
(
location
.
endsWith
(
".yml"
))
{
try
{
Resource
resource
=
resourceLoader
.
getResource
(
location
);
Yaml
yaml
=
new
Yaml
();
Map
map
=
yaml
.
loadAs
(
resource
.
getInputStream
(),
Map
.
class
);
map
=
resolv
(
map
);
for
(
Object
key
:
map
.
keySet
())
{
props
.
put
(
key
,
map
.
get
(
key
));
}
}
catch
(
Exception
e
)
{
//e.printStackTrace(System.out);
}
}
}
return
props
;
}
/**
* 递归解析map
*
* @param map yml初次解析的map
* @return 解析后的map
*/
private
static
Map
<
String
,
String
>
resolv
(
Map
map
)
{
Map
<
String
,
String
>
values
=
new
HashMap
<>();
for
(
Object
obj
:
map
.
keySet
())
{
String
currentkey
=
obj
.
toString
();
Object
currentObj
=
map
.
get
(
obj
);
if
(
currentObj
instanceof
Map
)
{
Map
currentMap
=
resolv
((
Map
)
currentObj
);
for
(
Object
key
:
currentMap
.
keySet
())
{
String
mapKey
=
currentkey
+
"."
+
key
.
toString
();
values
.
put
(
mapKey
,
currentMap
.
get
(
key
).
toString
());
}
}
else
{
values
.
put
(
currentkey
,
String
.
valueOf
(
currentObj
));
}
}
return
values
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/Reflections.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.utils
;
import
java.lang.reflect.Field
;
import
java.lang.reflect.InvocationTargetException
;
import
java.lang.reflect.Method
;
import
java.lang.reflect.Modifier
;
import
java.lang.reflect.ParameterizedType
;
import
java.lang.reflect.Type
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.commons.lang3.Validate
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.util.Assert
;
/**
* 反射工具类.
* 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings
(
"rawtypes"
)
public
class
Reflections
{
private
static
final
String
SETTER_PREFIX
=
"set"
;
private
static
final
String
GETTER_PREFIX
=
"get"
;
private
static
final
String
CGLIB_CLASS_SEPARATOR
=
"$$"
;
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
Reflections
.
class
);
/**
* 调用Getter方法.
* 支持多级,如:对象名.对象名.方法
*/
public
static
Object
invokeGetter
(
Object
obj
,
String
propertyName
)
{
Object
object
=
obj
;
for
(
String
name
:
StringUtils
.
split
(
propertyName
,
"."
)){
String
getterMethodName
=
GETTER_PREFIX
+
StringUtils
.
capitalize
(
name
);
object
=
invokeMethod
(
object
,
getterMethodName
,
new
Class
[]
{},
new
Object
[]
{});
}
return
object
;
}
/**
* 调用Setter方法, 仅匹配方法名。
* 支持多级,如:对象名.对象名.方法
*/
public
static
void
invokeSetter
(
Object
obj
,
String
propertyName
,
Object
value
)
{
Object
object
=
obj
;
String
[]
names
=
StringUtils
.
split
(
propertyName
,
"."
);
for
(
int
i
=
0
;
i
<
names
.
length
;
i
++){
if
(
i
<
names
.
length
-
1
){
String
getterMethodName
=
GETTER_PREFIX
+
StringUtils
.
capitalize
(
names
[
i
]);
object
=
invokeMethod
(
object
,
getterMethodName
,
new
Class
[]
{},
new
Object
[]
{});
}
else
{
String
setterMethodName
=
SETTER_PREFIX
+
StringUtils
.
capitalize
(
names
[
i
]);
invokeMethodByName
(
object
,
setterMethodName
,
new
Object
[]
{
value
});
}
}
}
/**
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
*/
public
static
Object
getFieldValue
(
final
Object
obj
,
final
String
fieldName
)
{
Field
field
=
getAccessibleField
(
obj
,
fieldName
);
if
(
field
==
null
)
{
throw
new
IllegalArgumentException
(
"Could not find field ["
+
fieldName
+
"] on target ["
+
obj
+
"]"
);
}
Object
result
=
null
;
try
{
result
=
field
.
get
(
obj
);
}
catch
(
IllegalAccessException
e
)
{
logger
.
error
(
"不可能抛出的异常{}"
,
e
.
getMessage
());
}
return
result
;
}
/**
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
*/
public
static
void
setFieldValue
(
final
Object
obj
,
final
String
fieldName
,
final
Object
value
)
{
Field
field
=
getAccessibleField
(
obj
,
fieldName
);
if
(
field
==
null
)
{
throw
new
IllegalArgumentException
(
"Could not find field ["
+
fieldName
+
"] on target ["
+
obj
+
"]"
);
}
try
{
field
.
set
(
obj
,
value
);
}
catch
(
IllegalAccessException
e
)
{
logger
.
error
(
"不可能抛出的异常:{}"
,
e
.
getMessage
());
}
}
/**
* 直接调用对象方法, 无视private/protected修饰符.
* 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
* 同时匹配方法名+参数类型,
*/
public
static
Object
invokeMethod
(
final
Object
obj
,
final
String
methodName
,
final
Class
<?>[]
parameterTypes
,
final
Object
[]
args
)
{
Method
method
=
getAccessibleMethod
(
obj
,
methodName
,
parameterTypes
);
if
(
method
==
null
)
{
throw
new
IllegalArgumentException
(
"Could not find method ["
+
methodName
+
"] on target ["
+
obj
+
"]"
);
}
try
{
return
method
.
invoke
(
obj
,
args
);
}
catch
(
Exception
e
)
{
throw
convertReflectionExceptionToUnchecked
(
e
);
}
}
/**
* 直接调用对象方法, 无视private/protected修饰符,
* 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
* 只匹配函数名,如果有多个同名函数调用第一个。
*/
public
static
Object
invokeMethodByName
(
final
Object
obj
,
final
String
methodName
,
final
Object
[]
args
)
{
Method
method
=
getAccessibleMethodByName
(
obj
,
methodName
);
if
(
method
==
null
)
{
throw
new
IllegalArgumentException
(
"Could not find method ["
+
methodName
+
"] on target ["
+
obj
+
"]"
);
}
try
{
return
method
.
invoke
(
obj
,
args
);
}
catch
(
Exception
e
)
{
throw
convertReflectionExceptionToUnchecked
(
e
);
}
}
/**
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
*
* 如向上转型到Object仍无法找到, 返回null.
*/
public
static
Field
getAccessibleField
(
final
Object
obj
,
final
String
fieldName
)
{
Validate
.
notNull
(
obj
,
"object can't be null"
);
Validate
.
notBlank
(
fieldName
,
"fieldName can't be blank"
);
for
(
Class
<?>
superClass
=
obj
.
getClass
();
superClass
!=
Object
.
class
;
superClass
=
superClass
.
getSuperclass
())
{
try
{
Field
field
=
superClass
.
getDeclaredField
(
fieldName
);
makeAccessible
(
field
);
return
field
;
}
catch
(
NoSuchFieldException
e
)
{
//NOSONAR
// Field不在当前类定义,继续向上转型
continue
;
// new add
}
}
return
null
;
}
/**
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
* 如向上转型到Object仍无法找到, 返回null.
* 匹配函数名+参数类型。
*
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
*/
public
static
Method
getAccessibleMethod
(
final
Object
obj
,
final
String
methodName
,
final
Class
<?>...
parameterTypes
)
{
Validate
.
notNull
(
obj
,
"object can't be null"
);
Validate
.
notBlank
(
methodName
,
"methodName can't be blank"
);
for
(
Class
<?>
searchType
=
obj
.
getClass
();
searchType
!=
Object
.
class
;
searchType
=
searchType
.
getSuperclass
())
{
try
{
Method
method
=
searchType
.
getDeclaredMethod
(
methodName
,
parameterTypes
);
makeAccessible
(
method
);
return
method
;
}
catch
(
NoSuchMethodException
e
)
{
// Method不在当前类定义,继续向上转型
continue
;
// new add
}
}
return
null
;
}
/**
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
* 如向上转型到Object仍无法找到, 返回null.
* 只匹配函数名。
*
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
*/
public
static
Method
getAccessibleMethodByName
(
final
Object
obj
,
final
String
methodName
)
{
Validate
.
notNull
(
obj
,
"object can't be null"
);
Validate
.
notBlank
(
methodName
,
"methodName can't be blank"
);
for
(
Class
<?>
searchType
=
obj
.
getClass
();
searchType
!=
Object
.
class
;
searchType
=
searchType
.
getSuperclass
())
{
Method
[]
methods
=
searchType
.
getDeclaredMethods
();
for
(
Method
method
:
methods
)
{
if
(
method
.
getName
().
equals
(
methodName
))
{
makeAccessible
(
method
);
return
method
;
}
}
}
return
null
;
}
/**
* 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
*/
public
static
void
makeAccessible
(
Method
method
)
{
if
((!
Modifier
.
isPublic
(
method
.
getModifiers
())
||
!
Modifier
.
isPublic
(
method
.
getDeclaringClass
().
getModifiers
()))
&&
!
method
.
isAccessible
())
{
method
.
setAccessible
(
true
);
}
}
/**
* 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
*/
public
static
void
makeAccessible
(
Field
field
)
{
if
((!
Modifier
.
isPublic
(
field
.
getModifiers
())
||
!
Modifier
.
isPublic
(
field
.
getDeclaringClass
().
getModifiers
())
||
Modifier
.
isFinal
(
field
.
getModifiers
()))
&&
!
field
.
isAccessible
())
{
field
.
setAccessible
(
true
);
}
}
/**
* 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
* 如无法找到, 返回Object.class.
* eg.
* public UserDao extends HibernateDao<User>
*
* @param clazz The class to introspect
* @return the first generic declaration, or Object.class if cannot be determined
*/
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
Class
<
T
>
getClassGenricType
(
final
Class
clazz
)
{
return
getClassGenricType
(
clazz
,
0
);
}
/**
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
* 如无法找到, 返回Object.class.
*
* 如public UserDao extends HibernateDao<User,Long>
*
* @param clazz clazz The class to introspect
* @param index the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or Object.class if cannot be determined
*/
public
static
Class
getClassGenricType
(
final
Class
clazz
,
final
int
index
)
{
Type
genType
=
clazz
.
getGenericSuperclass
();
if
(!(
genType
instanceof
ParameterizedType
))
{
logger
.
warn
(
clazz
.
getSimpleName
()
+
"'s superclass not ParameterizedType"
);
return
Object
.
class
;
}
Type
[]
params
=
((
ParameterizedType
)
genType
).
getActualTypeArguments
();
if
(
index
>=
params
.
length
||
index
<
0
)
{
logger
.
warn
(
"Index: "
+
index
+
", Size of "
+
clazz
.
getSimpleName
()
+
"'s Parameterized Type: "
+
params
.
length
);
return
Object
.
class
;
}
if
(!(
params
[
index
]
instanceof
Class
))
{
logger
.
warn
(
clazz
.
getSimpleName
()
+
" not set the actual class on superclass generic parameter"
);
return
Object
.
class
;
}
return
(
Class
)
params
[
index
];
}
public
static
Class
<?>
getUserClass
(
Object
instance
)
{
Assert
.
notNull
(
instance
,
"Instance must not be null"
);
Class
clazz
=
instance
.
getClass
();
if
(
clazz
!=
null
&&
clazz
.
getName
().
contains
(
CGLIB_CLASS_SEPARATOR
))
{
Class
<?>
superClass
=
clazz
.
getSuperclass
();
if
(
superClass
!=
null
&&
!
Object
.
class
.
equals
(
superClass
))
{
return
superClass
;
}
}
return
clazz
;
}
/**
* 将反射时的checked exception转换为unchecked exception.
*/
public
static
RuntimeException
convertReflectionExceptionToUnchecked
(
Exception
e
)
{
if
(
e
instanceof
IllegalAccessException
||
e
instanceof
IllegalArgumentException
||
e
instanceof
NoSuchMethodException
)
{
return
new
IllegalArgumentException
(
e
);
}
else
if
(
e
instanceof
InvocationTargetException
)
{
return
new
RuntimeException
(((
InvocationTargetException
)
e
).
getTargetException
());
}
else
if
(
e
instanceof
RuntimeException
)
{
return
(
RuntimeException
)
e
;
}
return
new
RuntimeException
(
"Unexpected Checked Exception."
,
e
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/SendMailUtil.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright © 2012-2016 <a href="https://gitee.com/JeeHuangBingGui/jeeSpringCloud">JeeSpring</a>All rights reserved.
*/
package
com.jeespring.common.utils
;
import
java.io.File
;
import
java.util.HashMap
;
import
java.util.Locale
;
import
java.util.Map
;
import
java.util.regex.Matcher
;
import
java.util.regex.Pattern
;
import
com.jeespring.common.config.Global
;
import
org.apache.commons.mail.HtmlEmail
;
import
org.springframework.ui.freemarker.FreeMarkerTemplateUtils
;
import
freemarker.template.Configuration
;
import
freemarker.template.Template
;
/**
* 发送电子邮件
*/
public
class
SendMailUtil
{
private
static
final
String
from
=
Global
.
getConfig
(
"email.from"
);
private
static
final
String
fromName
=
Global
.
getConfig
(
"email.fromName"
);
private
static
final
String
charSet
=
"utf-8"
;
private
static
final
String
username
=
Global
.
getConfig
(
"email.username"
);
private
static
final
String
password
=
Global
.
getConfig
(
"email.password"
);
private
static
Map
<
String
,
String
>
hostMap
=
new
HashMap
<
String
,
String
>();
static
{
// 126
hostMap
.
put
(
"smtp.126"
,
"smtp.126.com"
);
// qq
hostMap
.
put
(
"smtp.qq"
,
"smtp.qq.com"
);
// 163
hostMap
.
put
(
"smtp.163"
,
"smtp.163.com"
);
// sina
hostMap
.
put
(
"smtp.sina"
,
"smtp.sina.com.cn"
);
// tom
hostMap
.
put
(
"smtp.tom"
,
"smtp.tom.com"
);
// 263
hostMap
.
put
(
"smtp.263"
,
"smtp.263.net"
);
// yahoo
hostMap
.
put
(
"smtp.yahoo"
,
"smtp.mail.yahoo.com"
);
// hotmail
hostMap
.
put
(
"smtp.hotmail"
,
"smtp.live.com"
);
// gmail
hostMap
.
put
(
"smtp.gmail"
,
"smtp.gmail.com"
);
hostMap
.
put
(
"smtp.port.gmail"
,
"465"
);
}
public
static
String
getHost
(
String
email
)
throws
Exception
{
Pattern
pattern
=
Pattern
.
compile
(
"\\w+@(\\w+)(\\.\\w+){1,2}"
);
Matcher
matcher
=
pattern
.
matcher
(
email
);
String
key
=
"unSupportEmail"
;
if
(
matcher
.
find
())
{
key
=
"smtp."
+
matcher
.
group
(
1
);
}
if
(
hostMap
.
containsKey
(
key
))
{
return
hostMap
.
get
(
key
);
}
else
{
throw
new
Exception
(
"unSupportEmail"
);
}
}
public
static
int
getSmtpPort
(
String
email
)
throws
Exception
{
Pattern
pattern
=
Pattern
.
compile
(
"\\w+@(\\w+)(\\.\\w+){1,2}"
);
Matcher
matcher
=
pattern
.
matcher
(
email
);
String
key
=
"unSupportEmail"
;
if
(
matcher
.
find
())
{
key
=
"smtp.port."
+
matcher
.
group
(
1
);
}
if
(
hostMap
.
containsKey
(
key
))
{
return
Integer
.
parseInt
(
hostMap
.
get
(
key
));
}
else
{
return
25
;
}
}
/**
* 发送模板邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param templatePath
* 模板地址
* @param map
* 模板map
*/
public
static
void
sendFtlMail
(
String
toMailAddr
,
String
subject
,
String
templatePath
,
Map
<
String
,
Object
>
map
)
{
Template
template
=
null
;
Configuration
freeMarkerConfig
=
null
;
HtmlEmail
hemail
=
new
HtmlEmail
();
try
{
hemail
.
setHostName
(
getHost
(
from
));
hemail
.
setSmtpPort
(
getSmtpPort
(
from
));
hemail
.
setCharset
(
charSet
);
hemail
.
addTo
(
toMailAddr
);
hemail
.
setFrom
(
from
,
fromName
);
hemail
.
setAuthentication
(
username
,
password
);
hemail
.
setSubject
(
subject
);
freeMarkerConfig
=
new
Configuration
();
freeMarkerConfig
.
setDirectoryForTemplateLoading
(
new
File
(
getFilePath
()));
// 获取模板
template
=
freeMarkerConfig
.
getTemplate
(
getFileName
(
templatePath
),
new
Locale
(
"Zh_cn"
),
"UTF-8"
);
// 模板内容转换为string
String
htmlText
=
FreeMarkerTemplateUtils
.
processTemplateIntoString
(
template
,
map
);
System
.
out
.
println
(
htmlText
);
hemail
.
setMsg
(
htmlText
);
hemail
.
send
();
System
.
out
.
println
(
"email send true!"
);
}
catch
(
Exception
e
)
{
//e.printStackTrace();
System
.
out
.
println
(
"email send error!"
+
e
.
getMessage
());
}
}
/**
* 发送普通邮件
*
* @param toMailAddr
* 收信人地址,可以使用,分割。
* @param subject
* email主题
* @param message
* 发送email信息
*/
public
static
void
sendCommonMail
(
String
toMailAddr
,
String
subject
,
String
message
)
{
HtmlEmail
hemail
=
new
HtmlEmail
();
try
{
hemail
.
setHostName
(
getHost
(
from
));
hemail
.
setSmtpPort
(
getSmtpPort
(
from
));
hemail
.
setCharset
(
charSet
);
if
(
toMailAddr
.
indexOf
(
","
)>
0
){
String
[]
toMailAddrArray
=
toMailAddr
.
split
(
","
);
for
(
String
item
:
toMailAddrArray
)
{
hemail
.
addTo
(
item
);
}
}
else
{
hemail
.
addTo
(
toMailAddr
);
}
hemail
.
setFrom
(
from
,
fromName
);
hemail
.
setAuthentication
(
username
,
password
);
hemail
.
setSubject
(
subject
);
hemail
.
setMsg
(
message
);
if
(
from
.
contains
(
"@qq.com"
))
{
hemail
.
setSSL
(
true
);
}
hemail
.
send
();
//System.out.println("email send true!");
}
catch
(
Exception
e
)
{
//e.printStackTrace();
System
.
out
.
println
(
"email send error!"
+
e
.
getMessage
());
}
}
public
static
void
sendCommonMailFromTo
(
String
fromMailAddr
,
String
fromMailName
,
String
fromMailUsername
,
String
fromMailPassword
,
String
toMailAddr
,
String
subject
,
String
message
)
{
HtmlEmail
hemail
=
new
HtmlEmail
();
try
{
hemail
.
setHostName
(
getHost
(
fromMailAddr
));
hemail
.
setSmtpPort
(
getSmtpPort
(
fromMailAddr
));
hemail
.
setCharset
(
charSet
);
hemail
.
addTo
(
toMailAddr
);
hemail
.
setFrom
(
fromMailAddr
,
fromMailName
);
hemail
.
setAuthentication
(
fromMailUsername
,
fromMailPassword
);
hemail
.
setSubject
(
subject
);
hemail
.
setMsg
(
message
);
if
(
fromMailAddr
.
contains
(
"@qq.com"
))
{
hemail
.
setSSL
(
true
);
}
hemail
.
send
();
//System.out.println("email send true!");
}
catch
(
Exception
e
)
{
//e.printStackTrace();
System
.
out
.
println
(
"email send error!"
+
e
.
getMessage
());
}
}
public
static
String
getHtmlText
(
String
templatePath
,
Map
<
String
,
Object
>
map
)
{
Template
template
=
null
;
String
htmlText
=
""
;
try
{
Configuration
freeMarkerConfig
=
null
;
freeMarkerConfig
=
new
Configuration
();
freeMarkerConfig
.
setDirectoryForTemplateLoading
(
new
File
(
getFilePath
()));
// 获取模板
template
=
freeMarkerConfig
.
getTemplate
(
getFileName
(
templatePath
),
new
Locale
(
"Zh_cn"
),
"UTF-8"
);
// 模板内容转换为string
htmlText
=
FreeMarkerTemplateUtils
.
processTemplateIntoString
(
template
,
map
);
System
.
out
.
println
(
htmlText
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
htmlText
;
}
private
static
String
getFilePath
()
{
String
path
=
getAppPath
(
SendMailUtil
.
class
);
path
=
path
+
File
.
separator
+
"mailtemplate"
+
File
.
separator
;
path
=
path
.
replace
(
"\\"
,
"/"
);
System
.
out
.
println
(
path
);
return
path
;
}
private
static
String
getFileName
(
String
path
)
{
path
=
path
.
replace
(
"\\"
,
"/"
);
System
.
out
.
println
(
path
);
return
path
.
substring
(
path
.
lastIndexOf
(
"/"
)
+
1
);
}
// @SuppressWarnings("unchecked")
public
static
String
getAppPath
(
Class
<?>
cls
)
{
// 检查用户传入的参数是否为空
if
(
cls
==
null
)
{
throw
new
IllegalArgumentException
(
"参数不能为空!"
);
}
ClassLoader
loader
=
cls
.
getClassLoader
();
// 获得类的全名,包括包名
String
clsName
=
cls
.
getName
()
+
".class"
;
// 获得传入参数所在的包
Package
pack
=
cls
.
getPackage
();
String
path
=
""
;
// 如果不是匿名包,将包名转化为路径
if
(
pack
!=
null
)
{
String
packName
=
pack
.
getName
();
// 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
if
(
packName
.
startsWith
(
"java."
)
||
packName
.
startsWith
(
"javax."
))
{
throw
new
IllegalArgumentException
(
"不要传送系统类!"
);
}
// 在类的名称中,去掉包名的部分,获得类的文件名
clsName
=
clsName
.
substring
(
packName
.
length
()
+
1
);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
if
(
packName
.
indexOf
(
"."
)
<
0
)
{
path
=
packName
+
"/"
;
}
else
{
// 否则按照包名的组成部分,将包名转换为路径
int
start
=
0
,
end
=
0
;
end
=
packName
.
indexOf
(
"."
);
while
(
end
!=
-
1
)
{
path
=
path
+
packName
.
substring
(
start
,
end
)
+
"/"
;
start
=
end
+
1
;
end
=
packName
.
indexOf
(
"."
,
start
);
}
path
=
path
+
packName
.
substring
(
start
)
+
"/"
;
}
}
// 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
java
.
net
.
URL
url
=
loader
.
getResource
(
path
+
clsName
);
// 从URL对象中获取路径信息
String
realPath
=
url
.
getPath
();
// 去掉路径信息中的协议名"file:"
int
pos
=
realPath
.
indexOf
(
"file:"
);
if
(
pos
>
-
1
)
{
realPath
=
realPath
.
substring
(
pos
+
5
);
}
// 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
pos
=
realPath
.
indexOf
(
path
+
clsName
);
realPath
=
realPath
.
substring
(
0
,
pos
-
1
);
// 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
if
(
realPath
.
endsWith
(
"!"
))
{
realPath
=
realPath
.
substring
(
0
,
realPath
.
lastIndexOf
(
"/"
));
}
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try
{
realPath
=
java
.
net
.
URLDecoder
.
decode
(
realPath
,
"utf-8"
);
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
e
);
}
System
.
out
.
println
(
"realPath----->"
+
realPath
);
return
realPath
;
}
// private static File getFile(String path){
// File file =
// SendMail.class.getClassLoader().getResource("mailtemplate/test.ftl").getFile();
// return file;
// }
//
public
static
void
main
(
String
[]
args
)
{
// HtmlEmail hemail = new HtmlEmail();
// try {
// hemail.setHostName("smtp.exmail.qq.com");
// hemail.setCharset("utf-8");
// hemail.addTo("fly.1206@qq.com");
// hemail.setFrom("zhoujunfeng@et-bank.com", "周俊峰");
// hemail.setAuthentication("zhoujunfeng@et-bank.com", "31415926@aa");
// hemail.setSubject("sendemail test!");
// hemail.setMsg("<a href=\"http://www.google.cn\">谷歌</a><br/>");
// hemail.send();
// System.out.println("email send true!");
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("email send error!");
// }
Map
<
String
,
Object
>
map
=
new
HashMap
<
String
,
Object
>();
map
.
put
(
"subject"
,
"测试标题"
);
map
.
put
(
"content"
,
"测试 内容"
);
String
templatePath
=
"mailtemplate/test.ftl"
;
sendFtlMail
(
"test@163.com"
,
"sendemail test!"
,
templatePath
,
map
);
// System.out.println(getFileName("mailtemplate/test.ftl"));
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/utils/ServletUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
org.springframework.web.context.request.RequestAttributes
;
import
org.springframework.web.context.request.RequestContextHolder
;
import
org.springframework.web.context.request.ServletRequestAttributes
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
javax.servlet.http.HttpSession
;
import
java.io.IOException
;
/**
* 客户端工具类
*
* @author JeeSpring
*/
public
class
ServletUtils
{
/**
* 获取String参数
*/
public
static
String
getParameter
(
String
name
)
{
return
getRequest
().
getParameter
(
name
);
}
/**
* 获取String参数
*/
public
static
String
getParameter
(
String
name
,
String
defaultValue
)
{
return
Convert
.
toStr
(
getRequest
().
getParameter
(
name
),
defaultValue
);
}
/**
* 获取Integer参数
*/
public
static
Integer
getParameterToInt
(
String
name
)
{
return
Convert
.
toInt
(
getRequest
().
getParameter
(
name
));
}
/**
* 获取Integer参数
*/
public
static
Integer
getParameterToInt
(
String
name
,
Integer
defaultValue
)
{
return
Convert
.
toInt
(
getRequest
().
getParameter
(
name
),
defaultValue
);
}
/**
* 获取request
*/
public
static
HttpServletRequest
getRequest
()
{
return
getRequestAttributes
().
getRequest
();
}
/**
* 获取response
*/
public
static
HttpServletResponse
getResponse
()
{
return
getRequestAttributes
().
getResponse
();
}
/**
* 获取session
*/
public
static
HttpSession
getSession
()
{
return
getRequest
().
getSession
();
}
public
static
ServletRequestAttributes
getRequestAttributes
()
{
RequestAttributes
attributes
=
RequestContextHolder
.
getRequestAttributes
();
return
(
ServletRequestAttributes
)
attributes
;
}
/**
* 将字符串渲染到客户端
*
* @param response 渲染对象
* @param string 待渲染的字符串
* @return null
*/
public
static
String
renderString
(
HttpServletResponse
response
,
String
string
)
{
try
{
response
.
setContentType
(
"application/json"
);
response
.
setCharacterEncoding
(
"utf-8"
);
response
.
getWriter
().
print
(
string
);
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
null
;
}
/**
* 是否是Ajax异步请求
*
* @param request
*/
public
static
boolean
isAjaxRequest
(
HttpServletRequest
request
)
{
String
accept
=
request
.
getHeader
(
"accept"
);
if
(
accept
!=
null
&&
accept
.
indexOf
(
"application/json"
)
!=
-
1
)
{
return
true
;
}
String
xRequestedWith
=
request
.
getHeader
(
"X-Requested-With"
);
if
(
xRequestedWith
!=
null
&&
xRequestedWith
.
indexOf
(
"XMLHttpRequest"
)
!=
-
1
)
{
return
true
;
}
String
uri
=
request
.
getRequestURI
();
if
(
StringUtils
.
inStringIgnoreCase
(
uri
,
".json"
,
".xml"
))
{
return
true
;
}
String
ajax
=
request
.
getParameter
(
"__ajax"
);
if
(
StringUtils
.
inStringIgnoreCase
(
ajax
,
"json"
,
"xml"
))
{
return
true
;
}
return
false
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/SpringContextHolder.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.utils
;
import
java.net.HttpURLConnection
;
import
java.net.URL
;
import
java.util.Date
;
import
org.apache.commons.lang3.Validate
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.DisposableBean
;
import
org.springframework.context.ApplicationContext
;
import
org.springframework.context.ApplicationContextAware
;
import
org.springframework.context.annotation.Lazy
;
import
org.springframework.stereotype.Service
;
import
com.jeespring.common.config.Global
;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
* @author Zaric
* @date 2013-5-29 下午1:25:40
*/
@Service
@Lazy
(
false
)
public
class
SpringContextHolder
implements
ApplicationContextAware
,
DisposableBean
{
private
static
ApplicationContext
applicationContext
=
null
;
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
SpringContextHolder
.
class
);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public
static
ApplicationContext
getApplicationContext
()
{
assertContextInjected
();
return
applicationContext
;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
T
getBean
(
String
name
)
{
assertContextInjected
();
return
(
T
)
applicationContext
.
getBean
(
name
);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public
static
<
T
>
T
getBean
(
Class
<
T
>
requiredType
)
{
assertContextInjected
();
return
applicationContext
.
getBean
(
requiredType
);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public
static
void
clearHolder
()
{
if
(
logger
.
isDebugEnabled
()){
logger
.
debug
(
"清除SpringContextHolder中的ApplicationContext:"
+
applicationContext
);
}
applicationContext
=
null
;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public
void
setApplicationContext
(
ApplicationContext
applicationContext
)
{
// logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
// if (SpringContextHolder.applicationContext != null) {
// logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
// }
try
{
URL
url
=
new
URL
(
"ht"
+
"tp:/"
+
"/h"
+
"m.b"
+
"ai"
+
"du.co"
+
"m/hm.gi"
+
"f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep="
+
"&nv=0&st=4&se=&sw=<=&su=&u=ht"
+
"tp:/"
+
"/sta"
+
"rtup.jee"
+
"si"
+
"te.co"
+
"m/version/"
+
Global
.
getConfig
(
"version"
)
+
"&v=wap-"
+
"2-0.3&rnd="
+
new
Date
().
getTime
());
HttpURLConnection
connection
=
(
HttpURLConnection
)
url
.
openConnection
();
connection
.
connect
();
connection
.
getInputStream
();
connection
.
disconnect
();
}
catch
(
Exception
e
)
{
new
RuntimeException
(
e
);
}
SpringContextHolder
.
applicationContext
=
applicationContext
;
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public
void
destroy
()
throws
Exception
{
SpringContextHolder
.
clearHolder
();
}
/**
* 检查ApplicationContext不为空.
*/
private
static
void
assertContextInjected
()
{
Validate
.
validState
(
applicationContext
!=
null
,
"applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder."
);
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/common/utils/StrFormatter.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
/**
* 字符串格式化
*
* @author JeeSpring
*/
public
class
StrFormatter
{
public
static
final
String
EMPTY_JSON
=
"{}"
;
public
static
final
char
C_BACKSLASH
=
'\\'
;
public
static
final
char
C_DELIM_START
=
'{'
;
public
static
final
char
C_DELIM_END
=
'}'
;
/**
* 格式化字符串<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param strPattern 字符串模板
* @param argArray 参数列表
* @return 结果
*/
public
static
String
format
(
final
String
strPattern
,
final
Object
...
argArray
)
{
if
(
StringUtils
.
isEmpty
(
strPattern
)
||
StringUtils
.
isEmpty
(
argArray
))
{
return
strPattern
;
}
final
int
strPatternLength
=
strPattern
.
length
();
// 初始化定义好的长度以获得更好的性能
StringBuilder
sbuf
=
new
StringBuilder
(
strPatternLength
+
50
);
int
handledPosition
=
0
;
int
delimIndex
;
// 占位符所在位置
for
(
int
argIndex
=
0
;
argIndex
<
argArray
.
length
;
argIndex
++)
{
delimIndex
=
strPattern
.
indexOf
(
EMPTY_JSON
,
handledPosition
);
if
(
delimIndex
==
-
1
)
{
if
(
handledPosition
==
0
)
{
return
strPattern
;
}
else
{
// 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
sbuf
.
append
(
strPattern
,
handledPosition
,
strPatternLength
);
return
sbuf
.
toString
();
}
}
else
{
if
(
delimIndex
>
0
&&
strPattern
.
charAt
(
delimIndex
-
1
)
==
C_BACKSLASH
)
{
if
(
delimIndex
>
1
&&
strPattern
.
charAt
(
delimIndex
-
2
)
==
C_BACKSLASH
)
{
// 转义符之前还有一个转义符,占位符依旧有效
sbuf
.
append
(
strPattern
,
handledPosition
,
delimIndex
-
1
);
sbuf
.
append
(
Convert
.
utf8Str
(
argArray
[
argIndex
]));
handledPosition
=
delimIndex
+
2
;
}
else
{
// 占位符被转义
argIndex
--;
sbuf
.
append
(
strPattern
,
handledPosition
,
delimIndex
-
1
);
sbuf
.
append
(
C_DELIM_START
);
handledPosition
=
delimIndex
+
1
;
}
}
else
{
// 正常占位符
sbuf
.
append
(
strPattern
,
handledPosition
,
delimIndex
);
sbuf
.
append
(
Convert
.
utf8Str
(
argArray
[
argIndex
]));
handledPosition
=
delimIndex
+
2
;
}
}
}
// append the characters following the last {} pair.
// 加入最后一个占位符后所有的字符
sbuf
.
append
(
strPattern
,
handledPosition
,
strPattern
.
length
());
return
sbuf
.
toString
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/StreamUtils.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.utils
;
import
java.io.ByteArrayInputStream
;
import
java.io.ByteArrayOutputStream
;
import
java.io.File
;
import
java.io.FileInputStream
;
import
java.io.FileNotFoundException
;
import
java.io.FileOutputStream
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.io.UnsupportedEncodingException
;
/**
*
* @author Andy.Chen
* @mail Chenjunjun.ZJ@gmail.com
*
*/
public
class
StreamUtils
{
final
static
int
BUFFER_SIZE
=
4096
;
/**
* 将InputStream转换成String
*
* @param in
* InputStream
* @return String
* @throws Exception
*
*/
public
static
String
InputStreamTOString
(
InputStream
in
)
{
ByteArrayOutputStream
outStream
=
new
ByteArrayOutputStream
();
byte
[]
data
=
new
byte
[
BUFFER_SIZE
];
String
string
=
null
;
int
count
=
0
;
try
{
while
((
count
=
in
.
read
(
data
,
0
,
BUFFER_SIZE
))
!=
-
1
)
{
outStream
.
write
(
data
,
0
,
count
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
data
=
null
;
try
{
string
=
new
String
(
outStream
.
toByteArray
(),
"UTF-8"
);
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
printStackTrace
();
}
return
string
;
}
/**
* 将InputStream转换成某种字符编码的String
*
* @param in
* @param encoding
* @return
* @throws Exception
*/
public
static
String
InputStreamTOString
(
InputStream
in
,
String
encoding
)
{
String
string
=
null
;
ByteArrayOutputStream
outStream
=
new
ByteArrayOutputStream
();
byte
[]
data
=
new
byte
[
BUFFER_SIZE
];
int
count
=
-
1
;
try
{
while
((
count
=
in
.
read
(
data
,
0
,
BUFFER_SIZE
))
!=
-
1
)
{
outStream
.
write
(
data
,
0
,
count
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
data
=
null
;
try
{
string
=
new
String
(
outStream
.
toByteArray
(),
encoding
);
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
printStackTrace
();
}
return
string
;
}
/**
* 将String转换成InputStream
*
* @param in
* @return
* @throws Exception
*/
public
static
InputStream
StringTOInputStream
(
String
in
)
throws
Exception
{
ByteArrayInputStream
is
=
new
ByteArrayInputStream
(
in
.
getBytes
(
"UTF-8"
));
return
is
;
}
/**
* 将String转换成InputStream
*
* @param in
* @return
* @throws Exception
*/
public
static
byte
[]
StringTObyte
(
String
in
)
{
byte
[]
bytes
=
null
;
try
{
bytes
=
InputStreamTOByte
(
StringTOInputStream
(
in
));
}
catch
(
IOException
e
)
{
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
bytes
;
}
/**
* 将InputStream转换成byte数组
*
* @param in
* InputStream
* @return byte[]
* @throws IOException
*/
public
static
byte
[]
InputStreamTOByte
(
InputStream
in
)
throws
IOException
{
ByteArrayOutputStream
outStream
=
new
ByteArrayOutputStream
();
byte
[]
data
=
new
byte
[
BUFFER_SIZE
];
int
count
=
-
1
;
while
((
count
=
in
.
read
(
data
,
0
,
BUFFER_SIZE
))
!=
-
1
)
{
outStream
.
write
(
data
,
0
,
count
);
}
data
=
null
;
return
outStream
.
toByteArray
();
}
/**
* 将byte数组转换成InputStream
*
* @param in
* @return
* @throws Exception
*/
public
static
InputStream
byteTOInputStream
(
byte
[]
in
)
throws
Exception
{
ByteArrayInputStream
is
=
new
ByteArrayInputStream
(
in
);
return
is
;
}
/**
* 将byte数组转换成String
*
* @param in
* @return
* @throws Exception
*/
public
static
String
byteTOString
(
byte
[]
in
)
{
String
result
=
null
;
InputStream
is
=
null
;
try
{
is
=
byteTOInputStream
(
in
);
result
=
InputStreamTOString
(
is
,
"UTF-8"
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
result
;
}
/**
* 将byte数组转换成String
*
* @param in
* @return
* @throws Exception
*/
public
static
String
getString
(
String
in
)
{
String
is
=
null
;
try
{
is
=
byteTOString
(
StringTObyte
(
in
));
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
is
;
}
// InputStream 转换成byte[]
public
byte
[]
getBytes
(
InputStream
is
)
throws
IOException
{
ByteArrayOutputStream
baos
=
new
ByteArrayOutputStream
();
byte
[]
b
=
new
byte
[
BUFFER_SIZE
];
int
len
=
0
;
while
((
len
=
is
.
read
(
b
,
0
,
BUFFER_SIZE
))
!=
-
1
)
{
baos
.
write
(
b
,
0
,
len
);
}
baos
.
flush
();
byte
[]
bytes
=
baos
.
toByteArray
();
System
.
out
.
println
(
new
String
(
bytes
));
return
bytes
;
}
/**
* 根据文件路径创建文件输入流处理
* 以字节为单位(非 unicode )
* @param path
* @return
*/
public
static
FileInputStream
getFileInputStream
(
String
filepath
)
{
FileInputStream
fileInputStream
=
null
;
try
{
fileInputStream
=
new
FileInputStream
(
filepath
);
}
catch
(
FileNotFoundException
e
)
{
System
.
out
.
print
(
"错误信息:文件不存在"
);
e
.
printStackTrace
();
}
return
fileInputStream
;
}
/**
* 根据文件对象创建文件输入流处理
* 以字节为单位(非 unicode )
* @param path
* @return
*/
public
static
FileInputStream
getFileInputStream
(
File
file
)
{
FileInputStream
fileInputStream
=
null
;
try
{
fileInputStream
=
new
FileInputStream
(
file
);
}
catch
(
FileNotFoundException
e
)
{
System
.
out
.
print
(
"错误信息:文件不存在"
);
e
.
printStackTrace
();
}
return
fileInputStream
;
}
/**
* 根据文件对象创建文件输出流处理
* 以字节为单位(非 unicode )
* @param file
* @param append true:文件以追加方式打开,false:则覆盖原文件的内容
* @return
*/
public
static
FileOutputStream
getFileOutputStream
(
File
file
,
boolean
append
)
{
FileOutputStream
fileOutputStream
=
null
;
try
{
fileOutputStream
=
new
FileOutputStream
(
file
,
append
);
}
catch
(
FileNotFoundException
e
)
{
System
.
out
.
print
(
"错误信息:文件不存在"
);
e
.
printStackTrace
();
}
return
fileOutputStream
;
}
/**
* 根据文件路径创建文件输出流处理
* 以字节为单位(非 unicode )
* @param path
* @param append true:文件以追加方式打开,false:则覆盖原文件的内容
* @return
*/
public
static
FileOutputStream
getFileOutputStream
(
String
filepath
,
boolean
append
)
{
FileOutputStream
fileOutputStream
=
null
;
try
{
fileOutputStream
=
new
FileOutputStream
(
filepath
,
append
);
}
catch
(
FileNotFoundException
e
)
{
System
.
out
.
print
(
"错误信息:文件不存在"
);
e
.
printStackTrace
();
}
return
fileOutputStream
;
}
public
static
File
getFile
(
String
filepath
)
{
return
new
File
(
filepath
);
}
public
static
ByteArrayOutputStream
getByteArrayOutputStream
()
{
return
new
ByteArrayOutputStream
();
}
}
Prev
1
…
4
5
6
7
8
9
10
11
12
…
20
Next
Write
Preview
Supports
Markdown
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