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
RuoYi Vue
Commits
46444bd0
Commit
46444bd0
authored
Oct 08, 2019
by
RuoYi
Browse files
RuoYi-Vue 1.0
parent
5bc74554
Changes
400
Hide whitespace changes
Inline
Side-by-side
ruoyi/src/main/java/com/ruoyi/framework/datasource/DynamicDataSourceContextHolder.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.datasource
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
/**
* 数据源切换处理
*
* @author ruoyi
*/
public
class
DynamicDataSourceContextHolder
{
public
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
DynamicDataSourceContextHolder
.
class
);
/**
* 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
* 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
*/
private
static
final
ThreadLocal
<
String
>
CONTEXT_HOLDER
=
new
ThreadLocal
<>();
/**
* 设置数据源的变量
*/
public
static
void
setDataSourceType
(
String
dsType
)
{
log
.
info
(
"切换到{}数据源"
,
dsType
);
CONTEXT_HOLDER
.
set
(
dsType
);
}
/**
* 获得数据源的变量
*/
public
static
String
getDataSourceType
()
{
return
CONTEXT_HOLDER
.
get
();
}
/**
* 清空数据源变量
*/
public
static
void
clearDataSourceType
()
{
CONTEXT_HOLDER
.
remove
();
}
}
ruoyi/src/main/java/com/ruoyi/framework/manager/AsyncManager.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.manager
;
import
java.util.TimerTask
;
import
java.util.concurrent.ScheduledExecutorService
;
import
java.util.concurrent.TimeUnit
;
import
com.ruoyi.common.utils.Threads
;
import
com.ruoyi.common.utils.spring.SpringUtils
;
/**
* 异步任务管理器
*
* @author ruoyi
*/
public
class
AsyncManager
{
/**
* 操作延迟10毫秒
*/
private
final
int
OPERATE_DELAY_TIME
=
10
;
/**
* 异步操作任务调度线程池
*/
private
ScheduledExecutorService
executor
=
SpringUtils
.
getBean
(
"scheduledExecutorService"
);
/**
* 单例模式
*/
private
AsyncManager
(){}
private
static
AsyncManager
me
=
new
AsyncManager
();
public
static
AsyncManager
me
()
{
return
me
;
}
/**
* 执行任务
*
* @param task 任务
*/
public
void
execute
(
TimerTask
task
)
{
executor
.
schedule
(
task
,
OPERATE_DELAY_TIME
,
TimeUnit
.
MILLISECONDS
);
}
/**
* 停止任务线程池
*/
public
void
shutdown
()
{
Threads
.
shutdownAndAwaitTermination
(
executor
);
}
}
ruoyi/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.manager
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.stereotype.Component
;
import
javax.annotation.PreDestroy
;
/**
* 确保应用退出时能关闭后台线程
*
* @author ruoyi
*/
@Component
public
class
ShutdownManager
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
"sys-user"
);
@PreDestroy
public
void
destroy
()
{
shutdownAsyncManager
();
}
/**
* 停止异步执行任务
*/
private
void
shutdownAsyncManager
()
{
try
{
logger
.
info
(
"====关闭后台任务任务线程池===="
);
AsyncManager
.
me
().
shutdown
();
}
catch
(
Exception
e
)
{
logger
.
error
(
e
.
getMessage
(),
e
);
}
}
}
ruoyi/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.manager.factory
;
import
java.util.TimerTask
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
com.ruoyi.common.constant.Constants
;
import
com.ruoyi.common.utils.LogUtils
;
import
com.ruoyi.common.utils.ServletUtils
;
import
com.ruoyi.common.utils.ip.AddressUtils
;
import
com.ruoyi.common.utils.ip.IpUtils
;
import
com.ruoyi.common.utils.spring.SpringUtils
;
import
com.ruoyi.project.monitor.domain.SysLogininfor
;
import
com.ruoyi.project.monitor.domain.SysOperLog
;
import
com.ruoyi.project.monitor.service.ISysLogininforService
;
import
com.ruoyi.project.monitor.service.ISysOperLogService
;
import
eu.bitwalker.useragentutils.UserAgent
;
/**
* 异步工厂(产生任务用)
*
* @author ruoyi
*/
public
class
AsyncFactory
{
private
static
final
Logger
sys_user_logger
=
LoggerFactory
.
getLogger
(
"sys-user"
);
/**
* 记录登陆信息
*
* @param username 用户名
* @param status 状态
* @param message 消息
* @param args 列表
* @return 任务task
*/
public
static
TimerTask
recordLogininfor
(
final
String
username
,
final
String
status
,
final
String
message
,
final
Object
...
args
)
{
final
UserAgent
userAgent
=
UserAgent
.
parseUserAgentString
(
ServletUtils
.
getRequest
().
getHeader
(
"User-Agent"
));
final
String
ip
=
IpUtils
.
getIpAddr
(
ServletUtils
.
getRequest
());
return
new
TimerTask
()
{
@Override
public
void
run
()
{
String
address
=
AddressUtils
.
getRealAddressByIP
(
ip
);
StringBuilder
s
=
new
StringBuilder
();
s
.
append
(
LogUtils
.
getBlock
(
ip
));
s
.
append
(
address
);
s
.
append
(
LogUtils
.
getBlock
(
username
));
s
.
append
(
LogUtils
.
getBlock
(
status
));
s
.
append
(
LogUtils
.
getBlock
(
message
));
// 打印信息到日志
sys_user_logger
.
info
(
s
.
toString
(),
args
);
// 获取客户端操作系统
String
os
=
userAgent
.
getOperatingSystem
().
getName
();
// 获取客户端浏览器
String
browser
=
userAgent
.
getBrowser
().
getName
();
// 封装对象
SysLogininfor
logininfor
=
new
SysLogininfor
();
logininfor
.
setUserName
(
username
);
logininfor
.
setIpaddr
(
ip
);
logininfor
.
setLoginLocation
(
address
);
logininfor
.
setBrowser
(
browser
);
logininfor
.
setOs
(
os
);
logininfor
.
setMsg
(
message
);
// 日志状态
if
(
Constants
.
LOGIN_SUCCESS
.
equals
(
status
)
||
Constants
.
LOGOUT
.
equals
(
status
))
{
logininfor
.
setStatus
(
Constants
.
SUCCESS
);
}
else
if
(
Constants
.
LOGIN_FAIL
.
equals
(
status
))
{
logininfor
.
setStatus
(
Constants
.
FAIL
);
}
// 插入数据
SpringUtils
.
getBean
(
ISysLogininforService
.
class
).
insertLogininfor
(
logininfor
);
}
};
}
/**
* 操作日志记录
*
* @param operLog 操作日志信息
* @return 任务task
*/
public
static
TimerTask
recordOper
(
final
SysOperLog
operLog
)
{
return
new
TimerTask
()
{
@Override
public
void
run
()
{
// 远程查询操作地点
operLog
.
setOperLocation
(
AddressUtils
.
getRealAddressByIP
(
operLog
.
getOperIp
()));
SpringUtils
.
getBean
(
ISysOperLogService
.
class
).
insertOperlog
(
operLog
);
}
};
}
}
ruoyi/src/main/java/com/ruoyi/framework/redis/RedisCache.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.redis
;
import
java.util.ArrayList
;
import
java.util.Collection
;
import
java.util.HashSet
;
import
java.util.Iterator
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.Set
;
import
java.util.concurrent.TimeUnit
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.data.redis.core.BoundSetOperations
;
import
org.springframework.data.redis.core.HashOperations
;
import
org.springframework.data.redis.core.ListOperations
;
import
org.springframework.data.redis.core.RedisTemplate
;
import
org.springframework.data.redis.core.ValueOperations
;
import
org.springframework.stereotype.Component
;
/**
* spring redis 工具类
*
* @author ruoyi
**/
@SuppressWarnings
(
value
=
{
"unchecked"
,
"rawtypes"
})
@Component
public
class
RedisCache
{
@Autowired
public
RedisTemplate
redisTemplate
;
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @return 缓存的对象
*/
public
<
T
>
ValueOperations
<
String
,
T
>
setCacheObject
(
String
key
,
T
value
)
{
ValueOperations
<
String
,
T
>
operation
=
redisTemplate
.
opsForValue
();
operation
.
set
(
key
,
value
);
return
operation
;
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
* @return 缓存的对象
*/
public
<
T
>
ValueOperations
<
String
,
T
>
setCacheObject
(
String
key
,
T
value
,
Integer
timeout
,
TimeUnit
timeUnit
)
{
ValueOperations
<
String
,
T
>
operation
=
redisTemplate
.
opsForValue
();
operation
.
set
(
key
,
value
,
timeout
,
timeUnit
);
return
operation
;
}
/**
* 获得缓存的基本对象。
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public
<
T
>
T
getCacheObject
(
String
key
)
{
ValueOperations
<
String
,
T
>
operation
=
redisTemplate
.
opsForValue
();
return
operation
.
get
(
key
);
}
/**
* 删除单个对象
*
* @param key
*/
public
void
deleteObject
(
String
key
)
{
redisTemplate
.
delete
(
key
);
}
/**
* 删除集合对象
*
* @param collection
*/
public
void
deleteObject
(
Collection
collection
)
{
redisTemplate
.
delete
(
collection
);
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public
<
T
>
ListOperations
<
String
,
T
>
setCacheList
(
String
key
,
List
<
T
>
dataList
)
{
ListOperations
listOperation
=
redisTemplate
.
opsForList
();
if
(
null
!=
dataList
)
{
int
size
=
dataList
.
size
();
for
(
int
i
=
0
;
i
<
size
;
i
++)
{
listOperation
.
leftPush
(
key
,
dataList
.
get
(
i
));
}
}
return
listOperation
;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public
<
T
>
List
<
T
>
getCacheList
(
String
key
)
{
List
<
T
>
dataList
=
new
ArrayList
<
T
>();
ListOperations
<
String
,
T
>
listOperation
=
redisTemplate
.
opsForList
();
Long
size
=
listOperation
.
size
(
key
);
for
(
int
i
=
0
;
i
<
size
;
i
++)
{
dataList
.
add
(
listOperation
.
index
(
key
,
i
));
}
return
dataList
;
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public
<
T
>
BoundSetOperations
<
String
,
T
>
setCacheSet
(
String
key
,
Set
<
T
>
dataSet
)
{
BoundSetOperations
<
String
,
T
>
setOperation
=
redisTemplate
.
boundSetOps
(
key
);
Iterator
<
T
>
it
=
dataSet
.
iterator
();
while
(
it
.
hasNext
())
{
setOperation
.
add
(
it
.
next
());
}
return
setOperation
;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public
<
T
>
Set
<
T
>
getCacheSet
(
String
key
)
{
Set
<
T
>
dataSet
=
new
HashSet
<
T
>();
BoundSetOperations
<
String
,
T
>
operation
=
redisTemplate
.
boundSetOps
(
key
);
Long
size
=
operation
.
size
();
for
(
int
i
=
0
;
i
<
size
;
i
++)
{
dataSet
.
add
(
operation
.
pop
());
}
return
dataSet
;
}
/**
* 缓存Map
*
* @param key
* @param dataMap
* @return
*/
public
<
T
>
HashOperations
<
String
,
String
,
T
>
setCacheMap
(
String
key
,
Map
<
String
,
T
>
dataMap
)
{
HashOperations
hashOperations
=
redisTemplate
.
opsForHash
();
if
(
null
!=
dataMap
)
{
for
(
Map
.
Entry
<
String
,
T
>
entry
:
dataMap
.
entrySet
())
{
hashOperations
.
put
(
key
,
entry
.
getKey
(),
entry
.
getValue
());
}
}
return
hashOperations
;
}
/**
* 获得缓存的Map
*
* @param key
* @return
*/
public
<
T
>
Map
<
String
,
T
>
getCacheMap
(
String
key
)
{
Map
<
String
,
T
>
map
=
redisTemplate
.
opsForHash
().
entries
(
key
);
return
map
;
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/LoginUser.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security
;
import
java.util.Collection
;
import
java.util.Set
;
import
org.springframework.security.core.GrantedAuthority
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
com.fasterxml.jackson.annotation.JsonIgnore
;
import
com.ruoyi.project.system.domain.SysUser
;
/**
* 登录用户身份权限
*
* @author ruoyi
*/
public
class
LoginUser
implements
UserDetails
{
private
static
final
long
serialVersionUID
=
1L
;
/**
* 用户唯一标识
*/
private
String
token
;
/**
* 登陆时间
*/
private
Long
loginTime
;
/**
* 过期时间
*/
private
Long
expireTime
;
/**
* 权限列表
*/
private
Set
<
String
>
permissions
;
/**
* 用户信息
*/
private
SysUser
user
;
public
String
getToken
()
{
return
token
;
}
public
void
setToken
(
String
token
)
{
this
.
token
=
token
;
}
public
LoginUser
()
{
}
public
LoginUser
(
SysUser
user
,
Set
<
String
>
permissions
)
{
this
.
user
=
user
;
this
.
permissions
=
permissions
;
}
@JsonIgnore
@Override
public
String
getPassword
()
{
return
user
.
getPassword
();
}
@Override
public
String
getUsername
()
{
return
user
.
getUserName
();
}
/**
* 账户是否未过期,过期无法验证
*/
@JsonIgnore
@Override
public
boolean
isAccountNonExpired
()
{
return
true
;
}
/**
* 指定用户是否解锁,锁定的用户无法进行身份验证
*
* @return
*/
@JsonIgnore
@Override
public
boolean
isAccountNonLocked
()
{
return
true
;
}
/**
* 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
*
* @return
*/
@JsonIgnore
@Override
public
boolean
isCredentialsNonExpired
()
{
return
true
;
}
/**
* 是否可用 ,禁用的用户不能身份验证
*
* @return
*/
@JsonIgnore
@Override
public
boolean
isEnabled
()
{
return
true
;
}
public
Long
getLoginTime
()
{
return
loginTime
;
}
public
void
setLoginTime
(
Long
loginTime
)
{
this
.
loginTime
=
loginTime
;
}
public
Long
getExpireTime
()
{
return
expireTime
;
}
public
void
setExpireTime
(
Long
expireTime
)
{
this
.
expireTime
=
expireTime
;
}
public
Set
<
String
>
getPermissions
()
{
return
permissions
;
}
public
void
setPermissions
(
Set
<
String
>
permissions
)
{
this
.
permissions
=
permissions
;
}
public
SysUser
getUser
()
{
return
user
;
}
public
void
setUser
(
SysUser
user
)
{
this
.
user
=
user
;
}
@Override
public
Collection
<?
extends
GrantedAuthority
>
getAuthorities
()
{
return
null
;
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/filter/JwtAuthenticationTokenFilter.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.filter
;
import
java.io.IOException
;
import
javax.servlet.FilterChain
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.context.SecurityContextHolder
;
import
org.springframework.security.web.authentication.WebAuthenticationDetailsSource
;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.filter.OncePerRequestFilter
;
import
com.ruoyi.common.utils.SecurityUtils
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.framework.security.LoginUser
;
import
com.ruoyi.framework.security.service.TokenService
;
/**
* token过滤器 验证token有效性
*
* @author ruoyi
*/
@Component
public
class
JwtAuthenticationTokenFilter
extends
OncePerRequestFilter
{
@Autowired
private
TokenService
tokenService
;
@Override
protected
void
doFilterInternal
(
HttpServletRequest
request
,
HttpServletResponse
response
,
FilterChain
chain
)
throws
ServletException
,
IOException
{
LoginUser
loginUser
=
tokenService
.
getLoginUser
(
request
);
if
(
StringUtils
.
isNotNull
(
loginUser
)
&&
StringUtils
.
isNull
(
SecurityUtils
.
getAuthentication
()))
{
tokenService
.
verifyToken
(
loginUser
);
UsernamePasswordAuthenticationToken
authenticationToken
=
new
UsernamePasswordAuthenticationToken
(
loginUser
,
null
,
loginUser
.
getAuthorities
());
authenticationToken
.
setDetails
(
new
WebAuthenticationDetailsSource
().
buildDetails
(
request
));
SecurityContextHolder
.
getContext
().
setAuthentication
(
authenticationToken
);
}
chain
.
doFilter
(
request
,
response
);
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/handle/AuthenticationEntryPointImpl.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.handle
;
import
java.io.IOException
;
import
java.io.Serializable
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.springframework.security.core.AuthenticationException
;
import
org.springframework.security.web.AuthenticationEntryPoint
;
import
org.springframework.stereotype.Component
;
import
com.alibaba.fastjson.JSON
;
import
com.ruoyi.common.constant.HttpStatus
;
import
com.ruoyi.common.utils.ServletUtils
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.framework.web.domain.AjaxResult
;
/**
* 认证失败处理类 返回未授权
*
* @author ruoyi
*/
@Component
public
class
AuthenticationEntryPointImpl
implements
AuthenticationEntryPoint
,
Serializable
{
private
static
final
long
serialVersionUID
=
-
8970718410437077606L
;
@Override
public
void
commence
(
HttpServletRequest
request
,
HttpServletResponse
response
,
AuthenticationException
e
)
throws
IOException
{
int
code
=
HttpStatus
.
UNAUTHORIZED
;
String
msg
=
StringUtils
.
format
(
"请求访问:{},认证失败,无法访问系统资源"
,
request
.
getRequestURI
());
ServletUtils
.
renderString
(
response
,
JSON
.
toJSONString
(
AjaxResult
.
error
(
code
,
msg
)));
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/handle/LogoutSuccessHandlerImpl.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.handle
;
import
java.io.IOException
;
import
javax.servlet.ServletException
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.security.web.authentication.logout.LogoutSuccessHandler
;
import
com.alibaba.fastjson.JSON
;
import
com.ruoyi.common.constant.Constants
;
import
com.ruoyi.common.constant.HttpStatus
;
import
com.ruoyi.common.utils.ServletUtils
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.framework.manager.AsyncManager
;
import
com.ruoyi.framework.manager.factory.AsyncFactory
;
import
com.ruoyi.framework.security.LoginUser
;
import
com.ruoyi.framework.security.service.TokenService
;
import
com.ruoyi.framework.web.domain.AjaxResult
;
/**
* 自定义退出处理类 返回成功
*
* @author ruoyi
*/
@Configuration
public
class
LogoutSuccessHandlerImpl
implements
LogoutSuccessHandler
{
@Autowired
private
TokenService
tokenService
;
/**
* 退出处理
*
* @return
*/
@Override
public
void
onLogoutSuccess
(
HttpServletRequest
request
,
HttpServletResponse
response
,
Authentication
authentication
)
throws
IOException
,
ServletException
{
LoginUser
loginUser
=
tokenService
.
getLoginUser
(
request
);
if
(
StringUtils
.
isNotNull
(
loginUser
))
{
String
userName
=
loginUser
.
getUsername
();
// 记录用户退出日志
AsyncManager
.
me
().
execute
(
AsyncFactory
.
recordLogininfor
(
userName
,
Constants
.
LOGOUT
,
"退出成功"
));
}
ServletUtils
.
renderString
(
response
,
JSON
.
toJSONString
(
AjaxResult
.
error
(
HttpStatus
.
SUCCESS
,
"退出成功"
)));
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/service/PermissionService.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.service
;
import
java.util.Set
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Service
;
import
org.springframework.util.CollectionUtils
;
import
com.ruoyi.common.utils.ServletUtils
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.framework.security.LoginUser
;
import
com.ruoyi.project.system.domain.SysRole
;
/**
* RuoYi首创 自定义权限实现,se取自SpringSecurity首字母
*
* @author ruoyi
*/
@Service
(
"ss"
)
public
class
PermissionService
{
/** 所有权限标识 */
private
static
final
String
ALL_PERMISSION
=
"*:*:*"
;
/** 管理员角色权限标识 */
private
static
final
String
SUPER_ADMIN
=
"admin"
;
private
static
final
String
ROLE_DELIMETER
=
","
;
private
static
final
String
PERMISSION_DELIMETER
=
","
;
@Autowired
private
TokenService
tokenService
;
/**
* 验证用户是否具备某权限
*
* @param permission 权限字符串
* @return 用户是否具备某权限
*/
public
boolean
hasPermi
(
String
permission
)
{
if
(
StringUtils
.
isEmpty
(
permission
))
{
return
false
;
}
LoginUser
loginUser
=
tokenService
.
getLoginUser
(
ServletUtils
.
getRequest
());
if
(
StringUtils
.
isNull
(
loginUser
)
||
CollectionUtils
.
isEmpty
(
loginUser
.
getPermissions
()))
{
return
false
;
}
return
hasPermissions
(
loginUser
.
getPermissions
(),
permission
);
}
/**
* 验证用户是否不具备某权限,与 hasPermi逻辑相反
*
* @param permission 权限字符串
* @return 用户是否不具备某权限
*/
public
boolean
lacksPermi
(
String
permission
)
{
return
hasPermi
(
permission
)
!=
true
;
}
/**
* 验证用户是否具有以下任意一个权限
*
* @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表
* @return 用户是否具有以下任意一个权限
*/
public
boolean
hasAnyPermi
(
String
permissions
)
{
if
(
StringUtils
.
isEmpty
(
permissions
))
{
return
false
;
}
LoginUser
loginUser
=
tokenService
.
getLoginUser
(
ServletUtils
.
getRequest
());
if
(
StringUtils
.
isNull
(
loginUser
)
||
CollectionUtils
.
isEmpty
(
loginUser
.
getPermissions
()))
{
return
false
;
}
Set
<
String
>
authorities
=
loginUser
.
getPermissions
();
for
(
String
permission
:
permissions
.
split
(
PERMISSION_DELIMETER
))
{
if
(
permission
!=
null
&&
hasPermissions
(
authorities
,
permission
))
{
return
true
;
}
}
return
false
;
}
/**
* 判断用户是否拥有某个角色
*
* @param role 角色字符串
* @return 用户是否具备某角色
*/
public
boolean
hasRole
(
String
role
)
{
if
(
StringUtils
.
isEmpty
(
role
))
{
return
false
;
}
LoginUser
loginUser
=
tokenService
.
getLoginUser
(
ServletUtils
.
getRequest
());
if
(
StringUtils
.
isNull
(
loginUser
)
||
CollectionUtils
.
isEmpty
(
loginUser
.
getUser
().
getRoles
()))
{
return
false
;
}
for
(
SysRole
sysRole
:
loginUser
.
getUser
().
getRoles
())
{
String
roleKey
=
sysRole
.
getRoleKey
();
if
(
SUPER_ADMIN
.
contains
(
roleKey
)
||
roleKey
.
contains
(
StringUtils
.
trim
(
role
)))
{
return
true
;
}
}
return
false
;
}
/**
* 验证用户是否不具备某角色,与 isRole逻辑相反。
*
* @param role 角色名称
* @return 用户是否不具备某角色
*/
public
boolean
lacksRole
(
String
role
)
{
return
hasRole
(
role
)
!=
true
;
}
/**
* 验证用户是否具有以下任意一个角色
*
* @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表
* @return 用户是否具有以下任意一个角色
*/
public
boolean
hasAnyRoles
(
String
roles
)
{
if
(
StringUtils
.
isEmpty
(
roles
))
{
return
false
;
}
LoginUser
loginUser
=
tokenService
.
getLoginUser
(
ServletUtils
.
getRequest
());
if
(
StringUtils
.
isNull
(
loginUser
)
||
CollectionUtils
.
isEmpty
(
loginUser
.
getUser
().
getRoles
()))
{
return
false
;
}
for
(
String
role
:
roles
.
split
(
ROLE_DELIMETER
))
{
if
(
hasRole
(
role
))
{
return
true
;
}
}
return
false
;
}
/**
* 判断是否包含权限
*
* @param permissions 权限列表
* @param permission 权限字符串
* @return 用户是否具备某权限
*/
private
boolean
hasPermissions
(
Set
<
String
>
permissions
,
String
permission
)
{
return
permissions
.
contains
(
ALL_PERMISSION
)
||
permissions
.
contains
(
StringUtils
.
trim
(
permission
));
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/service/SysLoginService.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.service
;
import
javax.annotation.Resource
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.authentication.AuthenticationManager
;
import
org.springframework.security.authentication.BadCredentialsException
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.stereotype.Component
;
import
com.ruoyi.common.constant.Constants
;
import
com.ruoyi.common.exception.CustomException
;
import
com.ruoyi.common.exception.user.CaptchaException
;
import
com.ruoyi.common.exception.user.CaptchaExpireException
;
import
com.ruoyi.common.exception.user.UserPasswordNotMatchException
;
import
com.ruoyi.common.utils.MessageUtils
;
import
com.ruoyi.framework.manager.AsyncManager
;
import
com.ruoyi.framework.manager.factory.AsyncFactory
;
import
com.ruoyi.framework.redis.RedisCache
;
import
com.ruoyi.framework.security.LoginUser
;
/**
* 登录校验方法
*
* @author ruoyi
*/
@Component
public
class
SysLoginService
{
@Autowired
private
TokenService
tokenService
;
@Resource
private
AuthenticationManager
authenticationManager
;
@Autowired
private
RedisCache
redisCache
;
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @param captcha 验证码
* @param uuid 唯一标识
* @return 结果
*/
public
String
login
(
String
username
,
String
password
,
String
code
,
String
uuid
)
{
String
verifyKey
=
Constants
.
CAPTCHA_CODE_KEY
+
uuid
;
String
captcha
=
redisCache
.
getCacheObject
(
verifyKey
);
redisCache
.
deleteObject
(
verifyKey
);
if
(
captcha
==
null
)
{
AsyncManager
.
me
().
execute
(
AsyncFactory
.
recordLogininfor
(
username
,
Constants
.
LOGIN_FAIL
,
MessageUtils
.
message
(
"user.jcaptcha.error"
)));
throw
new
CaptchaExpireException
();
}
if
(!
code
.
equalsIgnoreCase
(
captcha
))
{
AsyncManager
.
me
().
execute
(
AsyncFactory
.
recordLogininfor
(
username
,
Constants
.
LOGIN_FAIL
,
MessageUtils
.
message
(
"user.jcaptcha.expire"
)));
throw
new
CaptchaException
();
}
// 用户验证
Authentication
authentication
=
null
;
try
{
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication
=
authenticationManager
.
authenticate
(
new
UsernamePasswordAuthenticationToken
(
username
,
password
));
}
catch
(
Exception
e
)
{
if
(
e
instanceof
BadCredentialsException
)
{
AsyncManager
.
me
().
execute
(
AsyncFactory
.
recordLogininfor
(
username
,
Constants
.
LOGIN_FAIL
,
MessageUtils
.
message
(
"user.password.not.match"
)));
throw
new
UserPasswordNotMatchException
();
}
else
{
AsyncManager
.
me
().
execute
(
AsyncFactory
.
recordLogininfor
(
username
,
Constants
.
LOGIN_FAIL
,
e
.
getMessage
()));
throw
new
CustomException
(
e
.
getMessage
());
}
}
AsyncManager
.
me
().
execute
(
AsyncFactory
.
recordLogininfor
(
username
,
Constants
.
LOGIN_SUCCESS
,
MessageUtils
.
message
(
"user.login.success"
)));
LoginUser
loginUser
=
(
LoginUser
)
authentication
.
getPrincipal
();
// 生成token
return
tokenService
.
createToken
(
loginUser
);
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/service/SysPermissionService.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.service
;
import
java.util.HashSet
;
import
java.util.Set
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Component
;
import
com.ruoyi.project.system.domain.SysUser
;
import
com.ruoyi.project.system.service.ISysMenuService
;
import
com.ruoyi.project.system.service.ISysRoleService
;
/**
* 用户权限处理
*
* @author ruoyi
*/
@Component
public
class
SysPermissionService
{
@Autowired
private
ISysRoleService
roleService
;
@Autowired
private
ISysMenuService
menuService
;
/**
* 获取角色数据权限
*
* @param user 用户信息
* @return 角色权限信息
*/
public
Set
<
String
>
getRolePermission
(
SysUser
user
)
{
Set
<
String
>
roles
=
new
HashSet
<
String
>();
// 管理员拥有所有权限
if
(
user
.
isAdmin
())
{
roles
.
add
(
"admin"
);
}
else
{
roles
.
addAll
(
roleService
.
selectRolePermissionByUserId
(
user
.
getUserId
()));
}
return
roles
;
}
/**
* 获取菜单数据权限
*
* @param user 用户信息
* @return 菜单权限信息
*/
public
Set
<
String
>
getMenuPermission
(
SysUser
user
)
{
Set
<
String
>
roles
=
new
HashSet
<
String
>();
// 管理员拥有所有权限
if
(
user
.
isAdmin
())
{
roles
.
add
(
"*:*:*"
);
}
else
{
roles
.
addAll
(
menuService
.
selectMenuPermsByUserId
(
user
.
getUserId
()));
}
return
roles
;
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/service/TokenService.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.service
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.concurrent.TimeUnit
;
import
javax.servlet.http.HttpServletRequest
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.stereotype.Component
;
import
com.ruoyi.common.constant.Constants
;
import
com.ruoyi.common.utils.IdUtils
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.framework.redis.RedisCache
;
import
com.ruoyi.framework.security.LoginUser
;
import
io.jsonwebtoken.Claims
;
import
io.jsonwebtoken.Jwts
;
import
io.jsonwebtoken.SignatureAlgorithm
;
/**
* token验证处理
*
* @author ruoyi
*/
@Component
public
class
TokenService
{
// 令牌自定义标识
@Value
(
"${token.header}"
)
private
String
header
;
// 令牌秘钥
@Value
(
"${token.secret}"
)
private
String
secret
;
// 令牌有效期(默认30分钟)
@Value
(
"${token.expireTime}"
)
private
int
expireTime
;
protected
static
final
long
MILLIS_SECOND
=
1000
;
protected
static
final
long
MILLIS_MINUTE
=
60
*
MILLIS_SECOND
;
private
static
final
Long
MILLIS_MINUTE_TEN
=
20
*
60
*
1000L
;
@Autowired
private
RedisCache
redisCache
;
/**
* 获取用户身份信息
*
* @return 用户信息
*/
public
LoginUser
getLoginUser
(
HttpServletRequest
request
)
{
// 获取请求携带的令牌
String
token
=
getToken
(
request
);
if
(
StringUtils
.
isNotEmpty
(
token
))
{
Claims
claims
=
parseToken
(
token
);
// 解析对应的权限以及用户信息
String
uuid
=
(
String
)
claims
.
get
(
Constants
.
LOGIN_USER_KEY
);
String
userKey
=
getTokenKey
(
uuid
);
LoginUser
user
=
redisCache
.
getCacheObject
(
userKey
);
return
user
;
}
return
null
;
}
/**
* 创建令牌
*
* @param loginUser 用户信息
* @return 令牌
*/
public
String
createToken
(
LoginUser
loginUser
)
{
String
token
=
IdUtils
.
fastUUID
();
loginUser
.
setToken
(
token
);
refreshToken
(
loginUser
);
Map
<
String
,
Object
>
claims
=
new
HashMap
<>();
claims
.
put
(
Constants
.
LOGIN_USER_KEY
,
token
);
return
createToken
(
claims
);
}
/**
* 验证令牌有效期,相差不足20分钟,自动刷新缓存
*
* @param token 令牌
* @return 令牌
*/
public
void
verifyToken
(
LoginUser
loginUser
)
{
long
expireTime
=
loginUser
.
getExpireTime
();
long
currentTime
=
System
.
currentTimeMillis
();
if
(
expireTime
-
currentTime
<=
MILLIS_MINUTE_TEN
)
{
String
token
=
loginUser
.
getToken
();
loginUser
.
setToken
(
token
);
refreshToken
(
loginUser
);
}
}
/**
* 刷新令牌有效期
*
* @param token 令牌
* @return 令牌
*/
public
void
refreshToken
(
LoginUser
loginUser
)
{
loginUser
.
setLoginTime
(
System
.
currentTimeMillis
());
loginUser
.
setExpireTime
(
loginUser
.
getLoginTime
()
+
expireTime
*
MILLIS_MINUTE
);
// 根据uuid将loginUser缓存
String
userKey
=
getTokenKey
(
loginUser
.
getToken
());
redisCache
.
setCacheObject
(
userKey
,
loginUser
,
expireTime
,
TimeUnit
.
MINUTES
);
}
/**
* 从数据声明生成令牌
*
* @param claims 数据声明
* @return 令牌
*/
private
String
createToken
(
Map
<
String
,
Object
>
claims
)
{
String
token
=
Jwts
.
builder
()
.
setClaims
(
claims
)
.
signWith
(
SignatureAlgorithm
.
HS512
,
secret
).
compact
();
return
token
;
}
/**
* 从令牌中获取数据声明
*
* @param token 令牌
* @return 数据声明
*/
private
Claims
parseToken
(
String
token
)
{
return
Jwts
.
parser
()
.
setSigningKey
(
secret
)
.
parseClaimsJws
(
token
)
.
getBody
();
}
/**
* 从令牌中获取用户名
*
* @param token 令牌
* @return 用户名
*/
public
String
getUsernameFromToken
(
String
token
)
{
Claims
claims
=
parseToken
(
token
);
return
claims
.
getSubject
();
}
/**
* 获取请求token
*
* @param request
* @return token
*/
private
String
getToken
(
HttpServletRequest
request
)
{
String
token
=
request
.
getHeader
(
header
);
if
(
StringUtils
.
isNotEmpty
(
token
)
&&
token
.
startsWith
(
Constants
.
TOKEN_PREFIX
))
{
token
=
token
.
replace
(
Constants
.
TOKEN_PREFIX
,
""
);
}
return
token
;
}
private
String
getTokenKey
(
String
uuid
)
{
return
Constants
.
LOGIN_TOKEN_KEY
+
uuid
;
}
}
ruoyi/src/main/java/com/ruoyi/framework/security/service/UserDetailsServiceImpl.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.security.service
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.security.core.userdetails.UserDetails
;
import
org.springframework.security.core.userdetails.UserDetailsService
;
import
org.springframework.security.core.userdetails.UsernameNotFoundException
;
import
org.springframework.stereotype.Service
;
import
com.ruoyi.common.enums.UserStatus
;
import
com.ruoyi.common.exception.BaseException
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.framework.security.LoginUser
;
import
com.ruoyi.project.system.domain.SysUser
;
import
com.ruoyi.project.system.service.ISysUserService
;
/**
* 用户验证处理
*
* @author ruoyi
*/
@Service
public
class
UserDetailsServiceImpl
implements
UserDetailsService
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
UserDetailsServiceImpl
.
class
);
@Autowired
private
ISysUserService
userService
;
@Autowired
private
SysPermissionService
permissionService
;
@Override
public
UserDetails
loadUserByUsername
(
String
username
)
throws
UsernameNotFoundException
{
SysUser
user
=
userService
.
selectUserByUserName
(
username
);
if
(
StringUtils
.
isNull
(
user
))
{
log
.
info
(
"登录用户:{} 不存在."
,
username
);
throw
new
UsernameNotFoundException
(
"登录用户:"
+
username
+
" 不存在"
);
}
else
if
(
UserStatus
.
DELETED
.
getCode
().
equals
(
user
.
getDelFlag
()))
{
log
.
info
(
"登录用户:{} 已被删除."
,
username
);
throw
new
BaseException
(
"对不起,您的账号:"
+
username
+
" 已被删除"
);
}
else
if
(
UserStatus
.
DISABLE
.
getCode
().
equals
(
user
.
getStatus
()))
{
log
.
info
(
"登录用户:{} 已被停用."
,
username
);
throw
new
BaseException
(
"对不起,您的账号:"
+
username
+
" 已停用"
);
}
return
createLoginUser
(
user
);
}
public
UserDetails
createLoginUser
(
SysUser
user
)
{
return
new
LoginUser
(
user
,
permissionService
.
getMenuPermission
(
user
));
}
}
ruoyi/src/main/java/com/ruoyi/framework/web/controller/BaseController.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.web.controller
;
import
java.beans.PropertyEditorSupport
;
import
java.util.Date
;
import
java.util.List
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.web.bind.WebDataBinder
;
import
org.springframework.web.bind.annotation.InitBinder
;
import
com.github.pagehelper.PageHelper
;
import
com.github.pagehelper.PageInfo
;
import
com.ruoyi.common.constant.HttpStatus
;
import
com.ruoyi.common.utils.DateUtils
;
import
com.ruoyi.common.utils.StringUtils
;
import
com.ruoyi.common.utils.sql.SqlUtil
;
import
com.ruoyi.framework.web.domain.AjaxResult
;
import
com.ruoyi.framework.web.page.PageDomain
;
import
com.ruoyi.framework.web.page.TableDataInfo
;
import
com.ruoyi.framework.web.page.TableSupport
;
/**
* web层通用数据处理
*
* @author ruoyi
*/
public
class
BaseController
{
protected
final
Logger
logger
=
LoggerFactory
.
getLogger
(
BaseController
.
class
);
/**
* 将前台传递过来的日期格式的字符串,自动转化为Date类型
*/
@InitBinder
public
void
initBinder
(
WebDataBinder
binder
)
{
// Date 类型转换
binder
.
registerCustomEditor
(
Date
.
class
,
new
PropertyEditorSupport
()
{
@Override
public
void
setAsText
(
String
text
)
{
setValue
(
DateUtils
.
parseDate
(
text
));
}
});
}
/**
* 设置请求分页数据
*/
protected
void
startPage
()
{
PageDomain
pageDomain
=
TableSupport
.
buildPageRequest
();
Integer
pageNum
=
pageDomain
.
getPageNum
();
Integer
pageSize
=
pageDomain
.
getPageSize
();
if
(
StringUtils
.
isNotNull
(
pageNum
)
&&
StringUtils
.
isNotNull
(
pageSize
))
{
String
orderBy
=
SqlUtil
.
escapeOrderBySql
(
pageDomain
.
getOrderBy
());
PageHelper
.
startPage
(
pageNum
,
pageSize
,
orderBy
);
}
}
/**
* 响应请求分页数据
*/
@SuppressWarnings
({
"rawtypes"
,
"unchecked"
})
protected
TableDataInfo
getDataTable
(
List
<?>
list
)
{
TableDataInfo
rspData
=
new
TableDataInfo
();
rspData
.
setCode
(
HttpStatus
.
SUCCESS
);
rspData
.
setRows
(
list
);
rspData
.
setTotal
(
new
PageInfo
(
list
).
getTotal
());
return
rspData
;
}
/**
* 响应返回结果
*
* @param rows 影响行数
* @return 操作结果
*/
protected
AjaxResult
toAjax
(
int
rows
)
{
return
rows
>
0
?
AjaxResult
.
success
()
:
AjaxResult
.
error
();
}
}
ruoyi/src/main/java/com/ruoyi/framework/web/domain/AjaxResult.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.web.domain
;
import
java.util.HashMap
;
import
com.ruoyi.common.constant.HttpStatus
;
import
com.ruoyi.common.utils.StringUtils
;
/**
* 操作消息提醒
*
* @author ruoyi
*/
public
class
AjaxResult
extends
HashMap
<
String
,
Object
>
{
private
static
final
long
serialVersionUID
=
1L
;
/** 状态码 */
public
static
final
String
CODE_TAG
=
"code"
;
/** 返回内容 */
public
static
final
String
MSG_TAG
=
"msg"
;
/** 数据对象 */
public
static
final
String
DATA_TAG
=
"data"
;
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public
AjaxResult
()
{
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public
AjaxResult
(
int
code
,
String
msg
)
{
super
.
put
(
CODE_TAG
,
code
);
super
.
put
(
MSG_TAG
,
msg
);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public
AjaxResult
(
int
code
,
String
msg
,
Object
data
)
{
super
.
put
(
CODE_TAG
,
code
);
super
.
put
(
MSG_TAG
,
msg
);
if
(
StringUtils
.
isNotNull
(
data
))
{
super
.
put
(
DATA_TAG
,
data
);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public
static
AjaxResult
success
()
{
return
AjaxResult
.
success
(
"操作成功"
);
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public
static
AjaxResult
success
(
Object
data
)
{
return
AjaxResult
.
success
(
"操作成功"
,
data
);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public
static
AjaxResult
success
(
String
msg
)
{
return
AjaxResult
.
success
(
msg
,
null
);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public
static
AjaxResult
success
(
String
msg
,
Object
data
)
{
return
new
AjaxResult
(
HttpStatus
.
SUCCESS
,
msg
,
data
);
}
/**
* 返回错误消息
*
* @return
*/
public
static
AjaxResult
error
()
{
return
AjaxResult
.
error
(
"操作失败"
);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public
static
AjaxResult
error
(
String
msg
)
{
return
AjaxResult
.
error
(
msg
,
null
);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public
static
AjaxResult
error
(
String
msg
,
Object
data
)
{
return
new
AjaxResult
(
HttpStatus
.
ERROR
,
msg
,
data
);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public
static
AjaxResult
error
(
int
code
,
String
msg
)
{
return
new
AjaxResult
(
code
,
msg
,
null
);
}
}
ruoyi/src/main/java/com/ruoyi/framework/web/domain/BaseEntity.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.web.domain
;
import
java.io.Serializable
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.Map
;
import
com.alibaba.fastjson.JSON
;
import
com.fasterxml.jackson.annotation.JsonFormat
;
import
com.fasterxml.jackson.annotation.JsonIgnore
;
/**
* Entity基类
*
* @author ruoyi
*/
public
class
BaseEntity
implements
Serializable
{
private
static
final
long
serialVersionUID
=
1L
;
/** 搜索值 */
private
String
searchValue
;
/** 创建者 */
private
String
createBy
;
/** 创建时间 */
@JsonFormat
(
pattern
=
"yyyy-MM-dd HH:mm:ss"
)
private
Date
createTime
;
/** 更新者 */
private
String
updateBy
;
/** 更新时间 */
@JsonFormat
(
pattern
=
"yyyy-MM-dd HH:mm:ss"
)
private
Date
updateTime
;
/** 备注 */
private
String
remark
;
/** 数据权限 */
private
String
dataScope
;
/** 请求参数 */
@JsonIgnore
private
String
params
;
public
String
getSearchValue
()
{
return
searchValue
;
}
public
void
setSearchValue
(
String
searchValue
)
{
this
.
searchValue
=
searchValue
;
}
public
String
getCreateBy
()
{
return
createBy
;
}
public
void
setCreateBy
(
String
createBy
)
{
this
.
createBy
=
createBy
;
}
public
Date
getCreateTime
()
{
return
createTime
;
}
public
void
setCreateTime
(
Date
createTime
)
{
this
.
createTime
=
createTime
;
}
public
String
getUpdateBy
()
{
return
updateBy
;
}
public
void
setUpdateBy
(
String
updateBy
)
{
this
.
updateBy
=
updateBy
;
}
public
Date
getUpdateTime
()
{
return
updateTime
;
}
public
void
setUpdateTime
(
Date
updateTime
)
{
this
.
updateTime
=
updateTime
;
}
public
String
getRemark
()
{
return
remark
;
}
public
void
setRemark
(
String
remark
)
{
this
.
remark
=
remark
;
}
public
String
getDataScope
()
{
return
dataScope
;
}
public
void
setDataScope
(
String
dataScope
)
{
this
.
dataScope
=
dataScope
;
}
@SuppressWarnings
(
"unchecked"
)
public
Map
<
String
,
Object
>
getParams
()
{
if
(
params
==
null
)
{
return
new
HashMap
<>();
}
return
JSON
.
parseObject
(
params
,
Map
.
class
);
}
public
void
setParams
(
String
params
)
{
this
.
params
=
params
;
}
}
ruoyi/src/main/java/com/ruoyi/framework/web/domain/Server.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.web.domain
;
import
java.net.UnknownHostException
;
import
java.util.LinkedList
;
import
java.util.List
;
import
java.util.Properties
;
import
com.ruoyi.common.utils.Arith
;
import
com.ruoyi.common.utils.ip.IpUtils
;
import
com.ruoyi.framework.web.domain.server.Cpu
;
import
com.ruoyi.framework.web.domain.server.Jvm
;
import
com.ruoyi.framework.web.domain.server.Mem
;
import
com.ruoyi.framework.web.domain.server.Sys
;
import
com.ruoyi.framework.web.domain.server.SysFile
;
import
oshi.SystemInfo
;
import
oshi.hardware.CentralProcessor
;
import
oshi.hardware.CentralProcessor.TickType
;
import
oshi.hardware.GlobalMemory
;
import
oshi.hardware.HardwareAbstractionLayer
;
import
oshi.software.os.FileSystem
;
import
oshi.software.os.OSFileStore
;
import
oshi.software.os.OperatingSystem
;
import
oshi.util.Util
;
/**
* 服务器相关信息
*
* @author ruoyi
*/
public
class
Server
{
private
static
final
int
OSHI_WAIT_SECOND
=
1000
;
/**
* CPU相关信息
*/
private
Cpu
cpu
=
new
Cpu
();
/**
* 內存相关信息
*/
private
Mem
mem
=
new
Mem
();
/**
* JVM相关信息
*/
private
Jvm
jvm
=
new
Jvm
();
/**
* 服务器相关信息
*/
private
Sys
sys
=
new
Sys
();
/**
* 磁盘相关信息
*/
private
List
<
SysFile
>
sysFiles
=
new
LinkedList
<
SysFile
>();
public
Cpu
getCpu
()
{
return
cpu
;
}
public
void
setCpu
(
Cpu
cpu
)
{
this
.
cpu
=
cpu
;
}
public
Mem
getMem
()
{
return
mem
;
}
public
void
setMem
(
Mem
mem
)
{
this
.
mem
=
mem
;
}
public
Jvm
getJvm
()
{
return
jvm
;
}
public
void
setJvm
(
Jvm
jvm
)
{
this
.
jvm
=
jvm
;
}
public
Sys
getSys
()
{
return
sys
;
}
public
void
setSys
(
Sys
sys
)
{
this
.
sys
=
sys
;
}
public
List
<
SysFile
>
getSysFiles
()
{
return
sysFiles
;
}
public
void
setSysFiles
(
List
<
SysFile
>
sysFiles
)
{
this
.
sysFiles
=
sysFiles
;
}
public
void
copyTo
()
throws
Exception
{
SystemInfo
si
=
new
SystemInfo
();
HardwareAbstractionLayer
hal
=
si
.
getHardware
();
setCpuInfo
(
hal
.
getProcessor
());
setMemInfo
(
hal
.
getMemory
());
setSysInfo
();
setJvmInfo
();
setSysFiles
(
si
.
getOperatingSystem
());
}
/**
* 设置CPU信息
*/
private
void
setCpuInfo
(
CentralProcessor
processor
)
{
// CPU信息
long
[]
prevTicks
=
processor
.
getSystemCpuLoadTicks
();
Util
.
sleep
(
OSHI_WAIT_SECOND
);
long
[]
ticks
=
processor
.
getSystemCpuLoadTicks
();
long
nice
=
ticks
[
TickType
.
NICE
.
getIndex
()]
-
prevTicks
[
TickType
.
NICE
.
getIndex
()];
long
irq
=
ticks
[
TickType
.
IRQ
.
getIndex
()]
-
prevTicks
[
TickType
.
IRQ
.
getIndex
()];
long
softirq
=
ticks
[
TickType
.
SOFTIRQ
.
getIndex
()]
-
prevTicks
[
TickType
.
SOFTIRQ
.
getIndex
()];
long
steal
=
ticks
[
TickType
.
STEAL
.
getIndex
()]
-
prevTicks
[
TickType
.
STEAL
.
getIndex
()];
long
cSys
=
ticks
[
TickType
.
SYSTEM
.
getIndex
()]
-
prevTicks
[
TickType
.
SYSTEM
.
getIndex
()];
long
user
=
ticks
[
TickType
.
USER
.
getIndex
()]
-
prevTicks
[
TickType
.
USER
.
getIndex
()];
long
iowait
=
ticks
[
TickType
.
IOWAIT
.
getIndex
()]
-
prevTicks
[
TickType
.
IOWAIT
.
getIndex
()];
long
idle
=
ticks
[
TickType
.
IDLE
.
getIndex
()]
-
prevTicks
[
TickType
.
IDLE
.
getIndex
()];
long
totalCpu
=
user
+
nice
+
cSys
+
idle
+
iowait
+
irq
+
softirq
+
steal
;
cpu
.
setCpuNum
(
processor
.
getLogicalProcessorCount
());
cpu
.
setTotal
(
totalCpu
);
cpu
.
setSys
(
cSys
);
cpu
.
setUsed
(
user
);
cpu
.
setWait
(
iowait
);
cpu
.
setFree
(
idle
);
}
/**
* 设置内存信息
*/
private
void
setMemInfo
(
GlobalMemory
memory
)
{
mem
.
setTotal
(
memory
.
getTotal
());
mem
.
setUsed
(
memory
.
getTotal
()
-
memory
.
getAvailable
());
mem
.
setFree
(
memory
.
getAvailable
());
}
/**
* 设置服务器信息
*/
private
void
setSysInfo
()
{
Properties
props
=
System
.
getProperties
();
sys
.
setComputerName
(
IpUtils
.
getHostName
());
sys
.
setComputerIp
(
IpUtils
.
getHostIp
());
sys
.
setOsName
(
props
.
getProperty
(
"os.name"
));
sys
.
setOsArch
(
props
.
getProperty
(
"os.arch"
));
sys
.
setUserDir
(
props
.
getProperty
(
"user.dir"
));
}
/**
* 设置Java虚拟机
*/
private
void
setJvmInfo
()
throws
UnknownHostException
{
Properties
props
=
System
.
getProperties
();
jvm
.
setTotal
(
Runtime
.
getRuntime
().
totalMemory
());
jvm
.
setMax
(
Runtime
.
getRuntime
().
maxMemory
());
jvm
.
setFree
(
Runtime
.
getRuntime
().
freeMemory
());
jvm
.
setVersion
(
props
.
getProperty
(
"java.version"
));
jvm
.
setHome
(
props
.
getProperty
(
"java.home"
));
}
/**
* 设置磁盘信息
*/
private
void
setSysFiles
(
OperatingSystem
os
)
{
FileSystem
fileSystem
=
os
.
getFileSystem
();
OSFileStore
[]
fsArray
=
fileSystem
.
getFileStores
();
for
(
OSFileStore
fs
:
fsArray
)
{
long
free
=
fs
.
getUsableSpace
();
long
total
=
fs
.
getTotalSpace
();
long
used
=
total
-
free
;
SysFile
sysFile
=
new
SysFile
();
sysFile
.
setDirName
(
fs
.
getMount
());
sysFile
.
setSysTypeName
(
fs
.
getType
());
sysFile
.
setTypeName
(
fs
.
getName
());
sysFile
.
setTotal
(
convertFileSize
(
total
));
sysFile
.
setFree
(
convertFileSize
(
free
));
sysFile
.
setUsed
(
convertFileSize
(
used
));
sysFile
.
setUsage
(
Arith
.
mul
(
Arith
.
div
(
used
,
total
,
4
),
100
));
sysFiles
.
add
(
sysFile
);
}
}
/**
* 字节转换
*
* @param size 字节大小
* @return 转换后值
*/
public
String
convertFileSize
(
long
size
)
{
long
kb
=
1024
;
long
mb
=
kb
*
1024
;
long
gb
=
mb
*
1024
;
if
(
size
>=
gb
)
{
return
String
.
format
(
"%.1f GB"
,
(
float
)
size
/
gb
);
}
else
if
(
size
>=
mb
)
{
float
f
=
(
float
)
size
/
mb
;
return
String
.
format
(
f
>
100
?
"%.0f MB"
:
"%.1f MB"
,
f
);
}
else
if
(
size
>=
kb
)
{
float
f
=
(
float
)
size
/
kb
;
return
String
.
format
(
f
>
100
?
"%.0f KB"
:
"%.1f KB"
,
f
);
}
else
{
return
String
.
format
(
"%d B"
,
size
);
}
}
}
ruoyi/src/main/java/com/ruoyi/framework/web/domain/TreeSelect.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.web.domain
;
import
java.io.Serializable
;
import
java.util.List
;
import
java.util.stream.Collectors
;
import
com.fasterxml.jackson.annotation.JsonInclude
;
import
com.ruoyi.project.system.domain.SysDept
;
import
com.ruoyi.project.system.domain.SysMenu
;
/**
* Treeselect树结构实体类
*
* @author ruoyi
*/
public
class
TreeSelect
implements
Serializable
{
private
static
final
long
serialVersionUID
=
1L
;
/** 节点ID */
private
Long
id
;
/** 节点名称 */
private
String
label
;
/** 子节点 */
@JsonInclude
(
JsonInclude
.
Include
.
NON_EMPTY
)
private
List
<
TreeSelect
>
children
;
public
TreeSelect
()
{
}
public
TreeSelect
(
SysDept
dept
)
{
this
.
id
=
dept
.
getDeptId
();
this
.
label
=
dept
.
getDeptName
();
this
.
children
=
dept
.
getChildren
().
stream
().
map
(
TreeSelect:
:
new
).
collect
(
Collectors
.
toList
());
}
public
TreeSelect
(
SysMenu
menu
)
{
this
.
id
=
menu
.
getMenuId
();
this
.
label
=
menu
.
getMenuName
();
this
.
children
=
menu
.
getChildren
().
stream
().
map
(
TreeSelect:
:
new
).
collect
(
Collectors
.
toList
());
}
public
Long
getId
()
{
return
id
;
}
public
void
setId
(
Long
id
)
{
this
.
id
=
id
;
}
public
String
getLabel
()
{
return
label
;
}
public
void
setLabel
(
String
label
)
{
this
.
label
=
label
;
}
public
List
<
TreeSelect
>
getChildren
()
{
return
children
;
}
public
void
setChildren
(
List
<
TreeSelect
>
children
)
{
this
.
children
=
children
;
}
}
ruoyi/src/main/java/com/ruoyi/framework/web/domain/server/Cpu.java
0 → 100644
View file @
46444bd0
package
com.ruoyi.framework.web.domain.server
;
import
com.ruoyi.common.utils.Arith
;
/**
* CPU相关信息
*
* @author ruoyi
*/
public
class
Cpu
{
/**
* 核心数
*/
private
int
cpuNum
;
/**
* CPU总的使用率
*/
private
double
total
;
/**
* CPU系统使用率
*/
private
double
sys
;
/**
* CPU用户使用率
*/
private
double
used
;
/**
* CPU当前等待率
*/
private
double
wait
;
/**
* CPU当前空闲率
*/
private
double
free
;
public
int
getCpuNum
()
{
return
cpuNum
;
}
public
void
setCpuNum
(
int
cpuNum
)
{
this
.
cpuNum
=
cpuNum
;
}
public
double
getTotal
()
{
return
Arith
.
round
(
Arith
.
mul
(
total
,
100
),
2
);
}
public
void
setTotal
(
double
total
)
{
this
.
total
=
total
;
}
public
double
getSys
()
{
return
Arith
.
round
(
Arith
.
mul
(
sys
/
total
,
100
),
2
);
}
public
void
setSys
(
double
sys
)
{
this
.
sys
=
sys
;
}
public
double
getUsed
()
{
return
Arith
.
round
(
Arith
.
mul
(
used
/
total
,
100
),
2
);
}
public
void
setUsed
(
double
used
)
{
this
.
used
=
used
;
}
public
double
getWait
()
{
return
Arith
.
round
(
Arith
.
mul
(
wait
/
total
,
100
),
2
);
}
public
void
setWait
(
double
wait
)
{
this
.
wait
=
wait
;
}
public
double
getFree
()
{
return
Arith
.
round
(
Arith
.
mul
(
free
/
total
,
100
),
2
);
}
public
void
setFree
(
double
free
)
{
this
.
free
=
free
;
}
}
Prev
1
…
11
12
13
14
15
16
17
18
19
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