Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
open-source
/
push-platform-service
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 3501a16d
authored
Apr 08, 2021
by
fz
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
1.友盟push推送demo
1 parent
380e758b
Hide whitespace changes
Inline
Side-by-side
Showing
20 changed files
with
1405 additions
and
16 deletions
pom.xml
src/main/java/com/glsx/Application.java
src/main/java/com/glsx/common/utils/HttpUtil.java
src/main/java/com/glsx/modules/notify/demo/AndroidNotification.java
src/main/java/com/glsx/modules/notify/demo/BroadCastService.java
src/main/java/com/glsx/modules/notify/demo/IOSNotification.java
src/main/java/com/glsx/modules/notify/demo/PushClient.java
src/main/java/com/glsx/modules/notify/demo/UmengNotification.java
src/main/java/com/glsx/modules/notify/demo/android/AndroidBroadcast.java
src/main/java/com/glsx/modules/notify/demo/android/AndroidCustomizedcast.java
src/main/java/com/glsx/modules/notify/demo/android/AndroidFilecast.java
src/main/java/com/glsx/modules/notify/demo/android/AndroidGroupcast.java
src/main/java/com/glsx/modules/notify/demo/android/AndroidUnicast.java
src/main/java/com/glsx/modules/notify/demo/ios/IOSBroadcast.java
src/main/java/com/glsx/modules/notify/demo/ios/IOSCustomizedcast.java
src/main/java/com/glsx/modules/notify/demo/ios/IOSFilecast.java
src/main/java/com/glsx/modules/notify/demo/ios/IOSGroupcast.java
src/main/java/com/glsx/modules/notify/demo/ios/IOSUnicast.java
src/main/java/com/glsx/modules/notify/service/DeviceService.java
src/test/java/com/glsx/modules/notify/controller/DeviceControllerTest.java
pom.xml
View file @
3501a16
...
@@ -12,11 +12,6 @@
...
@@ -12,11 +12,6 @@
<artifactId>
youMeng-platform-service
</artifactId>
<artifactId>
youMeng-platform-service
</artifactId>
<properties>
<kaptcha.version>
0.0.9
</kaptcha.version>
<shiro.version>
1.6.0
</shiro.version>
</properties>
<dependencies>
<dependencies>
<dependency>
<dependency>
<groupId>
com.glsx
</groupId>
<groupId>
com.glsx
</groupId>
...
...
src/main/java/com/glsx/Application.java
View file @
3501a16
...
@@ -7,8 +7,10 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
...
@@ -7,8 +7,10 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import
org.springframework.context.annotation.EnableMBeanExport
;
import
org.springframework.context.annotation.EnableMBeanExport
;
import
org.springframework.jmx.support.RegistrationPolicy
;
import
org.springframework.jmx.support.RegistrationPolicy
;
import
org.springframework.transaction.annotation.EnableTransactionManagement
;
import
org.springframework.transaction.annotation.EnableTransactionManagement
;
import
javax.annotation.PostConstruct
;
import
javax.annotation.PostConstruct
;
import
java.util.TimeZone
;
import
java.util.TimeZone
;
import
static
java
.
time
.
ZoneId
.
of
;
import
static
java
.
time
.
ZoneId
.
of
;
import
static
java
.
util
.
TimeZone
.
getTimeZone
;
import
static
java
.
util
.
TimeZone
.
getTimeZone
;
...
...
src/main/java/com/glsx/common/utils/HttpUtil.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
common
.
utils
;
import
com.alibaba.fastjson.JSONObject
;
import
org.apache.commons.lang.ObjectUtils
;
import
org.apache.commons.lang.StringUtils
;
import
org.apache.commons.lang.time.DateFormatUtils
;
import
org.apache.commons.logging.Log
;
import
org.apache.commons.logging.LogFactory
;
import
org.apache.http.*
;
import
org.apache.http.client.ClientProtocolException
;
import
org.apache.http.client.HttpClient
;
import
org.apache.http.client.HttpRequestRetryHandler
;
import
org.apache.http.client.config.RequestConfig
;
import
org.apache.http.client.entity.UrlEncodedFormEntity
;
import
org.apache.http.client.methods.HttpDelete
;
import
org.apache.http.client.methods.HttpGet
;
import
org.apache.http.client.methods.HttpPost
;
import
org.apache.http.client.methods.HttpPut
;
import
org.apache.http.client.protocol.HttpClientContext
;
import
org.apache.http.client.utils.HttpClientUtils
;
import
org.apache.http.config.Registry
;
import
org.apache.http.config.RegistryBuilder
;
import
org.apache.http.config.SocketConfig
;
import
org.apache.http.conn.ConnectTimeoutException
;
import
org.apache.http.conn.socket.ConnectionSocketFactory
;
import
org.apache.http.conn.socket.LayeredConnectionSocketFactory
;
import
org.apache.http.conn.socket.PlainConnectionSocketFactory
;
import
org.apache.http.conn.ssl.SSLConnectionSocketFactory
;
import
org.apache.http.entity.ContentType
;
import
org.apache.http.entity.StringEntity
;
import
org.apache.http.impl.client.CloseableHttpClient
;
import
org.apache.http.impl.client.HttpClients
;
import
org.apache.http.impl.conn.PoolingHttpClientConnectionManager
;
import
org.apache.http.message.BasicNameValuePair
;
import
org.apache.http.protocol.HttpContext
;
import
org.apache.http.util.EntityUtils
;
import
javax.net.ssl.SSLContext
;
import
javax.net.ssl.SSLException
;
import
javax.net.ssl.SSLHandshakeException
;
import
javax.xml.ws.http.HTTPException
;
import
java.io.IOException
;
import
java.io.InterruptedIOException
;
import
java.net.UnknownHostException
;
import
java.nio.charset.Charset
;
import
java.security.NoSuchAlgorithmException
;
import
java.util.*
;
public
class
HttpUtil
{
private
static
final
Log
logger
=
LogFactory
.
getLog
(
HttpUtil
.
class
);
final
static
int
CONNECTION_TIMEOUT
=
10000
;
// 设置请求超时 10 秒钟 根据业务调整
final
static
int
SOCKET_TIMEOUT
=
180000
;
// 数据传输时间 3 分钟
final
static
int
SEARCH_CONNECTION_TIMEOUT
=
500
;
// 连接不够用的时候等待超时时间,不设置默认等于 CONNECTION_TIMEOUT
public
final
static
ContentType
JSON_UTF8
=
ContentType
.
create
(
"application/json"
,
"utf-8"
);
static
PoolingHttpClientConnectionManager
httpClientConnectionManager
=
null
;
static
{
LayeredConnectionSocketFactory
sslsf
=
null
;
try
{
sslsf
=
new
SSLConnectionSocketFactory
(
SSLContext
.
getDefault
());
}
catch
(
NoSuchAlgorithmException
e
)
{
e
.
printStackTrace
();
}
Registry
<
ConnectionSocketFactory
>
socketFactoryRegistry
=
RegistryBuilder
.<
ConnectionSocketFactory
>
create
().
register
(
"https"
,
sslsf
)
.
register
(
"http"
,
new
PlainConnectionSocketFactory
()).
build
();
httpClientConnectionManager
=
new
PoolingHttpClientConnectionManager
(
socketFactoryRegistry
);
httpClientConnectionManager
.
setMaxTotal
(
200
);
// 总的连接池的大小
httpClientConnectionManager
.
setDefaultMaxPerRoute
(
20
);
// 对每个主机的最大连接大小,每个主机最大20 个连接,总共 200 个连接,支持 10 台主机
}
public
static
CloseableHttpClient
getHttpClient
()
{
RequestConfig
requestConfig
=
RequestConfig
.
custom
().
setConnectTimeout
(
CONNECTION_TIMEOUT
).
setSocketTimeout
(
SOCKET_TIMEOUT
)
.
setConnectionRequestTimeout
(
SEARCH_CONNECTION_TIMEOUT
).
build
();
SocketConfig
socketConfig
=
SocketConfig
.
custom
()
.
setSoKeepAlive
(
true
)
.
setTcpNoDelay
(
true
).
build
();
// 请求重试处理
HttpRequestRetryHandler
httpRequestRetryHandler
=
new
HttpRequestRetryHandler
()
{
@Override
public
boolean
retryRequest
(
IOException
exception
,
int
executionCount
,
HttpContext
context
)
{
if
(
executionCount
>=
3
)
{
// 如果已经重试了 3 次,就放弃
return
false
;
}
if
(
exception
instanceof
NoHttpResponseException
)
{
// 如果服务器丢掉了连接,那么就重试
return
true
;
}
if
(
exception
instanceof
SSLHandshakeException
)
{
// 不要重试SSL握手异常
return
false
;
}
if
(
exception
instanceof
InterruptedIOException
)
{
// 超时
return
false
;
}
if
(
exception
instanceof
UnknownHostException
)
{
// 目标服务器不可达
return
false
;
}
if
(
exception
instanceof
ConnectTimeoutException
)
{
// 连接被拒绝
return
false
;
}
if
(
exception
instanceof
SSLException
)
{
// SSL握手异常
return
false
;
}
HttpClientContext
clientContext
=
HttpClientContext
.
adapt
(
context
);
HttpRequest
request
=
clientContext
.
getRequest
();
// 如果请求是幂等的,就再次尝试
if
(!(
request
instanceof
HttpEntityEnclosingRequest
))
{
return
true
;
}
return
false
;
}
};
CloseableHttpClient
httpClient
=
HttpClients
.
custom
().
setConnectionManager
(
httpClientConnectionManager
)
.
setDefaultRequestConfig
(
requestConfig
)
.
setRetryHandler
(
httpRequestRetryHandler
)
.
setDefaultSocketConfig
(
socketConfig
).
build
();
return
httpClient
;
}
/**
* 作者:sanri <br/>
* 时间:2017-7-26下午3:47:02<br/>
* 功能:将 map 型 的参数转换为NameValuePair 类型 <br/>
*
* @param params 注:日期将会转格式为 yyyy-MM-dd
* @return
*/
public
static
List
<
NameValuePair
>
transferParam
(
Map
<
String
,
?
extends
Object
>
params
)
{
return
transferParam
(
params
,
"yyyy-MM-dd"
);
}
public
static
List
<
NameValuePair
>
transferParam
(
Map
<
String
,
?
extends
Object
>
params
,
String
dateFormat
)
{
List
<
NameValuePair
>
nameValuePairs
=
new
ArrayList
<
NameValuePair
>();
if
(
params
!=
null
&&
!
params
.
isEmpty
())
{
Set
<?>
entrySet
=
params
.
entrySet
();
Iterator
<?>
paramIterator
=
entrySet
.
iterator
();
while
(
paramIterator
.
hasNext
())
{
Map
.
Entry
<
String
,
?
extends
Object
>
param
=
(
Map
.
Entry
<
String
,
?
extends
Object
>)
paramIterator
.
next
();
Object
value
=
param
.
getValue
();
if
(
value
==
null
)
{
nameValuePairs
.
add
(
new
BasicNameValuePair
(
param
.
getKey
(),
null
));
}
else
{
if
(
value
instanceof
Date
)
{
Date
date
=
(
Date
)
value
;
String
dateString
=
""
;
if
(
StringUtils
.
isBlank
(
dateFormat
))
{
dateString
=
date
.
toString
();
}
else
{
dateString
=
DateFormatUtils
.
format
(
date
,
dateFormat
);
}
nameValuePairs
.
add
(
new
BasicNameValuePair
(
param
.
getKey
(),
dateString
));
continue
;
}
nameValuePairs
.
add
(
new
BasicNameValuePair
(
param
.
getKey
(),
ObjectUtils
.
toString
(
value
)));
}
}
}
return
nameValuePairs
;
}
/**
* http发送post请求
*
* @param url
* @return
* @throws IOException
*/
public
static
JSONObject
sendPost
(
String
url
,
String
json
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
{
String
formData
=
postData
(
url
,
json
,
headerParams
);
if
(
StringUtils
.
isNotBlank
(
formData
))
{
return
JSONObject
.
parseObject
(
formData
);
}
return
new
JSONObject
();
}
/**
* http发送post请求
*
* @param url
* @return
* @throws IOException
*/
public
static
JSONObject
sendPost
(
String
url
,
String
json
)
throws
IOException
{
return
sendPost
(
url
,
json
,
new
HashMap
<>());
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @param data
* @return
* @throws IOException
*/
private
static
String
postData
(
String
url
,
String
data
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
,
HTTPException
{
HttpClient
httpClient
=
getHttpClient
();
//请求头,请求体数据封装
HttpPost
postMethod
=
new
HttpPost
(
url
);
postMethod
.
addHeader
(
"Content-Type"
,
"application/json"
);
if
(!
headerParams
.
isEmpty
())
{
headerParams
.
forEach
((
key
,
value
)
->
{
postMethod
.
addHeader
(
key
,
value
);
});
}
postMethod
.
addHeader
(
"User-Agent"
,
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
);
StringEntity
dataEntity
=
new
StringEntity
(
data
,
JSON_UTF8
);
postMethod
.
setEntity
(
dataEntity
);
HttpResponse
response
=
null
;
try
{
//开始请求,记录请求数据和请求时间
response
=
httpClient
.
execute
(
postMethod
);
//获取响应
HttpEntity
entity
=
response
.
getEntity
();
StatusLine
statusLine
=
response
.
getStatusLine
();
int
statusCode
=
statusLine
.
getStatusCode
();
if
(
statusCode
!=
200
)
{
HTTPException
exception
=
new
HTTPException
(
statusCode
);
logger
.
error
(
"请求地址"
+
url
+
"出错,http 状态码为:"
+
statusCode
,
exception
);
throw
exception
;
}
String
retData
=
EntityUtils
.
toString
(
entity
,
JSON_UTF8
.
getCharset
());
return
retData
;
}
catch
(
ClientProtocolException
e
)
{
throw
new
IllegalArgumentException
(
"客户端协议错误 ,检查 url 配置 url: "
+
url
,
e
);
}
finally
{
HttpClientUtils
.
closeQuietly
(
response
);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @param data
* @return
* @throws IOException
*/
public
static
String
putData
(
String
url
,
String
data
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
,
HTTPException
{
HttpClient
httpClient
=
getHttpClient
();
//请求头,请求体数据封装
HttpPut
postMethod
=
new
HttpPut
(
url
);
postMethod
.
addHeader
(
"Content-Type"
,
"application/json"
);
if
(!
headerParams
.
isEmpty
())
{
headerParams
.
forEach
((
key
,
value
)
->
{
postMethod
.
addHeader
(
key
,
value
);
});
}
postMethod
.
addHeader
(
"User-Agent"
,
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
);
StringEntity
dataEntity
=
new
StringEntity
(
data
,
JSON_UTF8
);
postMethod
.
setEntity
(
dataEntity
);
HttpResponse
response
=
null
;
try
{
//开始请求,记录请求数据和请求时间
response
=
httpClient
.
execute
(
postMethod
);
//获取响应
HttpEntity
entity
=
response
.
getEntity
();
StatusLine
statusLine
=
response
.
getStatusLine
();
int
statusCode
=
statusLine
.
getStatusCode
();
if
(
statusCode
!=
200
)
{
HTTPException
exception
=
new
HTTPException
(
statusCode
);
logger
.
error
(
"请求地址"
+
url
+
"出错,http 状态码为:"
+
statusCode
,
exception
);
throw
exception
;
}
String
retData
=
EntityUtils
.
toString
(
entity
,
JSON_UTF8
.
getCharset
());
return
retData
;
}
catch
(
ClientProtocolException
e
)
{
throw
new
IllegalArgumentException
(
"客户端协议错误 ,检查 url 配置 url: "
+
url
,
e
);
}
finally
{
HttpClientUtils
.
closeQuietly
(
response
);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-10-19下午2:25:40<br/>
* 功能:向指定 url 提交数据 <br/>
*
* @param url
* @return
* @throws IOException
*/
public
static
String
deleteData
(
String
url
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
,
HTTPException
{
HttpClient
httpClient
=
getHttpClient
();
//请求头,请求体数据封装
HttpDelete
httpDelete
=
new
HttpDelete
(
url
);
httpDelete
.
addHeader
(
"Content-Type"
,
"application/json"
);
if
(!
headerParams
.
isEmpty
())
{
headerParams
.
forEach
((
key
,
value
)
->
{
httpDelete
.
addHeader
(
key
,
value
);
});
}
httpDelete
.
addHeader
(
"User-Agent"
,
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
);
HttpResponse
response
=
null
;
try
{
//开始请求,记录请求数据和请求时间
response
=
httpClient
.
execute
(
httpDelete
);
//获取响应
HttpEntity
entity
=
response
.
getEntity
();
StatusLine
statusLine
=
response
.
getStatusLine
();
int
statusCode
=
statusLine
.
getStatusCode
();
if
(
statusCode
!=
200
)
{
HTTPException
exception
=
new
HTTPException
(
statusCode
);
logger
.
error
(
"请求地址"
+
url
+
"出错,http 状态码为:"
+
statusCode
,
exception
);
throw
exception
;
}
String
retData
=
EntityUtils
.
toString
(
entity
,
JSON_UTF8
.
getCharset
());
return
retData
;
}
catch
(
ClientProtocolException
e
)
{
throw
new
IllegalArgumentException
(
"客户端协议错误 ,检查 url 配置 url: "
+
url
,
e
);
}
finally
{
HttpClientUtils
.
closeQuietly
(
response
);
}
}
/**
* 作者:sanri <br/>
* 时间:2018-3-28下午8:57:50<br/>
* 功能: 请求地址获取数据<br/>
*
* @param url
* @param urlEncoded
* @return
* @throws IOException
* @throws ParseException
*/
public
static
String
getData
(
final
String
url
,
final
String
urlEncoded
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
{
HttpClient
httpClient
=
getHttpClient
();
String
queryUrl
=
url
;
if
(
StringUtils
.
isNotBlank
(
urlEncoded
))
{
queryUrl
+=
"?"
+
urlEncoded
;
}
HttpGet
httpGet
=
new
HttpGet
(
queryUrl
);
if
(!
headerParams
.
isEmpty
())
{
headerParams
.
forEach
((
key
,
value
)
->
{
httpGet
.
addHeader
(
key
,
value
);
});
}
httpGet
.
addHeader
(
"User-Agent"
,
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
);
HttpResponse
response
=
null
;
try
{
response
=
httpClient
.
execute
(
httpGet
);
StatusLine
statusLine
=
response
.
getStatusLine
();
int
statusCode
=
statusLine
.
getStatusCode
();
if
(
statusCode
!=
200
)
{
HTTPException
exception
=
new
HTTPException
(
statusCode
);
logger
.
error
(
"请求地址"
+
url
+
"出错,http 状态码为:"
+
statusCode
,
exception
);
throw
exception
;
}
HttpEntity
msgEntity
=
response
.
getEntity
();
String
message
=
EntityUtils
.
toString
(
msgEntity
);
return
message
;
}
catch
(
ClientProtocolException
e
)
{
throw
new
IllegalArgumentException
(
"客户端协议错误 ,检查 url 配置 url: "
+
url
,
e
);
}
finally
{
HttpClientUtils
.
closeQuietly
(
response
);
}
}
/**
* 作者:sanri <br/>
* 时间:2017-7-26下午3:36:40<br/>
* 功能:兼容以前的功能,传入路径和参数,返回字符串的返回结果 <br/>
*
* @param url
* @param params
* @return
* @throws IOException
*/
public
static
String
getData
(
String
url
,
Map
<
String
,
String
>
params
,
Charset
charset
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
{
List
<
NameValuePair
>
nameValuePairs
=
transferParam
(
params
);
HttpEntity
urlEncodedFormEntity
=
new
UrlEncodedFormEntity
(
nameValuePairs
,
charset
);
String
urlEncoded
=
EntityUtils
.
toString
(
urlEncodedFormEntity
,
charset
);
String
data
=
getData
(
url
,
urlEncoded
,
headerParams
);
return
data
;
}
/**
* http发送get请求
*
* @param url
* @param params
* @param headerParams
* @return
* @throws IOException
*/
public
static
JSONObject
sendGet
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
{
String
retData
=
getData
(
url
,
params
,
Consts
.
UTF_8
,
headerParams
);
if
(
StringUtils
.
isNotBlank
(
retData
))
{
return
JSONObject
.
parseObject
(
retData
);
}
return
new
JSONObject
();
}
/**
* http的put方法
*
* @param url 请求url
* @param json 请求body
* @param headerParams 请求参数
* @return
* @throws IOException
*/
public
static
JSONObject
sendPut
(
String
url
,
String
json
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
{
String
formData
=
putData
(
url
,
json
,
headerParams
);
if
(
StringUtils
.
isNotBlank
(
formData
))
{
return
JSONObject
.
parseObject
(
formData
);
}
return
new
JSONObject
();
}
/**
* http发送delete请求
*
* @param url url
* @param headerParams 请求参数
* @return
* @throws IOException
*/
public
static
JSONObject
sendDelete
(
String
url
,
Map
<
String
,
String
>
headerParams
)
throws
IOException
{
String
retData
=
deleteData
(
url
,
headerParams
);
if
(
StringUtils
.
isNotBlank
(
retData
))
{
return
JSONObject
.
parseObject
(
retData
);
}
return
new
JSONObject
();
}
}
\ No newline at end of file
\ No newline at end of file
src/main/java/com/glsx/modules/notify/demo/AndroidNotification.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
;
import
com.alibaba.fastjson.JSONObject
;
import
java.util.Arrays
;
import
java.util.HashSet
;
public
abstract
class
AndroidNotification
extends
UmengNotification
{
// Keys can be set in the payload level
protected
static
final
HashSet
<
String
>
PAYLOAD_KEYS
=
new
HashSet
<
String
>(
Arrays
.
asList
(
new
String
[]{
"display_type"
}));
// Keys can be set in the body level
protected
static
final
HashSet
<
String
>
BODY_KEYS
=
new
HashSet
<
String
>(
Arrays
.
asList
(
new
String
[]{
"ticker"
,
"title"
,
"text"
,
"builder_id"
,
"icon"
,
"largeIcon"
,
"img"
,
"play_vibrate"
,
"play_lights"
,
"play_sound"
,
"sound"
,
"after_open"
,
"url"
,
"activity"
,
"custom"
}));
public
enum
DisplayType
{
NOTIFICATION
{
public
String
getValue
(){
return
"notification"
;}},
///通知:消息送达到用户设备后,由友盟SDK接管处理并在通知栏上显示通知内容。
MESSAGE
{
public
String
getValue
(){
return
"message"
;}};
///消息:消息送达到用户设备后,消息内容透传给应用自身进行解析处理。
public
abstract
String
getValue
();
}
public
enum
AfterOpenAction
{
go_app
,
//打开应用
go_url
,
//跳转到URL
go_activity
,
//打开特定的activity
go_custom
//用户自定义内容。
}
// Set key/value in the rootJson, for the keys can be set please see ROOT_KEYS, PAYLOAD_KEYS,
// BODY_KEYS and POLICY_KEYS.
@Override
public
boolean
setPredefinedKeyValue
(
String
key
,
Object
value
)
throws
Exception
{
if
(
ROOT_KEYS
.
contains
(
key
))
{
// This key should be in the root level
rootJson
.
put
(
key
,
value
);
}
else
if
(
PAYLOAD_KEYS
.
contains
(
key
))
{
// This key should be in the payload level
JSONObject
payloadJson
=
null
;
if
(
rootJson
.
containsKey
(
"payload"
))
{
payloadJson
=
rootJson
.
getJSONObject
(
"payload"
);
}
else
{
payloadJson
=
new
JSONObject
();
rootJson
.
put
(
"payload"
,
payloadJson
);
}
payloadJson
.
put
(
key
,
value
);
}
else
if
(
BODY_KEYS
.
contains
(
key
))
{
// This key should be in the body level
JSONObject
bodyJson
=
null
;
JSONObject
payloadJson
=
null
;
// 'body' is under 'payload', so build a payload if it doesn't exist
if
(
rootJson
.
containsKey
(
"payload"
))
{
payloadJson
=
rootJson
.
getJSONObject
(
"payload"
);
}
else
{
payloadJson
=
new
JSONObject
();
rootJson
.
put
(
"payload"
,
payloadJson
);
}
// Get body JSONObject, generate one if not existed
if
(
payloadJson
.
containsKey
(
"body"
))
{
bodyJson
=
payloadJson
.
getJSONObject
(
"body"
);
}
else
{
bodyJson
=
new
JSONObject
();
payloadJson
.
put
(
"body"
,
bodyJson
);
}
bodyJson
.
put
(
key
,
value
);
}
else
if
(
POLICY_KEYS
.
contains
(
key
))
{
// This key should be in the body level
JSONObject
policyJson
=
null
;
if
(
rootJson
.
containsKey
(
"policy"
))
{
policyJson
=
rootJson
.
getJSONObject
(
"policy"
);
}
else
{
policyJson
=
new
JSONObject
();
rootJson
.
put
(
"policy"
,
policyJson
);
}
policyJson
.
put
(
key
,
value
);
}
else
{
if
(
key
==
"payload"
||
key
==
"body"
||
key
==
"policy"
||
key
==
"extra"
)
{
throw
new
Exception
(
"You don't need to set value for "
+
key
+
" , just set values for the sub keys in it."
);
}
else
{
throw
new
Exception
(
"Unknown key: "
+
key
);
}
}
return
true
;
}
// Set extra key/value for Android notification
public
boolean
setExtraField
(
String
key
,
String
value
)
throws
Exception
{
JSONObject
payloadJson
=
null
;
JSONObject
extraJson
=
null
;
if
(
rootJson
.
containsKey
(
"payload"
))
{
payloadJson
=
rootJson
.
getJSONObject
(
"payload"
);
}
else
{
payloadJson
=
new
JSONObject
();
rootJson
.
put
(
"payload"
,
payloadJson
);
}
if
(
payloadJson
.
containsKey
(
"extra"
))
{
extraJson
=
payloadJson
.
getJSONObject
(
"extra"
);
}
else
{
extraJson
=
new
JSONObject
();
payloadJson
.
put
(
"extra"
,
extraJson
);
}
extraJson
.
put
(
key
,
value
);
return
true
;
}
//
public
void
setDisplayType
(
DisplayType
d
)
throws
Exception
{
setPredefinedKeyValue
(
"display_type"
,
d
.
getValue
());
}
///通知栏提示文字
public
void
setTicker
(
String
ticker
)
throws
Exception
{
setPredefinedKeyValue
(
"ticker"
,
ticker
);
}
///通知标题
public
void
setTitle
(
String
title
)
throws
Exception
{
setPredefinedKeyValue
(
"title"
,
title
);
}
///通知文字描述
public
void
setText
(
String
text
)
throws
Exception
{
setPredefinedKeyValue
(
"text"
,
text
);
}
///用于标识该通知采用的样式。使用该参数时, 必须在SDK里面实现自定义通知栏样式。
public
void
setBuilderId
(
Integer
builder_id
)
throws
Exception
{
setPredefinedKeyValue
(
"builder_id"
,
builder_id
);
}
///状态栏图标ID, R.drawable.[smallIcon],如果没有, 默认使用应用图标。
public
void
setIcon
(
String
icon
)
throws
Exception
{
setPredefinedKeyValue
(
"icon"
,
icon
);
}
///通知栏拉开后左侧图标ID
public
void
setLargeIcon
(
String
largeIcon
)
throws
Exception
{
setPredefinedKeyValue
(
"largeIcon"
,
largeIcon
);
}
///通知栏大图标的URL链接。该字段的优先级大于largeIcon。该字段要求以http或者https开头。
public
void
setImg
(
String
img
)
throws
Exception
{
setPredefinedKeyValue
(
"img"
,
img
);
}
///收到通知是否震动,默认为"true"
public
void
setPlayVibrate
(
Boolean
play_vibrate
)
throws
Exception
{
setPredefinedKeyValue
(
"play_vibrate"
,
play_vibrate
.
toString
());
}
///收到通知是否闪灯,默认为"true"
public
void
setPlayLights
(
Boolean
play_lights
)
throws
Exception
{
setPredefinedKeyValue
(
"play_lights"
,
play_lights
.
toString
());
}
///收到通知是否发出声音,默认为"true"
public
void
setPlaySound
(
Boolean
play_sound
)
throws
Exception
{
setPredefinedKeyValue
(
"play_sound"
,
play_sound
.
toString
());
}
///通知声音,R.raw.[sound]. 如果该字段为空,采用SDK默认的声音
public
void
setSound
(
String
sound
)
throws
Exception
{
setPredefinedKeyValue
(
"sound"
,
sound
);
}
///收到通知后播放指定的声音文件
public
void
setPlaySound
(
String
sound
)
throws
Exception
{
setPlaySound
(
true
);
setSound
(
sound
);
}
///点击"通知"的后续行为,默认为打开app。
public
void
goAppAfterOpen
()
throws
Exception
{
setAfterOpenAction
(
AfterOpenAction
.
go_app
);
}
public
void
goUrlAfterOpen
(
String
url
)
throws
Exception
{
setAfterOpenAction
(
AfterOpenAction
.
go_url
);
setUrl
(
url
);
}
public
void
goActivityAfterOpen
(
String
activity
)
throws
Exception
{
setAfterOpenAction
(
AfterOpenAction
.
go_activity
);
setActivity
(
activity
);
}
public
void
goCustomAfterOpen
(
String
custom
)
throws
Exception
{
setAfterOpenAction
(
AfterOpenAction
.
go_custom
);
setCustomField
(
custom
);
}
public
void
goCustomAfterOpen
(
JSONObject
custom
)
throws
Exception
{
setAfterOpenAction
(
AfterOpenAction
.
go_custom
);
setCustomField
(
custom
);
}
///点击"通知"的后续行为,默认为打开app。原始接口
public
void
setAfterOpenAction
(
AfterOpenAction
action
)
throws
Exception
{
setPredefinedKeyValue
(
"after_open"
,
action
.
toString
());
}
public
void
setUrl
(
String
url
)
throws
Exception
{
setPredefinedKeyValue
(
"url"
,
url
);
}
public
void
setActivity
(
String
activity
)
throws
Exception
{
setPredefinedKeyValue
(
"activity"
,
activity
);
}
///can be a string of json
public
void
setCustomField
(
String
custom
)
throws
Exception
{
setPredefinedKeyValue
(
"custom"
,
custom
);
}
public
void
setCustomField
(
JSONObject
custom
)
throws
Exception
{
setPredefinedKeyValue
(
"custom"
,
custom
);
}
}
src/main/java/com/glsx/modules/notify/demo/BroadCastService.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
;
import
com.alibaba.fastjson.JSONArray
;
import
com.alibaba.fastjson.JSONObject
;
import
com.glsx.modules.notify.demo.android.AndroidBroadcast
;
import
com.glsx.modules.notify.demo.android.AndroidCustomizedcast
;
import
com.glsx.modules.notify.demo.android.AndroidGroupcast
;
import
com.glsx.modules.notify.demo.android.AndroidUnicast
;
import
com.glsx.modules.notify.demo.ios.IOSBroadcast
;
import
com.glsx.modules.notify.demo.ios.IOSCustomizedcast
;
import
com.glsx.modules.notify.demo.ios.IOSGroupcast
;
import
com.glsx.modules.notify.demo.ios.IOSUnicast
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.stereotype.Service
;
@Service
public
class
BroadCastService
{
@Value
(
"${youmeng.appkey}"
)
private
String
appkey
;
@Value
(
"${youmeng.appMasterSecret}"
)
private
String
appMasterSecret
;
@Autowired
private
PushClient
client
;
public
void
sendAndroidBroadcast
()
throws
Exception
{
AndroidBroadcast
broadcast
=
new
AndroidBroadcast
(
appkey
,
appMasterSecret
);
broadcast
.
setTicker
(
"Android broadcast ticker"
);
broadcast
.
setTitle
(
"中文的title"
);
broadcast
.
setText
(
"Android broadcast text"
);
broadcast
.
goAppAfterOpen
();
broadcast
.
setDisplayType
(
AndroidNotification
.
DisplayType
.
NOTIFICATION
);
// TODO Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
broadcast
.
setProductionMode
();
// Set customized fields
broadcast
.
setExtraField
(
"test"
,
"helloworld"
);
//厂商通道相关参数
broadcast
.
setChannelActivity
(
"your channel activity"
);
broadcast
.
setChannelProperties
(
"abc"
);
client
.
send
(
broadcast
);
}
public
void
sendAndroidUnicast
()
throws
Exception
{
AndroidUnicast
unicast
=
new
AndroidUnicast
(
appkey
,
appMasterSecret
);
// TODO Set your device token
unicast
.
setDeviceToken
(
"your device_token"
);
unicast
.
setTicker
(
"Android unicast ticker"
);
unicast
.
setTitle
(
"中文的title"
);
unicast
.
setText
(
"Android unicast text"
);
unicast
.
goAppAfterOpen
();
unicast
.
setDisplayType
(
AndroidNotification
.
DisplayType
.
NOTIFICATION
);
// TODO Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
unicast
.
setProductionMode
();
// Set customized fields
unicast
.
setExtraField
(
"test"
,
"helloworld"
);
unicast
.
setChannelActivity
(
"your channel activity"
);
unicast
.
setChannelProperties
(
"abc"
);
client
.
send
(
unicast
);
}
public
void
sendAndroidGroupcast
()
throws
Exception
{
AndroidGroupcast
groupcast
=
new
AndroidGroupcast
(
appkey
,
appMasterSecret
);
/* TODO
* Construct the filter condition:
* "where":
* {
* "and":
* [
* {"tag":"test"},
* {"tag":"Test"}
* ]
* }
*/
JSONObject
filterJson
=
new
JSONObject
();
JSONObject
whereJson
=
new
JSONObject
();
JSONArray
tagArray
=
new
JSONArray
();
JSONObject
testTag
=
new
JSONObject
();
JSONObject
TestTag
=
new
JSONObject
();
testTag
.
put
(
"tag"
,
"test"
);
TestTag
.
put
(
"tag"
,
"Test"
);
tagArray
.
add
(
testTag
);
tagArray
.
add
(
TestTag
);
whereJson
.
put
(
"and"
,
tagArray
);
filterJson
.
put
(
"where"
,
whereJson
);
groupcast
.
setFilter
(
filterJson
);
groupcast
.
setTicker
(
"Android groupcast ticker"
);
groupcast
.
setTitle
(
"中文的title"
);
groupcast
.
setText
(
"Android groupcast text"
);
groupcast
.
goAppAfterOpen
();
groupcast
.
setDisplayType
(
AndroidNotification
.
DisplayType
.
NOTIFICATION
);
groupcast
.
setChannelActivity
(
"your channel activity"
);
// TODO Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
groupcast
.
setProductionMode
();
//厂商通道相关参数
groupcast
.
setChannelActivity
(
"your channel activity"
);
groupcast
.
setChannelProperties
(
"abc"
);
client
.
send
(
groupcast
);
}
public
void
sendAndroidCustomizedcast
()
throws
Exception
{
AndroidCustomizedcast
customizedcast
=
new
AndroidCustomizedcast
(
appkey
,
appMasterSecret
);
// TODO Set your alias here, and use comma to split them if there are multiple alias.
// And if you have many alias, you can also upload a file containing these alias, then
// use file_id to send customized notification.
//addAlias("你与后台商定的用来区分用户的不能相同的", "可以是写死的别名项目名随意"
customizedcast
.
setAlias
(
"alias"
,
"alias_type"
);
//通知栏提示文字
customizedcast
.
setTicker
(
"Android customizedcast ticker"
);
//通知标题
customizedcast
.
setTitle
(
"中文的title"
);
//通知文字描述
customizedcast
.
setText
(
"Android customizedcast text"
);
customizedcast
.
goAppAfterOpen
();
customizedcast
.
setDisplayType
(
AndroidNotification
.
DisplayType
.
NOTIFICATION
);
// TODO Set 'production_mode' to 'false' if it's a test device.
// For how to register a test device, please see the developer doc.
customizedcast
.
setProductionMode
();
//厂商通道相关参数
customizedcast
.
setChannelActivity
(
"your channel activity"
);
customizedcast
.
setChannelProperties
(
"abc"
);
client
.
send
(
customizedcast
);
}
//public void sendAndroidCustomizedcastFile() throws Exception {
// AndroidCustomizedcast customizedcast = new AndroidCustomizedcast(appkey,appMasterSecret);
// // TODO Set your alias here, and use comma to split them if there are multiple alias.
// // And if you have many alias, you can also upload a file containing these alias, then
// // use file_id to send customized notification.
// String fileId = client.uploadContents(appkey,appMasterSecret,"aa"+"\n"+"bb"+"\n"+"alias");
// customizedcast.setFileId(fileId, "alias_type");
// customizedcast.setTicker( "Android customizedcast ticker");
// customizedcast.setTitle( "中文的title");
// customizedcast.setText( "Android customizedcast text");
// customizedcast.goAppAfterOpen();
// customizedcast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
// // TODO Set 'production_mode' to 'false' if it's a test device.
// // For how to register a test device, please see the developer doc.
// customizedcast.setProductionMode();
// //厂商通道相关参数
// customizedcast.setChannelActivity("your channel activity");
// customizedcast.setChannelProperties("abc");
// client.send(customizedcast);
//}
//
//public void sendAndroidFilecast() throws Exception {
// AndroidFilecast filecast = new AndroidFilecast(appkey,appMasterSecret);
// // TODO upload your device tokens, and use '\n' to split them if there are multiple tokens
// String fileId = client.uploadContents(appkey,appMasterSecret,"aa"+"\n"+"bb");
// filecast.setFileId( fileId);
// filecast.setTicker( "Android filecast ticker");
// filecast.setTitle( "中文的title");
// filecast.setText( "Android filecast text");
// filecast.goAppAfterOpen();
// filecast.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION);
// //厂商通道相关参数
// filecast.setChannelActivity("your channel activity");
// filecast.setChannelProperties("abc");
// client.send(filecast);
//}
public
void
sendIOSBroadcast
()
throws
Exception
{
IOSBroadcast
broadcast
=
new
IOSBroadcast
(
appkey
,
appMasterSecret
);
//alert值设置为字符串
//broadcast.setAlert("IOS 广播测试");
//alert的值设置为字典
broadcast
.
setAlert
(
"今日天气"
,
""
,
"今日可能下雨🌂"
);
broadcast
.
setBadge
(
0
);
broadcast
.
setSound
(
"default"
);
// TODO set 'production_mode' to 'true' if your app is under production mode
broadcast
.
setTestMode
();
// Set customized fields
broadcast
.
setCustomizedField
(
"test"
,
"helloworld"
);
client
.
send
(
broadcast
);
}
public
void
sendIOSUnicast
()
throws
Exception
{
IOSUnicast
unicast
=
new
IOSUnicast
(
appkey
,
appMasterSecret
);
// TODO Set your device token
unicast
.
setDeviceToken
(
"your device_token"
);
//alert值设置为字符串
//unicast.setAlert("IOS 单播测试");
//alert的值设置为字典
unicast
.
setAlert
(
"今日天气"
,
""
,
"今日可能下雨🌂"
);
unicast
.
setBadge
(
0
);
unicast
.
setSound
(
"default"
);
// TODO set 'production_mode' to 'true' if your app is under production mode
unicast
.
setTestMode
();
// Set customized fields
unicast
.
setCustomizedField
(
"test"
,
"helloworld"
);
client
.
send
(
unicast
);
}
public
void
sendIOSGroupcast
()
throws
Exception
{
IOSGroupcast
groupcast
=
new
IOSGroupcast
(
appkey
,
appMasterSecret
);
/* TODO
* Construct the filter condition:
* "where":
* {
* "and":
* [
* {"tag":"iostest"}
* ]
* }
*/
JSONObject
filterJson
=
new
JSONObject
();
JSONObject
whereJson
=
new
JSONObject
();
JSONArray
tagArray
=
new
JSONArray
();
JSONObject
testTag
=
new
JSONObject
();
testTag
.
put
(
"tag"
,
"iostest"
);
tagArray
.
add
(
testTag
);
whereJson
.
put
(
"and"
,
tagArray
);
filterJson
.
put
(
"where"
,
whereJson
);
System
.
out
.
println
(
filterJson
.
toString
());
// Set filter condition into rootJson
groupcast
.
setFilter
(
filterJson
);
//groupcast.setAlert("IOS 组播测试");
//alert的值设置为字典
groupcast
.
setAlert
(
"今日天气"
,
"subtitle"
,
"今日可能下雨🌂"
);
groupcast
.
setBadge
(
0
);
groupcast
.
setSound
(
"default"
);
// TODO set 'production_mode' to 'true' if your app is under production mode
groupcast
.
setTestMode
();
client
.
send
(
groupcast
);
}
public
void
sendIOSCustomizedcast
()
throws
Exception
{
IOSCustomizedcast
customizedcast
=
new
IOSCustomizedcast
(
appkey
,
appMasterSecret
);
// TODO Set your alias and alias_type here, and use comma to split them if there are multiple alias.
// And if you have many alias, you can also upload a file containing these alias, then
// use file_id to send customized notification.
customizedcast
.
setAlias
(
"alias"
,
"alias_type"
);
//customizedcast.setAlert("IOS 个性化测试");
//alert的值设置为字典
customizedcast
.
setAlert
(
"今日天气"
,
""
,
"今日可能下雨🌂"
);
customizedcast
.
setBadge
(
0
);
customizedcast
.
setSound
(
"default"
);
// TODO set 'production_mode' to 'true' if your app is under production mode
customizedcast
.
setTestMode
();
client
.
send
(
customizedcast
);
}
//public void sendIOSFilecast() throws Exception {
// IOSFilecast filecast = new IOSFilecast(appkey,appMasterSecret);
// // TODO upload your device tokens, and use '\n' to split them if there are multiple tokens
// String fileId = client.uploadContents(appkey,appMasterSecret,"aa"+"\n"+"bb");
// filecast.setFileId( fileId);
// //filecast.setAlert("IOS 文件播测试");
// //alert的值设置为字典
// filecast.setAlert("今日天气" , "" , "今日可能下雨🌂");
// filecast.setBadge( 0);
// filecast.setSound( "default");
// // TODO set 'production_mode' to 'true' if your app is under production mode
// filecast.setTestMode();
// client.send(filecast);
//}
}
src/main/java/com/glsx/modules/notify/demo/IOSNotification.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
;
import
com.alibaba.fastjson.JSONObject
;
import
java.util.Arrays
;
import
java.util.HashSet
;
public
abstract
class
IOSNotification
extends
UmengNotification
{
// Keys can be set in the aps level
protected
static
final
HashSet
<
String
>
APS_KEYS
=
new
HashSet
<
String
>(
Arrays
.
asList
(
new
String
[]{
"alert"
,
"badge"
,
"sound"
,
"content-available"
}));
@Override
public
boolean
setPredefinedKeyValue
(
String
key
,
Object
value
)
throws
Exception
{
if
(
ROOT_KEYS
.
contains
(
key
))
{
// This key should be in the root level
rootJson
.
put
(
key
,
value
);
}
else
if
(
APS_KEYS
.
contains
(
key
))
{
// This key should be in the aps level
JSONObject
apsJson
=
null
;
JSONObject
payloadJson
=
null
;
if
(
rootJson
.
containsKey
(
"payload"
))
{
payloadJson
=
rootJson
.
getJSONObject
(
"payload"
);
}
else
{
payloadJson
=
new
JSONObject
();
rootJson
.
put
(
"payload"
,
payloadJson
);
}
if
(
payloadJson
.
containsKey
(
"aps"
))
{
apsJson
=
payloadJson
.
getJSONObject
(
"aps"
);
}
else
{
apsJson
=
new
JSONObject
();
payloadJson
.
put
(
"aps"
,
apsJson
);
}
apsJson
.
put
(
key
,
value
);
}
else
if
(
POLICY_KEYS
.
contains
(
key
))
{
// This key should be in the body level
JSONObject
policyJson
=
null
;
if
(
rootJson
.
containsKey
(
"policy"
))
{
policyJson
=
rootJson
.
getJSONObject
(
"policy"
);
}
else
{
policyJson
=
new
JSONObject
();
rootJson
.
put
(
"policy"
,
policyJson
);
}
policyJson
.
put
(
key
,
value
);
}
else
{
if
(
key
==
"payload"
||
key
==
"aps"
||
key
==
"policy"
)
{
throw
new
Exception
(
"You don't need to set value for "
+
key
+
" , just set values for the sub keys in it."
);
}
else
{
throw
new
Exception
(
"Unknownd key: "
+
key
);
}
}
return
true
;
}
// Set customized key/value for IOS notification
public
boolean
setCustomizedField
(
String
key
,
String
value
)
throws
Exception
{
//rootJson.put(key, value);
JSONObject
payloadJson
=
null
;
if
(
rootJson
.
containsKey
(
"payload"
))
{
payloadJson
=
rootJson
.
getJSONObject
(
"payload"
);
}
else
{
payloadJson
=
new
JSONObject
();
rootJson
.
put
(
"payload"
,
payloadJson
);
}
payloadJson
.
put
(
key
,
value
);
return
true
;
}
public
void
setAlert
(
String
token
)
throws
Exception
{
setPredefinedKeyValue
(
"alert"
,
token
);
}
public
void
setAlert
(
String
title
,
String
subtitle
,
String
body
)
throws
Exception
{
JSONObject
object
=
new
JSONObject
();
object
.
put
(
"title"
,
title
);
object
.
put
(
"subtitle"
,
subtitle
);
object
.
put
(
"body"
,
body
);
setPredefinedKeyValue
(
"alert"
,
object
);
}
public
void
setBadge
(
Integer
badge
)
throws
Exception
{
setPredefinedKeyValue
(
"badge"
,
badge
);
}
public
void
setSound
(
String
sound
)
throws
Exception
{
setPredefinedKeyValue
(
"sound"
,
sound
);
}
public
void
setContentAvailable
(
Integer
contentAvailable
)
throws
Exception
{
setPredefinedKeyValue
(
"content-available"
,
contentAvailable
);
}
}
src/main/java/com/glsx/modules/notify/demo/PushClient.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
;
import
com.alibaba.fastjson.JSONObject
;
import
com.glsx.common.utils.HttpUtil
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.codec.digest.DigestUtils
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.stereotype.Component
;
import
java.io.IOException
;
@Component
@Slf4j
public
class
PushClient
{
// The user agent
//protected final String USER_AGENT = "Mozilla/5.0";
//
//// This object is used for sending the post request to Umeng
//protected HttpClient client = new DefaultHttpClient();
//
//// The host
@Value
(
"${youmeng.host}"
)
protected
String
host
;
//
//// The upload path
////protected static final String uploadPath = "/upload";
//
//// The post path
@Value
(
"${youmeng.postPath}"
)
protected
String
postPath
;
//
//public boolean send(UmengNotification msg) throws Exception {
// String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
// msg.setPredefinedKeyValue("timestamp", timestamp);
// String url = host + postPath;
// String postBody = msg.getPostBody();
// String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
// url = url + "?sign=" + sign;
// HttpPost post = new HttpPost(url);
// post.setHeader("User-Agent", USER_AGENT);
// StringEntity se = new StringEntity(postBody, "UTF-8");
// post.setEntity(se);
// // Send the post request and get the response
// HttpResponse response = client.execute(post);
// int status = response.getStatusLine().getStatusCode();
// System.out.println("Response Code : " + status);
// BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// StringBuffer result = new StringBuffer();
// String line = "";
// while ((line = rd.readLine()) != null) {
// result.append(line);
// }
// System.out.println(result.toString());
// if (status == 200) {
// System.out.println("Notification sent successfully.");
// } else {
// System.out.println("Failed to send the notification!");
// }
// return true;
//}
// Upload file with device_tokens to Umeng
//public String uploadContents(String appkey,String appMasterSecret,String contents) throws Exception {
// // Construct the json string
// JSONObject uploadJson = new JSONObject();
// uploadJson.put("appkey", appkey);
// String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
// uploadJson.put("timestamp", timestamp);
// uploadJson.put("content", contents);
// // Construct the request
// String url = host + uploadPath;
// String postBody = uploadJson.toString();
// String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
// url = url + "?sign=" + sign;
// HttpPost post = new HttpPost(url);
// post.setHeader("User-Agent", USER_AGENT);
// StringEntity se = new StringEntity(postBody, "UTF-8");
// post.setEntity(se);
// // Send the post request and get the response
// HttpResponse response = client.execute(post);
// System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
// BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// StringBuffer result = new StringBuffer();
// String line = "";
// while ((line = rd.readLine()) != null) {
// result.append(line);
// }
// System.out.println(result.toString());
// // Decode response string and get file_id from it
// JSONObject respJson = new JSONObject(result.toString());
// String ret = respJson.getString("ret");
// if (!ret.equals("SUCCESS")) {
// throw new Exception("Failed to upload file");
// }
// JSONObject data = respJson.getJSONObject("data");
// String fileId = data.getString("file_id");
// // Set file_id into rootJson using setPredefinedKeyValue
//
// return fileId;
//}
public
boolean
send
(
UmengNotification
msg
)
throws
Exception
{
String
timestamp
=
Integer
.
toString
((
int
)
(
System
.
currentTimeMillis
()
/
1000
));
msg
.
setPredefinedKeyValue
(
"timestamp"
,
timestamp
);
String
url
=
host
+
postPath
;
String
postBody
=
msg
.
getPostBody
();
log
.
info
(
"调用url======="
+
url
);
log
.
info
(
"调用body======="
+
postBody
);
String
sign
=
DigestUtils
.
md5Hex
((
"POST"
+
url
+
postBody
+
msg
.
getAppMasterSecret
()).
getBytes
(
"utf8"
));
url
=
url
+
"?sign="
+
sign
;
JSONObject
respJson
=
null
;
try
{
respJson
=
HttpUtil
.
sendPost
(
url
,
postBody
);
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
log
.
info
(
"调用请求失败:"
+
e
.
getMessage
());
}
String
ret
=
respJson
.
getString
(
"ret"
);
JSONObject
data
=
respJson
.
getJSONObject
(
"data"
);
if
(!
ret
.
equals
(
"SUCCESS"
))
{
String
errorCode
=
data
.
getString
(
"error_code"
);
String
errorMsg
=
data
.
getString
(
"error_msg"
);
log
.
error
(
"友盟fail===errorCode:"
+
errorCode
+
"===errorMsg:"
+
errorMsg
);
return
false
;
}
return
true
;
}
}
src/main/java/com/glsx/modules/notify/demo/UmengNotification.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
;
import
com.alibaba.fastjson.JSONObject
;
import
java.util.Arrays
;
import
java.util.HashSet
;
public
abstract
class
UmengNotification
{
// This JSONObject is used for constructing the whole request string.
protected
final
JSONObject
rootJson
=
new
JSONObject
();
// The app master secret
protected
String
appMasterSecret
;
// Keys can be set in the root level
protected
static
final
HashSet
<
String
>
ROOT_KEYS
=
new
HashSet
<
String
>(
Arrays
.
asList
(
new
String
[]{
"appkey"
,
"timestamp"
,
"type"
,
"device_tokens"
,
"alias"
,
"alias_type"
,
"file_id"
,
"filter"
,
"production_mode"
,
"feedback"
,
"description"
,
"thirdparty_id"
,
"mipush"
,
"mi_activity"
,
"channel_properties"
}));
// Keys can be set in the policy level
protected
static
final
HashSet
<
String
>
POLICY_KEYS
=
new
HashSet
<
String
>(
Arrays
.
asList
(
new
String
[]{
"start_time"
,
"expire_time"
,
"max_send_num"
}));
// Set predefined keys in the rootJson, for extra keys(Android) or customized keys(IOS) please
// refer to corresponding methods in the subclass.
public
abstract
boolean
setPredefinedKeyValue
(
String
key
,
Object
value
)
throws
Exception
;
public
void
setAppMasterSecret
(
String
secret
)
{
appMasterSecret
=
secret
;
}
public
String
getPostBody
(){
return
rootJson
.
toString
();
}
protected
final
String
getAppMasterSecret
(){
return
appMasterSecret
;
}
protected
void
setProductionMode
(
Boolean
prod
)
throws
Exception
{
setPredefinedKeyValue
(
"production_mode"
,
prod
.
toString
());
}
///正式模式
public
void
setProductionMode
()
throws
Exception
{
setProductionMode
(
true
);
}
///测试模式
public
void
setTestMode
()
throws
Exception
{
setProductionMode
(
false
);
}
///发送消息描述,建议填写。
public
void
setDescription
(
String
description
)
throws
Exception
{
setPredefinedKeyValue
(
"description"
,
description
);
}
///定时发送时间,若不填写表示立即发送。格式: "YYYY-MM-DD hh:mm:ss"。
public
void
setStartTime
(
String
startTime
)
throws
Exception
{
setPredefinedKeyValue
(
"start_time"
,
startTime
);
}
///消息过期时间,格式: "YYYY-MM-DD hh:mm:ss"。
public
void
setExpireTime
(
String
expireTime
)
throws
Exception
{
setPredefinedKeyValue
(
"expire_time"
,
expireTime
);
}
///发送限速,每秒发送的最大条数。
public
void
setMaxSendNum
(
Integer
num
)
throws
Exception
{
setPredefinedKeyValue
(
"max_send_num"
,
num
);
}
//厂商弹窗activity
public
void
setChannelActivity
(
String
activity
)
throws
Exception
{
setPredefinedKeyValue
(
"mipush"
,
"true"
);
setPredefinedKeyValue
(
"mi_activity"
,
activity
);
}
//厂商属性配置
public
void
setChannelProperties
(
String
xiaoMiChannelId
)
throws
Exception
{
JSONObject
object
=
new
JSONObject
();
object
.
put
(
"xiaomi_channel_id"
,
xiaoMiChannelId
);
setPredefinedKeyValue
(
"channel_properties"
,
object
);
}
}
src/main/java/com/glsx/modules/notify/demo/android/AndroidBroadcast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
android
;
import
com.glsx.modules.notify.demo.AndroidNotification
;
public
class
AndroidBroadcast
extends
AndroidNotification
{
public
AndroidBroadcast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"broadcast"
);
}
}
src/main/java/com/glsx/modules/notify/demo/android/AndroidCustomizedcast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
android
;
import
com.glsx.modules.notify.demo.AndroidNotification
;
public
class
AndroidCustomizedcast
extends
AndroidNotification
{
public
AndroidCustomizedcast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"customizedcast"
);
}
public
void
setAlias
(
String
alias
,
String
aliasType
)
throws
Exception
{
setPredefinedKeyValue
(
"alias"
,
alias
);
setPredefinedKeyValue
(
"alias_type"
,
aliasType
);
}
public
void
setFileId
(
String
fileId
,
String
aliasType
)
throws
Exception
{
setPredefinedKeyValue
(
"file_id"
,
fileId
);
setPredefinedKeyValue
(
"alias_type"
,
aliasType
);
}
}
src/main/java/com/glsx/modules/notify/demo/android/AndroidFilecast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
android
;
import
com.glsx.modules.notify.demo.AndroidNotification
;
public
class
AndroidFilecast
extends
AndroidNotification
{
public
AndroidFilecast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"filecast"
);
}
public
void
setFileId
(
String
fileId
)
throws
Exception
{
setPredefinedKeyValue
(
"file_id"
,
fileId
);
}
}
\ No newline at end of file
\ No newline at end of file
src/main/java/com/glsx/modules/notify/demo/android/AndroidGroupcast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
android
;
import
com.alibaba.fastjson.JSONObject
;
import
com.glsx.modules.notify.demo.AndroidNotification
;
public
class
AndroidGroupcast
extends
AndroidNotification
{
public
AndroidGroupcast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"groupcast"
);
}
public
void
setFilter
(
JSONObject
filter
)
throws
Exception
{
setPredefinedKeyValue
(
"filter"
,
filter
);
}
}
src/main/java/com/glsx/modules/notify/demo/android/AndroidUnicast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
android
;
import
com.glsx.modules.notify.demo.AndroidNotification
;
public
class
AndroidUnicast
extends
AndroidNotification
{
public
AndroidUnicast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"unicast"
);
}
public
void
setDeviceToken
(
String
token
)
throws
Exception
{
setPredefinedKeyValue
(
"device_tokens"
,
token
);
}
}
\ No newline at end of file
\ No newline at end of file
src/main/java/com/glsx/modules/notify/demo/ios/IOSBroadcast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
ios
;
import
com.glsx.modules.notify.demo.IOSNotification
;
public
class
IOSBroadcast
extends
IOSNotification
{
public
IOSBroadcast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"broadcast"
);
}
}
src/main/java/com/glsx/modules/notify/demo/ios/IOSCustomizedcast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
ios
;
import
com.glsx.modules.notify.demo.IOSNotification
;
public
class
IOSCustomizedcast
extends
IOSNotification
{
public
IOSCustomizedcast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"customizedcast"
);
}
public
void
setAlias
(
String
alias
,
String
aliasType
)
throws
Exception
{
setPredefinedKeyValue
(
"alias"
,
alias
);
setPredefinedKeyValue
(
"alias_type"
,
aliasType
);
}
public
void
setFileId
(
String
fileId
,
String
aliasType
)
throws
Exception
{
setPredefinedKeyValue
(
"file_id"
,
fileId
);
setPredefinedKeyValue
(
"alias_type"
,
aliasType
);
}
}
src/main/java/com/glsx/modules/notify/demo/ios/IOSFilecast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
ios
;
import
com.glsx.modules.notify.demo.IOSNotification
;
public
class
IOSFilecast
extends
IOSNotification
{
public
IOSFilecast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"filecast"
);
}
public
void
setFileId
(
String
fileId
)
throws
Exception
{
setPredefinedKeyValue
(
"file_id"
,
fileId
);
}
}
src/main/java/com/glsx/modules/notify/demo/ios/IOSGroupcast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
ios
;
import
com.alibaba.fastjson.JSONObject
;
import
com.glsx.modules.notify.demo.IOSNotification
;
public
class
IOSGroupcast
extends
IOSNotification
{
public
IOSGroupcast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"groupcast"
);
}
public
void
setFilter
(
JSONObject
filter
)
throws
Exception
{
setPredefinedKeyValue
(
"filter"
,
filter
);
}
}
src/main/java/com/glsx/modules/notify/demo/ios/IOSUnicast.java
0 → 100644
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
demo
.
ios
;
import
com.glsx.modules.notify.demo.IOSNotification
;
public
class
IOSUnicast
extends
IOSNotification
{
public
IOSUnicast
(
String
appkey
,
String
appMasterSecret
)
throws
Exception
{
setAppMasterSecret
(
appMasterSecret
);
setPredefinedKeyValue
(
"appkey"
,
appkey
);
this
.
setPredefinedKeyValue
(
"type"
,
"unicast"
);
}
public
void
setDeviceToken
(
String
token
)
throws
Exception
{
setPredefinedKeyValue
(
"device_tokens"
,
token
);
}
}
src/main/java/com/glsx/modules/notify/service/DeviceService.java
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
service
;
package
com
.
glsx
.
modules
.
notify
.
service
;
import
com.glsx.plat.core.web.R
;
import
com.glsx.plat.core.web.R
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiOperation
;
import
org.springframework.stereotype.Controller
;
import
org.springframework.stereotype.Service
;
import
org.springframework.stereotype.Service
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.PathVariable
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestMethod
;
import
org.springframework.web.bind.annotation.ResponseBody
;
/**
/**
...
...
src/test/java/com/glsx/modules/notify/controller/DeviceControllerTest.java
View file @
3501a16
package
com
.
glsx
.
modules
.
notify
.
controller
;
package
com
.
glsx
.
modules
.
notify
.
controller
;
import
com.glsx.modules.notify.demo.BroadCastService
;
import
com.glsx.modules.notify.service.DeviceService
;
import
com.glsx.modules.notify.service.DeviceService
;
import
com.glsx.plat.core.web.R
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
import
org.junit.Test
;
import
org.junit.Test
;
import
org.junit.runner.RunWith
;
import
org.junit.runner.RunWith
;
...
@@ -9,8 +9,6 @@ import org.springframework.beans.factory.annotation.Autowired;
...
@@ -9,8 +9,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.boot.test.context.SpringBootTest
;
import
org.springframework.boot.test.context.SpringBootTest
;
import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner
;
import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner
;
import
static
org
.
junit
.
Assert
.*;
@RunWith
(
SpringJUnit4ClassRunner
.
class
)
@RunWith
(
SpringJUnit4ClassRunner
.
class
)
@SpringBootTest
@SpringBootTest
@Slf4j
@Slf4j
...
@@ -18,9 +16,29 @@ public class DeviceControllerTest {
...
@@ -18,9 +16,29 @@ public class DeviceControllerTest {
@Autowired
@Autowired
private
DeviceService
deviceService
;
private
DeviceService
deviceService
;
@Autowired
private
BroadCastService
demo
;
@Test
@Test
public
void
getAllDevicesByUser
()
{
public
void
getAllDevicesByUser
()
{
R
r
=
deviceService
.
getAllDevicesByUser
(
"1"
);
try
{
log
.
info
(
r
.
toString
());
demo
.
sendAndroidUnicast
();
//demo.sendIOSUnicast();
/* TODO these methods are all available, just fill in some fields and do the test
* demo.sendAndroidCustomizedcastFile();
* demo.sendAndroidBroadcast();
* demo.sendAndroidGroupcast();
* demo.sendAndroidCustomizedcast();
* demo.sendAndroidFilecast();
*
* demo.sendIOSBroadcast();
* demo.sendIOSUnicast();
* demo.sendIOSGroupcast();
* demo.sendIOSCustomizedcast();
* demo.sendIOSFilecast();
*/
}
catch
(
Exception
ex
)
{
ex
.
printStackTrace
();
}
}
}
}
}
\ No newline at end of file
\ No newline at end of file
Write
Preview
Markdown
is supported
Attach a file
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 post a comment