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/tag/MenuTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag
;
import
java.io.IOException
;
import
javax.servlet.ServletContext
;
import
javax.servlet.jsp.JspTagException
;
import
javax.servlet.jsp.JspWriter
;
import
javax.servlet.jsp.tagext.TagSupport
;
import
com.jeespring.common.config.Global
;
import
com.jeespring.common.utils.SpringContextHolder
;
import
com.jeespring.modules.sys.entity.Menu
;
import
com.jeespring.modules.sys.utils.UserUtils
;
/**
*
* 类描述:菜单标签
*
*
* @date: 日期:2012-12-7 时间:上午10:17:45
* @version 1.0
*/
public
class
MenuTag
extends
TagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
protected
Menu
menu
;
//菜单Map
public
Menu
getMenu
()
{
return
menu
;
}
public
void
setMenu
(
Menu
menu
)
{
this
.
menu
=
menu
;
}
@Override
public
int
doStartTag
()
throws
JspTagException
{
return
EVAL_PAGE
;
}
@Override
public
int
doEndTag
()
throws
JspTagException
{
try
{
JspWriter
out
=
this
.
pageContext
.
getOut
();
String
menu
=
(
String
)
this
.
pageContext
.
getSession
().
getAttribute
(
"menu"
);
if
(
menu
!=
null
){
out
.
print
(
menu
);
}
else
{
menu
=
end
().
toString
();
out
.
print
(
menu
);
}
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
EVAL_PAGE
;
}
public
StringBuffer
end
()
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
getChildOfTree
(
menu
,
0
));
//System.out.println(sb);
return
sb
;
}
private
static
String
getChildOfTree
(
Menu
parent
,
int
level
)
{
StringBuffer
menuString
=
new
StringBuffer
();
String
href
=
""
;
if
(!
parent
.
hasPermisson
())
{
return
""
;
}
if
(
level
>
0
)
{
//level 为0是功能菜单
if
(
parent
.
hasChildren
())
//menu-open
{
menuString
.
append
(
"<li class=\"treeview\">"
);
}
else
{
menuString
.
append
(
"<li>"
);
}
ServletContext
context
=
SpringContextHolder
.
getBean
(
ServletContext
.
class
);
if
(
parent
.
getHref
()
!=
null
&&
parent
.
getHref
().
length
()
>
0
)
{
if
(
parent
.
getHref
().
endsWith
(
".html"
)&&!
parent
.
getHref
().
endsWith
(
"ckfinder.html"
)){
//如果是静态资源并且不是ckfinder.html,直接访问不加adminPath
href
=
context
.
getContextPath
()
+
parent
.
getHref
();
}
else
if
(
parent
.
getHref
().
contains
(
"http://"
)
||
parent
.
getHref
().
contains
(
"https://"
)){
href
=
context
.
getContextPath
()
+
parent
.
getHref
();
}
else
{
href
=
context
.
getContextPath
()
+
Global
.
getAdminPath
()
+
parent
.
getHref
();
}
}
}
if
(
parent
.
hasChildren
())
{
if
(
level
>
0
)
{
menuString
.
append
(
"<a title=\""
+
parent
.
getName
()+
"\" href=\"javascript:\" data-href=\"blank\" class=\"nav-link\" href=\""
+
href
+
"\"><i class=\"fa "
+
parent
.
getIcon
()+
"\"></i> <span class=\"nav-label\">"
+
parent
.
getName
()
//+ "</span><span class=\"fa arrow\"></span></a>");
+
"</span><span class=\"pull-right-container\"><i class=\"fa fa-angle-left pull-right\"></i></span></a>"
);
}
if
(
level
==
1
)
{
menuString
.
append
(
"<ul class=\"nav nav-second-level treeview-menu\" >"
);
}
else
if
(
level
==
2
)
{
menuString
.
append
(
"<ul class=\"nav nav-third-level treeview-menu\" >"
);
}
else
if
(
level
==
3
)
{
menuString
.
append
(
"<ul class=\"nav nav-forth-level treeview-menu\" >"
);
}
else
if
(
level
==
4
)
{
menuString
.
append
(
"<ul class=\"nav nav-fifth-level treeview-menu\" >"
);
}
for
(
Menu
child
:
parent
.
getChildren
())
{
if
(
"1"
.
equals
(
child
.
getIsShow
()))
{
menuString
.
append
(
getChildOfTree
(
child
,
level
+
1
));
}
}
if
(
level
>
0
)
{
menuString
.
append
(
"</ul>"
);
}
}
else
{
//javascript:
menuString
.
append
(
"<a title=\""
+
parent
.
getName
()+
"\" class=\"nav-link\" target=\""
+
parent
.
getTarget
()+
"\" href=\""
+
href
+
"\" data-href=\""
+
href
+
"\"><i class=\"fa "
+
parent
.
getIcon
()+
"\"></i> <span class=\"nav-label\">"
+
parent
.
getName
()+
"</span></a>"
);
}
if
(
level
>
0
)
{
menuString
.
append
(
"</li>"
);
}
return
menuString
.
toString
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/tag/echarts/EChartsBarTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag.echarts
;
import
java.io.IOException
;
import
java.util.List
;
import
java.util.Map
;
import
javax.servlet.jsp.JspException
;
import
javax.servlet.jsp.tagext.BodyTag
;
import
javax.servlet.jsp.tagext.BodyTagSupport
;
import
javax.servlet.jsp.tagext.Tag
;
import
com.github.abel533.echarts.axis.CategoryAxis
;
import
com.github.abel533.echarts.axis.ValueAxis
;
import
com.github.abel533.echarts.code.*
;
import
com.github.abel533.echarts.feature.MagicType
;
import
com.github.abel533.echarts.json.GsonOption
;
import
com.github.abel533.echarts.series.Line
;
public
class
EChartsBarTag
extends
BodyTagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
title
;
private
String
subtitle
;
private
String
xAxisName
;
private
String
yAxisName
;
private
List
<
String
>
xAxisData
;
private
Map
<
String
,
Integer
>
yAxisIndex
;
private
Map
<
String
,
List
<
Double
>>
yAxisData
;
@Override
public
int
doStartTag
()
throws
JspException
{
return
BodyTag
.
EVAL_BODY_BUFFERED
;
}
@Override
public
int
doEndTag
()
throws
JspException
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
"<script type='text/javascript'>"
);
sb
.
append
(
"require([ 'echarts', 'echarts/chart/bar'], function(ec) {"
);
sb
.
append
(
"var myChart= ec.init(document.getElementById('"
+
id
+
"'));"
);
// 创建GsonOption对象,即为json字符串
GsonOption
option
=
new
GsonOption
();
option
.
tooltip
().
trigger
(
Trigger
.
axis
);
option
.
title
(
title
,
subtitle
);
// 工具栏
option
.
toolbox
().
show
(
true
).
feature
(
Tool
.
mark
,
Tool
.
dataView
,
Tool
.
saveAsImage
,
//new MagicType(Magic.line, Magic.bar,Magic.stack,Magic.tiled),
Tool
.
dataZoom
,
Tool
.
restore
);
option
.
calculable
(
true
);
option
.
dataZoom
().
show
(
true
).
realtime
(
true
).
start
(
0
).
end
(
100
);
// X轴数据封装并解析
ValueAxis
valueAxis
=
new
ValueAxis
();
for
(
String
s
:
xAxisData
)
{
valueAxis
.
type
(
AxisType
.
category
).
data
(
s
);
}
// X轴单位
valueAxis
.
name
(
xAxisName
);
option
.
xAxis
(
valueAxis
);
for
(
String
key
:
yAxisData
.
keySet
())
{
option
.
legend
().
data
(
key
);
}
// Y轴数据封装并解析
String
[]
unitNameArray
=
yAxisName
.
split
(
","
);
for
(
String
s
:
unitNameArray
)
{
CategoryAxis
categoryAxis
=
new
CategoryAxis
();
categoryAxis
.
type
(
AxisType
.
value
);
option
.
yAxis
(
categoryAxis
.
name
(
s
));
}
int
i
=
0
;
for
(
String
key
:
yAxisData
.
keySet
())
{
// 遍历list得到数据
List
<
Double
>
list
=
yAxisData
.
get
(
key
);
Line
line
=
new
Line
().
name
(
key
);
for
(
Double
d
:
list
)
{
// KW与MW单位的转换
// if(settingGlobal!=null&&settingGlobal.getIskw()==0){
// d = d/1000;
// }
// 数据为空的话会报错,为空则为零
if
(
d
!=
null
)
{
line
.
type
(
SeriesType
.
bar
).
data
(
d
);
}
else
{
line
.
type
(
SeriesType
.
bar
).
data
(
0
);
}
if
(
yAxisIndex
!=
null
&&
yAxisIndex
.
get
(
key
)
!=
null
)
{
line
.
type
(
SeriesType
.
bar
).
yAxisIndex
(
yAxisIndex
.
get
(
key
));
line
.
symbol
(
Symbol
.
none
);
}
else
{
line
.
type
(
SeriesType
.
bar
).
yAxisIndex
(
0
);
line
.
symbol
(
Symbol
.
none
);
}
}
option
.
series
(
line
);
i
++;
}
sb
.
append
(
"var option="
+
option
.
toString
()
+
";"
);
sb
.
append
(
"myChart.setOption(option);"
);
sb
.
append
(
"});"
);
sb
.
append
(
"</script>"
);
try
{
this
.
pageContext
.
getOut
().
write
(
sb
.
toString
());
}
catch
(
IOException
e
)
{
System
.
err
.
print
(
e
);
}
return
Tag
.
EVAL_PAGE
;
// 继续处理页面
}
@Override
public
String
getId
()
{
return
id
;
}
@Override
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getTitle
()
{
return
title
;
}
public
void
setTitle
(
String
title
)
{
this
.
title
=
title
;
}
public
String
getSubtitle
()
{
return
subtitle
;
}
public
void
setSubtitle
(
String
subtitle
)
{
this
.
subtitle
=
subtitle
;
}
public
String
getxAxisName
()
{
return
xAxisName
;
}
public
void
setxAxisName
(
String
xAxisName
)
{
this
.
xAxisName
=
xAxisName
;
}
public
String
getyAxisName
()
{
return
yAxisName
;
}
public
void
setyAxisName
(
String
yAxisName
)
{
this
.
yAxisName
=
yAxisName
;
}
public
List
<
String
>
getxAxisData
()
{
return
xAxisData
;
}
public
void
setxAxisData
(
List
<
String
>
xAxisData
)
{
this
.
xAxisData
=
xAxisData
;
}
public
Map
<
String
,
Integer
>
getyAxisIndex
()
{
return
yAxisIndex
;
}
public
void
setyAxisIndex
(
Map
<
String
,
Integer
>
yAxisIndex
)
{
this
.
yAxisIndex
=
yAxisIndex
;
}
public
Map
<
String
,
List
<
Double
>>
getyAxisData
()
{
return
yAxisData
;
}
public
void
setyAxisData
(
Map
<
String
,
List
<
Double
>>
yAxisData
)
{
this
.
yAxisData
=
yAxisData
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/tag/echarts/EChartsLineDoubleNumTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag.echarts
;
import
java.io.IOException
;
import
java.util.Map
;
import
javax.servlet.jsp.JspException
;
import
javax.servlet.jsp.tagext.BodyTag
;
import
javax.servlet.jsp.tagext.BodyTagSupport
;
import
javax.servlet.jsp.tagext.Tag
;
import
com.github.abel533.echarts.axis.CategoryAxis
;
import
com.github.abel533.echarts.axis.ValueAxis
;
import
com.github.abel533.echarts.code.*
;
import
com.github.abel533.echarts.feature.MagicType
;
import
com.github.abel533.echarts.json.GsonOption
;
import
com.github.abel533.echarts.series.Line
;
import
com.github.abel533.echarts.style.LineStyle
;
public
class
EChartsLineDoubleNumTag
extends
BodyTagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
title
;
private
String
subtitle
;
private
String
xAxisName
;
private
String
yAxisName
;
private
Map
<
String
,
Integer
>
yAxisIndex
;
private
Map
<
String
,
Double
[][]>
axisDataArr
;
@Override
public
int
doStartTag
()
throws
JspException
{
return
BodyTag
.
EVAL_BODY_BUFFERED
;
}
@SuppressWarnings
(
"unchecked"
)
@Override
public
int
doEndTag
()
throws
JspException
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
"<script type='text/javascript'>"
);
sb
.
append
(
"require([ 'echarts', 'echarts/chart/line'], function(ec) {"
);
sb
.
append
(
"var myChart= ec.init(document.getElementById('"
+
id
+
"'));"
);
// 创建GsonOption对象,即为json字符串
GsonOption
option
=
new
GsonOption
();
/**
* tooltip : { trigger: 'axis' }
*/
option
.
tooltip
().
trigger
(
Trigger
.
axis
);
option
.
tooltip
().
axisPointer
().
show
(
true
).
type
(
PointerType
.
cross
)
.
lineStyle
(
new
LineStyle
().
type
(
LineType
.
dashed
).
width
(
1
));
/**
* title : { 'text':'2002全国宏观经济关联分析(GDP vs 房地产)', 'subtext':'数据来自国家统计局'
* }
*/
option
.
title
(
title
,
subtitle
);
/**
* toolbox: { show : true, feature : { mark : {show: true}, dataZoom :
* {show: true}, dataView : {show: true}, magicType : {show: true, type:
* ['line', 'bar', 'stack', 'tiled']}, restore : {show: true},
* saveAsImage : {show: true} } }
*/
// 工具栏
option
.
toolbox
().
show
(
true
).
feature
(
Tool
.
mark
,
Tool
.
dataZoom
,
Tool
.
dataView
,
//new MagicType(Magic.line, Magic.bar,Magic.stack,Magic.tiled),
Tool
.
restore
,
Tool
.
saveAsImage
);
option
.
calculable
(
true
);
option
.
dataZoom
().
show
(
true
).
realtime
(
true
).
start
(
0
).
end
(
100
);
/**
* xAxis : [ { type: 'value' } ]
*/
// X轴数据设置类型
ValueAxis
valueAxis
=
new
ValueAxis
();
valueAxis
.
type
(
AxisType
.
value
);
valueAxis
.
name
(
xAxisName
);
option
.
xAxis
(
valueAxis
);
// Y轴数据设置类型
CategoryAxis
categoryAxis
=
new
CategoryAxis
();
categoryAxis
.
type
(
AxisType
.
value
);
categoryAxis
.
name
(
yAxisName
);
option
.
yAxis
(
categoryAxis
);
for
(
String
xtitle
:
axisDataArr
.
keySet
())
{
option
.
legend
().
data
(
xtitle
);
}
for
(
String
mapkey
:
axisDataArr
.
keySet
())
{
Line
line
=
new
Line
();
// 显示直线,而不是密密麻麻的点,一点都不好看
line
.
name
(
mapkey
).
type
(
SeriesType
.
line
).
symbol
(
Symbol
.
none
);
Object
[][]
dataArr
=
(
Double
[][])
axisDataArr
.
get
(
mapkey
);
for
(
int
num
=
0
;
num
<
dataArr
.
length
;
num
++)
{
line
.
data
().
add
(
dataArr
[
num
]);
}
if
(
yAxisIndex
!=
null
&&
yAxisIndex
.
get
(
mapkey
)
!=
null
)
{
line
.
yAxisIndex
(
yAxisIndex
.
get
(
mapkey
));
}
else
{
line
.
yAxisIndex
(
0
);
}
option
.
series
(
line
);
}
sb
.
append
(
"var option="
+
option
.
toString
()+
";"
);
sb
.
append
(
"myChart.setOption(option);"
);
sb
.
append
(
"});"
);
sb
.
append
(
"</script>"
);
try
{
this
.
pageContext
.
getOut
().
write
(
sb
.
toString
());
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
Tag
.
EVAL_PAGE
;
// 继续处理页面
}
@Override
public
String
getId
()
{
return
id
;
}
@Override
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getTitle
()
{
return
title
;
}
public
void
setTitle
(
String
title
)
{
this
.
title
=
title
;
}
public
String
getSubtitle
()
{
return
subtitle
;
}
public
void
setSubtitle
(
String
subtitle
)
{
this
.
subtitle
=
subtitle
;
}
public
String
getxAxisName
()
{
return
xAxisName
;
}
public
void
setxAxisName
(
String
xAxisName
)
{
this
.
xAxisName
=
xAxisName
;
}
public
String
getyAxisName
()
{
return
yAxisName
;
}
public
void
setyAxisName
(
String
yAxisName
)
{
this
.
yAxisName
=
yAxisName
;
}
public
Map
<
String
,
Integer
>
getyAxisIndex
()
{
return
yAxisIndex
;
}
public
void
setyAxisIndex
(
Map
<
String
,
Integer
>
yAxisIndex
)
{
this
.
yAxisIndex
=
yAxisIndex
;
}
public
Map
<
String
,
Double
[][]>
getAxisDataArr
()
{
return
axisDataArr
;
}
public
void
setAxisDataArr
(
Map
<
String
,
Double
[][]>
axisDataArr
)
{
this
.
axisDataArr
=
axisDataArr
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/tag/echarts/EChartsLineTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag.echarts
;
import
java.io.IOException
;
import
java.util.List
;
import
java.util.Map
;
import
javax.servlet.jsp.JspException
;
import
javax.servlet.jsp.tagext.BodyTag
;
import
javax.servlet.jsp.tagext.BodyTagSupport
;
import
javax.servlet.jsp.tagext.Tag
;
import
com.github.abel533.echarts.axis.CategoryAxis
;
import
com.github.abel533.echarts.axis.ValueAxis
;
import
com.github.abel533.echarts.code.*
;
import
com.github.abel533.echarts.feature.MagicType
;
import
com.github.abel533.echarts.json.GsonOption
;
import
com.github.abel533.echarts.series.Line
;
public
class
EChartsLineTag
extends
BodyTagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
title
;
private
String
subtitle
;
private
String
xAxisName
;
private
String
yAxisName
;
private
List
<
String
>
xAxisData
;
private
Map
<
String
,
Integer
>
yAxisIndex
;
private
Map
<
String
,
List
<
Double
>>
yAxisData
;
@Override
public
int
doStartTag
()
throws
JspException
{
return
BodyTag
.
EVAL_BODY_BUFFERED
;
}
@Override
public
int
doEndTag
()
throws
JspException
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
"<script type='text/javascript'>"
);
sb
.
append
(
"require([ 'echarts', 'echarts/chart/line','echarts/chart/bar'], function(ec) {"
);
sb
.
append
(
"var myChart= ec.init(document.getElementById('"
+
id
+
"'));"
);
// 创建GsonOption对象,即为json字符串
GsonOption
option
=
new
GsonOption
();
option
.
tooltip
().
trigger
(
Trigger
.
axis
);
option
.
title
(
title
,
subtitle
);
// 工具栏
option
.
toolbox
().
show
(
true
).
feature
(
Tool
.
mark
,
Tool
.
dataView
,
Tool
.
saveAsImage
,
Tool
.
magicType
,
new
MagicType
(
Magic
.
line
,
Magic
.
bar
,
Magic
.
stack
,
Magic
.
tiled
),
Tool
.
dataZoom
,
Tool
.
restore
);
option
.
calculable
(
true
);
option
.
dataZoom
().
show
(
true
).
realtime
(
true
).
start
(
0
).
end
(
100
);
// X轴数据封装并解析
ValueAxis
valueAxis
=
new
ValueAxis
();
for
(
String
s
:
xAxisData
)
{
valueAxis
.
type
(
AxisType
.
category
).
data
(
s
);
}
// X轴单位
valueAxis
.
name
(
xAxisName
);
option
.
xAxis
(
valueAxis
);
for
(
String
key
:
yAxisData
.
keySet
())
{
option
.
legend
().
data
(
key
);
}
// Y轴数据封装并解析
String
[]
unitNameArray
=
yAxisName
.
split
(
","
);
for
(
String
s
:
unitNameArray
)
{
CategoryAxis
categoryAxis
=
new
CategoryAxis
();
categoryAxis
.
type
(
AxisType
.
value
);
option
.
yAxis
(
categoryAxis
.
name
(
s
));
}
int
i
=
0
;
for
(
String
key
:
yAxisData
.
keySet
())
{
// 遍历list得到数据
List
<
Double
>
list
=
yAxisData
.
get
(
key
);
Line
line
=
new
Line
().
name
(
key
);
for
(
Double
d
:
list
)
{
// KW与MW单位的转换
// if(settingGlobal!=null&&settingGlobal.getIskw()==0){
// d = d/1000;
// }
// 数据为空的话会报错,为空则为零
if
(
d
!=
null
)
{
line
.
type
(
SeriesType
.
line
).
data
(
d
);
}
else
{
line
.
type
(
SeriesType
.
line
).
data
(
0
);
}
if
(
yAxisIndex
!=
null
&&
yAxisIndex
.
get
(
key
)
!=
null
)
{
line
.
type
(
SeriesType
.
line
).
yAxisIndex
(
yAxisIndex
.
get
(
key
));
line
.
symbol
(
Symbol
.
none
);
}
else
{
line
.
type
(
SeriesType
.
line
).
yAxisIndex
(
0
);
//显示直线,而不是密密麻麻的点,一点都不好看
line
.
symbol
(
Symbol
.
none
);
}
}
option
.
series
(
line
);
i
++;
}
sb
.
append
(
"var option="
+
option
.
toString
()+
";"
);
sb
.
append
(
"myChart.setOption(option);"
);
sb
.
append
(
"});"
);
sb
.
append
(
"</script>"
);
try
{
this
.
pageContext
.
getOut
().
write
(
sb
.
toString
());
}
catch
(
IOException
e
)
{
System
.
err
.
print
(
e
);
}
return
Tag
.
EVAL_PAGE
;
// 继续处理页面
}
@Override
public
String
getId
()
{
return
id
;
}
@Override
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getTitle
()
{
return
title
;
}
public
void
setTitle
(
String
title
)
{
this
.
title
=
title
;
}
public
String
getSubtitle
()
{
return
subtitle
;
}
public
void
setSubtitle
(
String
subtitle
)
{
this
.
subtitle
=
subtitle
;
}
public
String
getxAxisName
()
{
return
xAxisName
;
}
public
void
setxAxisName
(
String
xAxisName
)
{
this
.
xAxisName
=
xAxisName
;
}
public
String
getyAxisName
()
{
return
yAxisName
;
}
public
void
setyAxisName
(
String
yAxisName
)
{
this
.
yAxisName
=
yAxisName
;
}
public
List
<
String
>
getxAxisData
()
{
return
xAxisData
;
}
public
void
setxAxisData
(
List
<
String
>
xAxisData
)
{
this
.
xAxisData
=
xAxisData
;
}
public
Map
<
String
,
Integer
>
getyAxisIndex
()
{
return
yAxisIndex
;
}
public
void
setyAxisIndex
(
Map
<
String
,
Integer
>
yAxisIndex
)
{
this
.
yAxisIndex
=
yAxisIndex
;
}
public
Map
<
String
,
List
<
Double
>>
getyAxisData
()
{
return
yAxisData
;
}
public
void
setyAxisData
(
Map
<
String
,
List
<
Double
>>
yAxisData
)
{
this
.
yAxisData
=
yAxisData
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/tag/echarts/EChartsLineTimeLineTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag.echarts
;
import
java.io.IOException
;
import
java.util.List
;
import
java.util.Map
;
import
javax.servlet.jsp.JspException
;
import
javax.servlet.jsp.tagext.BodyTag
;
import
javax.servlet.jsp.tagext.BodyTagSupport
;
import
javax.servlet.jsp.tagext.Tag
;
import
com.github.abel533.echarts.axis.CategoryAxis
;
import
com.github.abel533.echarts.axis.ValueAxis
;
import
com.github.abel533.echarts.code.*
;
import
com.github.abel533.echarts.feature.MagicType
;
import
com.github.abel533.echarts.json.GsonOption
;
import
com.github.abel533.echarts.series.Line
;
public
class
EChartsLineTimeLineTag
extends
BodyTagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
title
;
private
String
subtitle
;
private
String
xAxisName
;
private
String
yAxisName
;
private
List
<
String
>
xAxisData
;
private
Map
<
String
,
Integer
>
yAxisIndex
;
private
Map
<
String
,
List
<
Double
>>
yAxisData
;
private
List
<
String
>
timelineData
;
private
List
<
Map
<
String
,
List
<
Double
>>>
timelineAxisData
;
@Override
public
int
doStartTag
()
throws
JspException
{
return
BodyTag
.
EVAL_BODY_BUFFERED
;
}
@Override
public
int
doEndTag
()
throws
JspException
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
"<script type='text/javascript'>"
);
sb
.
append
(
"require([ 'echarts', 'echarts/chart/line'], function(ec) {"
);
sb
.
append
(
"var myChart= ec.init(document.getElementById('"
+
id
+
"'));"
);
GsonOption
option
=
new
GsonOption
();
GsonOption
options
=
new
GsonOption
();
/**
* timeline:{ data:[
* '2002-01-01','2003-01-01','2004-01-01','2005-01-01','2006-01-01',
* '2007-01-01','2008-01-01','2009-01-01','2010-01-01','2011-01-01' ],
* label : { formatter : function(s) { return s.slice(0, 4); } },
* autoPlay : true, playInterval : 1000 },
*/
option
.
timeline
().
autoPlay
(
true
).
playInterval
(
1000
).
label
()
.
formatter
(
"function(s){return s.slice(0, 4);}"
);
for
(
String
key
:
timelineData
)
{
option
.
timeline
().
data
(
key
);
}
/**
* title : { 'text':'2002全国宏观经济指标', 'subtext':'数据来自国家统计局' },
*/
options
.
title
(
title
,
subtitle
);
/**
* tooltip : {'trigger':'axis'},
*/
options
.
tooltip
().
trigger
(
Trigger
.
axis
);
/**
* legend : { x:'right', 'data':['GDP','金融','房地产','第一产业','第二产业','第三产业'],
* 'selected':{ 'GDP':true, '金融':false, '房地产':true, '第一产业':false,
* '第二产业':false, '第三产业':false } },
*/
options
.
legend
().
x
(
X
.
right
);
for
(
String
key
:
yAxisData
.
keySet
())
{
options
.
legend
().
data
(
key
);
}
/**
* toolbox : { 'show':true, orient : 'vertical', x: 'right', y:
* 'center', 'feature':{ 'mark':{'show':true},
* 'dataView':{'show':true,'readOnly':false},
* 'magicType':{'show':true,'type':['line','bar','stack','tiled']},
* 'restore':{'show':true}, 'saveAsImage':{'show':true} } }, calculable
* : true,
*/
// 工具栏
options
.
toolbox
().
orient
(
Orient
.
vertical
).
x
(
X
.
right
).
y
(
Y
.
center
)
.
show
(
true
).
feature
(
Tool
.
mark
,
Tool
.
dataView
,
Tool
.
saveAsImage
,
//new MagicType(Magic.line, Magic.bar,Magic.stack,Magic.tiled),
Tool
.
dataZoom
,
Tool
.
restore
);
options
.
calculable
(
true
);
options
.
dataZoom
().
show
(
true
).
realtime
(
true
).
start
(
0
).
end
(
100
);
/**
* xAxis : [{ 'type':'category', 'axisLabel':{'interval':0}, 'data':[
* '北京','\n天津','河北','\n山西','内蒙古','\n辽宁','吉林','\n黑龙江',
* '上海','\n江苏','浙江','\n安徽','福建','\n江西','山东','\n河南',
* '湖北','\n湖南','广东','\n广西','海南','\n重庆','四川','\n贵州',
* '云南','\n西藏','陕西','\n甘肃','青海','\n宁夏','新疆' ] }],
*/
// X轴数据封装并解析
ValueAxis
valueAxis
=
new
ValueAxis
();
for
(
String
s
:
xAxisData
)
{
valueAxis
.
type
(
AxisType
.
category
).
data
(
s
);
}
// X轴单位
valueAxis
.
name
(
xAxisName
);
options
.
xAxis
(
valueAxis
);
/**
* yAxis : [ { 'type':'value', 'name':'GDP(亿元)', 'max':53500 }, {
* 'type':'value', 'name':'其他(亿元)' } ],
*/
// Y轴数据封装并解析
String
[]
unitNameArray
=
yAxisName
.
split
(
","
);
for
(
String
s
:
unitNameArray
)
{
CategoryAxis
categoryAxis
=
new
CategoryAxis
();
categoryAxis
.
type
(
AxisType
.
value
);
options
.
yAxis
(
categoryAxis
.
name
(
s
));
}
for
(
String
key
:
yAxisData
.
keySet
())
{
// 遍历list得到数据
List
<
Double
>
list
=
yAxisData
.
get
(
key
);
Line
line
=
new
Line
().
name
(
key
);
for
(
Double
d
:
list
)
{
// KW与MW单位的转换
// if(settingGlobal!=null&&settingGlobal.getIskw()==0){
// d = d/1000;
// }
// 数据为空的话会报错,为空则为零
if
(
d
!=
null
)
{
line
.
type
(
SeriesType
.
line
).
data
(
d
);
}
else
{
line
.
type
(
SeriesType
.
line
).
data
(
0
);
}
if
(
yAxisIndex
!=
null
&&
yAxisIndex
.
get
(
key
)
!=
null
)
{
line
.
type
(
SeriesType
.
line
).
yAxisIndex
(
yAxisIndex
.
get
(
key
));
// 显示直线,而不是密密麻麻的点,一点都不好看
line
.
symbol
(
Symbol
.
none
);
}
else
{
line
.
type
(
SeriesType
.
line
).
yAxisIndex
(
0
);
line
.
symbol
(
Symbol
.
none
);
}
}
options
.
series
(
line
);
}
option
.
options
(
options
);
for
(
int
ii
=
1
;
ii
<
timelineData
.
size
();
ii
++)
{
Map
<
String
,
List
<
Double
>>
timelineAxisDataMap
=
timelineAxisData
.
get
(
ii
-
1
);
GsonOption
timeLineOption
=
new
GsonOption
();
timeLineOption
.
title
(
timelineData
.
get
(
ii
)
+
title
.
substring
(
4
,
title
.
length
()),
subtitle
);
for
(
String
key
:
timelineAxisDataMap
.
keySet
())
{
// 遍历list得到数据
List
<
Double
>
list
=
timelineAxisDataMap
.
get
(
key
);
Line
line
=
new
Line
().
name
(
key
);
for
(
Double
d
:
list
)
{
// KW与MW单位的转换
// if(settingGlobal!=null&&settingGlobal.getIskw()==0){
// d = d/1000;
// }
// 数据为空的话会报错,为空则为零
if
(
d
!=
null
)
{
line
.
type
(
SeriesType
.
line
).
data
(
d
);
}
else
{
line
.
type
(
SeriesType
.
line
).
data
(
0
);
}
if
(
yAxisIndex
!=
null
&&
yAxisIndex
.
get
(
key
)
!=
null
)
{
line
.
type
(
SeriesType
.
line
).
yAxisIndex
(
yAxisIndex
.
get
(
key
));
// 显示直线,而不是密密麻麻的点,一点都不好看
line
.
symbol
(
Symbol
.
none
);
}
else
{
line
.
type
(
SeriesType
.
line
).
yAxisIndex
(
0
);
line
.
symbol
(
Symbol
.
none
);
}
}
timeLineOption
.
series
(
line
);
}
option
.
options
(
timeLineOption
);
}
sb
.
append
(
"var option="
+
option
.
toString
()
+
";"
);
sb
.
append
(
"myChart.setOption(option);"
);
sb
.
append
(
"});"
);
sb
.
append
(
"</script>"
);
try
{
this
.
pageContext
.
getOut
().
write
(
sb
.
toString
());
}
catch
(
IOException
e
)
{
System
.
err
.
print
(
e
);
}
return
Tag
.
EVAL_PAGE
;
// 继续处理页面
}
@Override
public
String
getId
()
{
return
id
;
}
@Override
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getTitle
()
{
return
title
;
}
public
void
setTitle
(
String
title
)
{
this
.
title
=
title
;
}
public
String
getSubtitle
()
{
return
subtitle
;
}
public
void
setSubtitle
(
String
subtitle
)
{
this
.
subtitle
=
subtitle
;
}
public
String
getxAxisName
()
{
return
xAxisName
;
}
public
void
setxAxisName
(
String
xAxisName
)
{
this
.
xAxisName
=
xAxisName
;
}
public
String
getyAxisName
()
{
return
yAxisName
;
}
public
void
setyAxisName
(
String
yAxisName
)
{
this
.
yAxisName
=
yAxisName
;
}
public
List
<
String
>
getxAxisData
()
{
return
xAxisData
;
}
public
void
setxAxisData
(
List
<
String
>
xAxisData
)
{
this
.
xAxisData
=
xAxisData
;
}
public
Map
<
String
,
Integer
>
getyAxisIndex
()
{
return
yAxisIndex
;
}
public
void
setyAxisIndex
(
Map
<
String
,
Integer
>
yAxisIndex
)
{
this
.
yAxisIndex
=
yAxisIndex
;
}
public
Map
<
String
,
List
<
Double
>>
getyAxisData
()
{
return
yAxisData
;
}
public
void
setyAxisData
(
Map
<
String
,
List
<
Double
>>
yAxisData
)
{
this
.
yAxisData
=
yAxisData
;
}
public
List
<
String
>
getTimelineData
()
{
return
timelineData
;
}
public
void
setTimelineData
(
List
<
String
>
timelineData
)
{
this
.
timelineData
=
timelineData
;
}
public
List
<
Map
<
String
,
List
<
Double
>>>
getTimelineAxisData
()
{
return
timelineAxisData
;
}
public
void
setTimelineAxisData
(
List
<
Map
<
String
,
List
<
Double
>>>
timelineAxisData
)
{
this
.
timelineAxisData
=
timelineAxisData
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/tag/echarts/EChartsPieTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag.echarts
;
import
java.io.IOException
;
import
java.util.Map
;
import
javax.servlet.jsp.JspException
;
import
javax.servlet.jsp.tagext.BodyTag
;
import
javax.servlet.jsp.tagext.BodyTagSupport
;
import
javax.servlet.jsp.tagext.Tag
;
import
com.github.abel533.echarts.code.*
;
import
com.github.abel533.echarts.data.Data
;
import
com.github.abel533.echarts.feature.MagicType
;
import
com.github.abel533.echarts.json.GsonOption
;
import
com.github.abel533.echarts.series.Line
;
public
class
EChartsPieTag
extends
BodyTagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
title
;
private
String
subtitle
;
private
Map
<
String
,
Object
>
orientData
;
@Override
public
int
doStartTag
()
throws
JspException
{
return
BodyTag
.
EVAL_BODY_BUFFERED
;
}
@Override
public
int
doEndTag
()
throws
JspException
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
"<script type='text/javascript'>"
);
sb
.
append
(
"require([ 'echarts','echarts/chart/pie'], function(ec) {"
);
sb
.
append
(
"var myChart= ec.init(document.getElementById('"
+
id
+
"'));"
);
// 创建GsonOption对象,即为json字符串
GsonOption
option
=
new
GsonOption
();
option
.
tooltip
().
trigger
(
Trigger
.
item
).
formatter
(
"{a} <br/>{b} : {c} ({d}%)"
);
option
.
title
(
title
,
subtitle
);
// 工具栏
option
.
toolbox
().
show
(
true
).
feature
(
Tool
.
mark
,
Tool
.
dataView
,
Tool
.
saveAsImage
,
//Tool.magicType,
//new MagicType(Magic.line, Magic.bar,Magic.pie,Magic.stack,Magic.tiled),
Tool
.
dataZoom
,
Tool
.
restore
);
option
.
calculable
(
true
);
// 数据轴封装并解析
for
(
String
xdata
:
orientData
.
keySet
())
{
//option.legend().orient(Orient.horizontal).x(X.left).y(Y.bottom).data(xdata);
option
.
legend
().
orient
(
Orient
.
vertical
).
x
(
X
.
left
).
y
(
Y
.
bottom
).
data
(
xdata
);
}
if
(
orientData
!=
null
)
{
Line
line
=
new
Line
();
line
.
name
(
title
).
type
(
SeriesType
.
pie
);
for
(
String
title
:
orientData
.
keySet
())
{
Object
value
=
orientData
.
get
(
title
);
Data
data
=
new
Data
().
name
(
title
);
data
.
value
(
value
);
line
.
data
(
data
);
}
option
.
series
(
line
);
}
sb
.
append
(
"var option="
+
option
.
toString
()
+
";\n"
);
/*sb.append("option.series[0].label={\nnormal: { formatter: ' {b|{b}:}{c} {per|{d}%} ',");
sb.append("backgroundColor: '#eee',borderColor: '#aaa',borderWidth: 1,borderRadius: 4,");
sb.append("rich: {a: {color: '#999',lineHeight: 22,align: 'center'},");
sb.append("hr: {borderColor: '#aaa',width: '100%',borderWidth: 0.5,height: 0},");
sb.append("b: {fontSize: 16,lineHeight: 33},");
sb.append("per: {color: '#eee',backgroundColor: '#334455',padding: [2, 4],borderRadius: 2}");
sb.append("}}\n};\n");*/
sb
.
append
(
"myChart.setOption(option);\n"
);
sb
.
append
(
"});"
);
sb
.
append
(
"</script>"
);
try
{
this
.
pageContext
.
getOut
().
write
(
sb
.
toString
());
}
catch
(
IOException
e
)
{
System
.
err
.
print
(
e
);
}
return
Tag
.
EVAL_PAGE
;
// 继续处理页面
}
@Override
public
String
getId
()
{
return
id
;
}
@Override
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getTitle
()
{
return
title
;
}
public
void
setTitle
(
String
title
)
{
this
.
title
=
title
;
}
public
String
getSubtitle
()
{
return
subtitle
;
}
public
void
setSubtitle
(
String
subtitle
)
{
this
.
subtitle
=
subtitle
;
}
public
Map
<
String
,
Object
>
getOrientData
()
{
return
orientData
;
}
public
void
setOrientData
(
Map
<
String
,
Object
>
orientData
)
{
this
.
orientData
=
orientData
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/tag/echarts/EChartsRadarTag.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.tag.echarts
;
import
java.io.IOException
;
import
java.util.List
;
import
java.util.Map
;
import
javax.servlet.jsp.JspException
;
import
javax.servlet.jsp.tagext.BodyTag
;
import
javax.servlet.jsp.tagext.BodyTagSupport
;
import
javax.servlet.jsp.tagext.Tag
;
import
com.github.abel533.echarts.Polar
;
import
com.github.abel533.echarts.code.*
;
import
com.github.abel533.echarts.data.Data
;
import
com.github.abel533.echarts.feature.MagicType
;
import
com.github.abel533.echarts.json.GsonOption
;
import
com.github.abel533.echarts.series.Line
;
public
class
EChartsRadarTag
extends
BodyTagSupport
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
id
;
private
String
title
;
private
String
subtitle
;
private
Integer
polarType
;
private
List
<
Map
<
String
,
Object
>>
orientData
;
@Override
public
int
doStartTag
()
throws
JspException
{
return
BodyTag
.
EVAL_BODY_BUFFERED
;
}
@Override
public
int
doEndTag
()
throws
JspException
{
StringBuffer
sb
=
new
StringBuffer
();
sb
.
append
(
"<script type='text/javascript'>"
);
sb
.
append
(
"require([ 'echarts', 'echarts/chart/radar'], function(ec) {"
);
sb
.
append
(
"var myChart= ec.init(document.getElementById('"
+
id
+
"'));"
);
// 创建GsonOption对象,即为json字符串
GsonOption
option
=
new
GsonOption
();
/**
* title: { text: '实时风向玫瑰图', subtext: '预测时间:' },
*/
option
.
title
(
title
,
subtitle
);
/**
* tooltip: { trigger: 'axis' },
*/
option
.
tooltip
().
trigger
(
Trigger
.
axis
);
/**
* polar: [ { indicator: [ { text: '正北(N)', max: 100 }, { text:
* '西北(NW)', max: 100 }, { text: '正西(W)', max: 100 }, { text: '西南(SW)',
* max: 100 }, { text: '正南(S)', max: 100 }, { text: '东南(SE)', max: 100
* }, { text: '正东(E)', max: 100 }, { text: '东北(NE)', max: 100 } ] } ]
*/
// 工具栏
option
.
toolbox
().
show
(
true
).
feature
(
Tool
.
mark
,
Tool
.
dataView
,
Tool
.
saveAsImage
,
//new MagicType(Magic.line, Magic.bar,Magic.stack,Magic.tiled),
Tool
.
dataZoom
,
Tool
.
restore
);
Polar
polar
=
new
Polar
();
if
(
polarType
==
8
)
{
polar
.
indicator
(
new
Data
().
text
(
"正北(N)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"西北(NW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"正西(W)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"西南(SW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"正南(S)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"东南(SE)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"正东(E)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"东北(NE)"
).
max
(
100
));
}
else
if
(
polarType
==
16
)
{
polar
.
indicator
(
new
Data
().
text
(
"正北(N)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"北西北(NNW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"西北(NW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"西北西(WNW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"正西(W)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"西南西(WSW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"西南(SW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"南西南(SSW)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"正南(S)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"南东南(SSE)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"东南(SE)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"东南东(ESE)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"正东(E)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"东北东(ENE)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"东北(NE)"
).
max
(
100
))
.
indicator
(
new
Data
().
text
(
"北东北(NNE)"
).
max
(
100
));
}
option
.
polar
(
polar
);
option
.
calculable
(
true
);
/**
* legend: { orient: 'horizontal', x: 'left', y: 'bottom', data: [
* <c:forEach var="item" items="${towerList}" varStatus="status">
* '${item.tower_mater}米风向', </c:forEach> ] },
*/
if
(
orientData
!=
null
)
{
for
(
Map
<
String
,
Object
>
legendMap
:
orientData
)
{
String
title
=
legendMap
.
get
(
"title"
).
toString
();
option
.
legend
().
orient
(
Orient
.
horizontal
).
x
(
X
.
left
).
y
(
Y
.
bottom
).
data
(
title
);
Line
line
=
new
Line
();
Data
data
=
new
Data
().
name
(
title
);
Object
[]
dataArr
=
(
Double
[])
legendMap
.
get
(
"dataArr"
);
data
.
value
(
dataArr
);
line
.
type
(
SeriesType
.
radar
).
data
(
data
);
option
.
series
(
line
);
}
}
sb
.
append
(
"var option="
+
option
.
toString
()+
";"
);
sb
.
append
(
"myChart.setOption(option);"
);
sb
.
append
(
"});"
);
sb
.
append
(
"</script>"
);
try
{
this
.
pageContext
.
getOut
().
write
(
sb
.
toString
());
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
Tag
.
EVAL_PAGE
;
// 继续处理页面
}
@Override
public
String
getId
()
{
return
id
;
}
@Override
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
String
getTitle
()
{
return
title
;
}
public
void
setTitle
(
String
title
)
{
this
.
title
=
title
;
}
public
String
getSubtitle
()
{
return
subtitle
;
}
public
void
setSubtitle
(
String
subtitle
)
{
this
.
subtitle
=
subtitle
;
}
public
Integer
getPolarType
()
{
return
polarType
;
}
public
void
setPolarType
(
Integer
polarType
)
{
this
.
polarType
=
polarType
;
}
public
List
<
Map
<
String
,
Object
>>
getOrientData
()
{
return
orientData
;
}
public
void
setOrientData
(
List
<
Map
<
String
,
Object
>>
orientData
)
{
this
.
orientData
=
orientData
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/AddressUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
com.alibaba.fastjson.JSONObject
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.jeespring.common.utils.http.HttpUtils
;
import
org.springframework.beans.factory.annotation.Value
;
/**
* 获取地址类
*
* @author JeeSpring
*/
public
class
AddressUtils
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
AddressUtils
.
class
);
public
static
final
String
IP_URL
=
"http://ip.taobao.com/service/getIpInfo.php"
;
/** 获取地址开关 */
private
static
boolean
addressEnabled
=
false
;
public
static
String
getRealAddressByIP
(
String
ip
)
{
String
address
=
""
;
try
{
if
(
addressEnabled
)
{
address
=
HttpUtils
.
sendPost
(
IP_URL
,
"ip="
+
ip
);
JSONObject
json
=
JSONObject
.
parseObject
(
address
);
JSONObject
object
=
json
.
getObject
(
"data"
,
JSONObject
.
class
);
String
region
=
object
.
getString
(
"region"
);
String
city
=
object
.
getString
(
"city"
);
address
=
region
+
" "
+
city
;
}
}
catch
(
Exception
e
)
{
log
.
error
(
"获取地理位置异常:"
,
e
.
getMessage
());
}
return
address
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/Base64ImageUtils.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
sun.misc.BASE64Decoder
;
import
sun.misc.BASE64Encoder
;
import
java.io.*
;
import
java.net.HttpURLConnection
;
import
java.net.URL
;
/**
* Created by zhangwenchao on 2017/9/29.
* 本地或者网络图片资源转为Base64字符串
*/
public
class
Base64ImageUtils
{
/**
* @Title: GetImageStrFromUrl
* @Description: 将一张网络图片转化成Base64字符串
* @param imgURL 网络资源位置
* @return Base64字符串
*/
public
static
String
GetImageStrFromUrl
(
String
imgURL
)
{
byte
[]
data
=
null
;
try
{
// 创建URL
URL
url
=
new
URL
(
imgURL
);
// 创建链接
HttpURLConnection
conn
=
(
HttpURLConnection
)
url
.
openConnection
();
conn
.
setRequestMethod
(
"GET"
);
conn
.
setConnectTimeout
(
5
*
1000
);
InputStream
inStream
=
conn
.
getInputStream
();
data
=
new
byte
[
inStream
.
available
()];
inStream
.
read
(
data
);
inStream
.
close
();
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
// 对字节数组Base64编码
BASE64Encoder
encoder
=
new
BASE64Encoder
();
// 返回Base64编码过的字节数组字符串
return
encoder
.
encode
(
data
);
}
/**
* @Title: GetImageStrFromPath
* @Description: (将一张本地图片转化成Base64字符串)
* @param imgPath
* @return
*/
public
static
String
GetImageStrFromPath
(
String
imgPath
)
{
InputStream
in
=
null
;
byte
[]
data
=
null
;
// 读取图片字节数组
try
{
in
=
new
FileInputStream
(
imgPath
);
data
=
new
byte
[
in
.
available
()];
in
.
read
(
data
);
in
.
close
();
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
// 对字节数组Base64编码
BASE64Encoder
encoder
=
new
BASE64Encoder
();
// 返回Base64编码过的字节数组字符串
return
encoder
.
encode
(
data
);
}
/**
* @Title: GenerateImage
* @Description: base64字符串转化成图片
* @param imgStr
* @param imgFilePath 图片文件名,如“E:/tmp.jpg”
* @return
*/
public
static
boolean
saveImage
(
String
imgStr
,
String
imgFilePath
)
{
if
(
imgStr
==
null
)
// 图像数据为空
{
return
false
;
}
BASE64Decoder
decoder
=
new
BASE64Decoder
();
try
{
// Base64解码
byte
[]
b
=
decoder
.
decodeBuffer
(
imgStr
);
for
(
int
i
=
0
;
i
<
b
.
length
;
++
i
)
{
if
(
b
[
i
]
<
0
)
{
// 调整异常数据
b
[
i
]
+=
256
;
}
}
// 生成jpeg图片
OutputStream
out
=
new
FileOutputStream
(
imgFilePath
);
out
.
write
(
b
);
out
.
flush
();
out
.
close
();
return
true
;
}
catch
(
Exception
e
)
{
return
false
;
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/CacheUtils.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.apache.shiro.cache.Cache
;
import
org.apache.shiro.cache.CacheManager
;
/**
* Cache工具类
*
* @author 黄炳桂 516821420@qq.com
* @version 2013-5-29
*/
public
class
CacheUtils
{
private
static
CacheManager
cacheManager
=
SpringContextHolder
.
getBean
(
CacheManager
.
class
);
private
static
final
String
SYS_CACHE
=
"sysCache"
;
/**
* 获取SYS_CACHE缓存
*
* @param key
* @return
*/
public
static
Object
get
(
String
key
)
{
return
get
(
SYS_CACHE
,
key
);
}
/**
* 获取SYS_CACHE缓存
*
* @param key
* @param defaultValue
* @return
*/
public
static
Object
get
(
String
key
,
Object
defaultValue
)
{
Object
value
=
get
(
key
);
return
value
!=
null
?
value
:
defaultValue
;
}
/**
* 写入SYS_CACHE缓存
*
* @param key
* @return
*/
public
static
void
put
(
String
key
,
Object
value
)
{
put
(
SYS_CACHE
,
key
,
value
);
}
/**
* 从SYS_CACHE缓存中移除
*
* @param key
* @return
*/
public
static
void
remove
(
String
key
)
{
remove
(
SYS_CACHE
,
key
);
}
/**
* 获取缓存
*
* @param cacheName
* @param key
* @return
*/
public
static
Object
get
(
String
cacheName
,
String
key
)
{
return
getCache
(
cacheName
).
get
(
key
);
}
/**
* 获取缓存
*
* @param cacheName
* @param key
* @param defaultValue
* @return
*/
public
static
Object
get
(
String
cacheName
,
String
key
,
Object
defaultValue
)
{
Object
value
=
get
(
cacheName
,
key
);
return
value
!=
null
?
value
:
defaultValue
;
}
/**
* 写入缓存
*
* @param cacheName
* @param key
* @param value
*/
public
static
void
put
(
String
cacheName
,
String
key
,
Object
value
)
{
getCache
(
cacheName
).
put
(
key
,
value
);
}
/**
* 从缓存中移除
*
* @param cacheName
* @param key
*/
public
static
void
remove
(
String
cacheName
,
String
key
)
{
getCache
(
cacheName
).
remove
(
key
);
}
/**
* 获得一个Cache,没有则显示日志。
*
* @param cacheName
* @return
*/
private
static
Cache
<
String
,
Object
>
getCache
(
String
cacheName
)
{
Cache
<
String
,
Object
>
cache
=
cacheManager
.
getCache
(
cacheName
);
if
(
cache
==
null
)
{
throw
new
RuntimeException
(
"当前系统中没有定义“"
+
cacheName
+
"”这个缓存。"
);
}
return
cache
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/CharsetKit.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.nio.charset.Charset
;
import
java.nio.charset.StandardCharsets
;
/**
* 字符集工具类
*
* @author JeeSpring
*
*/
public
class
CharsetKit
{
/** ISO-8859-1 */
public
static
final
String
ISO_8859_1
=
"ISO-8859-1"
;
/** UTF-8 */
public
static
final
String
UTF_8
=
"UTF-8"
;
/** GBK */
public
static
final
String
GBK
=
"GBK"
;
/** ISO-8859-1 */
public
static
final
Charset
CHARSET_ISO_8859_1
=
Charset
.
forName
(
ISO_8859_1
);
/** UTF-8 */
public
static
final
Charset
CHARSET_UTF_8
=
Charset
.
forName
(
UTF_8
);
/** GBK */
public
static
final
Charset
CHARSET_GBK
=
Charset
.
forName
(
GBK
);
/**
* 转换为Charset对象
*
* @param charset 字符集,为空则返回默认字符集
* @return Charset
*/
public
static
Charset
charset
(
String
charset
)
{
return
StringUtils
.
isEmpty
(
charset
)
?
Charset
.
defaultCharset
()
:
Charset
.
forName
(
charset
);
}
/**
* 转换字符串的字符集编码
*
* @param source 字符串
* @param srcCharset 源字符集,默认ISO-8859-1
* @param destCharset 目标字符集,默认UTF-8
* @return 转换后的字符集
*/
public
static
String
convert
(
String
source
,
String
srcCharset
,
String
destCharset
)
{
return
convert
(
source
,
Charset
.
forName
(
srcCharset
),
Charset
.
forName
(
destCharset
));
}
/**
* 转换字符串的字符集编码
*
* @param source 字符串
* @param srcCharset 源字符集,默认ISO-8859-1
* @param destCharset 目标字符集,默认UTF-8
* @return 转换后的字符集
*/
public
static
String
convert
(
String
source
,
Charset
srcCharset
,
Charset
destCharset
)
{
if
(
null
==
srcCharset
)
{
srcCharset
=
StandardCharsets
.
ISO_8859_1
;
}
if
(
null
==
destCharset
)
{
srcCharset
=
StandardCharsets
.
UTF_8
;
}
if
(
StringUtils
.
isEmpty
(
source
)
||
srcCharset
.
equals
(
destCharset
))
{
return
source
;
}
return
new
String
(
source
.
getBytes
(
srcCharset
),
destCharset
);
}
/**
* @return 系统字符集编码
*/
public
static
String
systemCharset
()
{
return
Charset
.
defaultCharset
().
name
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/Collections3.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.utils
;
import
java.util.ArrayList
;
import
java.util.Collection
;
import
java.util.HashMap
;
import
java.util.Iterator
;
import
java.util.List
;
import
java.util.Map
;
import
org.apache.commons.beanutils.PropertyUtils
;
import
org.apache.commons.lang3.StringUtils
;
/**
* Collections工具集.
* 在JDK的Collections和Guava的Collections2后, 命名为Collections3.
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings
(
"rawtypes"
)
public
class
Collections3
{
/**
* 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
*
* @param collection 来源集合.
* @param keyPropertyName 要提取为Map中的Key值的属性名.
* @param valuePropertyName 要提取为Map中的Value值的属性名.
*/
@SuppressWarnings
(
"unchecked"
)
public
static
Map
extractToMap
(
final
Collection
collection
,
final
String
keyPropertyName
,
final
String
valuePropertyName
)
{
Map
map
=
new
HashMap
(
collection
.
size
());
try
{
for
(
Object
obj
:
collection
)
{
map
.
put
(
PropertyUtils
.
getProperty
(
obj
,
keyPropertyName
),
PropertyUtils
.
getProperty
(
obj
,
valuePropertyName
));
}
}
catch
(
Exception
e
)
{
throw
Reflections
.
convertReflectionExceptionToUnchecked
(
e
);
}
return
map
;
}
/**
* 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
*
* @param collection 来源集合.
* @param propertyName 要提取的属性名.
*/
@SuppressWarnings
(
"unchecked"
)
public
static
List
extractToList
(
final
Collection
collection
,
final
String
propertyName
)
{
List
list
=
new
ArrayList
(
collection
.
size
());
try
{
for
(
Object
obj
:
collection
)
{
list
.
add
(
PropertyUtils
.
getProperty
(
obj
,
propertyName
));
}
}
catch
(
Exception
e
)
{
throw
Reflections
.
convertReflectionExceptionToUnchecked
(
e
);
}
return
list
;
}
/**
* 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
*
* @param collection 来源集合.
* @param propertyName 要提取的属性名.
* @param separator 分隔符.
*/
public
static
String
extractToString
(
final
Collection
collection
,
final
String
propertyName
,
final
String
separator
)
{
List
list
=
extractToList
(
collection
,
propertyName
);
return
StringUtils
.
join
(
list
,
separator
);
}
/**
* 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
*/
public
static
String
convertToString
(
final
Collection
collection
,
final
String
separator
)
{
return
StringUtils
.
join
(
collection
,
separator
);
}
/**
* 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix,后面加入postfix,如<div>mymessage</div>。
*/
public
static
String
convertToString
(
final
Collection
collection
,
final
String
prefix
,
final
String
postfix
)
{
StringBuilder
builder
=
new
StringBuilder
();
for
(
Object
o
:
collection
)
{
builder
.
append
(
prefix
).
append
(
o
).
append
(
postfix
);
}
return
builder
.
toString
();
}
/**
* 判断是否为空.
*/
public
static
boolean
isEmpty
(
Collection
collection
)
{
return
(
collection
==
null
||
collection
.
isEmpty
());
}
/**
* 取得Collection的第一个元素,如果collection为空返回null.
*/
public
static
<
T
>
T
getFirst
(
Collection
<
T
>
collection
)
{
if
(
isEmpty
(
collection
))
{
return
null
;
}
return
collection
.
iterator
().
next
();
}
/**
* 获取Collection的最后一个元素 ,如果collection为空返回null.
*/
public
static
<
T
>
T
getLast
(
Collection
<
T
>
collection
)
{
if
(
isEmpty
(
collection
))
{
return
null
;
}
//当类型为List时,直接取得最后一个元素 。
if
(
collection
instanceof
List
)
{
List
<
T
>
list
=
(
List
<
T
>)
collection
;
return
list
.
get
(
list
.
size
()
-
1
);
}
//其他类型通过iterator滚动到最后一个元素.
Iterator
<
T
>
iterator
=
collection
.
iterator
();
while
(
true
)
{
T
current
=
iterator
.
next
();
if
(!
iterator
.
hasNext
())
{
return
current
;
}
}
}
/**
* 返回a+b的新List.
*/
public
static
<
T
>
List
<
T
>
union
(
final
Collection
<
T
>
a
,
final
Collection
<
T
>
b
)
{
List
<
T
>
result
=
new
ArrayList
<
T
>(
a
);
result
.
addAll
(
b
);
return
result
;
}
/**
* 返回a-b的新List.
*/
public
static
<
T
>
List
<
T
>
subtract
(
final
Collection
<
T
>
a
,
final
Collection
<
T
>
b
)
{
List
<
T
>
list
=
new
ArrayList
<
T
>(
a
);
for
(
T
element
:
b
)
{
list
.
remove
(
element
);
}
return
list
;
}
/**
* 返回a与b的交集的新List.
*/
public
static
<
T
>
List
<
T
>
intersection
(
Collection
<
T
>
a
,
Collection
<
T
>
b
)
{
List
<
T
>
list
=
new
ArrayList
<
T
>();
for
(
T
element
:
a
)
{
if
(
b
.
contains
(
element
))
{
list
.
add
(
element
);
}
}
return
list
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/Convert.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.math.BigDecimal
;
import
java.math.BigInteger
;
import
java.nio.ByteBuffer
;
import
java.nio.charset.Charset
;
import
java.text.NumberFormat
;
import
java.util.Set
;
/**
* 类型转换器
*
* @author JeeSpring
*
*/
public
class
Convert
{
/**
* 转换为字符串<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
String
toStr
(
Object
value
,
String
defaultValue
)
{
if
(
null
==
value
)
{
return
defaultValue
;
}
if
(
value
instanceof
String
)
{
return
(
String
)
value
;
}
return
value
.
toString
();
}
/**
* 转换为字符串<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
String
toStr
(
Object
value
)
{
return
toStr
(
value
,
null
);
}
/**
* 转换为字符<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Character
toChar
(
Object
value
,
Character
defaultValue
)
{
if
(
null
==
value
)
{
return
defaultValue
;
}
if
(
value
instanceof
Character
)
{
return
(
Character
)
value
;
}
final
String
valueStr
=
toStr
(
value
,
null
);
return
StringUtils
.
isEmpty
(
valueStr
)
?
defaultValue
:
valueStr
.
charAt
(
0
);
}
/**
* 转换为字符<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Character
toChar
(
Object
value
)
{
return
toChar
(
value
,
null
);
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Byte
toByte
(
Object
value
,
Byte
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Byte
)
{
return
(
Byte
)
value
;
}
if
(
value
instanceof
Number
)
{
return
((
Number
)
value
).
byteValue
();
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
Byte
.
parseByte
(
valueStr
);
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Byte
toByte
(
Object
value
)
{
return
toByte
(
value
,
null
);
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Short
toShort
(
Object
value
,
Short
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Short
)
{
return
(
Short
)
value
;
}
if
(
value
instanceof
Number
)
{
return
((
Number
)
value
).
shortValue
();
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
Short
.
parseShort
(
valueStr
.
trim
());
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Short
toShort
(
Object
value
)
{
return
toShort
(
value
,
null
);
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Number
toNumber
(
Object
value
,
Number
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Number
)
{
return
(
Number
)
value
;
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
NumberFormat
.
getInstance
().
parse
(
valueStr
);
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Number
toNumber
(
Object
value
)
{
return
toNumber
(
value
,
null
);
}
/**
* 转换为int<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Integer
toInt
(
Object
value
,
Integer
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Integer
)
{
return
(
Integer
)
value
;
}
if
(
value
instanceof
Number
)
{
return
((
Number
)
value
).
intValue
();
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
Integer
.
parseInt
(
valueStr
.
trim
());
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为int<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Integer
toInt
(
Object
value
)
{
return
toInt
(
value
,
null
);
}
/**
* 转换为Integer数组<br>
*
* @param split 被转换的值
* @return 结果
*/
public
static
Integer
[]
toIntArray
(
String
str
)
{
return
toIntArray
(
","
,
str
);
}
/**
* 转换为Long数组<br>
*
* @param split 被转换的值
* @return 结果
*/
public
static
Long
[]
toLongArray
(
String
str
)
{
return
toLongArray
(
","
,
str
);
}
/**
* 转换为Integer数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public
static
Integer
[]
toIntArray
(
String
split
,
String
str
)
{
if
(
StringUtils
.
isEmpty
(
str
))
{
return
new
Integer
[]
{};
}
String
[]
arr
=
str
.
split
(
split
);
final
Integer
[]
ints
=
new
Integer
[
arr
.
length
];
for
(
int
i
=
0
;
i
<
arr
.
length
;
i
++)
{
final
Integer
v
=
toInt
(
arr
[
i
],
0
);
ints
[
i
]
=
v
;
}
return
ints
;
}
/**
* 转换为Long数组<br>
*
* @param isIgnoreConvertError 是否忽略转换错误,忽略则给值null
* @param values 被转换的值
* @return 结果
*/
public
static
Long
[]
toLongArray
(
String
split
,
String
str
)
{
if
(
StringUtils
.
isEmpty
(
str
))
{
return
new
Long
[]
{};
}
String
[]
arr
=
str
.
split
(
split
);
final
Long
[]
longs
=
new
Long
[
arr
.
length
];
for
(
int
i
=
0
;
i
<
arr
.
length
;
i
++)
{
final
Long
v
=
toLong
(
arr
[
i
],
null
);
longs
[
i
]
=
v
;
}
return
longs
;
}
/**
* 转换为String数组<br>
*
* @param split 被转换的值
* @return 结果
*/
public
static
String
[]
toStrArray
(
String
str
)
{
return
toStrArray
(
","
,
str
);
}
/**
* 转换为String数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public
static
String
[]
toStrArray
(
String
split
,
String
str
)
{
return
str
.
split
(
split
);
}
/**
* 转换为long<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Long
toLong
(
Object
value
,
Long
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Long
)
{
return
(
Long
)
value
;
}
if
(
value
instanceof
Number
)
{
return
((
Number
)
value
).
longValue
();
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
// 支持科学计数法
return
new
BigDecimal
(
valueStr
.
trim
()).
longValue
();
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为long<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Long
toLong
(
Object
value
)
{
return
toLong
(
value
,
null
);
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Double
toDouble
(
Object
value
,
Double
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Double
)
{
return
(
Double
)
value
;
}
if
(
value
instanceof
Number
)
{
return
((
Number
)
value
).
doubleValue
();
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
// 支持科学计数法
return
new
BigDecimal
(
valueStr
.
trim
()).
doubleValue
();
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Double
toDouble
(
Object
value
)
{
return
toDouble
(
value
,
null
);
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Float
toFloat
(
Object
value
,
Float
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Float
)
{
return
(
Float
)
value
;
}
if
(
value
instanceof
Number
)
{
return
((
Number
)
value
).
floatValue
();
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
Float
.
parseFloat
(
valueStr
.
trim
());
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Float
toFloat
(
Object
value
)
{
return
toFloat
(
value
,
null
);
}
/**
* 转换为boolean<br>
* String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
Boolean
toBool
(
Object
value
,
Boolean
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
Boolean
)
{
return
(
Boolean
)
value
;
}
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
valueStr
=
valueStr
.
trim
().
toLowerCase
();
switch
(
valueStr
)
{
case
"true"
:
return
true
;
case
"false"
:
return
false
;
case
"yes"
:
return
true
;
case
"ok"
:
return
true
;
case
"no"
:
return
false
;
case
"1"
:
return
true
;
case
"0"
:
return
false
;
default
:
return
defaultValue
;
}
}
/**
* 转换为boolean<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
Boolean
toBool
(
Object
value
)
{
return
toBool
(
value
,
null
);
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
*
* @param clazz Enum的Class
* @param value 值
* @param defaultValue 默认值
* @return Enum
*/
public
static
<
E
extends
Enum
<
E
>>
E
toEnum
(
Class
<
E
>
clazz
,
Object
value
,
E
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
clazz
.
isAssignableFrom
(
value
.
getClass
()))
{
@SuppressWarnings
(
"unchecked"
)
E
myE
=
(
E
)
value
;
return
myE
;
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
Enum
.
valueOf
(
clazz
,
valueStr
);
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
*
* @param clazz Enum的Class
* @param value 值
* @return Enum
*/
public
static
<
E
extends
Enum
<
E
>>
E
toEnum
(
Class
<
E
>
clazz
,
Object
value
)
{
return
toEnum
(
clazz
,
value
,
null
);
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
BigInteger
toBigInteger
(
Object
value
,
BigInteger
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
BigInteger
)
{
return
(
BigInteger
)
value
;
}
if
(
value
instanceof
Long
)
{
return
BigInteger
.
valueOf
((
Long
)
value
);
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
new
BigInteger
(
valueStr
);
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
BigInteger
toBigInteger
(
Object
value
)
{
return
toBigInteger
(
value
,
null
);
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public
static
BigDecimal
toBigDecimal
(
Object
value
,
BigDecimal
defaultValue
)
{
if
(
value
==
null
)
{
return
defaultValue
;
}
if
(
value
instanceof
BigDecimal
)
{
return
(
BigDecimal
)
value
;
}
if
(
value
instanceof
Long
)
{
return
new
BigDecimal
((
Long
)
value
);
}
if
(
value
instanceof
Double
)
{
return
new
BigDecimal
((
Double
)
value
);
}
if
(
value
instanceof
Integer
)
{
return
new
BigDecimal
((
Integer
)
value
);
}
final
String
valueStr
=
toStr
(
value
,
null
);
if
(
StringUtils
.
isEmpty
(
valueStr
))
{
return
defaultValue
;
}
try
{
return
new
BigDecimal
(
valueStr
);
}
catch
(
Exception
e
)
{
return
defaultValue
;
}
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public
static
BigDecimal
toBigDecimal
(
Object
value
)
{
return
toBigDecimal
(
value
,
null
);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @return 字符串
*/
public
static
String
utf8Str
(
Object
obj
)
{
return
str
(
obj
,
CharsetKit
.
CHARSET_UTF_8
);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @param charsetName 字符集
* @return 字符串
*/
public
static
String
str
(
Object
obj
,
String
charsetName
)
{
return
str
(
obj
,
Charset
.
forName
(
charsetName
));
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @param charset 字符集
* @return 字符串
*/
public
static
String
str
(
Object
obj
,
Charset
charset
)
{
if
(
null
==
obj
)
{
return
null
;
}
if
(
obj
instanceof
String
)
{
return
(
String
)
obj
;
}
else
if
(
obj
instanceof
byte
[]
||
obj
instanceof
Byte
[])
{
return
str
((
Byte
[])
obj
,
charset
);
}
else
if
(
obj
instanceof
ByteBuffer
)
{
return
str
((
ByteBuffer
)
obj
,
charset
);
}
return
obj
.
toString
();
}
/**
* 将byte数组转为字符串
*
* @param bytes byte数组
* @param charset 字符集
* @return 字符串
*/
public
static
String
str
(
byte
[]
bytes
,
String
charset
)
{
return
str
(
bytes
,
StringUtils
.
isEmpty
(
charset
)
?
Charset
.
defaultCharset
()
:
Charset
.
forName
(
charset
));
}
/**
* 解码字节码
*
* @param data 字符串
* @param charset 字符集,如果此字段为空,则解码的结果取决于平台
* @return 解码后的字符串
*/
public
static
String
str
(
byte
[]
data
,
Charset
charset
)
{
if
(
data
==
null
)
{
return
null
;
}
if
(
null
==
charset
)
{
return
new
String
(
data
);
}
return
new
String
(
data
,
charset
);
}
/**
* 将编码的byteBuffer数据转换为字符串
*
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public
static
String
str
(
ByteBuffer
data
,
String
charset
)
{
if
(
data
==
null
)
{
return
null
;
}
return
str
(
data
,
Charset
.
forName
(
charset
));
}
/**
* 将编码的byteBuffer数据转换为字符串
*
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public
static
String
str
(
ByteBuffer
data
,
Charset
charset
)
{
if
(
null
==
charset
)
{
charset
=
Charset
.
defaultCharset
();
}
return
charset
.
decode
(
data
).
toString
();
}
// ----------------------------------------------------------------------- 全角半角转换
/**
* 半角转全角
*
* @param input String.
* @return 全角字符串.
*/
public
static
String
toSBC
(
String
input
)
{
return
toSBC
(
input
,
null
);
}
/**
* 半角转全角
*
* @param input String
* @param notConvertSet 不替换的字符集合
* @return 全角字符串.
*/
public
static
String
toSBC
(
String
input
,
Set
<
Character
>
notConvertSet
)
{
char
[]
c
=
input
.
toCharArray
();
for
(
int
i
=
0
;
i
<
c
.
length
;
i
++)
{
if
(
null
!=
notConvertSet
&&
notConvertSet
.
contains
(
c
[
i
]))
{
// 跳过不替换的字符
continue
;
}
if
(
c
[
i
]
==
' '
)
{
c
[
i
]
=
'\u3000'
;
}
else
if
(
c
[
i
]
<
'\
177
'
)
{
c
[
i
]
=
(
char
)
(
c
[
i
]
+
65248
);
}
}
return
new
String
(
c
);
}
/**
* 全角转半角
*
* @param input String.
* @return 半角字符串
*/
public
static
String
toDBC
(
String
input
)
{
return
toDBC
(
input
,
null
);
}
/**
* 替换全角为半角
*
* @param text 文本
* @param notConvertSet 不替换的字符集合
* @return 替换后的字符
*/
public
static
String
toDBC
(
String
text
,
Set
<
Character
>
notConvertSet
)
{
char
[]
c
=
text
.
toCharArray
();
for
(
int
i
=
0
;
i
<
c
.
length
;
i
++)
{
if
(
null
!=
notConvertSet
&&
notConvertSet
.
contains
(
c
[
i
]))
{
// 跳过不替换的字符
continue
;
}
if
(
c
[
i
]
==
'\u3000'
)
{
c
[
i
]
=
' '
;
}
else
if
(
c
[
i
]
>
'\
uFF00
'
&&
c
[
i
]
<
'\
uFF5F
'
)
{
c
[
i
]
=
(
char
)
(
c
[
i
]
-
65248
);
}
}
String
returnString
=
new
String
(
c
);
return
returnString
;
}
/**
* 数字金额大写转换 先写个完整的然后将如零拾替换成零
*
* @param n 数字
* @return 中文大写数字
*/
public
static
String
digitUppercase
(
double
n
)
{
String
[]
fraction
=
{
"角"
,
"分"
};
String
[]
digit
=
{
"零"
,
"壹"
,
"贰"
,
"叁"
,
"肆"
,
"伍"
,
"陆"
,
"柒"
,
"捌"
,
"玖"
};
String
[][]
unit
=
{
{
"元"
,
"万"
,
"亿"
},
{
""
,
"拾"
,
"佰"
,
"仟"
}
};
String
head
=
n
<
0
?
"负"
:
""
;
n
=
Math
.
abs
(
n
);
String
s
=
""
;
for
(
int
i
=
0
;
i
<
fraction
.
length
;
i
++)
{
s
+=
(
digit
[(
int
)
(
Math
.
floor
(
n
*
10
*
Math
.
pow
(
10
,
i
))
%
10
)]
+
fraction
[
i
]).
replaceAll
(
"(零.)+"
,
""
);
}
if
(
s
.
length
()
<
1
)
{
s
=
"整"
;
}
int
integerPart
=
(
int
)
Math
.
floor
(
n
);
for
(
int
i
=
0
;
i
<
unit
[
0
].
length
&&
integerPart
>
0
;
i
++)
{
String
p
=
""
;
for
(
int
j
=
0
;
j
<
unit
[
1
].
length
&&
n
>
0
;
j
++)
{
p
=
digit
[
integerPart
%
10
]
+
unit
[
1
][
j
]
+
p
;
integerPart
=
integerPart
/
10
;
}
s
=
p
.
replaceAll
(
"(零.)*零$"
,
""
).
replaceAll
(
"^$"
,
"零"
)
+
unit
[
0
][
i
]
+
s
;
}
return
head
+
s
.
replaceAll
(
"(零.)*零元"
,
"元"
).
replaceFirst
(
"(零.)+"
,
""
).
replaceAll
(
"(零.)+"
,
"零"
).
replaceAll
(
"^整$"
,
"零元整"
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/CookieUtils.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.UnsupportedEncodingException
;
import
java.net.URLDecoder
;
import
java.net.URLEncoder
;
import
javax.servlet.http.Cookie
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
/**
* Cookie工具类
* @author 黄炳桂 516821420@qq.com
* @version 2013-01-15
*/
public
class
CookieUtils
{
/**
* 设置 Cookie(生成时间为1天)
* @param name 名称
* @param value 值
*/
public
static
void
setCookie
(
HttpServletResponse
response
,
String
name
,
String
value
)
{
setCookie
(
response
,
name
,
value
,
60
*
60
*
24
);
}
/**
* 设置 Cookie
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param uri 路径
*/
public
static
void
setCookie
(
HttpServletResponse
response
,
String
name
,
String
value
,
String
path
)
{
setCookie
(
response
,
name
,
value
,
path
,
60
*
60
*
24
);
}
/**
* 设置 Cookie
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param uri 路径
*/
public
static
void
setCookie
(
HttpServletResponse
response
,
String
name
,
String
value
,
int
maxAge
)
{
setCookie
(
response
,
name
,
value
,
"/"
,
maxAge
);
}
/**
* 设置 Cookie
* @param name 名称
* @param value 值
* @param maxAge 生存时间(单位秒)
* @param uri 路径
*/
public
static
void
setCookie
(
HttpServletResponse
response
,
String
name
,
String
value
,
String
path
,
int
maxAge
)
{
Cookie
cookie
=
new
Cookie
(
name
,
null
);
cookie
.
setPath
(
path
);
cookie
.
setMaxAge
(
maxAge
);
try
{
cookie
.
setValue
(
URLEncoder
.
encode
(
value
,
"utf-8"
));
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
printStackTrace
();
}
response
.
addCookie
(
cookie
);
}
/**
* 获得指定Cookie的值
* @param name 名称
* @return 值
*/
public
static
String
getCookie
(
HttpServletRequest
request
,
String
name
)
{
return
getCookie
(
request
,
null
,
name
,
false
);
}
/**
* 获得指定Cookie的值,并删除。
* @param name 名称
* @return 值
*/
public
static
String
getCookie
(
HttpServletRequest
request
,
HttpServletResponse
response
,
String
name
)
{
return
getCookie
(
request
,
response
,
name
,
true
);
}
/**
* 获得指定Cookie的值
* @param request 请求对象
* @param response 响应对象
* @param name 名字
* @param isRemove 是否移除
* @return 值
*/
public
static
String
getCookie
(
HttpServletRequest
request
,
HttpServletResponse
response
,
String
name
,
boolean
isRemove
)
{
String
value
=
null
;
Cookie
[]
cookies
=
request
.
getCookies
();
if
(
cookies
!=
null
)
{
for
(
Cookie
cookie
:
cookies
)
{
if
(
cookie
.
getName
().
equals
(
name
))
{
try
{
value
=
URLDecoder
.
decode
(
cookie
.
getValue
(),
"utf-8"
);
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
printStackTrace
();
}
if
(
isRemove
)
{
cookie
.
setMaxAge
(
0
);
response
.
addCookie
(
cookie
);
}
}
}
}
return
value
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/DateUtils.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.text.ParseException
;
import
java.util.Date
;
import
org.apache.commons.lang3.time.DateFormatUtils
;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author 黄炳桂 516821420@qq.com
* @version 2014-4-15
*/
public
class
DateUtils
extends
org
.
apache
.
commons
.
lang3
.
time
.
DateUtils
{
private
static
String
[]
parsePatterns
=
{
"yyyy-MM-dd"
,
"yyyy-MM-dd HH:mm:ss"
,
"yyyy-MM-dd HH:mm"
,
"yyyy-MM"
,
"yyyy/MM/dd"
,
"yyyy/MM/dd HH:mm:ss"
,
"yyyy/MM/dd HH:mm"
,
"yyyy/MM"
,
"yyyy.MM.dd"
,
"yyyy.MM.dd HH:mm:ss"
,
"yyyy.MM.dd HH:mm"
,
"yyyy.MM"
};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public
static
String
getDate
()
{
return
getDate
(
"yyyy-MM-dd"
);
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public
static
String
getDate
(
String
pattern
)
{
return
DateFormatUtils
.
format
(
new
Date
(),
pattern
);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public
static
String
formatDate
(
Date
date
,
Object
...
pattern
)
{
String
formatDate
=
null
;
if
(
pattern
!=
null
&&
pattern
.
length
>
0
)
{
formatDate
=
DateFormatUtils
.
format
(
date
,
pattern
[
0
].
toString
());
}
else
{
formatDate
=
DateFormatUtils
.
format
(
date
,
"yyyy-MM-dd"
);
}
return
formatDate
;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public
static
String
formatDateTime
(
Date
date
)
{
return
formatDate
(
date
,
"yyyy-MM-dd HH:mm:ss"
);
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public
static
String
getTime
()
{
return
formatDate
(
new
Date
(),
"HH:mm:ss"
);
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public
static
String
getDateTime
()
{
return
formatDate
(
new
Date
(),
"yyyy-MM-dd HH:mm:ss"
);
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public
static
String
getYear
()
{
return
formatDate
(
new
Date
(),
"yyyy"
);
}
/**
* 得到当前月份字符串 格式(MM)
*/
public
static
String
getMonth
()
{
return
formatDate
(
new
Date
(),
"MM"
);
}
/**
* 得到当天字符串 格式(dd)
*/
public
static
String
getDay
()
{
return
formatDate
(
new
Date
(),
"dd"
);
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public
static
String
getWeek
()
{
return
formatDate
(
new
Date
(),
"E"
);
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public
static
Date
parseDate
(
Object
str
)
{
if
(
str
==
null
){
return
null
;
}
try
{
return
parseDate
(
str
.
toString
(),
parsePatterns
);
}
catch
(
ParseException
e
)
{
return
null
;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public
static
long
pastDays
(
Date
date
)
{
long
t
=
new
Date
().
getTime
()-
date
.
getTime
();
return
t
/(
24
*
60
*
60
*
1000
);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public
static
long
pastHour
(
Date
date
)
{
long
t
=
new
Date
().
getTime
()-
date
.
getTime
();
return
t
/(
60
*
60
*
1000
);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public
static
long
pastMinutes
(
Date
date
)
{
long
t
=
new
Date
().
getTime
()-
date
.
getTime
();
return
t
/(
60
*
1000
);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public
static
String
formatDateTime
(
long
timeMillis
){
long
day
=
timeMillis
/(
24
*
60
*
60
*
1000
);
long
hour
=
(
timeMillis
/(
60
*
60
*
1000
)-
day
*
24
);
long
min
=
((
timeMillis
/(
60
*
1000
))-
day
*
24
*
60
-
hour
*
60
);
long
s
=
(
timeMillis
/
1000
-
day
*
24
*
60
*
60
-
hour
*
60
*
60
-
min
*
60
);
long
sss
=
(
timeMillis
-
day
*
24
*
60
*
60
*
1000
-
hour
*
60
*
60
*
1000
-
min
*
60
*
1000
-
s
*
1000
);
return
(
day
>
0
?
day
+
","
:
""
)+
hour
+
":"
+
min
+
":"
+
s
+
"."
+
sss
;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public
static
double
getDistanceOfTwoDate
(
Date
before
,
Date
after
)
{
long
beforeTime
=
before
.
getTime
();
long
afterTime
=
after
.
getTime
();
return
(
afterTime
-
beforeTime
)
/
(
1000
*
60
*
60
*
24
);
}
/**
* @param args
* @throws ParseException
*/
// public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
// }
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/Encodes.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.utils
;
import
java.io.UnsupportedEncodingException
;
import
java.net.URLDecoder
;
import
java.net.URLEncoder
;
import
org.apache.commons.codec.DecoderException
;
import
org.apache.commons.codec.binary.Base64
;
import
org.apache.commons.codec.binary.Hex
;
import
org.apache.commons.lang3.StringEscapeUtils
;
/**
* 封装各种格式的编码解码工具类.
* 1.Commons-Codec的 hex/base64 编码
* 2.自制的base62 编码
* 3.Commons-Lang的xml/html escape
* 4.JDK提供的URLEncoder
* @author calvin
* @version 2013-01-15
*/
public
class
Encodes
{
private
static
final
String
DEFAULT_URL_ENCODING
=
"UTF-8"
;
private
static
final
char
[]
BASE62
=
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
.
toCharArray
();
/**
* Hex编码.
*/
public
static
String
encodeHex
(
byte
[]
input
)
{
return
new
String
(
Hex
.
encodeHex
(
input
));
}
/**
* Hex解码.
*/
public
static
byte
[]
decodeHex
(
String
input
)
{
try
{
return
Hex
.
decodeHex
(
input
.
toCharArray
());
}
catch
(
DecoderException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* Base64编码.
*/
public
static
String
encodeBase64
(
byte
[]
input
)
{
return
new
String
(
Base64
.
encodeBase64
(
input
));
}
/**
* Base64编码.
*/
public
static
String
encodeBase64
(
String
input
)
{
try
{
return
new
String
(
Base64
.
encodeBase64
(
input
.
getBytes
(
DEFAULT_URL_ENCODING
)));
}
catch
(
UnsupportedEncodingException
e
)
{
return
""
;
}
}
// /**
// * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
// */
// public static String encodeUrlSafeBase64(byte[] input) {
// return Base64.encodeBase64URLSafe(input);
// }
/**
* Base64解码.
*/
public
static
byte
[]
decodeBase64
(
String
input
)
{
return
Base64
.
decodeBase64
(
input
.
getBytes
());
}
/**
* Base64解码.
*/
public
static
String
decodeBase64String
(
String
input
)
{
try
{
return
new
String
(
Base64
.
decodeBase64
(
input
.
getBytes
()),
DEFAULT_URL_ENCODING
);
}
catch
(
UnsupportedEncodingException
e
)
{
return
""
;
}
}
/**
* Base62编码。
*/
public
static
String
encodeBase62
(
byte
[]
input
)
{
char
[]
chars
=
new
char
[
input
.
length
];
for
(
int
i
=
0
;
i
<
input
.
length
;
i
++)
{
chars
[
i
]
=
BASE62
[((
input
[
i
]
&
0xFF
)
%
BASE62
.
length
)];
}
return
new
String
(
chars
);
}
/**
* Html 转码.
*/
public
static
String
escapeHtml
(
String
html
)
{
return
StringEscapeUtils
.
escapeHtml4
(
html
);
}
/**
* Html 解码.
*/
public
static
String
unescapeHtml
(
String
htmlEscaped
)
{
return
StringEscapeUtils
.
unescapeHtml4
(
htmlEscaped
);
}
/**
* Xml 转码.
*/
public
static
String
escapeXml
(
String
xml
)
{
return
StringEscapeUtils
.
escapeXml10
(
xml
);
}
/**
* Xml 解码.
*/
public
static
String
unescapeXml
(
String
xmlEscaped
)
{
return
StringEscapeUtils
.
unescapeXml
(
xmlEscaped
);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public
static
String
urlEncode
(
String
part
)
{
try
{
return
URLEncoder
.
encode
(
part
,
DEFAULT_URL_ENCODING
);
}
catch
(
UnsupportedEncodingException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public
static
String
urlDecode
(
String
part
)
{
try
{
return
URLDecoder
.
decode
(
part
,
DEFAULT_URL_ENCODING
);
}
catch
(
UnsupportedEncodingException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/Exceptions.java
deleted
100644 → 0
View file @
b6becbcd
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.utils
;
import
java.io.PrintWriter
;
import
java.io.StringWriter
;
import
javax.servlet.http.HttpServletRequest
;
/**
* 关于异常的工具类.
*
* @author calvin
* @version 2013-01-15
*/
public
class
Exceptions
{
/**
* 将CheckedException转换为UncheckedException.
*/
public
static
RuntimeException
unchecked
(
Exception
e
)
{
if
(
e
instanceof
RuntimeException
)
{
return
RuntimeException
.
class
.
cast
(
e
);
}
else
{
return
new
RuntimeException
(
e
);
}
}
/**
* 将ErrorStack转化为String.
*/
public
static
String
getStackTraceAsString
(
Throwable
e
)
{
if
(
e
==
null
)
{
return
""
;
}
StringWriter
stringWriter
=
new
StringWriter
();
e
.
printStackTrace
(
new
PrintWriter
(
stringWriter
));
return
stringWriter
.
toString
();
}
/**
* 判断异常是否由某些底层的异常引起.
*/
@SuppressWarnings
(
"unchecked"
)
public
static
boolean
isCausedBy
(
Exception
ex
,
Class
<?
extends
Exception
>...
causeExceptionClasses
)
{
Throwable
cause
=
ex
.
getCause
();
while
(
cause
!=
null
)
{
for
(
Class
<?
extends
Exception
>
causeClass
:
causeExceptionClasses
)
{
if
(
causeClass
.
isInstance
(
cause
))
{
return
true
;
}
}
cause
=
cause
.
getCause
();
}
return
false
;
}
/**
* 在request中获取异常类
*
* @param request
* @return
*/
public
static
Throwable
getThrowable
(
HttpServletRequest
request
)
{
Throwable
ex
=
null
;
try
{
if
(
request
.
getAttribute
(
"exception"
)
!=
null
)
{
ex
=
Throwable
.
class
.
cast
(
request
.
getAttribute
(
"exception"
));
}
else
if
(
request
.
getAttribute
(
"javax.servlet.error.exception"
)
!=
null
)
{
ex
=
Throwable
.
class
.
cast
(
request
.
getAttribute
(
"javax.servlet.error.exception"
));
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
ex
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/FileSizeHelper.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.text.DecimalFormat
;
/**
* <p>
* 文件大小工具类.
* </p>
*
* @author poplar.yfyang
* @version 1.0 2013-01-02 12:50 PM
* @since JDK 1.5
*/
public
class
FileSizeHelper
{
public
static
long
ONE_KB
=
1024
;
public
static
long
ONE_MB
=
ONE_KB
*
1024
;
public
static
long
ONE_GB
=
ONE_MB
*
1024
;
public
static
long
ONE_TB
=
ONE_GB
*
(
long
)
1024
;
public
static
long
ONE_PB
=
ONE_TB
*
(
long
)
1024
;
public
static
String
getHumanReadableFileSize
(
Long
fileSize
)
{
if
(
fileSize
==
null
)
{
return
null
;
}
return
getHumanReadableFileSize
(
fileSize
.
longValue
());
}
public
static
String
getHumanReadableFileSize
(
long
fileSize
)
{
if
(
fileSize
<
0
)
{
return
String
.
valueOf
(
fileSize
);
}
String
result
=
getHumanReadableFileSize
(
fileSize
,
ONE_PB
,
"PB"
);
if
(
result
!=
null
)
{
return
result
;
}
result
=
getHumanReadableFileSize
(
fileSize
,
ONE_TB
,
"TB"
);
if
(
result
!=
null
)
{
return
result
;
}
result
=
getHumanReadableFileSize
(
fileSize
,
ONE_GB
,
"GB"
);
if
(
result
!=
null
)
{
return
result
;
}
result
=
getHumanReadableFileSize
(
fileSize
,
ONE_MB
,
"MB"
);
if
(
result
!=
null
)
{
return
result
;
}
result
=
getHumanReadableFileSize
(
fileSize
,
ONE_KB
,
"KB"
);
if
(
result
!=
null
)
{
return
result
;
}
return
String
.
valueOf
(
fileSize
)+
"B"
;
}
private
static
String
getHumanReadableFileSize
(
long
fileSize
,
long
unit
,
String
unitName
)
{
if
(
fileSize
==
0
)
{
return
"0"
;
}
if
(
fileSize
/
unit
>=
1
)
{
double
value
=
fileSize
/
(
double
)
unit
;
DecimalFormat
df
=
new
DecimalFormat
(
"######.##"
+
unitName
);
return
df
.
format
(
value
);
}
return
null
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/FileUtil.java
deleted
100644 → 0
View file @
b6becbcd
package
com.jeespring.common.utils
;
import
java.io.*
;
/**
* 文件读取工具类
*/
public
class
FileUtil
{
/**
* 读取文件内容,作为字符串返回
*/
public
static
String
readFileAsString
(
String
filePath
)
throws
IOException
{
File
file
=
new
File
(
filePath
);
if
(!
file
.
exists
())
{
throw
new
FileNotFoundException
(
filePath
);
}
if
(
file
.
length
()
>
1024
*
1024
*
1024
)
{
throw
new
IOException
(
"File is too large"
);
}
StringBuilder
sb
=
new
StringBuilder
((
int
)
(
file
.
length
()));
// 创建字节输入流
FileInputStream
fis
=
new
FileInputStream
(
filePath
);
// 创建一个长度为10240的Buffer
byte
[]
bbuf
=
new
byte
[
10240
];
// 用于保存实际读取的字节数
int
hasRead
=
0
;
while
((
hasRead
=
fis
.
read
(
bbuf
))
>
0
)
{
sb
.
append
(
new
String
(
bbuf
,
0
,
hasRead
));
}
fis
.
close
();
return
sb
.
toString
();
}
/**
* 根据文件路径读取byte[] 数组
*/
public
static
byte
[]
readFileByBytes
(
String
filePath
)
throws
IOException
{
File
file
=
new
File
(
filePath
);
if
(!
file
.
exists
())
{
throw
new
FileNotFoundException
(
filePath
);
}
else
{
ByteArrayOutputStream
bos
=
new
ByteArrayOutputStream
((
int
)
file
.
length
());
BufferedInputStream
in
=
null
;
try
{
in
=
new
BufferedInputStream
(
new
FileInputStream
(
file
));
short
bufSize
=
1024
;
byte
[]
buffer
=
new
byte
[
bufSize
];
int
len1
;
while
(-
1
!=
(
len1
=
in
.
read
(
buffer
,
0
,
bufSize
)))
{
bos
.
write
(
buffer
,
0
,
len1
);
}
byte
[]
var7
=
bos
.
toByteArray
();
return
var7
;
}
finally
{
try
{
if
(
in
!=
null
)
{
in
.
close
();
}
}
catch
(
IOException
var14
)
{
var14
.
printStackTrace
();
}
bos
.
close
();
}
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/utils/FileUtils.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.BufferedOutputStream
;
import
java.io.File
;
import
java.io.FileInputStream
;
import
java.io.FileOutputStream
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.io.OutputStream
;
import
java.io.RandomAccessFile
;
import
java.util.Enumeration
;
import
java.util.List
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.apache.tools.zip.ZipEntry
;
import
org.apache.tools.zip.ZipFile
;
import
org.apache.tools.zip.ZipOutputStream
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.google.common.collect.Lists
;
/**
* 文件操作工具类
* 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能
* @author 黄炳桂 516821420@qq.com
* @version 2015-3-16
*/
public
class
FileUtils
extends
org
.
apache
.
commons
.
io
.
FileUtils
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
FileUtils
.
class
);
/**
* 复制单个文件,如果目标文件存在,则不覆盖
* @param srcFileName 待复制的文件名
* @param descFileName 目标文件名
* @return 如果复制成功,则返回true,否则返回false
*/
public
static
boolean
copyFile
(
String
srcFileName
,
String
descFileName
)
{
return
FileUtils
.
copyFileCover
(
srcFileName
,
descFileName
,
false
);
}
/**
* 复制单个文件
* @param srcFileName 待复制的文件名
* @param descFileName 目标文件名
* @param coverlay 如果目标文件已存在,是否覆盖
* @return 如果复制成功,则返回true,否则返回false
*/
public
static
boolean
copyFileCover
(
String
srcFileName
,
String
descFileName
,
boolean
coverlay
)
{
File
srcFile
=
new
File
(
srcFileName
);
// 判断源文件是否存在
if
(!
srcFile
.
exists
())
{
logger
.
debug
(
"复制文件失败,源文件 "
+
srcFileName
+
" 不存在!"
);
return
false
;
}
// 判断源文件是否是合法的文件
else
if
(!
srcFile
.
isFile
())
{
logger
.
debug
(
"复制文件失败,"
+
srcFileName
+
" 不是一个文件!"
);
return
false
;
}
File
descFile
=
new
File
(
descFileName
);
// 判断目标文件是否存在
if
(
descFile
.
exists
())
{
// 如果目标文件存在,并且允许覆盖
if
(
coverlay
)
{
logger
.
debug
(
"目标文件已存在,准备删除!"
);
if
(!
FileUtils
.
delFile
(
descFileName
))
{
logger
.
debug
(
"删除目标文件 "
+
descFileName
+
" 失败!"
);
return
false
;
}
}
else
{
logger
.
debug
(
"复制文件失败,目标文件 "
+
descFileName
+
" 已存在!"
);
return
false
;
}
}
else
{
if
(!
descFile
.
getParentFile
().
exists
())
{
// 如果目标文件所在的目录不存在,则创建目录
logger
.
debug
(
"目标文件所在的目录不存在,创建目录!"
);
// 创建目标文件所在的目录
if
(!
descFile
.
getParentFile
().
mkdirs
())
{
logger
.
debug
(
"创建目标文件所在的目录失败!"
);
return
false
;
}
}
}
// 准备复制文件
// 读取的位数
int
readByte
=
0
;
InputStream
ins
=
null
;
OutputStream
outs
=
null
;
try
{
// 打开源文件
ins
=
new
FileInputStream
(
srcFile
);
// 打开目标文件的输出流
outs
=
new
FileOutputStream
(
descFile
);
byte
[]
buf
=
new
byte
[
1024
];
// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕
while
((
readByte
=
ins
.
read
(
buf
))
!=
-
1
)
{
// 将读取的字节流写入到输出流
outs
.
write
(
buf
,
0
,
readByte
);
}
logger
.
debug
(
"复制单个文件 "
+
srcFileName
+
" 到"
+
descFileName
+
"成功!"
);
return
true
;
}
catch
(
Exception
e
)
{
logger
.
debug
(
"复制文件失败:"
+
e
.
getMessage
());
return
false
;
}
finally
{
// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
if
(
outs
!=
null
)
{
try
{
outs
.
close
();
}
catch
(
IOException
oute
)
{
oute
.
printStackTrace
();
}
}
if
(
ins
!=
null
)
{
try
{
ins
.
close
();
}
catch
(
IOException
ine
)
{
ine
.
printStackTrace
();
}
}
}
}
/**
* 复制整个目录的内容,如果目标目录存在,则不覆盖
* @param srcDirName 源目录名
* @param descDirName 目标目录名
* @return 如果复制成功返回true,否则返回false
*/
public
static
boolean
copyDirectory
(
String
srcDirName
,
String
descDirName
)
{
return
FileUtils
.
copyDirectoryCover
(
srcDirName
,
descDirName
,
false
);
}
/**
* 复制整个目录的内容
* @param srcDirName 源目录名
* @param descDirName 目标目录名
* @param coverlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public
static
boolean
copyDirectoryCover
(
String
srcDirName
,
String
descDirName
,
boolean
coverlay
)
{
File
srcDir
=
new
File
(
srcDirName
);
// 判断源目录是否存在
if
(!
srcDir
.
exists
())
{
logger
.
debug
(
"复制目录失败,源目录 "
+
srcDirName
+
" 不存在!"
);
return
false
;
}
// 判断源目录是否是目录
else
if
(!
srcDir
.
isDirectory
())
{
logger
.
debug
(
"复制目录失败,"
+
srcDirName
+
" 不是一个目录!"
);
return
false
;
}
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
String
descDirNames
=
descDirName
;
if
(!
descDirNames
.
endsWith
(
File
.
separator
))
{
descDirNames
=
descDirNames
+
File
.
separator
;
}
File
descDir
=
new
File
(
descDirNames
);
// 如果目标文件夹存在
if
(
descDir
.
exists
())
{
if
(
coverlay
)
{
// 允许覆盖目标目录
logger
.
debug
(
"目标目录已存在,准备删除!"
);
if
(!
FileUtils
.
delFile
(
descDirNames
))
{
logger
.
debug
(
"删除目录 "
+
descDirNames
+
" 失败!"
);
return
false
;
}
}
else
{
logger
.
debug
(
"目标目录复制失败,目标目录 "
+
descDirNames
+
" 已存在!"
);
return
false
;
}
}
else
{
// 创建目标目录
logger
.
debug
(
"目标目录不存在,准备创建!"
);
if
(!
descDir
.
mkdirs
())
{
logger
.
debug
(
"创建目标目录失败!"
);
return
false
;
}
}
boolean
flag
=
true
;
// 列出源目录下的所有文件名和子目录名
File
[]
files
=
srcDir
.
listFiles
();
for
(
int
i
=
0
;
i
<
files
.
length
;
i
++)
{
// 如果是一个单个文件,则直接复制
if
(
files
[
i
].
isFile
())
{
flag
=
FileUtils
.
copyFile
(
files
[
i
].
getAbsolutePath
(),
descDirName
+
files
[
i
].
getName
());
// 如果拷贝文件失败,则退出循环
if
(!
flag
)
{
break
;
}
}
// 如果是子目录,则继续复制目录
if
(
files
[
i
].
isDirectory
())
{
flag
=
FileUtils
.
copyDirectory
(
files
[
i
]
.
getAbsolutePath
(),
descDirName
+
files
[
i
].
getName
());
// 如果拷贝目录失败,则退出循环
if
(!
flag
)
{
break
;
}
}
}
if
(!
flag
)
{
logger
.
debug
(
"复制目录 "
+
srcDirName
+
" 到 "
+
descDirName
+
" 失败!"
);
return
false
;
}
logger
.
debug
(
"复制目录 "
+
srcDirName
+
" 到 "
+
descDirName
+
" 成功!"
);
return
true
;
}
/**
*
* 删除文件,可以删除单个文件或文件夹
*
* @param fileName 被删除的文件名
* @return 如果删除成功,则返回true,否是返回false
*/
public
static
boolean
delFile
(
String
fileName
)
{
File
file
=
new
File
(
fileName
);
if
(!
file
.
exists
())
{
logger
.
debug
(
fileName
+
" 文件不存在!"
);
return
true
;
}
else
{
if
(
file
.
isFile
())
{
return
FileUtils
.
deleteFile
(
fileName
);
}
else
{
return
FileUtils
.
deleteDirectory
(
fileName
);
}
}
}
/**
*
* 删除单个文件
*
* @param fileName 被删除的文件名
* @return 如果删除成功,则返回true,否则返回false
*/
public
static
boolean
deleteFile
(
String
fileName
)
{
File
file
=
new
File
(
fileName
);
if
(
file
.
exists
()
&&
file
.
isFile
())
{
if
(
file
.
delete
())
{
logger
.
debug
(
"删除文件 "
+
fileName
+
" 成功!"
);
return
true
;
}
else
{
logger
.
debug
(
"删除文件 "
+
fileName
+
" 失败!"
);
return
false
;
}
}
else
{
logger
.
debug
(
fileName
+
" 文件不存在!"
);
return
true
;
}
}
/**
*
* 删除目录及目录下的文件
*
* @param dirName 被删除的目录所在的文件路径
* @return 如果目录删除成功,则返回true,否则返回false
*/
public
static
boolean
deleteDirectory
(
String
dirName
)
{
String
dirNames
=
dirName
;
if
(!
dirNames
.
endsWith
(
File
.
separator
))
{
dirNames
=
dirNames
+
File
.
separator
;
}
File
dirFile
=
new
File
(
dirNames
);
if
(!
dirFile
.
exists
()
||
!
dirFile
.
isDirectory
())
{
logger
.
debug
(
dirNames
+
" 目录不存在!"
);
return
true
;
}
boolean
flag
=
true
;
// 列出全部文件及子目录
File
[]
files
=
dirFile
.
listFiles
();
for
(
int
i
=
0
;
i
<
files
.
length
;
i
++)
{
// 删除子文件
if
(
files
[
i
].
isFile
())
{
flag
=
FileUtils
.
deleteFile
(
files
[
i
].
getAbsolutePath
());
// 如果删除文件失败,则退出循环
if
(!
flag
)
{
break
;
}
}
// 删除子目录
else
if
(
files
[
i
].
isDirectory
())
{
flag
=
FileUtils
.
deleteDirectory
(
files
[
i
]
.
getAbsolutePath
());
// 如果删除子目录失败,则退出循环
if
(!
flag
)
{
break
;
}
}
}
if
(!
flag
)
{
logger
.
debug
(
"删除目录失败!"
);
return
false
;
}
// 删除当前目录
if
(
dirFile
.
delete
())
{
logger
.
debug
(
"删除目录 "
+
dirName
+
" 成功!"
);
return
true
;
}
else
{
logger
.
debug
(
"删除目录 "
+
dirName
+
" 失败!"
);
return
false
;
}
}
/**
* 创建单个文件
* @param descFileName 文件名,包含路径
* @return 如果创建成功,则返回true,否则返回false
*/
public
static
boolean
createFile
(
String
descFileName
)
{
File
file
=
new
File
(
descFileName
);
if
(
file
.
exists
())
{
logger
.
debug
(
"文件 "
+
descFileName
+
" 已存在!"
);
return
false
;
}
if
(
descFileName
.
endsWith
(
File
.
separator
))
{
logger
.
debug
(
descFileName
+
" 为目录,不能创建目录!"
);
return
false
;
}
if
(!
file
.
getParentFile
().
exists
())
{
// 如果文件所在的目录不存在,则创建目录
if
(!
file
.
getParentFile
().
mkdirs
())
{
logger
.
debug
(
"创建文件所在的目录失败!"
);
return
false
;
}
}
// 创建文件
try
{
if
(
file
.
createNewFile
())
{
logger
.
debug
(
descFileName
+
" 文件创建成功!"
);
return
true
;
}
else
{
logger
.
debug
(
descFileName
+
" 文件创建失败!"
);
return
false
;
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
logger
.
debug
(
descFileName
+
" 文件创建失败!"
);
return
false
;
}
}
/**
* 创建目录
* @param descDirName 目录名,包含路径
* @return 如果创建成功,则返回true,否则返回false
*/
public
static
boolean
createDirectory
(
String
descDirName
)
{
String
descDirNames
=
descDirName
;
if
(!
descDirNames
.
endsWith
(
File
.
separator
))
{
descDirNames
=
descDirNames
+
File
.
separator
;
}
File
descDir
=
new
File
(
descDirNames
);
if
(
descDir
.
exists
())
{
logger
.
debug
(
"目录 "
+
descDirNames
+
" 已存在!"
);
return
false
;
}
// 创建目录
if
(
descDir
.
mkdirs
())
{
logger
.
debug
(
"目录 "
+
descDirNames
+
" 创建成功!"
);
return
true
;
}
else
{
logger
.
debug
(
"目录 "
+
descDirNames
+
" 创建失败!"
);
return
false
;
}
}
/**
* 写入文件
* @param file 要写入的文件
*/
public
static
void
writeToFile
(
String
fileName
,
String
content
,
boolean
append
)
{
try
{
FileUtils
.
write
(
new
File
(
fileName
),
content
,
"utf-8"
,
append
);
logger
.
debug
(
"文件 "
+
fileName
+
" 写入成功!"
);
}
catch
(
IOException
e
)
{
logger
.
debug
(
"文件 "
+
fileName
+
" 写入失败! "
+
e
.
getMessage
());
}
}
/**
* 写入文件
* @param file 要写入的文件
*/
public
static
void
writeToFile
(
String
fileName
,
String
content
,
String
encoding
,
boolean
append
)
{
try
{
FileUtils
.
write
(
new
File
(
fileName
),
content
,
encoding
,
append
);
logger
.
debug
(
"文件 "
+
fileName
+
" 写入成功!"
);
}
catch
(
IOException
e
)
{
logger
.
debug
(
"文件 "
+
fileName
+
" 写入失败! "
+
e
.
getMessage
());
}
}
/**
* 压缩文件或目录
* @param srcDirName 压缩的根目录
* @param fileName 根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
* @param descFileName 目标zip文件
*/
public
static
void
zipFiles
(
String
srcDirName
,
String
fileName
,
String
descFileName
)
{
// 判断目录是否存在
if
(
srcDirName
==
null
)
{
logger
.
debug
(
"文件压缩失败,目录 "
+
srcDirName
+
" 不存在!"
);
return
;
}
File
fileDir
=
new
File
(
srcDirName
);
if
(!
fileDir
.
exists
()
||
!
fileDir
.
isDirectory
())
{
logger
.
debug
(
"文件压缩失败,目录 "
+
srcDirName
+
" 不存在!"
);
return
;
}
String
dirPath
=
fileDir
.
getAbsolutePath
();
File
descFile
=
new
File
(
descFileName
);
try
{
ZipOutputStream
zouts
=
new
ZipOutputStream
(
new
FileOutputStream
(
descFile
));
if
(
"*"
.
equals
(
fileName
)
||
""
.
equals
(
fileName
))
{
FileUtils
.
zipDirectoryToZipFile
(
dirPath
,
fileDir
,
zouts
);
}
else
{
File
file
=
new
File
(
fileDir
,
fileName
);
if
(
file
.
isFile
())
{
FileUtils
.
zipFilesToZipFile
(
dirPath
,
file
,
zouts
);
}
else
{
FileUtils
.
zipDirectoryToZipFile
(
dirPath
,
file
,
zouts
);
}
}
zouts
.
close
();
logger
.
debug
(
descFileName
+
" 文件压缩成功!"
);
}
catch
(
Exception
e
)
{
logger
.
debug
(
"文件压缩失败:"
+
e
.
getMessage
());
e
.
printStackTrace
();
}
}
/**
* 解压缩ZIP文件,将ZIP文件里的内容解压到descFileName目录下
* @param zipFileName 需要解压的ZIP文件
* @param descFileName 目标文件
*/
public
static
boolean
unZipFiles
(
String
zipFileName
,
String
descFileName
)
{
String
descFileNames
=
descFileName
;
if
(!
descFileNames
.
endsWith
(
File
.
separator
))
{
descFileNames
=
descFileNames
+
File
.
separator
;
}
try
{
// 根据ZIP文件创建ZipFile对象
ZipFile
zipFile
=
new
ZipFile
(
zipFileName
);
ZipEntry
entry
=
null
;
String
entryName
=
null
;
String
descFileDir
=
null
;
byte
[]
buf
=
new
byte
[
4096
];
int
readByte
=
0
;
// 获取ZIP文件里所有的entry
@SuppressWarnings
(
"rawtypes"
)
Enumeration
enums
=
zipFile
.
getEntries
();
// 遍历所有entry
while
(
enums
.
hasMoreElements
())
{
entry
=
(
ZipEntry
)
enums
.
nextElement
();
// 获得entry的名字
entryName
=
entry
.
getName
();
descFileDir
=
descFileNames
+
entryName
;
if
(
entry
.
isDirectory
())
{
// 如果entry是一个目录,则创建目录
new
File
(
descFileDir
).
mkdirs
();
continue
;
}
else
{
// 如果entry是一个文件,则创建父目录
new
File
(
descFileDir
).
getParentFile
().
mkdirs
();
}
File
file
=
new
File
(
descFileDir
);
// 打开文件输出流
OutputStream
os
=
new
FileOutputStream
(
file
);
// 从ZipFile对象中打开entry的输入流
InputStream
is
=
zipFile
.
getInputStream
(
entry
);
while
((
readByte
=
is
.
read
(
buf
))
!=
-
1
)
{
os
.
write
(
buf
,
0
,
readByte
);
}
os
.
close
();
is
.
close
();
}
zipFile
.
close
();
logger
.
debug
(
"文件解压成功!"
);
return
true
;
}
catch
(
Exception
e
)
{
logger
.
debug
(
"文件解压失败:"
+
e
.
getMessage
());
return
false
;
}
}
/**
* 将目录压缩到ZIP输出流
* @param dirPath 目录路径
* @param fileDir 文件信息
* @param zouts 输出流
*/
public
static
void
zipDirectoryToZipFile
(
String
dirPath
,
File
fileDir
,
ZipOutputStream
zouts
)
{
if
(
fileDir
.
isDirectory
())
{
File
[]
files
=
fileDir
.
listFiles
();
// 空的文件夹
if
(
files
.
length
==
0
)
{
// 目录信息
ZipEntry
entry
=
new
ZipEntry
(
getEntryName
(
dirPath
,
fileDir
));
try
{
zouts
.
putNextEntry
(
entry
);
zouts
.
closeEntry
();
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
;
}
for
(
int
i
=
0
;
i
<
files
.
length
;
i
++)
{
if
(
files
[
i
].
isFile
())
{
// 如果是文件,则调用文件压缩方法
FileUtils
.
zipFilesToZipFile
(
dirPath
,
files
[
i
],
zouts
);
}
else
{
// 如果是目录,则递归调用
FileUtils
.
zipDirectoryToZipFile
(
dirPath
,
files
[
i
],
zouts
);
}
}
}
}
/**
* 将文件压缩到ZIP输出流
* @param dirPath 目录路径
* @param file 文件
* @param zouts 输出流
*/
public
static
void
zipFilesToZipFile
(
String
dirPath
,
File
file
,
ZipOutputStream
zouts
)
{
FileInputStream
fin
=
null
;
ZipEntry
entry
=
null
;
// 创建复制缓冲区
byte
[]
buf
=
new
byte
[
4096
];
int
readByte
=
0
;
if
(
file
.
isFile
())
{
try
{
// 创建一个文件输入流
fin
=
new
FileInputStream
(
file
);
// 创建一个ZipEntry
entry
=
new
ZipEntry
(
getEntryName
(
dirPath
,
file
));
// 存储信息到压缩文件
zouts
.
putNextEntry
(
entry
);
// 复制字节到压缩文件
while
((
readByte
=
fin
.
read
(
buf
))
!=
-
1
)
{
zouts
.
write
(
buf
,
0
,
readByte
);
}
zouts
.
closeEntry
();
fin
.
close
();
System
.
out
.
println
(
"添加文件 "
+
file
.
getAbsolutePath
()
+
" 到zip文件中!"
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
}
/**
* 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名
* @param dirPat 目录名
* @param file entry文件名
* @return
*/
private
static
String
getEntryName
(
String
dirPath
,
File
file
)
{
String
dirPaths
=
dirPath
;
if
(!
dirPaths
.
endsWith
(
File
.
separator
))
{
dirPaths
=
dirPaths
+
File
.
separator
;
}
String
filePath
=
file
.
getAbsolutePath
();
// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
if
(
file
.
isDirectory
())
{
filePath
+=
"/"
;
}
int
index
=
filePath
.
indexOf
(
dirPaths
);
return
filePath
.
substring
(
index
+
dirPaths
.
length
());
}
/**
* 根据“文件名的后缀”获取文件内容类型(而非根据File.getContentType()读取的文件类型)
* @param returnFileName 带验证的文件名
* @return 返回文件类型
*/
public
static
String
getContentType
(
String
returnFileName
)
{
String
contentType
=
"application/octet-stream"
;
if
(
returnFileName
.
lastIndexOf
(
"."
)
<
0
)
{
return
contentType
;
}
returnFileName
=
returnFileName
.
toLowerCase
();
returnFileName
=
returnFileName
.
substring
(
returnFileName
.
lastIndexOf
(
"."
)
+
1
);
if
(
"html"
.
equals
(
returnFileName
)
||
"htm"
.
equals
(
returnFileName
)
||
"shtml"
.
equals
(
returnFileName
))
{
contentType
=
"text/html"
;
}
else
if
(
"apk"
.
equals
(
returnFileName
))
{
contentType
=
"application/vnd.android.package-archive"
;
}
else
if
(
"sis"
.
equals
(
returnFileName
))
{
contentType
=
"application/vnd.symbian.install"
;
}
else
if
(
"sisx"
.
equals
(
returnFileName
))
{
contentType
=
"application/vnd.symbian.install"
;
}
else
if
(
"exe"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-msdownload"
;
}
else
if
(
"msi"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-msdownload"
;
}
else
if
(
"css"
.
equals
(
returnFileName
))
{
contentType
=
"text/css"
;
}
else
if
(
"xml"
.
equals
(
returnFileName
))
{
contentType
=
"text/xml"
;
}
else
if
(
"gif"
.
equals
(
returnFileName
))
{
contentType
=
"image/gif"
;
}
else
if
(
"jpeg"
.
equals
(
returnFileName
)
||
"jpg"
.
equals
(
returnFileName
))
{
contentType
=
"image/jpeg"
;
}
else
if
(
"js"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-javascript"
;
}
else
if
(
"atom"
.
equals
(
returnFileName
))
{
contentType
=
"application/atom+xml"
;
}
else
if
(
"rss"
.
equals
(
returnFileName
))
{
contentType
=
"application/rss+xml"
;
}
else
if
(
"mml"
.
equals
(
returnFileName
))
{
contentType
=
"text/mathml"
;
}
else
if
(
"txt"
.
equals
(
returnFileName
))
{
contentType
=
"text/plain"
;
}
else
if
(
"jad"
.
equals
(
returnFileName
))
{
contentType
=
"text/vnd.sun.j2me.app-descriptor"
;
}
else
if
(
"wml"
.
equals
(
returnFileName
))
{
contentType
=
"text/vnd.wap.wml"
;
}
else
if
(
"htc"
.
equals
(
returnFileName
))
{
contentType
=
"text/x-component"
;
}
else
if
(
"png"
.
equals
(
returnFileName
))
{
contentType
=
"image/png"
;
}
else
if
(
"tif"
.
equals
(
returnFileName
)
||
"tiff"
.
equals
(
returnFileName
))
{
contentType
=
"image/tiff"
;
}
else
if
(
"wbmp"
.
equals
(
returnFileName
))
{
contentType
=
"image/vnd.wap.wbmp"
;
}
else
if
(
"ico"
.
equals
(
returnFileName
))
{
contentType
=
"image/x-icon"
;
}
else
if
(
"jng"
.
equals
(
returnFileName
))
{
contentType
=
"image/x-jng"
;
}
else
if
(
"bmp"
.
equals
(
returnFileName
))
{
contentType
=
"image/x-ms-bmp"
;
}
else
if
(
"svg"
.
equals
(
returnFileName
))
{
contentType
=
"image/svg+xml"
;
}
else
if
(
"jar"
.
equals
(
returnFileName
)
||
"var"
.
equals
(
returnFileName
)
||
"ear"
.
equals
(
returnFileName
))
{
contentType
=
"application/java-archive"
;
}
else
if
(
"doc"
.
equals
(
returnFileName
))
{
contentType
=
"application/msword"
;
}
else
if
(
"pdf"
.
equals
(
returnFileName
))
{
contentType
=
"application/pdf"
;
}
else
if
(
"rtf"
.
equals
(
returnFileName
))
{
contentType
=
"application/rtf"
;
}
else
if
(
"xls"
.
equals
(
returnFileName
))
{
contentType
=
"application/vnd.ms-excel"
;
}
else
if
(
"ppt"
.
equals
(
returnFileName
))
{
contentType
=
"application/vnd.ms-powerpoint"
;
}
else
if
(
"7z"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-7z-compressed"
;
}
else
if
(
"rar"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-rar-compressed"
;
}
else
if
(
"swf"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-shockwave-flash"
;
}
else
if
(
"rpm"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-redhat-package-manager"
;
}
else
if
(
"der"
.
equals
(
returnFileName
)
||
"pem"
.
equals
(
returnFileName
)
||
"crt"
.
equals
(
returnFileName
))
{
contentType
=
"application/x-x509-ca-cert"
;
}
else
if
(
"xhtml"
.
equals
(
returnFileName
))
{
contentType
=
"application/xhtml+xml"
;
}
else
if
(
"zip"
.
equals
(
returnFileName
))
{
contentType
=
"application/zip"
;
}
else
if
(
"mid"
.
equals
(
returnFileName
)
||
"midi"
.
equals
(
returnFileName
)
||
"kar"
.
equals
(
returnFileName
))
{
contentType
=
"audio/midi"
;
}
else
if
(
"mp3"
.
equals
(
returnFileName
))
{
contentType
=
"audio/mpeg"
;
}
else
if
(
"ogg"
.
equals
(
returnFileName
))
{
contentType
=
"audio/ogg"
;
}
else
if
(
"m4a"
.
equals
(
returnFileName
))
{
contentType
=
"audio/x-m4a"
;
}
else
if
(
"ra"
.
equals
(
returnFileName
))
{
contentType
=
"audio/x-realaudio"
;
}
else
if
(
"3gpp"
.
equals
(
returnFileName
)
||
"3gp"
.
equals
(
returnFileName
))
{
contentType
=
"video/3gpp"
;
}
else
if
(
"mp4"
.
equals
(
returnFileName
))
{
contentType
=
"video/mp4"
;
}
else
if
(
"mpeg"
.
equals
(
returnFileName
)
||
"mpg"
.
equals
(
returnFileName
))
{
contentType
=
"video/mpeg"
;
}
else
if
(
"mov"
.
equals
(
returnFileName
))
{
contentType
=
"video/quicktime"
;
}
else
if
(
"flv"
.
equals
(
returnFileName
))
{
contentType
=
"video/x-flv"
;
}
else
if
(
"m4v"
.
equals
(
returnFileName
))
{
contentType
=
"video/x-m4v"
;
}
else
if
(
"mng"
.
equals
(
returnFileName
))
{
contentType
=
"video/x-mng"
;
}
else
if
(
"asx"
.
equals
(
returnFileName
)
||
"asf"
.
equals
(
returnFileName
))
{
contentType
=
"video/x-ms-asf"
;
}
else
if
(
"wmv"
.
equals
(
returnFileName
))
{
contentType
=
"video/x-ms-wmv"
;
}
else
if
(
"avi"
.
equals
(
returnFileName
))
{
contentType
=
"video/x-msvideo"
;
}
return
contentType
;
}
/**
* 向浏览器发送文件下载,支持断点续传
* @param file 要下载的文件
* @param request 请求对象
* @param response 响应对象
* @return 返回错误信息,无错误信息返回null
*/
public
static
String
downFile
(
File
file
,
HttpServletRequest
request
,
HttpServletResponse
response
){
return
downFile
(
file
,
request
,
response
,
null
);
}
/**
* 向浏览器发送文件下载,支持断点续传
* @param file 要下载的文件
* @param request 请求对象
* @param response 响应对象
* @param fileName 指定下载的文件名
* @return 返回错误信息,无错误信息返回null
*/
public
static
String
downFile
(
File
file
,
HttpServletRequest
request
,
HttpServletResponse
response
,
String
fileName
){
String
error
=
null
;
if
(
file
!=
null
&&
file
.
exists
())
{
if
(
file
.
isFile
())
{
if
(
file
.
length
()
<=
0
)
{
error
=
"该文件是一个空文件。"
;
}
if
(!
file
.
canRead
())
{
error
=
"该文件没有读取权限。"
;
}
}
else
{
error
=
"该文件是一个文件夹。"
;
}
}
else
{
error
=
"文件已丢失或不存在!"
;
}
if
(
error
!=
null
){
logger
.
debug
(
"---------------"
+
file
+
" "
+
error
);
return
error
;
}
long
fileLength
=
file
.
length
();
// 记录文件大小
long
pastLength
=
0
;
// 记录已下载文件大小
int
rangeSwitch
=
0
;
// 0:从头开始的全文下载;1:从某字节开始的下载(bytes=27000-);2:从某字节开始到某字节结束的下载(bytes=27000-39000)
long
toLength
=
0
;
// 记录客户端需要下载的字节段的最后一个字节偏移量(比如bytes=27000-39000,则这个值是为39000)
long
contentLength
=
0
;
// 客户端请求的字节总量
String
rangeBytes
=
""
;
// 记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容
RandomAccessFile
raf
=
null
;
// 负责读取数据
OutputStream
os
=
null
;
// 写出数据
OutputStream
out
=
null
;
// 缓冲
byte
[]
b
=
new
byte
[
1024
];
// 暂存容器
if
(
request
.
getHeader
(
"Range"
)
!=
null
)
{
// 客户端请求的下载的文件块的开始字节
response
.
setStatus
(
HttpServletResponse
.
SC_PARTIAL_CONTENT
);
logger
.
debug
(
"request.getHeader(\"Range\") = "
+
request
.
getHeader
(
"Range"
));
rangeBytes
=
request
.
getHeader
(
"Range"
).
replaceAll
(
"bytes="
,
""
);
if
(
rangeBytes
.
indexOf
(
'-'
)
==
rangeBytes
.
length
()
-
1
)
{
// bytes=969998336-
rangeSwitch
=
1
;
rangeBytes
=
rangeBytes
.
substring
(
0
,
rangeBytes
.
indexOf
(
'-'
));
pastLength
=
Long
.
parseLong
(
rangeBytes
.
trim
());
contentLength
=
fileLength
-
pastLength
;
// 客户端请求的是 969998336 之后的字节
}
else
{
// bytes=1275856879-1275877358
rangeSwitch
=
2
;
String
temp0
=
rangeBytes
.
substring
(
0
,
rangeBytes
.
indexOf
(
'-'
));
String
temp2
=
rangeBytes
.
substring
(
rangeBytes
.
indexOf
(
'-'
)
+
1
,
rangeBytes
.
length
());
pastLength
=
Long
.
parseLong
(
temp0
.
trim
());
// bytes=1275856879-1275877358,从第 1275856879 个字节开始下载
toLength
=
Long
.
parseLong
(
temp2
);
// bytes=1275856879-1275877358,到第 1275877358 个字节结束
contentLength
=
toLength
-
pastLength
;
// 客户端请求的是 1275856879-1275877358 之间的字节
}
}
else
{
// 从开始进行下载
contentLength
=
fileLength
;
// 客户端要求全文下载
}
// 如果设设置了Content-Length,则客户端会自动进行多线程下载。如果不希望支持多线程,则不要设置这个参数。 响应的格式是:
// Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节]
// ServletActionContext.getResponse().setHeader("Content- Length", new Long(file.length() - p).toString());
response
.
reset
();
// 告诉客户端允许断点续传多线程连接下载,响应的格式是:Accept-Ranges: bytes
if
(
pastLength
!=
0
)
{
response
.
setHeader
(
"Accept-Ranges"
,
"bytes"
);
// 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1 200 OK
// 不是从最开始下载, 响应的格式是: Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
logger
.
debug
(
"---------------不是从开始进行下载!服务器即将开始断点续传..."
);
switch
(
rangeSwitch
)
{
case
1
:
{
// 针对 bytes=27000- 的请求
String
contentRange
=
new
StringBuffer
(
"bytes "
).
append
(
new
Long
(
pastLength
).
toString
()).
append
(
"-"
)
.
append
(
new
Long
(
fileLength
-
1
).
toString
()).
append
(
"/"
).
append
(
new
Long
(
fileLength
).
toString
()).
toString
();
response
.
setHeader
(
"Content-Range"
,
contentRange
);
break
;
}
case
2
:
{
// 针对 bytes=27000-39000 的请求
String
contentRange
=
rangeBytes
+
"/"
+
new
Long
(
fileLength
).
toString
();
response
.
setHeader
(
"Content-Range"
,
contentRange
);
break
;
}
default
:
{
break
;
}
}
}
else
{
// 是从开始下载
logger
.
debug
(
"---------------是从开始进行下载!"
);
}
try
{
response
.
addHeader
(
"Content-Disposition"
,
"attachment; filename=\""
+
Encodes
.
urlEncode
(
StringUtils
.
isBlank
(
fileName
)
?
file
.
getName
()
:
fileName
)
+
"\""
);
response
.
setContentType
(
getContentType
(
file
.
getName
()));
// set the MIME type.
response
.
addHeader
(
"Content-Length"
,
String
.
valueOf
(
contentLength
));
os
=
response
.
getOutputStream
();
out
=
new
BufferedOutputStream
(
os
);
raf
=
new
RandomAccessFile
(
file
,
"r"
);
try
{
switch
(
rangeSwitch
)
{
case
0
:
{
// 普通下载,或者从头开始的下载 同1
}
case
1
:
{
// 针对 bytes=27000- 的请求
raf
.
seek
(
pastLength
);
// 形如 bytes=969998336- 的客户端请求,跳过 969998336 个字节
int
n
=
0
;
while
((
n
=
raf
.
read
(
b
,
0
,
1024
))
!=
-
1
)
{
out
.
write
(
b
,
0
,
n
);
}
break
;
}
case
2
:
{
// 针对 bytes=27000-39000 的请求
raf
.
seek
(
pastLength
);
// 形如 bytes=1275856879-1275877358 的客户端请求,找到第 1275856879 个字节
int
n
=
0
;
long
readLength
=
0
;
// 记录已读字节数
while
(
readLength
<=
contentLength
-
1024
)
{
// 大部分字节在这里读取
n
=
raf
.
read
(
b
,
0
,
1024
);
readLength
+=
1024
;
out
.
write
(
b
,
0
,
n
);
}
if
(
readLength
<=
contentLength
)
{
// 余下的不足 1024 个字节在这里读取
n
=
raf
.
read
(
b
,
0
,
(
int
)
(
contentLength
-
readLength
));
out
.
write
(
b
,
0
,
n
);
}
break
;
}
default
:
{
break
;
}
}
out
.
flush
();
logger
.
debug
(
"---------------下载完成!"
);
}
catch
(
IOException
ie
)
{
/**
* 在写数据的时候, 对于 ClientAbortException 之类的异常,
* 是因为客户端取消了下载,而服务器端继续向浏览器写入数据时, 抛出这个异常,这个是正常的。
* 尤其是对于迅雷这种吸血的客户端软件, 明明已经有一个线程在读取 bytes=1275856879-1275877358,
* 如果短时间内没有读取完毕,迅雷会再启第二个、第三个。。。线程来读取相同的字节段, 直到有一个线程读取完毕,迅雷会 KILL
* 掉其他正在下载同一字节段的线程, 强行中止字节读出,造成服务器抛 ClientAbortException。
* 所以,我们忽略这种异常
*/
logger
.
debug
(
"提醒:向客户端传输时出现IO异常,但此异常是允许的,有可能客户端取消了下载,导致此异常,不用关心!"
);
}
}
catch
(
Exception
e
)
{
logger
.
error
(
e
.
getMessage
(),
e
);
}
finally
{
if
(
out
!=
null
)
{
try
{
out
.
close
();
}
catch
(
IOException
e
)
{
logger
.
error
(
e
.
getMessage
(),
e
);
}
}
if
(
raf
!=
null
)
{
try
{
raf
.
close
();
}
catch
(
IOException
e
)
{
logger
.
error
(
e
.
getMessage
(),
e
);
}
}
}
return
null
;
}
/**
* 修正路径,将 \\ 或 / 等替换为 File.separator
* @param path 待修正的路径
* @return 修正后的路径
*/
public
static
String
path
(
String
path
){
String
p
=
StringUtils
.
replace
(
path
,
"\\"
,
"/"
);
p
=
StringUtils
.
join
(
StringUtils
.
split
(
p
,
"/"
),
"/"
);
if
(!
StringUtils
.
startsWithAny
(
p
,
"/"
)
&&
StringUtils
.
startsWithAny
(
path
,
"\\"
,
"/"
)){
p
+=
"/"
;
}
if
(!
StringUtils
.
endsWithAny
(
p
,
"/"
)
&&
StringUtils
.
endsWithAny
(
path
,
"\\"
,
"/"
)){
p
=
p
+
"/"
;
}
if
(
path
!=
null
&&
path
.
startsWith
(
"/"
)){
p
=
"/"
+
p
;
// linux下路径
}
return
p
;
}
/**
* 获目录下的文件列表
* @param dir 搜索目录
* @param searchDirs 是否是搜索目录
* @return 文件列表
*/
public
static
List
<
String
>
findChildrenList
(
File
dir
,
boolean
searchDirs
)
{
List
<
String
>
files
=
Lists
.
newArrayList
();
for
(
String
subFiles
:
dir
.
list
())
{
File
file
=
new
File
(
dir
+
"/"
+
subFiles
);
if
(((
searchDirs
)
&&
(
file
.
isDirectory
()))
||
((!
searchDirs
)
&&
(!
file
.
isDirectory
())))
{
files
.
add
(
file
.
getName
());
}
}
return
files
;
}
/**
* 获取文件扩展名(返回小写)
* @param fileName 文件名
* @return 例如:test.jpg 返回: jpg
*/
public
static
String
getFileExtension
(
String
fileName
)
{
if
((
fileName
==
null
)
||
(
fileName
.
lastIndexOf
(
"."
)
==
-
1
)
||
(
fileName
.
lastIndexOf
(
"."
)
==
fileName
.
length
()
-
1
))
{
return
null
;
}
return
StringUtils
.
lowerCase
(
fileName
.
substring
(
fileName
.
lastIndexOf
(
"."
)
+
1
));
}
/**
* 获取文件名,不包含扩展名
* @param fileName 文件名
* @return 例如:d:\files\test.jpg 返回:d:\files\test
*/
public
static
String
getFileNameWithoutExtension
(
String
fileName
)
{
if
((
fileName
==
null
)
||
(
fileName
.
lastIndexOf
(
"."
)
==
-
1
))
{
return
null
;
}
return
fileName
.
substring
(
0
,
fileName
.
lastIndexOf
(
"."
));
}
}
Prev
1
…
3
4
5
6
7
8
9
10
11
…
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