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
e9629e7a
Commit
e9629e7a
authored
Dec 13, 2018
by
Sun
Browse files
no commit message
parent
e4054436
Changes
411
Show whitespace changes
Inline
Side-by-side
Too many changes to show.
To preserve performance only
20 of 411+
files are displayed.
Plain diff
Email patch
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/constant/ShiroConstants.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.constant
;
/**
* Shiro通用常量
*
* @author JeeSpring
*/
public
interface
ShiroConstants
{
/**
* 当前登录的用户
*/
public
static
final
String
CURRENT_USER
=
"currentUser"
;
/**
* 用户名
*/
public
static
final
String
CURRENT_USERNAME
=
"username"
;
/**
* 消息key
*/
public
static
String
MESSAGE
=
"message"
;
/**
* 错误key
*/
public
static
String
ERROR
=
"errorMsg"
;
/**
* 编码格式
*/
public
static
String
ENCODING
=
"UTF-8"
;
/**
* 当前在线会话
*/
public
String
ONLINE_SESSION
=
"online_session"
;
/**
* 验证码key
*/
public
static
final
String
CURRENT_CAPTCHA
=
"captcha"
;
/**
* 验证码开关
*/
public
static
final
String
CURRENT_EBABLED
=
"captchaEbabled"
;
/**
* 验证码开关
*/
public
static
final
String
CURRENT_TYPE
=
"captchaType"
;
/**
* 验证码
*/
public
static
final
String
CURRENT_VALIDATECODE
=
"validateCode"
;
/**
* 验证码错误
*/
public
static
final
String
CAPTCHA_ERROR
=
"captchaError"
;
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/druid/DruidConfiguration.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.druid
;
import
java.sql.SQLException
;
import
javax.sql.DataSource
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.context.annotation.Primary
;
import
com.alibaba.druid.pool.DruidDataSource
;
/**
*
* 描述:如果不使用代码手动初始化DataSource的话,监控界面的SQL监控会没有数据("是spring boot的bug???")
* @author chhliu
* 创建时间:2017年2月9日 下午10:33:08
* @version 1.2.0
*/
@Configuration
public
class
DruidConfiguration
{
@Value
(
"${spring.datasource.url}"
)
private
String
dbUrl
;
@Value
(
"${spring.datasource.username}"
)
private
String
username
;
@Value
(
"${spring.datasource.password}"
)
private
String
password
;
@Value
(
"${spring.datasource.driverClassName}"
)
private
String
driverClassName
;
@Value
(
"${spring.datasource.initialSize}"
)
private
int
initialSize
;
@Value
(
"${spring.datasource.minIdle}"
)
private
int
minIdle
;
@Value
(
"${spring.datasource.maxActive}"
)
private
int
maxActive
;
@Value
(
"${spring.datasource.maxWait}"
)
private
int
maxWait
;
@Value
(
"${spring.datasource.timeBetweenEvictionRunsMillis}"
)
private
int
timeBetweenEvictionRunsMillis
;
@Value
(
"${spring.datasource.minEvictableIdleTimeMillis}"
)
private
int
minEvictableIdleTimeMillis
;
@Value
(
"${spring.datasource.validationQuery}"
)
private
String
validationQuery
;
@Value
(
"${spring.datasource.testWhileIdle}"
)
private
boolean
testWhileIdle
;
@Value
(
"${spring.datasource.testOnBorrow}"
)
private
boolean
testOnBorrow
;
@Value
(
"${spring.datasource.testOnReturn}"
)
private
boolean
testOnReturn
;
@Value
(
"${spring.datasource.poolPreparedStatements}"
)
private
boolean
poolPreparedStatements
;
@Value
(
"${spring.datasource.maxPoolPreparedStatementPerConnectionSize}"
)
private
int
maxPoolPreparedStatementPerConnectionSize
;
@Value
(
"${spring.datasource.filters}"
)
private
String
filters
;
@Value
(
"${spring.datasource.connectionProperties}"
)
private
String
connectionProperties
;
@Value
(
"${spring.datasource.useGlobalDataSourceStat}"
)
private
boolean
useGlobalDataSourceStat
;
@Bean
//声明其为Bean实例
@Primary
//在同样的DataSource中,首先使用被标注的DataSource
public
DataSource
dataSource
(){
DruidDataSource
datasource
=
new
DruidDataSource
();
datasource
.
setUrl
(
this
.
dbUrl
);
datasource
.
setUsername
(
username
);
datasource
.
setPassword
(
password
);
datasource
.
setDriverClassName
(
driverClassName
);
//configuration
datasource
.
setInitialSize
(
initialSize
);
datasource
.
setMinIdle
(
minIdle
);
datasource
.
setMaxActive
(
maxActive
);
datasource
.
setMaxWait
(
maxWait
);
datasource
.
setTimeBetweenEvictionRunsMillis
(
timeBetweenEvictionRunsMillis
);
datasource
.
setMinEvictableIdleTimeMillis
(
minEvictableIdleTimeMillis
);
datasource
.
setValidationQuery
(
validationQuery
);
datasource
.
setTestWhileIdle
(
testWhileIdle
);
datasource
.
setTestOnBorrow
(
testOnBorrow
);
datasource
.
setTestOnReturn
(
testOnReturn
);
datasource
.
setPoolPreparedStatements
(
poolPreparedStatements
);
datasource
.
setMaxPoolPreparedStatementPerConnectionSize
(
maxPoolPreparedStatementPerConnectionSize
);
datasource
.
setUseGlobalDataSourceStat
(
useGlobalDataSourceStat
);
try
{
datasource
.
setFilters
(
filters
);
}
catch
(
SQLException
e
)
{
System
.
err
.
println
(
"druid configuration initialization filter: "
+
e
);
}
datasource
.
setConnectionProperties
(
connectionProperties
);
return
datasource
;
}
}
\ No newline at end of file
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/druid/DruidStatFilter.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.druid
;
import
javax.servlet.annotation.WebFilter
;
import
javax.servlet.annotation.WebInitParam
;
import
com.alibaba.druid.support.http.WebStatFilter
;
/**
* Druid的StatFilter
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年3月17日
*/
@WebFilter
(
filterName
=
"druidWebStatFilter"
,
urlPatterns
=
"/*"
,
initParams
={
@WebInitParam
(
name
=
"exclusions"
,
value
=
"*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
)
// 忽略资源
})
public
class
DruidStatFilter
extends
WebStatFilter
{
}
\ No newline at end of file
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/druid/DruidStatViewServlet.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.druid
;
import
javax.servlet.annotation.WebInitParam
;
import
javax.servlet.annotation.WebServlet
;
import
com.alibaba.druid.support.http.StatViewServlet
;
/**
* StatViewServlet
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年3月17日
*/
@SuppressWarnings
(
"serial"
)
@WebServlet
(
urlPatterns
=
"/druid/*"
,
initParams
={
@WebInitParam
(
name
=
"allow"
,
value
=
"192.168.16.110,127.0.0.1"
),
// IP白名单 (没有配置或者为空,则允许所有访问)
@WebInitParam
(
name
=
"deny"
,
value
=
"192.168.16.111"
),
// IP黑名单 (存在共同时,deny优先于allow)
//WebInitParam(name="loginUsername",value="shanhy"),// 用户名
//WebInitParam(name="loginPassword",value="shanhypwd"),// 密码
@WebInitParam
(
name
=
"resetEnable"
,
value
=
"false"
)
// 禁用HTML页面上的“Reset All”功能
})
public
class
DruidStatViewServlet
extends
StatViewServlet
{
}
\ No newline at end of file
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/exception/job/TaskException.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.exception.job
;
/**
* 计划策略异常
*
* @author JeeSpring
*/
public
class
TaskException
extends
Exception
{
private
static
final
long
serialVersionUID
=
1L
;
private
Code
code
;
public
TaskException
(
String
msg
,
Code
code
)
{
this
(
msg
,
code
,
null
);
}
public
TaskException
(
String
msg
,
Code
code
,
Exception
nestedEx
)
{
super
(
msg
,
nestedEx
);
this
.
code
=
code
;
}
public
Code
getCode
()
{
return
code
;
}
public
enum
Code
{
TASK_EXISTS
,
NO_TASK_EXISTS
,
TASK_ALREADY_STARTED
,
UNKNOWN
,
CONFIG_ERROR
,
TASK_NODE_NOT_AVAILABLE
}
}
\ No newline at end of file
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/filter/JeesiteFileUploadFilter.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.filter
;
import
com.ckfinder.connector.FileUploadFilter
;
import
javax.servlet.annotation.WebFilter
;
import
javax.servlet.annotation.WebInitParam
;
/**
* Created by zhao.weiwei
* create on 2017/1/10 12:23
* the email is zhao.weiwei@jyall.com.
*/
@WebFilter
(
urlPatterns
=
"/static/ckfinder/core/connector/java/connector.java"
,
initParams
=
{
@WebInitParam
(
name
=
"sessionCookieName"
,
value
=
"JSESSIONID"
),
@WebInitParam
(
name
=
"sessionParameterName"
,
value
=
"jsessionid"
)
})
public
class
JeesiteFileUploadFilter
extends
FileUploadFilter
{
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/filter/LogoutFilter.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.filter
;
import
com.jeespring.common.security.ShiroUtils
;
import
com.jeespring.common.utils.StringUtils
;
import
com.jeespring.modules.monitor.entity.OnlineSession
;
import
com.jeespring.modules.sys.dao.OnlineSessionDAO
;
import
com.jeespring.modules.sys.entity.SysUserOnline
;
import
com.jeespring.modules.sys.entity.User
;
import
com.jeespring.modules.sys.service.SysUserOnlineService
;
import
org.apache.shiro.session.SessionException
;
import
org.apache.shiro.subject.Subject
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.context.ApplicationContext
;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.context.support.WebApplicationContextUtils
;
import
javax.servlet.ServletContext
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
/**
* 退出过滤器
*
* @author JeeSpring
*/
public
class
LogoutFilter
extends
org
.
apache
.
shiro
.
web
.
filter
.
authc
.
LogoutFilter
{
private
SysUserOnlineService
sysUserOnlineService
;
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
LogoutFilter
.
class
);
/**
* 退出后重定向的地址
*/
private
String
loginUrl
=
"/admin/login"
;
public
String
getLoginUrl
()
{
return
loginUrl
;
}
public
void
setLoginUrl
(
String
loginUrl
)
{
this
.
loginUrl
=
loginUrl
;
}
@Override
protected
boolean
preHandle
(
ServletRequest
request
,
ServletResponse
response
)
throws
Exception
{
try
{
Subject
subject
=
getSubject
(
request
,
response
);
String
redirectUrl
=
getRedirectUrl
(
request
,
response
,
subject
);
try
{
User
user
=
ShiroUtils
.
getUser
();
if
(
StringUtils
.
isNotNull
(
user
))
{
String
loginName
=
user
.
getLoginName
();
SysUserOnline
sysUserOnline
=
new
SysUserOnline
();
sysUserOnline
.
setLoginName
(
user
.
getName
());
if
(
sysUserOnlineService
==
null
){
ServletContext
context
=
request
.
getServletContext
();
ApplicationContext
ctx
=
WebApplicationContextUtils
.
getWebApplicationContext
(
context
);
sysUserOnlineService
=
ctx
.
getBean
(
SysUserOnlineService
.
class
);
}
if
(
sysUserOnlineService
!=
null
){
sysUserOnline
=
sysUserOnlineService
.
get
(
subject
.
getSession
().
getId
().
toString
());
if
(
sysUserOnline
!=
null
){
sysUserOnline
.
setStatus
(
OnlineSession
.
OnlineStatus
.
off_line
.
toString
());
sysUserOnlineService
.
save
(
sysUserOnline
);
}
}
// 记录用户退出日志
//SystemLogUtils.log(loginName, Constants.LOGOUT, MessageUtils.message("user.logout.success"));
}
// 退出登录
subject
.
logout
();
}
catch
(
SessionException
ise
)
{
log
.
error
(
"logout fail."
,
ise
);
}
issueRedirect
(
request
,
response
,
redirectUrl
);
}
catch
(
Exception
e
)
{
log
.
error
(
"Encountered session exception during logout. This can generally safely be ignored."
,
e
);
}
return
false
;
}
/**
* 退出跳转URL
*/
@Override
protected
String
getRedirectUrl
(
ServletRequest
request
,
ServletResponse
response
,
Subject
subject
)
{
String
url
=
getLoginUrl
();
if
(
StringUtils
.
isNotEmpty
(
url
))
{
return
url
;
}
return
super
.
getRedirectUrl
(
request
,
response
,
subject
);
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/filter/OnlineSessionFilter.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.filter
;
import
com.jeespring.common.constant.ShiroConstants
;
import
com.jeespring.common.security.ShiroUtils
;
import
com.jeespring.common.utils.IpUtils
;
import
com.jeespring.common.utils.ServletUtils
;
import
com.jeespring.modules.sys.dao.OnlineSessionDAO
;
import
com.jeespring.modules.sys.entity.User
;
import
com.jeespring.modules.sys.service.SysUserOnlineService
;
import
eu.bitwalker.useragentutils.UserAgent
;
import
org.apache.shiro.SecurityUtils
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.subject.Subject
;
import
org.apache.shiro.web.filter.AccessControlFilter
;
import
org.apache.shiro.web.util.WebUtils
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
java.io.IOException
;
import
com.jeespring.modules.monitor.entity.OnlineSession
;
/**
* 自定义访问控制
*
* @author JeeSpring
*/
public
class
OnlineSessionFilter
//extends AccessControlFilter
{
/**
* 强制退出后重定向的地址
*/
@Value
(
"${shiro.user.loginUrl}"
)
private
String
loginUrl
=
"/admin/login"
;
/**
* 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
*/
//@Override
protected
boolean
isAccessAllowed
(
ServletRequest
request
,
ServletResponse
response
,
Object
mappedValue
)
throws
Exception
{
Subject
subject
=
getSubject
(
request
,
response
);
if
(
subject
==
null
||
subject
.
getSession
()
==
null
)
{
return
true
;
}
//Session session = onlineSessionDAO.readSession(subject.getSession().getId());
Session
session
=
subject
.
getSession
();
//&& session instanceof OnlineSession
if
(
session
!=
null
)
{
//OnlineSession onlineSession = (OnlineSession) session;
OnlineSession
onlineSession
=
new
OnlineSession
();
onlineSession
.
setId
(
subject
.
getSession
().
getId
().
toString
());
request
.
setAttribute
(
ShiroConstants
.
ONLINE_SESSION
,
onlineSession
);
// 把user对象设置进去
boolean
isGuest
=
onlineSession
.
getUserId
()
==
null
||
onlineSession
.
getUserId
()
==
""
;
if
(
isGuest
==
true
)
{
User
user
=
ShiroUtils
.
getUser
();
if
(
user
!=
null
)
{
onlineSession
.
setUserId
(
user
.
getId
());
onlineSession
.
setLoginName
(
user
.
getLoginName
());
if
(
user
.
getOffice
()!=
null
)
{
onlineSession
.
setDeptName
(
user
.
getOffice
().
getName
());
}
onlineSession
.
markAttributeChanged
();
UserAgent
userAgent
=
UserAgent
.
parseUserAgentString
(
ServletUtils
.
getRequest
().
getHeader
(
"User-Agent"
));
// 获取客户端操作系统
String
os
=
userAgent
.
getOperatingSystem
().
getName
();
// 获取客户端浏览器
String
browser
=
userAgent
.
getBrowser
().
getName
();
onlineSession
.
setHost
(
IpUtils
.
getIpAddr
((
HttpServletRequest
)
request
));
onlineSession
.
setBrowser
(
browser
);
onlineSession
.
setOs
(
os
);
}
}
if
(
onlineSession
.
getStatus
()
==
OnlineSession
.
OnlineStatus
.
off_line
)
{
return
false
;
}
}
return
true
;
}
/**
* 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。
*/
//@Override
protected
boolean
onAccessDenied
(
ServletRequest
request
,
ServletResponse
response
)
throws
Exception
{
Subject
subject
=
getSubject
(
request
,
response
);
if
(
subject
!=
null
)
{
subject
.
logout
();
}
//saveRequestAndRedirectToLogin(request, response);
return
true
;
}
// 跳转到登录页
//@Override
protected
void
redirectToLogin
(
ServletRequest
request
,
ServletResponse
response
)
throws
IOException
{
WebUtils
.
issueRedirect
(
request
,
response
,
loginUrl
);
}
/**
* 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
*/
protected
Subject
getSubject
(
ServletRequest
request
,
ServletResponse
response
)
{
return
SecurityUtils
.
getSubject
();
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/filter/PageCachingFilter.java
deleted
100644 → 0
View file @
e4054436
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.filter
;
import
com.jeespring.common.utils.SpringContextHolder
;
import
net.sf.ehcache.CacheManager
;
import
net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter
;
/**
* 页面高速缓存过滤器
* @author 黄炳桂 516821420@qq.com
* @version 2013-8-5
*/
public
class
PageCachingFilter
extends
SimplePageCachingFilter
{
private
CacheManager
cacheManager
=
SpringContextHolder
.
getBean
(
CacheManager
.
class
);
@Override
protected
CacheManager
getCacheManager
()
{
this
.
cacheName
=
"pageCachingFilter"
;
return
cacheManager
;
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/filter/SyncOnlineSessionFilter.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.filter
;
import
com.jeespring.common.constant.ShiroConstants
;
import
com.jeespring.common.redis.RedisUtils
;
import
com.jeespring.common.security.ShiroUtils
;
import
com.jeespring.common.utils.IpUtils
;
import
com.jeespring.common.utils.ServletUtils
;
import
com.jeespring.modules.monitor.entity.OnlineSession
;
import
com.jeespring.modules.sys.dao.OnlineSessionDAO
;
import
com.jeespring.modules.sys.entity.User
;
import
com.jeespring.modules.sys.service.SysUserOnlineService
;
import
eu.bitwalker.useragentutils.UserAgent
;
import
org.apache.shiro.SecurityUtils
;
import
org.apache.shiro.session.Session
;
import
org.apache.shiro.subject.Subject
;
import
org.apache.shiro.web.filter.PathMatchingFilter
;
import
org.apache.shiro.web.util.WebUtils
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.http.HttpServletRequest
;
import
java.io.IOException
;
/**
* 同步Session数据到Db
*
* @author JeeSpring
*/
public
class
SyncOnlineSessionFilter
extends
PathMatchingFilter
{
/**
* 日志对象
*/
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
SyncOnlineSessionFilter
.
class
);
@Autowired
private
SysUserOnlineService
sysUserOnlineService
;
/**
* 强制退出后重定向的地址
*/
@Value
(
"${shiro.user.loginUrl}"
)
private
String
loginUrl
;
/**
* 同步会话数据到DB 一次请求最多同步一次 防止过多处理 需要放到Shiro过滤器之前
*
* @param request
* @param response
* @return
* @throws Exception
*/
@Override
protected
boolean
preHandle
(
ServletRequest
request
,
ServletResponse
response
)
throws
Exception
{
try
{
OnlineSessionFilter
onlineSessionFilter
=
new
OnlineSessionFilter
();
onlineSessionFilter
.
isAccessAllowed
(
request
,
response
,
null
);
//isAccessAllowed(request, response);
OnlineSession
session
=
(
OnlineSession
)
request
.
getAttribute
(
ShiroConstants
.
ONLINE_SESSION
);
// 如果session stop了 也不同步
// session停止时间,如果stopTimestamp不为null,则代表已停止
if
(
session
!=
null
&&
session
.
getUserId
()
!=
null
&&
session
.
getStopTimestamp
()
==
null
)
{
sysUserOnlineService
.
syncToDb
(
session
);
}
return
true
;
}
catch
(
Exception
e
){
logger
.
error
(
"SyncOnlineSessionFilter preHandle error:"
,
e
.
getMessage
());
return
true
;
}
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/json/AjaxJson.java
deleted
100644 → 0
View file @
e4054436
/**
* * Copyright © 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package
com.jeespring.common.json
;
import
java.util.LinkedHashMap
;
import
com.fasterxml.jackson.annotation.JsonIgnore
;
import
com.jeespring.common.mapper.JsonMapper
;
/**
* $.ajax后需要接受的JSON
*
* @author
*
*/
public
class
AjaxJson
{
private
boolean
success
=
true
;
// 是否成功
private
String
errorCode
=
"-1"
;
//错误代码
private
String
msg
=
"操作成功"
;
// 提示信息
private
LinkedHashMap
<
String
,
Object
>
body
=
new
LinkedHashMap
();
//封装json的map
public
LinkedHashMap
<
String
,
Object
>
getBody
()
{
return
body
;
}
public
void
setBody
(
LinkedHashMap
<
String
,
Object
>
body
)
{
this
.
body
=
body
;
}
public
void
put
(
String
key
,
Object
value
){
//向json中添加属性,在js中访问,请调用data.map.key
body
.
put
(
key
,
value
);
}
public
void
remove
(
String
key
){
body
.
remove
(
key
);
}
public
String
getMsg
()
{
return
msg
;
}
public
void
setMsg
(
String
msg
)
{
//向json中添加属性,在js中访问,请调用data.msg
this
.
msg
=
msg
;
}
public
boolean
isSuccess
()
{
return
success
;
}
public
void
setSuccess
(
boolean
success
)
{
this
.
success
=
success
;
}
@JsonIgnore
//返回对象时忽略此属性
public
String
getJsonStr
()
{
//返回json字符串数组,将访问msg和key的方式统一化,都使用data.key的方式直接访问。
String
json
=
JsonMapper
.
getInstance
().
toJson
(
this
);
return
json
;
}
public
void
setErrorCode
(
String
errorCode
)
{
this
.
errorCode
=
errorCode
;
}
public
String
getErrorCode
()
{
return
errorCode
;
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/json/PrintJSON.java
deleted
100644 → 0
View file @
e4054436
/**
* * Copyright © 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package
com.jeespring.common.json
;
import
java.io.IOException
;
import
java.io.PrintWriter
;
import
javax.servlet.http.HttpServletResponse
;
public
class
PrintJSON
{
public
static
void
write
(
HttpServletResponse
response
,
String
content
)
{
response
.
reset
();
response
.
setContentType
(
"application/json"
);
response
.
setHeader
(
"Cache-Control"
,
"no-store"
);
response
.
setCharacterEncoding
(
"UTF-8"
);
try
{
PrintWriter
pw
=
response
.
getWriter
();
pw
.
write
(
content
);
pw
.
flush
();
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mail/MailAuthenticator.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.mail
;
/**
*
*/
import
javax.mail.*
;
public
class
MailAuthenticator
extends
Authenticator
{
String
userName
=
null
;
String
password
=
null
;
public
MailAuthenticator
(){
}
public
MailAuthenticator
(
String
username
,
String
password
)
{
this
.
userName
=
username
;
this
.
password
=
password
;
}
@Override
protected
PasswordAuthentication
getPasswordAuthentication
(){
return
new
PasswordAuthentication
(
userName
,
password
);
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mail/MailBody.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.mail
;
/**
*发送邮件需要使用的基本信息
*
*/
import
java.util.Properties
;
public
class
MailBody
{
// 发送邮件的服务器的IP和端口
private
String
mailServerHost
;
private
String
mailServerPort
=
"25"
;
// 邮件发送者的地址
private
String
fromAddress
;
// 邮件接收者的地址
private
String
toAddress
;
// 登陆邮件发送服务器的用户名和密码
private
String
userName
;
private
String
password
;
// 是否需要身份验证
private
boolean
validate
=
false
;
// 邮件主题
private
String
subject
;
// 邮件的文本内容
private
String
content
;
// 邮件附件的文件名
private
String
[]
attachFileNames
;
/**
* 获得邮件会话属性
*/
public
Properties
getProperties
(){
Properties
p
=
new
Properties
();
p
.
put
(
"mail.smtp.host"
,
this
.
mailServerHost
);
p
.
put
(
"mail.smtp.port"
,
this
.
mailServerPort
);
p
.
put
(
"mail.smtp.auth"
,
validate
?
"true"
:
"false"
);
return
p
;
}
public
String
getMailServerHost
()
{
return
mailServerHost
;
}
public
void
setMailServerHost
(
String
mailServerHost
)
{
this
.
mailServerHost
=
mailServerHost
;
}
public
String
getMailServerPort
()
{
return
mailServerPort
;
}
public
void
setMailServerPort
(
String
mailServerPort
)
{
this
.
mailServerPort
=
mailServerPort
;
}
public
boolean
isValidate
()
{
return
validate
;
}
public
void
setValidate
(
boolean
validate
)
{
this
.
validate
=
validate
;
}
public
String
[]
getAttachFileNames
()
{
return
attachFileNames
;
}
public
void
setAttachFileNames
(
String
[]
fileNames
)
{
this
.
attachFileNames
=
fileNames
;
}
public
String
getFromAddress
()
{
return
fromAddress
;
}
public
void
setFromAddress
(
String
fromAddress
)
{
this
.
fromAddress
=
fromAddress
;
}
public
String
getPassword
()
{
return
password
;
}
public
void
setPassword
(
String
password
)
{
this
.
password
=
password
;
}
public
String
getToAddress
()
{
return
toAddress
;
}
public
void
setToAddress
(
String
toAddress
)
{
this
.
toAddress
=
toAddress
;
}
public
String
getUserName
()
{
return
userName
;
}
public
void
setUserName
(
String
userName
)
{
this
.
userName
=
userName
;
}
public
String
getSubject
()
{
return
subject
;
}
public
void
setSubject
(
String
subject
)
{
this
.
subject
=
subject
;
}
public
String
getContent
()
{
return
content
;
}
public
void
setContent
(
String
textContent
)
{
this
.
content
=
textContent
;
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mail/MailSendUtils.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.mail
;
/**
* 简单邮件(不带附件的邮件)发送器
*/
import
java.util.Date
;
import
java.util.Properties
;
import
javax.mail.Address
;
import
javax.mail.BodyPart
;
import
javax.mail.Message
;
import
javax.mail.Multipart
;
import
javax.mail.Session
;
import
javax.mail.Transport
;
import
javax.mail.internet.InternetAddress
;
import
javax.mail.internet.MimeBodyPart
;
import
javax.mail.internet.MimeMessage
;
import
javax.mail.internet.MimeMultipart
;
public
class
MailSendUtils
{
/**
* 以文本格式发送邮件
* @param mailInfo 待发送的邮件的信息
*/
public
boolean
sendTextMail
(
MailBody
mailInfo
)
throws
Exception
{
// 判断是否需要身份认证
MailAuthenticator
authenticator
=
null
;
Properties
pro
=
mailInfo
.
getProperties
();
if
(
mailInfo
.
isValidate
())
{
// 如果需要身份认证,则创建一个密码验证器
authenticator
=
new
MailAuthenticator
(
mailInfo
.
getUserName
(),
mailInfo
.
getPassword
());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session
sendMailSession
=
Session
.
getDefaultInstance
(
pro
,
authenticator
);
// logBefore(logger, "构造一个发送邮件的session");
// 根据session创建一个邮件消息
Message
mailMessage
=
new
MimeMessage
(
sendMailSession
);
// 创建邮件发送者地址
Address
from
=
new
InternetAddress
(
mailInfo
.
getFromAddress
());
// 设置邮件消息的发送者
mailMessage
.
setFrom
(
from
);
// 创建邮件的接收者地址,并设置到邮件消息中
Address
to
=
new
InternetAddress
(
mailInfo
.
getToAddress
());
mailMessage
.
setRecipient
(
Message
.
RecipientType
.
TO
,
to
);
// 设置邮件消息的主题
mailMessage
.
setSubject
(
mailInfo
.
getSubject
());
// 设置邮件消息发送的时间
mailMessage
.
setSentDate
(
new
Date
());
// 设置邮件消息的主要内容
String
mailContent
=
mailInfo
.
getContent
();
mailMessage
.
setText
(
mailContent
);
// 发送邮件
Transport
.
send
(
mailMessage
);
System
.
out
.
println
(
"发送成功!"
);
return
true
;
}
/**
* 以HTML格式发送邮件
* @param mailInfo 待发送的邮件信息
*/
public
boolean
sendHtmlMail
(
MailBody
mailInfo
)
throws
Exception
{
// 判断是否需要身份认证
MailAuthenticator
authenticator
=
null
;
Properties
pro
=
mailInfo
.
getProperties
();
//如果需要身份认证,则创建一个密码验证器
if
(
mailInfo
.
isValidate
())
{
authenticator
=
new
MailAuthenticator
(
mailInfo
.
getUserName
(),
mailInfo
.
getPassword
());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session
sendMailSession
=
Session
.
getDefaultInstance
(
pro
,
authenticator
);
// 根据session创建一个邮件消息
Message
mailMessage
=
new
MimeMessage
(
sendMailSession
);
// 创建邮件发送者地址
Address
from
=
new
InternetAddress
(
mailInfo
.
getFromAddress
());
// 设置邮件消息的发送者
mailMessage
.
setFrom
(
from
);
// 创建邮件的接收者地址,并设置到邮件消息中
Address
to
=
new
InternetAddress
(
mailInfo
.
getToAddress
());
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage
.
setRecipient
(
Message
.
RecipientType
.
TO
,
to
);
// 设置邮件消息的主题
mailMessage
.
setSubject
(
mailInfo
.
getSubject
());
// 设置邮件消息发送的时间
mailMessage
.
setSentDate
(
new
Date
());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart
mainPart
=
new
MimeMultipart
();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart
html
=
new
MimeBodyPart
();
// 设置HTML内容
html
.
setContent
(
mailInfo
.
getContent
(),
"text/html; charset=utf-8"
);
mainPart
.
addBodyPart
(
html
);
// 将MiniMultipart对象设置为邮件内容
mailMessage
.
setContent
(
mainPart
);
// 发送邮件
Transport
.
send
(
mailMessage
);
return
true
;
}
/**
* @param SMTP
* 邮件服务器
* @param PORT
* 端口
* @param EMAIL
* 本邮箱账号
* @param PAW
* 本邮箱密码
* @param toEMAIL
* 对方箱账号
* @param TITLE
* 标题
* @param CONTENT
* 内容
* @param TYPE
* 1:文本格式;2:HTML格式
*/
public
static
boolean
sendEmail
(
String
SMTP
,
String
PORT
,
String
EMAIL
,
String
PAW
,
String
toEMAIL
,
String
TITLE
,
String
CONTENT
,
String
TYPE
)
{
// 这个类主要是设置邮件
MailBody
mailInfo
=
new
MailBody
();
mailInfo
.
setMailServerHost
(
SMTP
);
mailInfo
.
setMailServerPort
(
PORT
);
mailInfo
.
setValidate
(
true
);
mailInfo
.
setUserName
(
EMAIL
);
mailInfo
.
setPassword
(
PAW
);
mailInfo
.
setFromAddress
(
EMAIL
);
mailInfo
.
setToAddress
(
toEMAIL
);
mailInfo
.
setSubject
(
TITLE
);
mailInfo
.
setContent
(
CONTENT
);
// 这个类主要来发送邮件
MailSendUtils
sms
=
new
MailSendUtils
();
try
{
if
(
"1"
.
equals
(
TYPE
))
{
return
sms
.
sendTextMail
(
mailInfo
);
}
else
{
return
sms
.
sendHtmlMail
(
mailInfo
);
}
}
catch
(
Exception
e
)
{
return
false
;
}
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mapper/BeanMapper.java
deleted
100644 → 0
View file @
e4054436
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.mapper
;
import
java.util.Collection
;
import
java.util.List
;
import
org.dozer.DozerBeanMapper
;
import
com.google.common.collect.Lists
;
/**
* 简单封装Dozer, 实现深度转换Bean<->Bean的Mapper.实现:
*
* 1. 持有Mapper的单例.
* 2. 返回值类型转换.
* 3. 批量转换Collection中的所有对象.
* 4. 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
*
* @author calvin
* @version 2013-01-15
*/
public
class
BeanMapper
{
/**
* 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
*/
private
static
DozerBeanMapper
dozer
=
new
DozerBeanMapper
();
/**
* 基于Dozer转换对象的类型.
*/
public
static
<
T
>
T
map
(
Object
source
,
Class
<
T
>
destinationClass
)
{
return
dozer
.
map
(
source
,
destinationClass
);
}
/**
* 基于Dozer转换Collection中对象的类型.
*/
@SuppressWarnings
(
"rawtypes"
)
public
static
<
T
>
List
<
T
>
mapList
(
Collection
sourceList
,
Class
<
T
>
destinationClass
)
{
List
<
T
>
destinationList
=
Lists
.
newArrayList
();
for
(
Object
sourceObject
:
sourceList
)
{
T
destinationObject
=
dozer
.
map
(
sourceObject
,
destinationClass
);
destinationList
.
add
(
destinationObject
);
}
return
destinationList
;
}
/**
* 基于Dozer将对象A的值拷贝到对象B中.
*/
public
static
void
copy
(
Object
source
,
Object
destinationObject
)
{
dozer
.
map
(
source
,
destinationObject
);
}
}
\ No newline at end of file
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mapper/JaxbMapper.java
deleted
100644 → 0
View file @
e4054436
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package
com.jeespring.common.mapper
;
import
java.io.StringReader
;
import
java.io.StringWriter
;
import
java.util.Collection
;
import
java.util.concurrent.ConcurrentHashMap
;
import
java.util.concurrent.ConcurrentMap
;
import
javax.xml.bind.JAXBContext
;
import
javax.xml.bind.JAXBElement
;
import
javax.xml.bind.JAXBException
;
import
javax.xml.bind.Marshaller
;
import
javax.xml.bind.Unmarshaller
;
import
javax.xml.bind.annotation.XmlAnyElement
;
import
javax.xml.namespace.QName
;
import
org.springframework.http.converter.HttpMessageConversionException
;
import
org.springframework.util.Assert
;
import
com.jeespring.common.utils.Exceptions
;
import
com.jeespring.common.utils.Reflections
;
import
com.jeespring.common.utils.StringUtils
;
/**
* 使用Jaxb2.0实现XML<->Java Object的Mapper.
*
* 在创建时需要设定所有需要序列化的Root对象的Class.
* 特别支持Root对象是Collection的情形.
*
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings
(
"rawtypes"
)
public
class
JaxbMapper
{
private
static
ConcurrentMap
<
Class
,
JAXBContext
>
jaxbContexts
=
new
ConcurrentHashMap
<
Class
,
JAXBContext
>();
/**
* Java Object->Xml without encoding.
*/
public
static
String
toXml
(
Object
root
)
{
Class
clazz
=
Reflections
.
getUserClass
(
root
);
return
toXml
(
root
,
clazz
,
null
);
}
/**
* Java Object->Xml with encoding.
*/
public
static
String
toXml
(
Object
root
,
String
encoding
)
{
Class
clazz
=
Reflections
.
getUserClass
(
root
);
return
toXml
(
root
,
clazz
,
encoding
);
}
/**
* Java Object->Xml with encoding.
*/
public
static
String
toXml
(
Object
root
,
Class
clazz
,
String
encoding
)
{
try
{
StringWriter
writer
=
new
StringWriter
();
createMarshaller
(
clazz
,
encoding
).
marshal
(
root
,
writer
);
return
writer
.
toString
();
}
catch
(
JAXBException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
*/
public
static
String
toXml
(
Collection
<?>
root
,
String
rootName
,
Class
clazz
)
{
return
toXml
(
root
,
rootName
,
clazz
,
null
);
}
/**
* Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
*/
public
static
String
toXml
(
Collection
<?>
root
,
String
rootName
,
Class
clazz
,
String
encoding
)
{
try
{
CollectionWrapper
wrapper
=
new
CollectionWrapper
();
wrapper
.
collection
=
root
;
JAXBElement
<
CollectionWrapper
>
wrapperElement
=
new
JAXBElement
<
CollectionWrapper
>(
new
QName
(
rootName
),
CollectionWrapper
.
class
,
wrapper
);
StringWriter
writer
=
new
StringWriter
();
createMarshaller
(
clazz
,
encoding
).
marshal
(
wrapperElement
,
writer
);
return
writer
.
toString
();
}
catch
(
JAXBException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* Xml->Java Object.
*/
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
T
fromXml
(
String
xml
,
Class
<
T
>
clazz
)
{
try
{
StringReader
reader
=
new
StringReader
(
xml
);
return
(
T
)
createUnmarshaller
(
clazz
).
unmarshal
(
reader
);
}
catch
(
JAXBException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 创建Marshaller并设定encoding(可为null).
* 线程不安全,需要每次创建或pooling。
*/
public
static
Marshaller
createMarshaller
(
Class
clazz
,
String
encoding
)
{
try
{
JAXBContext
jaxbContext
=
getJaxbContext
(
clazz
);
Marshaller
marshaller
=
jaxbContext
.
createMarshaller
();
marshaller
.
setProperty
(
Marshaller
.
JAXB_FORMATTED_OUTPUT
,
Boolean
.
TRUE
);
if
(
StringUtils
.
isNotBlank
(
encoding
))
{
marshaller
.
setProperty
(
Marshaller
.
JAXB_ENCODING
,
encoding
);
}
return
marshaller
;
}
catch
(
JAXBException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
/**
* 创建UnMarshaller.
* 线程不安全,需要每次创建或pooling。
*/
public
static
Unmarshaller
createUnmarshaller
(
Class
clazz
)
{
try
{
JAXBContext
jaxbContext
=
getJaxbContext
(
clazz
);
return
jaxbContext
.
createUnmarshaller
();
}
catch
(
JAXBException
e
)
{
throw
Exceptions
.
unchecked
(
e
);
}
}
protected
static
JAXBContext
getJaxbContext
(
Class
clazz
)
{
Assert
.
notNull
(
clazz
,
"'clazz' must not be null"
);
JAXBContext
jaxbContext
=
jaxbContexts
.
get
(
clazz
);
if
(
jaxbContext
==
null
)
{
try
{
jaxbContext
=
JAXBContext
.
newInstance
(
clazz
,
CollectionWrapper
.
class
);
jaxbContexts
.
putIfAbsent
(
clazz
,
jaxbContext
);
}
catch
(
JAXBException
ex
)
{
throw
new
HttpMessageConversionException
(
"Could not instantiate JAXBContext for class ["
+
clazz
+
"]: "
+
ex
.
getMessage
(),
ex
);
}
}
return
jaxbContext
;
}
/**
* 封装Root Element 是 Collection的情况.
*/
public
static
class
CollectionWrapper
{
@XmlAnyElement
protected
Collection
<?>
collection
;
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mapper/JsonMapper.java
deleted
100644 → 0
View file @
e4054436
/**
* Copyright © 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package
com.jeespring.common.mapper
;
import
java.io.IOException
;
import
java.util.TimeZone
;
import
org.apache.commons.lang3.StringEscapeUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.fasterxml.jackson.annotation.JsonInclude.Include
;
import
com.fasterxml.jackson.core.JsonGenerator
;
import
com.fasterxml.jackson.core.JsonParser.Feature
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.DeserializationFeature
;
import
com.fasterxml.jackson.databind.JavaType
;
import
com.fasterxml.jackson.databind.JsonSerializer
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.databind.SerializationFeature
;
import
com.fasterxml.jackson.databind.SerializerProvider
;
import
com.fasterxml.jackson.databind.module.SimpleModule
;
import
com.fasterxml.jackson.databind.util.JSONPObject
;
import
com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule
;
/**
* 简单封装Jackson,实现JSON String<->Java Object的Mapper.
* 封装不同的输出风格, 使用不同的builder函数创建实例.
* @author 黄炳桂 516821420@qq.com
* @version 2013-11-15
*/
public
class
JsonMapper
extends
ObjectMapper
{
private
static
final
long
serialVersionUID
=
1L
;
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
JsonMapper
.
class
);
private
static
JsonMapper
mapper
;
public
JsonMapper
()
{
this
(
Include
.
NON_EMPTY
);
}
public
JsonMapper
(
Include
include
)
{
// 设置输出时包含属性的风格
if
(
include
!=
null
)
{
this
.
setSerializationInclusion
(
include
);
}
// 允许单引号、允许不带引号的字段名称
this
.
enableSimple
();
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
this
.
disable
(
DeserializationFeature
.
FAIL_ON_UNKNOWN_PROPERTIES
);
// 空值处理为空串
this
.
getSerializerProvider
().
setNullValueSerializer
(
new
JsonSerializer
<
Object
>(){
@Override
public
void
serialize
(
Object
value
,
JsonGenerator
jgen
,
SerializerProvider
provider
)
throws
IOException
,
JsonProcessingException
{
jgen
.
writeString
(
""
);
}
});
// 进行HTML解码。
this
.
registerModule
(
new
SimpleModule
().
addSerializer
(
String
.
class
,
new
JsonSerializer
<
String
>(){
@Override
public
void
serialize
(
String
value
,
JsonGenerator
jgen
,
SerializerProvider
provider
)
throws
IOException
,
JsonProcessingException
{
jgen
.
writeString
(
StringEscapeUtils
.
unescapeHtml4
(
value
));
}
}));
// 设置时区
this
.
setTimeZone
(
TimeZone
.
getDefault
());
//getTimeZone("GMT+8:00")
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public
static
JsonMapper
getInstance
()
{
if
(
mapper
==
null
){
mapper
=
new
JsonMapper
().
enableSimple
();
}
return
mapper
;
}
/**
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
*/
public
static
JsonMapper
nonDefaultMapper
()
{
if
(
mapper
==
null
){
mapper
=
new
JsonMapper
(
Include
.
NON_DEFAULT
);
}
return
mapper
;
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*/
public
String
toJson
(
Object
object
)
{
try
{
return
this
.
writeValueAsString
(
object
);
}
catch
(
IOException
e
)
{
logger
.
warn
(
"write to json string error:"
+
object
,
e
);
return
null
;
}
}
/**
* 反序列化POJO或简单Collection如List<String>.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
* @see #fromJson(String, JavaType)
*/
public
<
T
>
T
fromJson
(
String
jsonString
,
Class
<
T
>
clazz
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
this
.
readValue
(
jsonString
,
clazz
);
}
catch
(
IOException
e
)
{
logger
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
* @see #createCollectionType(Class, Class...)
*/
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
T
fromJson
(
String
jsonString
,
JavaType
javaType
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
(
T
)
this
.
readValue
(
jsonString
,
javaType
);
}
catch
(
IOException
e
)
{
logger
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
/**
* 構造泛型的Collection Type如:
* ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class)
* HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
*/
public
JavaType
createCollectionType
(
Class
<?>
collectionClass
,
Class
<?>...
elementClasses
)
{
return
this
.
getTypeFactory
().
constructParametricType
(
collectionClass
,
elementClasses
);
}
/**
* 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
*/
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
T
update
(
String
jsonString
,
T
object
)
{
try
{
return
(
T
)
this
.
readerForUpdating
(
object
).
readValue
(
jsonString
);
}
catch
(
JsonProcessingException
e
)
{
logger
.
warn
(
"update json string:"
+
jsonString
+
" to object:"
+
object
+
" error."
,
e
);
}
catch
(
IOException
e
)
{
logger
.
warn
(
"update json string:"
+
jsonString
+
" to object:"
+
object
+
" error."
,
e
);
}
return
null
;
}
/**
* 輸出JSONP格式數據.
*/
public
String
toJsonP
(
String
functionName
,
Object
object
)
{
return
toJson
(
new
JSONPObject
(
functionName
,
object
));
}
/**
* 設定是否使用Enum的toString函數來讀寫Enum,
* 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
* 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
*/
public
JsonMapper
enableEnumUseToString
()
{
this
.
enable
(
SerializationFeature
.
WRITE_ENUMS_USING_TO_STRING
);
this
.
enable
(
DeserializationFeature
.
READ_ENUMS_USING_TO_STRING
);
return
this
;
}
/**
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
*/
public
JsonMapper
enableJaxbAnnotation
()
{
JaxbAnnotationModule
module
=
new
JaxbAnnotationModule
();
this
.
registerModule
(
module
);
return
this
;
}
/**
* 允许单引号
* 允许不带引号的字段名称
*/
public
JsonMapper
enableSimple
()
{
this
.
configure
(
Feature
.
ALLOW_SINGLE_QUOTES
,
true
);
this
.
configure
(
Feature
.
ALLOW_UNQUOTED_FIELD_NAMES
,
true
);
return
this
;
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public
ObjectMapper
getMapper
()
{
return
this
;
}
/**
* 对象转换为JSON字符串
* @param object
* @return
*/
public
static
String
toJsonString
(
Object
object
){
return
JsonMapper
.
getInstance
().
toJson
(
object
);
}
/**
* JSON字符串转换为对象
* @param jsonString
* @param clazz
* @return
*/
public
static
Object
fromJsonString
(
String
jsonString
,
Class
<?>
clazz
){
return
JsonMapper
.
getInstance
().
fromJson
(
jsonString
,
clazz
);
}
/**
* 测试
*/
// public static void main(String[] args) {
// List<Map<String, Object>> list = Lists.newArrayList();
// Map<String, Object> map = Maps.newHashMap();
// map.put("id", 1);
// map.put("pId", -1);
// map.put("name", "根节点");
// list.add(map);
// map = Maps.newHashMap();
// map.put("id", 2);
// map.put("pId", 1);
// map.put("name", "你好");
// map.put("open", true);
// list.add(map);
// String json = JsonMapper.getInstance().toJson(list);
// System.out.println(json);
// }
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mapper/adapters/MapAdapter.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.mapper.adapters
;
import
java.util.HashMap
;
import
java.util.Map
;
import
javax.xml.bind.annotation.adapters.XmlAdapter
;
public
class
MapAdapter
extends
XmlAdapter
<
MapConvertor
,
Map
<
String
,
Object
>>
{
@Override
public
MapConvertor
marshal
(
Map
<
String
,
Object
>
map
)
throws
Exception
{
MapConvertor
convertor
=
new
MapConvertor
();
for
(
Map
.
Entry
<
String
,
Object
>
entry
:
map
.
entrySet
())
{
MapConvertor
.
MapEntry
e
=
new
MapConvertor
.
MapEntry
(
entry
);
convertor
.
addEntry
(
e
);
}
return
convertor
;
}
@Override
public
Map
<
String
,
Object
>
unmarshal
(
MapConvertor
map
)
throws
Exception
{
Map
<
String
,
Object
>
result
=
new
HashMap
<
String
,
Object
>();
for
(
MapConvertor
.
MapEntry
e
:
map
.
getEntries
())
{
result
.
put
(
e
.
getKey
(),
e
.
getValue
());
}
return
result
;
}
}
JeeSpringCloud/jeespring-framework/src/main/java/com/jeespring/common/mapper/adapters/MapConvertor.java
deleted
100644 → 0
View file @
e4054436
package
com.jeespring.common.mapper.adapters
;
import
java.util.ArrayList
;
import
java.util.List
;
import
java.util.Map
;
import
javax.xml.bind.annotation.XmlAccessType
;
import
javax.xml.bind.annotation.XmlAccessorType
;
import
javax.xml.bind.annotation.XmlType
;
@XmlType
(
name
=
"MapConvertor"
)
@XmlAccessorType
(
XmlAccessType
.
FIELD
)
public
class
MapConvertor
{
private
List
<
MapEntry
>
entries
=
new
ArrayList
<
MapEntry
>();
public
void
addEntry
(
MapEntry
entry
)
{
entries
.
add
(
entry
);
}
public
List
<
MapEntry
>
getEntries
()
{
return
entries
;
}
public
static
class
MapEntry
{
private
String
key
;
private
Object
value
;
public
MapEntry
()
{
super
();
}
public
MapEntry
(
Map
.
Entry
<
String
,
Object
>
entry
)
{
super
();
this
.
key
=
entry
.
getKey
();
this
.
value
=
entry
.
getValue
();
}
public
MapEntry
(
String
key
,
Object
value
)
{
super
();
this
.
key
=
key
;
this
.
value
=
value
;
}
public
String
getKey
()
{
return
key
;
}
public
void
setKey
(
String
key
)
{
this
.
key
=
key
;
}
public
Object
getValue
()
{
return
value
;
}
public
void
setValue
(
Object
value
)
{
this
.
value
=
value
;
}
}
}
\ No newline at end of file
Prev
1
…
4
5
6
7
8
9
10
11
12
…
21
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