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
8b643e22
Commit
8b643e22
authored
Oct 12, 2018
by
HuangBingGui
Browse files
no commit message
parent
563ff060
Changes
385
Hide whitespace changes
Inline
Side-by-side
Too many changes to show.
To preserve performance only
20 of 385+
files are displayed.
Plain diff
Email patch
JeeSpringCloud/src/main/java/com/jeespring/common/web/Result.java
0 → 100644
View file @
8b643e22
package
com.jeespring.common.web
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONObject
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
public
class
Result
extends
HashMap
<
String
,
Object
>
implements
Map
<
String
,
Object
>{
/**
*
*/
private
static
final
long
serialVersionUID
=
1L
;
private
HashMap
<
String
,
Object
>
resultHashMap
=
new
HashMap
<
String
,
Object
>();
public
void
setResultObject
(
Object
obejct
)
{
put
(
"RESULT"
,
obejct
);
}
public
void
setResultExtend
(
String
key
,
Object
object
){
JSONObject
jsonObject
=
JSON
.
parseObject
(
JSON
.
toJSONString
(
get
(
"RESULT"
)));
jsonObject
.
put
(
key
,
object
);
put
(
"RESULT"
,
jsonObject
);
}
public
void
setResultHashMap
(
String
item
,
Object
obejct
)
{
resultHashMap
.
put
(
item
,
obejct
);
put
(
"RESULT"
,
resultHashMap
);
}
public
void
setResultCode
(
Object
resultCode
)
{
put
(
"CODE"
,
resultCode
);
}
public
Object
getResultCoe
(){
return
get
(
"CODE"
);
}
public
Object
getResultCode
(){
return
get
(
"CODE"
);
}
public
<
T
>
List
<
T
>
getResutObjectList
()
{
return
(
List
<
T
>)
get
(
"RESULT"
);
}
public
<
V
,
K
>
Map
<
K
,
V
>
getResutObjectMap
()
{
return
(
Map
<
K
,
V
>)
get
(
"RESULT"
);
}
public
<
T
extends
Object
>
T
getResultObject
()
{
return
(
T
)
get
(
"RESULT"
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/web/ResultFactory.java
0 → 100644
View file @
8b643e22
package
com.jeespring.common.web
;
public
class
ResultFactory
{
private
ResultFactory
()
{
}
protected
static
final
String
SuccessCode
=
"0"
;
protected
static
final
String
ErrorCode
=
"-1"
;
public
static
Result
getSuccessResult
()
{
return
getResultBean
(
SuccessCode
,
"成功"
);
}
public
static
Result
getSuccessResult
(
String
resultMessage
)
{
return
getResultBean
(
SuccessCode
,
resultMessage
);
}
public
static
Result
getErrorResult
(
String
resultMessage
)
{
return
getResultBean
(
ErrorCode
,
resultMessage
);
}
private
static
Result
getResultBean
(
String
resultCode
,
String
resultMessage
)
{
Result
result
=
ResultBean
.
result
.
getResult
();
result
.
put
(
"CODE"
,
resultCode
);
result
.
put
(
"MESSAGE"
,
resultMessage
);
return
result
;
}
public
static
Result
getResultBean
(
String
resultMessage
,
Object
o
)
{
Result
result
=
ResultBean
.
result
.
getResult
();
result
.
put
(
"CODE"
,
SuccessCode
);
result
.
put
(
"MESSAGE"
,
resultMessage
);
result
.
put
(
"Object"
,
o
);
return
result
;
}
private
enum
ResultBean
{
result
;
Result
getResult
()
{
return
new
Result
();
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/web/Servlets.java
0 → 100644
View file @
8b643e22
/**
* Copyright (c) 2005-2012 springside.org.cn
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package
com.jeespring.common.web
;
import
java.io.UnsupportedEncodingException
;
import
java.util.Enumeration
;
import
java.util.Iterator
;
import
java.util.Map
;
import
java.util.Map.Entry
;
import
java.util.StringTokenizer
;
import
java.util.TreeMap
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.http.HttpServletRequest
;
import
javax.servlet.http.HttpServletResponse
;
import
org.apache.commons.lang3.Validate
;
import
org.springframework.web.context.request.RequestContextHolder
;
import
org.springframework.web.context.request.ServletRequestAttributes
;
import
com.google.common.net.HttpHeaders
;
import
com.jeespring.common.config.Global
;
import
com.jeespring.common.utils.Encodes
;
import
com.jeespring.common.utils.StringUtils
;
import
com.jeespring.modules.sys.security.SystemAuthorizingRealm.Principal
;
import
com.jeespring.modules.sys.utils.UserUtils
;
/**
* Http与Servlet工具类.
*
* @author calvin/HuangBingGui
* @version 2014-8-19
*/
public
class
Servlets
{
// -- 常用数值定义 --//
public
static
final
long
ONE_YEAR_SECONDS
=
60
*
60
*
24
*
365
;
// 静态文件后缀
private
static
String
[]
staticFiles
;
/**
* 设置客户端缓存过期时间 的Header.
*/
public
static
void
setExpiresHeader
(
HttpServletResponse
response
,
long
expiresSeconds
)
{
// Http 1.0 header, set a fix expires date.
response
.
setDateHeader
(
HttpHeaders
.
EXPIRES
,
System
.
currentTimeMillis
()
+
expiresSeconds
*
1000
);
// Http 1.1 header, set a time after now.
response
.
setHeader
(
HttpHeaders
.
CACHE_CONTROL
,
"private, max-age="
+
expiresSeconds
);
}
/**
* 设置禁止客户端缓存的Header.
*/
public
static
void
setNoCacheHeader
(
HttpServletResponse
response
)
{
// Http 1.0 header
response
.
setDateHeader
(
HttpHeaders
.
EXPIRES
,
1L
);
response
.
addHeader
(
HttpHeaders
.
PRAGMA
,
"no-cache"
);
// Http 1.1 header
response
.
setHeader
(
HttpHeaders
.
CACHE_CONTROL
,
"no-cache, no-store, max-age=0"
);
}
/**
* 设置LastModified Header.
*/
public
static
void
setLastModifiedHeader
(
HttpServletResponse
response
,
long
lastModifiedDate
)
{
response
.
setDateHeader
(
HttpHeaders
.
LAST_MODIFIED
,
lastModifiedDate
);
}
/**
* 设置Etag Header.
*/
public
static
void
setEtag
(
HttpServletResponse
response
,
String
etag
)
{
response
.
setHeader
(
HttpHeaders
.
ETAG
,
etag
);
}
/**
* 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
* <p>
* 如果无修改, checkIfModify返回false ,设置304 not modify status.
*
* @param lastModified 内容的最后修改时间.
*/
public
static
boolean
checkIfModifiedSince
(
HttpServletRequest
request
,
HttpServletResponse
response
,
long
lastModified
)
{
long
ifModifiedSince
=
request
.
getDateHeader
(
HttpHeaders
.
IF_MODIFIED_SINCE
);
if
((
ifModifiedSince
!=
-
1
)
&&
(
lastModified
<
ifModifiedSince
+
1000
))
{
response
.
setStatus
(
HttpServletResponse
.
SC_NOT_MODIFIED
);
return
false
;
}
return
true
;
}
/**
* 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
* <p>
* 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
*
* @param etag 内容的ETag.
*/
public
static
boolean
checkIfNoneMatchEtag
(
HttpServletRequest
request
,
HttpServletResponse
response
,
String
etag
)
{
String
headerValue
=
request
.
getHeader
(
HttpHeaders
.
IF_NONE_MATCH
);
if
(
headerValue
!=
null
)
{
boolean
conditionSatisfied
=
false
;
if
(!
"*"
.
equals
(
headerValue
))
{
StringTokenizer
commaTokenizer
=
new
StringTokenizer
(
headerValue
,
","
);
while
(!
conditionSatisfied
&&
commaTokenizer
.
hasMoreTokens
())
{
String
currentToken
=
commaTokenizer
.
nextToken
();
if
(
currentToken
.
trim
().
equals
(
etag
))
{
conditionSatisfied
=
true
;
}
}
}
else
{
conditionSatisfied
=
true
;
}
if
(
conditionSatisfied
)
{
response
.
setStatus
(
HttpServletResponse
.
SC_NOT_MODIFIED
);
response
.
setHeader
(
HttpHeaders
.
ETAG
,
etag
);
return
false
;
}
}
return
true
;
}
/**
* 设置让浏览器弹出下载对话框的Header.
*
* @param fileName 下载后的文件名.
*/
public
static
void
setFileDownloadHeader
(
HttpServletResponse
response
,
String
fileName
)
{
try
{
// 中文文件名支持
String
encodedfileName
=
new
String
(
fileName
.
getBytes
(),
"ISO8859-1"
);
response
.
setHeader
(
HttpHeaders
.
CONTENT_DISPOSITION
,
"attachment; filename=\""
+
encodedfileName
+
"\""
);
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
getMessage
();
}
}
/**
* 取得带相同前缀的Request Parameters, copy from spring WebUtils.
* <p>
* 返回的结果的Parameter名已去除前缀.
*/
@SuppressWarnings
(
"rawtypes"
)
public
static
Map
<
String
,
Object
>
getParametersStartingWith
(
ServletRequest
request
,
String
prefix
)
{
Validate
.
notNull
(
request
,
"Request must not be null"
);
Enumeration
paramNames
=
request
.
getParameterNames
();
Map
<
String
,
Object
>
params
=
new
TreeMap
<
String
,
Object
>();
String
pre
=
prefix
;
if
(
pre
==
null
)
{
pre
=
""
;
}
while
(
paramNames
!=
null
&&
paramNames
.
hasMoreElements
())
{
String
paramName
=
(
String
)
paramNames
.
nextElement
();
if
(
""
.
equals
(
pre
)
||
paramName
.
startsWith
(
pre
))
{
String
unprefixed
=
paramName
.
substring
(
pre
.
length
());
String
[]
values
=
request
.
getParameterValues
(
paramName
);
if
(
values
==
null
||
values
.
length
==
0
)
{
values
=
new
String
[]{};
// Do nothing, no values found at all.
}
else
if
(
values
.
length
>
1
)
{
params
.
put
(
unprefixed
,
values
);
}
else
{
params
.
put
(
unprefixed
,
values
[
0
]);
}
}
}
return
params
;
}
/**
* 组合Parameters生成Query String的Parameter部分,并在paramter name上加上prefix.
*/
public
static
String
encodeParameterStringWithPrefix
(
Map
<
String
,
Object
>
params
,
String
prefix
)
{
StringBuilder
queryStringBuilder
=
new
StringBuilder
();
String
pre
=
prefix
;
if
(
pre
==
null
)
{
pre
=
""
;
}
Iterator
<
Entry
<
String
,
Object
>>
it
=
params
.
entrySet
().
iterator
();
while
(
it
.
hasNext
())
{
Entry
<
String
,
Object
>
entry
=
it
.
next
();
queryStringBuilder
.
append
(
pre
).
append
(
entry
.
getKey
()).
append
(
"="
).
append
(
entry
.
getValue
());
if
(
it
.
hasNext
())
{
queryStringBuilder
.
append
(
"&"
);
}
}
return
queryStringBuilder
.
toString
();
}
/**
* 客户端对Http Basic验证的 Header进行编码.
*/
public
static
String
encodeHttpBasic
(
String
userName
,
String
password
)
{
String
encode
=
userName
+
":"
+
password
;
return
"Basic "
+
Encodes
.
encodeBase64
(
encode
.
getBytes
());
}
/**
* 是否是Ajax异步请求
*
* @param request
*/
public
static
boolean
isAjaxRequest
(
HttpServletRequest
request
)
{
String
accept
=
request
.
getHeader
(
"accept"
);
String
xRequestedWith
=
request
.
getHeader
(
"X-Requested-With"
);
Principal
principal
=
UserUtils
.
getPrincipal
();
// 如果是异步请求或是手机端,则直接返回信息
return
((
accept
!=
null
&&
accept
.
indexOf
(
"application/json"
)
!=
-
1
||
(
xRequestedWith
!=
null
&&
xRequestedWith
.
indexOf
(
"XMLHttpRequest"
)
!=
-
1
)
||
(
principal
!=
null
&&
principal
.
isMobileLogin
())));
}
/**
* 获取当前请求对象
*
* @return
*/
public
static
HttpServletRequest
getRequest
()
{
try
{
return
((
ServletRequestAttributes
)
RequestContextHolder
.
getRequestAttributes
()).
getRequest
();
}
catch
(
Exception
e
)
{
return
null
;
}
}
/**
* 判断访问URI是否是静态文件请求
*
* @throws Exception
*/
public
static
boolean
isStaticFile
(
String
uri
)
{
if
(
staticFiles
==
null
)
staticFiles
=
StringUtils
.
split
(
Global
.
getConfig
(
"web.staticFile"
),
","
);
return
StringUtils
.
endsWithAny
(
uri
,
staticFiles
)
&&
!
StringUtils
.
endsWithAny
(
uri
,
".html"
)
&&
!
StringUtils
.
endsWithAny
(
uri
,
".jsp"
)
&&
!
StringUtils
.
endsWithAny
(
uri
,
".java"
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/websocket/WebSockertFilter.java
0 → 100644
View file @
8b643e22
package
com.jeespring.common.websocket
;
import
java.io.IOException
;
import
java.net.UnknownHostException
;
import
java.util.Calendar
;
import
java.util.Date
;
import
java.util.Timer
;
import
java.util.TimerTask
;
import
javax.servlet.Filter
;
import
javax.servlet.FilterChain
;
import
javax.servlet.FilterConfig
;
import
javax.servlet.ServletException
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.ServletResponse
;
import
javax.servlet.annotation.WebFilter
;
import
org.java_websocket.WebSocketImpl
;
import
com.jeespring.common.websocket.onchat.ChatServer
;
public
class
WebSockertFilter
{
/**
* 初始化
*/
public
void
init
(
FilterConfig
fc
)
throws
ServletException
{
this
.
startWebsocketChatServer
();
// this.startWebsocketOnline();
}
/**
* 启动即时聊天服务
*/
public
void
startWebsocketChatServer
(){
WebSocketImpl
.
DEBUG
=
false
;
ChatServer
s
;
try
{
s
=
new
ChatServer
(
8668
);
s
.
start
();
System
.
out
.
println
(
"websocket服务器启动,端口"
+
s
.
getPort
()
);
}
catch
(
UnknownHostException
e
)
{
e
.
printStackTrace
();
}
}
//计时器
public
void
timer
()
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
set
(
Calendar
.
HOUR_OF_DAY
,
9
);
// 控制时
calendar
.
set
(
Calendar
.
MINUTE
,
0
);
// 控制分
calendar
.
set
(
Calendar
.
SECOND
,
0
);
// 控制秒
Date
time
=
calendar
.
getTime
();
// 得出执行任务的时间
Timer
timer
=
new
Timer
();
timer
.
scheduleAtFixedRate
(
new
TimerTask
()
{
public
void
run
()
{
//PersonService personService = (PersonService)ApplicationContext.getBean("personService");
//System.out.println("-------设定要指定任务--------");
}
},
time
,
1000
*
60
*
60
*
24
);
// 这里设定将延时每天固定执行
}
public
void
destroy
()
{
// TODO Auto-generated method stub
}
public
void
doFilter
(
ServletRequest
arg0
,
ServletResponse
arg1
,
FilterChain
arg2
)
throws
IOException
,
ServletException
{
// TODO Auto-generated method stub
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/websocket/onchat/ChatServer.java
0 → 100644
View file @
8b643e22
package
com.jeespring.common.websocket.onchat
;
import
java.io.IOException
;
import
java.net.InetSocketAddress
;
import
java.net.UnknownHostException
;
import
java.nio.ByteBuffer
;
import
java.nio.CharBuffer
;
import
java.nio.charset.Charset
;
import
java.nio.charset.CharsetDecoder
;
import
java.text.SimpleDateFormat
;
import
java.util.Collection
;
import
java.util.Date
;
import
org.java_websocket.WebSocket
;
import
org.java_websocket.WebSocketImpl
;
import
org.java_websocket.framing.Framedata
;
import
org.java_websocket.handshake.ClientHandshake
;
import
org.java_websocket.server.WebSocketServer
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
com.jeespring.common.json.AjaxJson
;
import
com.jeespring.common.utils.SpringContextHolder
;
import
com.jeespring.common.websocket.utils.Constant
;
import
com.jeespring.modules.iim.entity.ChatHistory
;
import
com.jeespring.modules.iim.service.ChatHistoryService
;
import
java.util.List
;
public
class
ChatServer
extends
WebSocketServer
{
public
ChatServer
(
int
port
)
throws
UnknownHostException
{
super
(
new
InetSocketAddress
(
port
));
}
public
ChatServer
(
InetSocketAddress
address
)
{
super
(
address
);
}
/**
* 触发连接事件
*/
@Override
public
void
onOpen
(
WebSocket
conn
,
ClientHandshake
handshake
)
{
// Collection<String> onlineUsers = MsgServerPool.getOnlineUser();
// AjaxJson j = new AjaxJson();
// j.put("data", onlineUsers);
// MsgServerPool.sendMessageToUser(conn, "_online_all_status_"+j.getJsonStr());//首次登陆系统时,获取用户的在线状态
}
/**
* 触发关闭事件
*/
@Override
public
void
onClose
(
WebSocket
conn
,
int
code
,
String
reason
,
boolean
remote
)
{
userLeave
(
conn
);
Collection
<
String
>
onlineUsers
=
ChatServerPool
.
getOnlineUser
();
AjaxJson
j
=
new
AjaxJson
();
j
.
put
(
"data"
,
onlineUsers
);
ChatServerPool
.
sendMessage
(
"_online_all_status_"
+
j
.
getJsonStr
());
//通知所有用户更新在线信息
}
/**
* 客户端发送消息到服务器时触发事件
*/
@Override
public
void
onMessage
(
WebSocket
conn
,
String
message
){
message
=
message
.
toString
();
ChatHistoryService
chatHistoryService
=
SpringContextHolder
.
getBean
(
"chatHistoryService"
);
// TODO Auto-generated catch block
if
(
null
!=
message
&&
message
.
startsWith
(
Constant
.
_online_user_
)){
//用户上线
String
userId
=
message
.
replaceFirst
(
Constant
.
_online_user_
,
""
);
this
.
userjoin
(
userId
,
conn
);
//通知所有用户更新在线信息
Collection
<
String
>
onlineUsers
=
ChatServerPool
.
getOnlineUser
();
AjaxJson
j
=
new
AjaxJson
();
j
.
put
(
"data"
,
onlineUsers
);
ChatServerPool
.
sendMessage
(
"_online_all_status_"
+
j
.
getJsonStr
());
//通知所有用户更新在线信息
//读取离线信息
ChatHistory
chat
=
new
ChatHistory
();
chat
.
setUserid2
(
userId
);
chat
.
setStatus
(
"0"
);
List
<
ChatHistory
>
list
=
chatHistoryService
.
findList
(
chat
);
for
(
ChatHistory
c
:
list
){
ChatServerPool
.
sendMessageToUser
(
conn
,
c
.
getUserid1
()+
Constant
.
_msg_
+
c
.
getUserid2
()+
Constant
.
_msg_
+
c
.
getMsg
()+
Constant
.
_msg_
+
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
).
format
(
c
.
getCreateDate
()));
//向所某用户发送消息
c
.
setStatus
(
"1"
);
//标记为已读
chatHistoryService
.
save
(
c
);
}
}
if
(
null
!=
message
&&
message
.
startsWith
(
Constant
.
_leave_user_
)){
//用户离线
this
.
userLeave
(
conn
);
Collection
<
String
>
onlineUsers
=
ChatServerPool
.
getOnlineUser
();
AjaxJson
j
=
new
AjaxJson
();
j
.
put
(
"data"
,
onlineUsers
);
ChatServerPool
.
sendMessage
(
"_online_all_status_"
+
j
.
getJsonStr
());
//通知所有用户更新在线信息
}
if
(
null
!=
message
&&
message
.
contains
(
Constant
.
_msg_
)){
//
String
[]
arr
=
message
.
split
(
Constant
.
_msg_
);
String
fromUser
=
arr
[
0
];
String
toUser
=
arr
[
1
];
String
msg
=
arr
[
2
];
//保存聊天记录
ChatHistory
chat
=
new
ChatHistory
();
chat
.
setUserid1
(
fromUser
);
chat
.
setUserid2
(
toUser
);
chat
.
setMsg
(
msg
);
chat
.
setCreateDate
(
new
Date
());
WebSocket
toUserConn
=
ChatServerPool
.
getWebSocketByUser
(
toUser
);
if
(
toUserConn
!=
null
){
ChatServerPool
.
sendMessageToUser
(
ChatServerPool
.
getWebSocketByUser
(
toUser
),
message
);
//向所某用户发送消息
chat
.
setStatus
(
"1"
);
//设置为已读
}
else
{
ChatServerPool
.
sendMessageToUser
(
conn
,
"_sys_对方现在离线,他将在上线后收到你的消息!"
);
//同时向本人发送消息
chat
.
setStatus
(
"0"
);
//设置为未读
}
chatHistoryService
.
save
(
chat
);
}
}
@Override
public
void
onMessage
(
WebSocket
conn
,
ByteBuffer
buffer
){
Charset
charset
=
null
;
CharsetDecoder
decoder
=
null
;
CharBuffer
charBuffer
=
null
;
try
{
charset
=
Charset
.
forName
(
"UTF-8"
);
decoder
=
charset
.
newDecoder
();
// charBuffer = decoder.decode(buffer);//用这个的话,只能输出来一次结果,第二次显示为空
charBuffer
=
decoder
.
decode
(
buffer
.
asReadOnlyBuffer
());
//return charBuffer.toString();
System
.
out
.
println
(
charBuffer
.
toString
());
}
catch
(
Exception
ex
)
{
ex
.
printStackTrace
();
}
}
public
void
onFragment
(
WebSocket
conn
,
Framedata
fragment
)
{
}
/**
* 触发异常事件
*/
@Override
public
void
onError
(
WebSocket
conn
,
Exception
ex
)
{
ex
.
printStackTrace
();
if
(
conn
!=
null
)
{
//some errors like port binding failed may not be assignable to a specific websocket
}
}
/**
* 用户加入处理
* @param user
*/
public
void
userjoin
(
String
user
,
WebSocket
conn
){
// AjaxJson j = new AjaxJson();
// j.put("type", "user_join");
// j.put("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
// MsgServerPool.sendMessage(j.getJsonStr()); //把当前用户加入到所有在线用户列表中
// String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"上线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
// MsgServerPool.sendMessage(joinMsg); //向所有在线用户推送当前用户上线的消息
// j = new AjaxJson();
// j.put("type", "get_online_user");
ChatServerPool
.
addUser
(
user
,
conn
);
//向连接池添加当前的连接对象
// j.put("list", MsgServerPool.getOnlineUser());
// MsgServerPool.sendMessageToUser(conn, j.getJsonStr()); //向当前连接发送当前在线用户的列表
}
/**
* 用户下线处理
* @param user
*/
public
void
userLeave
(
WebSocket
conn
){
String
user
=
ChatServerPool
.
getUserByKey
(
conn
);
boolean
b
=
ChatServerPool
.
removeUser
(
conn
);
//在连接池中移除连接
// if(b){
// AjaxJson j = new AjaxJson();
// j.put("type", "user_leave");
// j.put("user", "<a onclick=\"toUserMsg('"+user+"');\">"+user+"</a>");
// MsgServerPool.sendMessage(j.getJsonStr()); //把当前用户从所有在线用户列表中删除
// String joinMsg = "{\"from\":\"[系统]\",\"content\":\""+user+"下线了\",\"timestamp\":"+new Date().getTime()+",\"type\":\"message\"}";
// MsgServerPool.sendMessage(joinMsg); //向在线用户发送当前用户退出的消息
// }
}
public
static
void
main
(
String
[]
args
)
throws
InterruptedException
,
IOException
{
WebSocketImpl
.
DEBUG
=
false
;
int
port
=
8667
;
//端口
ChatServer
s
=
new
ChatServer
(
port
);
s
.
start
();
//System.out.println( "服务器的端口" + s.getPort() );
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/websocket/onchat/ChatServerPool.java
0 → 100644
View file @
8b643e22
package
com.jeespring.common.websocket.onchat
;
import
java.util.Collection
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.Set
;
import
org.java_websocket.WebSocket
;
public
class
ChatServerPool
{
private
static
final
Map
<
WebSocket
,
String
>
userconnections
=
new
HashMap
<
WebSocket
,
String
>();
/**
* 获取用户名
* @param session
*/
public
static
String
getUserByKey
(
WebSocket
conn
){
return
userconnections
.
get
(
conn
);
}
/**
* 获取WebSocket
* @param user
*/
public
static
WebSocket
getWebSocketByUser
(
String
user
){
Set
<
WebSocket
>
keySet
=
userconnections
.
keySet
();
synchronized
(
keySet
)
{
for
(
WebSocket
conn
:
keySet
)
{
String
cuser
=
userconnections
.
get
(
conn
);
if
(
cuser
.
equals
(
user
)){
return
conn
;
}
}
}
return
null
;
}
/**
* 向连接池中添加连接
* @param inbound
*/
public
static
void
addUser
(
String
user
,
WebSocket
conn
){
userconnections
.
put
(
conn
,
user
);
//添加连接
}
/**
* 获取所有的在线用户
* @return
*/
public
static
Collection
<
String
>
getOnlineUser
(){
// List<String> setUsers = new ArrayList<String>();
Collection
<
String
>
setUsers
=
userconnections
.
values
();
// for(String u:setUser){
// setUsers.add("<a onclick=\"toUserMsg('"+u+"');\">"+u+"</a>");
// }
return
setUsers
;
}
/**
* 移除连接池中的连接
* @param inbound
*/
public
static
boolean
removeUser
(
WebSocket
conn
){
if
(
userconnections
.
containsKey
(
conn
)){
userconnections
.
remove
(
conn
);
//移除连接
return
true
;
}
else
{
return
false
;
}
}
/**
* 向特定的用户发送数据
* @param user
* @param message
*/
public
static
void
sendMessageToUser
(
WebSocket
conn
,
String
message
){
if
(
null
!=
conn
&&
null
!=
userconnections
.
get
(
conn
)){
conn
.
send
(
message
);
}
}
/**
* 向所有的用户发送消息
* @param message
*/
public
static
void
sendMessage
(
String
message
){
Set
<
WebSocket
>
keySet
=
userconnections
.
keySet
();
synchronized
(
keySet
)
{
for
(
WebSocket
conn
:
keySet
)
{
String
user
=
userconnections
.
get
(
conn
);
if
(
user
!=
null
){
conn
.
send
(
message
);
}
}
}
}
}
JeeSpringCloud/src/main/java/com/jeespring/common/websocket/utils/Constant.java
0 → 100644
View file @
8b643e22
package
com.jeespring.common.websocket.utils
;
public
class
Constant
{
public
static
final
String
_online_user_
=
"_online_user_"
;
public
static
final
String
_leave_user_
=
"_leave_user_"
;
public
static
final
String
_msg_
=
"_msg_"
;
}
JeeSpringCloud/src/main/java/com/jeespring/framework/framework.txt
0 → 100644
View file @
8b643e22
JeeSpringCloud/src/main/java/com/jeespring/modules/activeMQ/Email.java
0 → 100644
View file @
8b643e22
package
com.jeespring.modules.activeMQ
;
import
com.jeespring.common.persistence.AbstractBaseEntity
;
/**
* 消息生产者.
* @author 黄炳桂 516821420@qq.com
* @version v.0.1
* @date 2016年8月23日
*/
public
class
Email
extends
AbstractBaseEntity
<
Email
>
{
private
String
toMailAddr
;
private
String
subject
;
private
String
message
;
public
String
getToMailAddr
()
{
return
toMailAddr
;
}
public
void
setToMailAddr
(
String
toMailAddr
)
{
this
.
toMailAddr
=
toMailAddr
;
}
public
String
getSubject
()
{
return
subject
;
}
public
void
setSubject
(
String
subject
)
{
this
.
subject
=
subject
;
}
public
String
getMessage
()
{
return
message
;
}
public
void
setMessage
(
String
message
)
{
this
.
message
=
message
;
}
}
JeeSpringCloud/src/main/java/com/jeespring/modules/activeMQ/JeeSpringConsumer.java
0 → 100644
View file @
8b643e22
package
com.jeespring.modules.activeMQ
;
import
com.jeespring.common.utils.SendMailUtil
;
import
org.springframework.jms.annotation.JmsListener
;
import
org.springframework.messaging.handler.annotation.SendTo
;
import
org.springframework.stereotype.Component
;
import
java.text.SimpleDateFormat
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.Map
;
/**
* 消息消费者.
* @author 黄炳桂 516821420@qq.com
* @version v.0.1
* @date 2016年8月23日
*/
@Component
public
class
JeeSpringConsumer
{
private
static
final
SimpleDateFormat
dateFormat
=
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
);
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener
(
destination
=
JeeSpringProducer
.
ActiveMQQueueKeySendMailList
)
public
void
receiveQueue
(
List
<
String
>
list
)
{
String
toMailAddr
=
list
.
get
(
0
);
String
subject
=
list
.
get
(
1
);
String
message
=
list
.
get
(
2
);
SendMailUtil
.
sendCommonMail
(
toMailAddr
,
subject
,
message
);
}
@JmsListener
(
destination
=
JeeSpringProducer
.
ActiveMQQueueKeySendMailObject
)
public
void
receiveQueue
(
Email
email
)
{
SendMailUtil
.
sendCommonMail
(
email
.
getToMailAddr
(),
email
.
getSubject
(),
email
.
getMessage
());
}
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener
(
destination
=
JeeSpringProducer
.
ActiveMQQueueKey
)
public
void
receiveQueue
(
String
text
)
{
System
.
out
.
println
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActiveMQ Consumer :"
+
JeeSpringProducer
.
ActiveMQQueueKey
+
":收到的报文为:"
+
text
);
}
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener
(
destination
=
JeeSpringProducer
.
ActiveMQQueueKeyA
)
public
void
receiveQueueA
(
String
text
)
{
System
.
out
.
println
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActiveMQ Consumer :"
+
JeeSpringProducer
.
ActiveMQQueueKeyA
+
":收到的报文为:"
+
text
);
}
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener
(
destination
=
JeeSpringProducer
.
ActiveMQQueueKeyB
)
@SendTo
(
"jeespring.out.queue"
)
public
String
receiveQueueB
(
String
text
)
{
System
.
out
.
println
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActiveMQ Consumer :"
+
JeeSpringProducer
.
ActiveMQQueueKeyA
+
"收到的报文为:"
+
text
);
return
"return message:"
+
text
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/activeMQ/JeeSpringProducer.java
0 → 100644
View file @
8b643e22
package
com.jeespring.modules.activeMQ
;
import
com.jeespring.common.redis.RedisUtils
;
import
org.apache.activemq.command.ActiveMQQueue
;
import
org.apache.xmlbeans.impl.xb.xsdschema.Public
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.jms.annotation.JmsListener
;
import
org.springframework.jms.core.JmsMessagingTemplate
;
import
org.springframework.stereotype.Service
;
import
javax.jms.Destination
;
import
java.text.SimpleDateFormat
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
/**
* 消息生产者.
* @author 黄炳桂 516821420@qq.com
* @version v.0.1
* @date 2016年8月23日
*/
@Service
public
class
JeeSpringProducer
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
RedisUtils
.
class
);
public
static
final
String
ActiveMQQueueKeySendMailList
=
"JeeSpring.ActiveMQ.queue.sendmaillist"
;
public
static
final
String
ActiveMQQueueKeySendMailObject
=
"JeeSpring.ActiveMQ.queue.sendmailobject"
;
public
static
final
String
ActiveMQQueueKey
=
"JeeSpring.ActiveMQ.queue"
;
public
static
final
String
ActiveMQQueueKeyA
=
"JeeSpring.ActiveMQ.queueA"
;
public
static
final
String
ActiveMQQueueKeyB
=
"JeeSpring.ActiveMQ.queueB"
;
public
static
String
RUN_MESSAGE
=
"ActvieMQ连接异常,请开启ActvieMQ服务."
;
private
static
final
SimpleDateFormat
dateFormat
=
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
);
// 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
@Autowired
private
JmsMessagingTemplate
jmsTemplate
;
// 发送消息,destination是发送到的队列,message是待发送的消息
public
void
sendMessage
(
Destination
destination
,
List
<
String
>
list
){
try
{
jmsTemplate
.
convertAndSend
(
destination
,
list
);
}
catch
(
Exception
e
){
logger
.
error
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActvieMQ:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
public
void
sendMessage
(
Destination
destination
,
Email
email
){
try
{
jmsTemplate
.
convertAndSend
(
destination
,
email
);
}
catch
(
Exception
e
){
logger
.
error
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActvieMQ:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
public
void
sendMessage
(
Destination
destination
,
String
message
){
try
{
jmsTemplate
.
convertAndSend
(
destination
,
message
);
}
catch
(
Exception
e
){
logger
.
error
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActvieMQ:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
public
void
sendMessageA
(
final
String
message
){
try
{
Destination
destinationA
=
new
ActiveMQQueue
(
JeeSpringProducer
.
ActiveMQQueueKeyA
);
jmsTemplate
.
convertAndSend
(
destinationA
,
message
);
}
catch
(
Exception
e
){
logger
.
error
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActvieMQ:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
public
void
sendMessageB
(
final
String
message
){
try
{
Destination
destinationB
=
new
ActiveMQQueue
(
JeeSpringProducer
.
ActiveMQQueueKeyA
);
jmsTemplate
.
convertAndSend
(
destinationB
,
message
);
}
catch
(
Exception
e
){
logger
.
error
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActvieMQ:"
+
RUN_MESSAGE
+
e
.
getMessage
(),
RUN_MESSAGE
+
e
.
getMessage
());
}
}
@JmsListener
(
destination
=
"jeespring.out.queue"
)
public
void
consumerMessage
(
String
text
){
System
.
out
.
println
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"ActvieMQ:从out.queue队列收到的回复报文为:"
+
text
);
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/activeMQ/JeeSpringProducerRestController.java
0 → 100644
View file @
8b643e22
package
com.jeespring.modules.activeMQ
;
import
com.jeespring.common.utils.SendMailUtil
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiImplicitParam
;
import
io.swagger.annotations.ApiImplicitParams
;
import
io.swagger.annotations.ApiOperation
;
import
org.apache.activemq.command.ActiveMQQueue
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestMethod
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
javax.jms.Destination
;
import
java.util.ArrayList
;
import
java.util.List
;
/**
* ActiveMQController
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
@RestController
@RequestMapping
(
value
=
"rest/mq/producer"
)
@Api
(
value
=
"ActiveMQ队列任务云接口"
,
description
=
"ActiveMQ队列任务云接口"
)
public
class
JeeSpringProducerRestController
{
@Autowired
private
JeeSpringProducer
jeeSpringProducer
;
@RequestMapping
(
value
=
{
"sendMessage"
},
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"ActiveMQ队列云发送信息(Content-Type为text/html)"
,
notes
=
"ActiveMQ队列云发送信息(Content-Type为text/html)"
)
@ApiImplicitParam
(
name
=
"message"
,
value
=
"信息"
,
required
=
false
,
dataType
=
"String"
,
paramType
=
"query"
)
public
void
sendMessage
(
@RequestParam
(
required
=
false
)
String
message
){
Destination
destination
=
new
ActiveMQQueue
(
JeeSpringProducer
.
ActiveMQQueueKey
);
jeeSpringProducer
.
sendMessage
(
destination
,
message
);
}
@RequestMapping
(
value
=
{
"sendMail"
},
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"ActiveMQ队列云发送邮件(Content-Type为text/html)"
,
notes
=
"ActiveMQ队列云发送邮件(Content-Type为text/html)"
)
@ApiImplicitParams
({
@ApiImplicitParam
(
name
=
"toMailAddr"
,
value
=
"接收邮件"
,
required
=
false
,
dataType
=
"String"
,
paramType
=
"query"
),
@ApiImplicitParam
(
name
=
"subject"
,
value
=
"邮件主题"
,
required
=
false
,
dataType
=
"String"
,
paramType
=
"query"
),
@ApiImplicitParam
(
name
=
"message"
,
value
=
"邮件内容"
,
required
=
false
,
dataType
=
"String"
,
paramType
=
"query"
)
})
public
void
sendMail
(
@RequestParam
(
required
=
false
)
String
toMailAddr
,
@RequestParam
(
required
=
false
)
String
subject
,
@RequestParam
(
required
=
false
)
String
message
)
{
List
<
String
>
list
=
new
ArrayList
();
list
.
add
(
toMailAddr
);
list
.
add
(
subject
);
list
.
add
(
message
);
Destination
destination
=
new
ActiveMQQueue
(
JeeSpringProducer
.
ActiveMQQueueKeySendMailList
);
jeeSpringProducer
.
sendMessage
(
destination
,
list
);
}
@RequestMapping
(
value
=
{
"sendMailObject"
},
method
={
RequestMethod
.
POST
,
RequestMethod
.
GET
})
@ApiOperation
(
value
=
"ActiveMQ队列云发送邮件(Content-Type为text/html)"
,
notes
=
"ActiveMQ队列云发送邮件(Content-Type为text/html)"
)
@ApiImplicitParam
(
name
=
"email"
,
value
=
"email信息{toMailAddr,subject,message}"
,
required
=
false
,
dataType
=
"Email"
,
paramType
=
"query"
)
public
void
sendMailObject
(
Email
email
)
{
Destination
destination
=
new
ActiveMQQueue
(
JeeSpringProducer
.
ActiveMQQueueKeySendMailObject
);
jeeSpringProducer
.
sendMessage
(
destination
,
email
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/modules/aop/AOPService.java
0 → 100644
View file @
8b643e22
package
com.jeespring.modules.aop
;
import
com.jeespring.common.utils.SendMailUtil
;
import
com.jeespring.modules.activeMQ.Email
;
import
org.aspectj.lang.JoinPoint
;
import
org.aspectj.lang.annotation.*
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.stereotype.Component
;
import
java.text.SimpleDateFormat
;
import
java.util.Date
;
/**
* JeeSpring AOP
* @author 黄炳桂 516821420@qq.com
* @version v.0.1
* @date 2016年8月23日
*/
@Aspect
@Component
public
class
AOPService
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
AOPService
.
class
);
private
static
final
SimpleDateFormat
dateFormat
=
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
);
// defined aop pointcut
//@Pointcut("execution(* com.company.project.modules.*.*(..))")
//@Pointcut("execution(* com.company.project.modules..*.*(..))")
/*任意公共方法的执行:
execution(public * *(..))
任何一个以“set”开始的方法的执行:
execution(* set*(..))
AccountService 接口的任意方法的执行:
execution(* com.xyz.service.AccountService.*(..))
定义在service包里的任意方法的执行:
execution(* com.xyz.service.*.*(..))
定义在service包和所有子包里的任意类的任意方法的执行:
execution(* com.xyz.service..*.*(..))
定义在pointcutexp包和所有子包里的JoinPointObjP2类的任意方法的执行:
execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))
最靠近(..)的为方法名,靠近.*(..))的为类名或者接口名,如上例的JoinPointObjP2.*(..))*/
@Pointcut
(
"execution(* com.company.project.modules.*.*.*.*(..))"
)
public
void
controllerLog
()
{
}
// log all of controller
@Before
(
"controllerLog()"
)
public
void
before
(
JoinPoint
joinPoint
)
{
//System.out.println("AOP Before:"+joinPoint.getSignature().getDeclaringType() + ",method:" + joinPoint.getSignature().getName()
//+ ",params:" + Arrays.asList(joinPoint.getArgs()));
logger
.
debug
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"AOP Before:"
+
joinPoint
.
getSignature
().
getDeclaringType
()
+
",method:"
+
joinPoint
.
getSignature
().
getName
());
/*Email email=new Email();
email.setToMailAddr("516821420@qq.com");
email.setSubject("JeeSpring");
email.setMessage("JeeSpring AOP!");
SendMailUtil.sendCommonMail(email.getToMailAddr(),email.getSubject(),email.getMessage());*/
}
/*@Around("controllerLog()")
public void around(ProceedingJoinPoint pjp) throws Throwable{
pjp.proceed();
}*/
// result of return
@AfterReturning
(
pointcut
=
"controllerLog()"
,
returning
=
"retVal"
)
public
void
after
(
JoinPoint
joinPoint
,
Object
retVal
)
{
//System.out.println("AOP AfterReturning:"+retVal);
logger
.
debug
(
dateFormat
.
format
(
new
Date
())
+
" | "
+
"AOP AfterReturning:Object"
);
}
}
JeeSpringCloud/src/main/java/com/jeespring/modules/baiduface/rest/FaceRecognitionRestController.java
0 → 100644
View file @
8b643e22
package
com.jeespring.modules.baiduface.rest
;
import
com.alibaba.fastjson.JSONArray
;
import
com.alibaba.fastjson.JSONObject
;
import
com.jeespring.common.utils.GsonUtils
;
import
com.jeespring.common.utils.HttpUtil
;
import
com.jeespring.common.web.AbstractBaseController
;
import
com.jeespring.common.web.Result
;
import
com.jeespring.common.web.ResultFactory
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiImplicitParam
;
import
io.swagger.annotations.ApiOperation
;
import
org.springframework.web.bind.annotation.RequestBody
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestMethod
;
import
org.springframework.web.bind.annotation.RestController
;
import
java.io.BufferedReader
;
import
java.io.InputStreamReader
;
import
java.net.HttpURLConnection
;
import
java.net.URL
;
import
java.util.ArrayList
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
/**
* 人脸识别Controller
* @author 唐继涛
* @version 2018-7-13
*/
@RestController
@RequestMapping
(
value
=
"/rest/face"
)
@Api
(
value
=
"face百度人脸识别API接口"
,
description
=
"face百度人脸识别API接口"
)
public
class
FaceRecognitionRestController
extends
AbstractBaseController
{
//设置APPID/AK/SK
public
static
final
String
APP_ID
=
"11483847"
;
public
static
final
String
API_KEY
=
"Hn5zrGgRe5WWiXV1GcWYirFT"
;
public
static
final
String
SECRET_KEY
=
"vlzV3XEvuc1zGa9cfi5PpdRuFlfz08gu"
;
public
String
id
=
null
;
@RequestMapping
(
value
=
{
"match"
},
method
=
{
RequestMethod
.
POST
})
@ApiOperation
(
value
=
"人脸对比(Content-Type为application/json)"
,
notes
=
"人脸对比(Content-Type为application/json)"
)
@ApiImplicitParam
(
name
=
"String"
,
value
=
"人脸对比"
,
dataType
=
"String"
)
public
String
match
(
@RequestBody
String
imgStr
)
{
// 请求url
String
url
=
"https://aip.baidubce.com/rest/2.0/face/v3/match"
;
//百度人脸对比的API
try
{
// String str = this.getUser(userId);
List
<
Map
<
String
,
Object
>>
images
=
new
ArrayList
<>();
Map
<
String
,
Object
>
map1
=
new
HashMap
<>();
map1
.
put
(
"image"
,
imgStr
);
map1
.
put
(
"image_type"
,
"BASE64"
);
map1
.
put
(
"face_type"
,
"LIVE"
);
map1
.
put
(
"quality_control"
,
"LOW"
);
map1
.
put
(
"liveness_control"
,
"NORMAL"
);
Map
<
String
,
Object
>
map2
=
new
HashMap
<>();
map2
.
put
(
"image"
,
imgStr
);
map2
.
put
(
"image_type"
,
"BASE64"
);
map2
.
put
(
"face_type"
,
"LIVE"
);
map2
.
put
(
"quality_control"
,
"LOW"
);
map2
.
put
(
"liveness_control"
,
"NORMAL"
);
images
.
add
(
map1
);
images
.
add
(
map2
);
String
param
=
GsonUtils
.
toJson
(
images
);
String
token
=
FaceRecognitionRestController
.
getAuth
();
String
result
=
HttpUtil
.
post
(
url
,
token
,
"application/json"
,
param
);
System
.
out
.
println
(
result
);
return
result
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
null
;
}
@RequestMapping
(
value
=
{
"search"
},
method
=
{
RequestMethod
.
POST
})
@ApiOperation
(
value
=
"人脸搜索(Content-Type为application/json)"
,
notes
=
"人脸搜索(Content-Type为application/json)"
)
@ApiImplicitParam
(
name
=
"String"
,
value
=
"人脸搜索"
,
dataType
=
"String"
)
public
Result
search
(
@RequestBody
String
imgStr
)
{
// 请求url
String
url
=
"https://aip.baidubce.com/rest/2.0/face/v3/search"
;
//百度人脸搜索的API
Result
result
=
ResultFactory
.
getSuccessResult
();
try
{
String
Str
=
this
.
GroupGetlist
();
//调用百度查询用户组的API接口,将查询返回的数据接收。
JSONObject
baiJsonObject
=
JSONObject
.
parseObject
(
Str
);
//将数据转换为json对象类型的数据。
String
str
=
baiJsonObject
.
getJSONObject
(
"result"
).
getString
(
"group_id_list"
).
replace
(
"\""
,
""
).
replace
(
"["
,
""
).
replace
(
"]"
,
""
);
Map
<
String
,
Object
>
map
=
new
HashMap
<>();
map
.
put
(
"image"
,
imgStr
);
map
.
put
(
"liveness_control"
,
"NORMAL"
);
map
.
put
(
"group_id_list"
,
str
);
map
.
put
(
"image_type"
,
"BASE64"
);
map
.
put
(
"quality_control"
,
"LOW"
);
String
param
=
GsonUtils
.
toJson
(
map
);
//调用百度的人脸检测API获取百度API返回的数据。
String
token
=
FaceRecognitionRestController
.
getAuth
();
String
baiDuResult
=
HttpUtil
.
post
(
url
,
token
,
"application/json"
,
param
);
JSONObject
returnResult
=
JSONObject
.
parseObject
(
baiDuResult
);
//将百度返回的数据转为json对象类型的数据。
String
user
=
returnResult
.
getJSONObject
(
"result"
).
getString
(
"user_list"
).
replace
(
"\""
,
""
).
replace
(
"["
,
""
)
.
replace
(
"]"
,
""
).
replace
(
"{"
,
""
).
replace
(
"}"
,
""
);
String
[]
userList
=
user
.
split
(
","
);
//根据逗号分隔用户信息。
JSONArray
jsonArray
=
(
JSONArray
)
JSONArray
.
toJSON
(
userList
);
//将字符串数组转为json 数组类型的。
String
[]
scoreList
=
((
String
)
jsonArray
.
get
(
0
)).
split
(
":"
);
//获取json数组第一条数据然后根据:分隔。
JSONArray
json
=
(
JSONArray
)
JSONArray
.
toJSON
(
scoreList
);
//获取百度返回user_list数据的score评分。
String
scoreString
=
String
.
valueOf
(
json
.
get
(
1
));
//将分数值转成string类型的。
Double
score
=
Double
.
parseDouble
(
scoreString
);
//将string类型的转换成double。
//判断分数值
if
(
score
>=
80
){
result
=
ResultFactory
.
getSuccessResult
(
"检测成功!"
);
}
else
result
=
ResultFactory
.
getErrorResult
(
"检测失败,请重新扫描!!"
);
return
result
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
null
;
}
@RequestMapping
(
value
=
{
"add"
},
method
=
{
RequestMethod
.
POST
})
@ApiOperation
(
value
=
"人脸注册(Content-Type为application/json)"
,
notes
=
"人脸注册(Content-Type为application/json)"
)
@ApiImplicitParam
(
name
=
"String"
,
value
=
"人脸注册"
,
dataType
=
"String"
)
public
Result
add
(
@RequestBody
String
imgStr
,
String
userId
)
{
// 请求url
String
url
=
"https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"
;
//百度添加到人脸库的API
Result
result
=
ResultFactory
.
getSuccessResult
();
try
{
Map
<
String
,
Object
>
map
=
new
HashMap
<>();
map
.
put
(
"image"
,
imgStr
);
map
.
put
(
"group_id"
,
"测试人脸库"
);
map
.
put
(
"user_id"
,
11
);
map
.
put
(
"user_info"
,
"测试"
);
map
.
put
(
"liveness_control"
,
"NORMAL"
);
map
.
put
(
"image_type"
,
"BASE64"
);
map
.
put
(
"quality_control"
,
"NORMAL"
);
String
param
=
GsonUtils
.
toJson
(
map
);
String
token
=
FaceRecognitionRestController
.
getAuth
();
String
baiDuResult
=
HttpUtil
.
post
(
url
,
token
,
"application/json"
,
param
);
if
(
baiDuResult
.
contains
(
"SUCCESS"
))
{
result
=
ResultFactory
.
getSuccessResult
(
"注册成功!"
);
}
else
result
=
ResultFactory
.
getErrorResult
(
"注册失败!"
);
return
result
;
}
catch
(
Exception
e
)
{
logger
.
info
(
e
.
toString
());
}
return
null
;
}
/**
* 组列表查询
*/
private
String
GroupGetlist
()
{
// 请求url
String
url
=
"https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getlist"
;
try
{
Map
<
String
,
Object
>
map
=
new
HashMap
<>();
map
.
put
(
"start"
,
0
);
map
.
put
(
"length"
,
100
);
String
param
=
GsonUtils
.
toJson
(
map
);
String
token
=
FaceRecognitionRestController
.
getAuth
();
String
result
=
HttpUtil
.
post
(
url
,
token
,
"application/json"
,
param
);
return
result
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
null
;
}
/**
* 获取API访问token
* 该token有一定的有效期,需要自行管理,当失效时需重新获取.
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
public
static
String
getAuth
()
{
// 获取token地址
String
authHost
=
"https://aip.baidubce.com/oauth/2.0/token?"
;
String
getAccessTokenUrl
=
authHost
// 1. grant_type为固定参数
+
"grant_type=client_credentials"
// 2. 官网获取的 API Key
+
"&client_id="
+
API_KEY
// 3. 官网获取的 Secret Key
+
"&client_secret="
+
SECRET_KEY
;
try
{
URL
realUrl
=
new
URL
(
getAccessTokenUrl
);
// 打开和URL之间的连接
HttpURLConnection
connection
=
(
HttpURLConnection
)
realUrl
.
openConnection
();
connection
.
setRequestMethod
(
"GET"
);
connection
.
connect
();
// 获取所有响应头字段
Map
<
String
,
List
<
String
>>
map
=
connection
.
getHeaderFields
();
// 遍历所有的响应头字段
for
(
String
key
:
map
.
keySet
())
{
System
.
err
.
println
(
key
+
"--->"
+
map
.
get
(
key
));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader
in
=
new
BufferedReader
(
new
InputStreamReader
(
connection
.
getInputStream
()));
String
result
=
""
;
String
line
;
while
((
line
=
in
.
readLine
())
!=
null
)
{
result
+=
line
;
}
JSONObject
jsonObject
=
JSONObject
.
parseObject
(
result
);
String
access_token
=
jsonObject
.
getString
(
"access_token"
);
System
.
out
.
print
(
access_token
);
return
access_token
;
}
catch
(
Exception
e
)
{
System
.
err
.
printf
(
"获取token失败!"
);
e
.
printStackTrace
(
System
.
err
);
}
return
null
;
}
public
static
void
main
(
String
[]
args
)
{
// new FaceSpot().getAuth();
getAuth
();
}
}
JeeSpringCloud/src/main/java/com/jeespring/modules/echarts/dao/ChinaWeatherDataBeanDao.java
0 → 100644
View file @
8b643e22
/**
* Copyright © 2015-2020 <a href="http://www.jeespring.org/">JeeSpring</a> All rights reserved.
*/
package
com.jeespring.modules.echarts.dao
;
import
com.jeespring.common.persistence.InterfaceBaseDao
;
import
com.jeespring.modules.echarts.entity.ChinaWeatherDataBean
;
import
org.apache.ibatis.annotations.Mapper
;
/**
* 城市气温DAO接口
* @author lgf
* @version 2016-06-02
*/
@Mapper
public
interface
ChinaWeatherDataBeanDao
extends
InterfaceBaseDao
<
ChinaWeatherDataBean
>
{
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/echarts/dao/PieClassDao.java
0 → 100644
View file @
8b643e22
/**
* Copyright © 2015-2020 <a href="http://www.jeespring.org/">JeeSpring</a> All rights reserved.
*/
package
com.jeespring.modules.echarts.dao
;
import
com.jeespring.common.persistence.InterfaceBaseDao
;
import
com.jeespring.modules.echarts.entity.PieClass
;
import
org.apache.ibatis.annotations.Mapper
;
/**
* 班级DAO接口
* @author lgf
* @version 2016-05-26
*/
@Mapper
public
interface
PieClassDao
extends
InterfaceBaseDao
<
PieClass
>
{
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/echarts/entity/ChinaWeatherDataBean.java
0 → 100644
View file @
8b643e22
/**
* Copyright © 2015-2020 <a href="http://www.jeespring.org/">JeeSpring</a> All rights reserved.
*/
package
com.jeespring.modules.echarts.entity
;
import
java.util.Date
;
import
com.fasterxml.jackson.annotation.JsonFormat
;
import
com.jeespring.common.persistence.AbstractBaseEntity
;
import
com.jeespring.common.utils.excel.annotation.ExcelField
;
/**
* 城市气温Entity
* @author lgf
* @version 2016-06-02
*/
public
class
ChinaWeatherDataBean
extends
AbstractBaseEntity
<
ChinaWeatherDataBean
>
{
private
static
final
long
serialVersionUID
=
1L
;
private
Date
datestr
;
// 日期
private
Double
beijingMaxTemp
;
// 北京最高气温
private
Double
beijingMinTemp
;
// 北京最低气温
private
Double
changchunMaxTemp
;
// 长春最高气温
private
Double
changchunMinTemp
;
// 长春最低气温
private
Double
shenyangMaxTemp
;
// 沈阳最高气温
private
Double
shenyangMinTemp
;
// 沈阳最低气温
private
Double
haerbinMaxTemp
;
// 哈尔滨最高气温
private
Double
haerbinMinTemp
;
// 哈尔滨最低气温
public
ChinaWeatherDataBean
()
{
super
();
}
public
ChinaWeatherDataBean
(
String
id
){
super
(
id
);
}
@JsonFormat
(
pattern
=
"yyyy-MM-dd HH:mm:ss"
)
@ExcelField
(
title
=
"日期"
,
align
=
2
,
sort
=
7
)
public
Date
getDatestr
()
{
return
datestr
;
}
public
void
setDatestr
(
Date
datestr
)
{
this
.
datestr
=
datestr
;
}
@ExcelField
(
title
=
"北京最高气温"
,
align
=
2
,
sort
=
8
)
public
Double
getBeijingMaxTemp
()
{
return
beijingMaxTemp
;
}
public
void
setBeijingMaxTemp
(
Double
beijingMaxTemp
)
{
this
.
beijingMaxTemp
=
beijingMaxTemp
;
}
@ExcelField
(
title
=
"北京最低气温"
,
align
=
2
,
sort
=
9
)
public
Double
getBeijingMinTemp
()
{
return
beijingMinTemp
;
}
public
void
setBeijingMinTemp
(
Double
beijingMinTemp
)
{
this
.
beijingMinTemp
=
beijingMinTemp
;
}
@ExcelField
(
title
=
"长春最高气温"
,
align
=
2
,
sort
=
10
)
public
Double
getChangchunMaxTemp
()
{
return
changchunMaxTemp
;
}
public
void
setChangchunMaxTemp
(
Double
changchunMaxTemp
)
{
this
.
changchunMaxTemp
=
changchunMaxTemp
;
}
@ExcelField
(
title
=
"长春最低气温"
,
align
=
2
,
sort
=
11
)
public
Double
getChangchunMinTemp
()
{
return
changchunMinTemp
;
}
public
void
setChangchunMinTemp
(
Double
changchunMinTemp
)
{
this
.
changchunMinTemp
=
changchunMinTemp
;
}
@ExcelField
(
title
=
"沈阳最高气温"
,
align
=
2
,
sort
=
12
)
public
Double
getShenyangMaxTemp
()
{
return
shenyangMaxTemp
;
}
public
void
setShenyangMaxTemp
(
Double
shenyangMaxTemp
)
{
this
.
shenyangMaxTemp
=
shenyangMaxTemp
;
}
@ExcelField
(
title
=
"沈阳最低气温"
,
align
=
2
,
sort
=
13
)
public
Double
getShenyangMinTemp
()
{
return
shenyangMinTemp
;
}
public
void
setShenyangMinTemp
(
Double
shenyangMinTemp
)
{
this
.
shenyangMinTemp
=
shenyangMinTemp
;
}
@ExcelField
(
title
=
"哈尔滨最高气温"
,
align
=
2
,
sort
=
14
)
public
Double
getHaerbinMaxTemp
()
{
return
haerbinMaxTemp
;
}
public
void
setHaerbinMaxTemp
(
Double
haerbinMaxTemp
)
{
this
.
haerbinMaxTemp
=
haerbinMaxTemp
;
}
@ExcelField
(
title
=
"哈尔滨最低气温"
,
align
=
2
,
sort
=
15
)
public
Double
getHaerbinMinTemp
()
{
return
haerbinMinTemp
;
}
public
void
setHaerbinMinTemp
(
Double
haerbinMinTemp
)
{
this
.
haerbinMinTemp
=
haerbinMinTemp
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/echarts/entity/PieClass.java
0 → 100644
View file @
8b643e22
/**
* Copyright © 2015-2020 <a href="http://www.jeespring.org/">JeeSpring</a> All rights reserved.
*/
package
com.jeespring.modules.echarts.entity
;
import
org.hibernate.validator.constraints.Length
;
import
com.jeespring.common.persistence.AbstractBaseEntity
;
import
com.jeespring.common.utils.excel.annotation.ExcelField
;
/**
* 班级Entity
* @author lgf
* @version 2016-05-26
*/
public
class
PieClass
extends
AbstractBaseEntity
<
PieClass
>
{
private
static
final
long
serialVersionUID
=
1L
;
private
String
className
;
// 班级
private
Integer
num
;
// 人数
public
PieClass
()
{
super
();
}
public
PieClass
(
String
id
){
super
(
id
);
}
@Length
(
min
=
0
,
max
=
64
,
message
=
"班级长度必须介于 0 和 64 之间"
)
@ExcelField
(
title
=
"班级"
,
align
=
2
,
sort
=
7
)
public
String
getClassName
()
{
return
className
;
}
public
void
setClassName
(
String
className
)
{
this
.
className
=
className
;
}
@ExcelField
(
title
=
"人数"
,
align
=
2
,
sort
=
8
)
public
Integer
getNum
()
{
return
num
;
}
public
void
setNum
(
Integer
num
)
{
this
.
num
=
num
;
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/echarts/service/ChinaWeatherDataBeanService.java
0 → 100644
View file @
8b643e22
/**
* Copyright © 2015-2020 <a href="http://www.jeespring.org/">JeeSpring</a> All rights reserved.
*/
package
com.jeespring.modules.echarts.service
;
import
java.util.List
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
com.jeespring.common.persistence.Page
;
import
com.jeespring.common.service.AbstractBaseService
;
import
com.jeespring.modules.echarts.entity.ChinaWeatherDataBean
;
import
com.jeespring.modules.echarts.dao.ChinaWeatherDataBeanDao
;
/**
* 城市气温Service
* @author lgf
* @version 2016-06-02
*/
@Service
@Transactional
(
readOnly
=
true
)
public
class
ChinaWeatherDataBeanService
extends
AbstractBaseService
<
ChinaWeatherDataBeanDao
,
ChinaWeatherDataBean
>
{
public
ChinaWeatherDataBean
get
(
String
id
)
{
return
super
.
get
(
id
);
}
public
List
<
ChinaWeatherDataBean
>
findList
(
ChinaWeatherDataBean
chinaWeatherDataBean
)
{
return
super
.
findList
(
chinaWeatherDataBean
);
}
public
Page
<
ChinaWeatherDataBean
>
findPage
(
Page
<
ChinaWeatherDataBean
>
page
,
ChinaWeatherDataBean
chinaWeatherDataBean
)
{
return
super
.
findPage
(
page
,
chinaWeatherDataBean
);
}
@Transactional
(
readOnly
=
false
)
public
void
save
(
ChinaWeatherDataBean
chinaWeatherDataBean
)
{
super
.
save
(
chinaWeatherDataBean
);
}
@Transactional
(
readOnly
=
false
)
public
void
delete
(
ChinaWeatherDataBean
chinaWeatherDataBean
)
{
super
.
delete
(
chinaWeatherDataBean
);
}
}
\ No newline at end of file
JeeSpringCloud/src/main/java/com/jeespring/modules/echarts/service/PieClassService.java
0 → 100644
View file @
8b643e22
/**
* Copyright © 2015-2020 <a href="http://www.jeespring.org/">JeeSpring</a> All rights reserved.
*/
package
com.jeespring.modules.echarts.service
;
import
java.util.List
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
com.jeespring.common.persistence.Page
;
import
com.jeespring.common.service.AbstractBaseService
;
import
com.jeespring.modules.echarts.entity.PieClass
;
import
com.jeespring.modules.echarts.dao.PieClassDao
;
/**
* 班级Service
* @author JeeSpring
* @version 2016-05-26
*/
@Service
@Transactional
(
readOnly
=
true
)
public
class
PieClassService
extends
AbstractBaseService
<
PieClassDao
,
PieClass
>
{
public
PieClass
get
(
String
id
)
{
return
super
.
get
(
id
);
}
public
List
<
PieClass
>
findList
(
PieClass
pieClass
)
{
return
super
.
findList
(
pieClass
);
}
public
Page
<
PieClass
>
findPage
(
Page
<
PieClass
>
page
,
PieClass
pieClass
)
{
return
super
.
findPage
(
page
,
pieClass
);
}
@Transactional
(
readOnly
=
false
)
public
void
save
(
PieClass
pieClass
)
{
super
.
save
(
pieClass
);
}
@Transactional
(
readOnly
=
false
)
public
void
delete
(
PieClass
pieClass
)
{
super
.
delete
(
pieClass
);
}
}
\ No newline at end of file
Prev
1
…
6
7
8
9
10
11
12
13
14
…
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