diff --git a/.classpath b/.classpath
deleted file mode 100644
index dce4385f..00000000
--- a/.classpath
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
new file mode 100644
index 00000000..126ba84c
--- /dev/null
+++ b/.github/workflows/maven.yml
@@ -0,0 +1,35 @@
+name: Publish package to the Maven Central Repository
+on:
+ release:
+ types: [published]
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v2
+ - name: Set up JDK 1.8
+ uses: actions/setup-java@v1
+ with:
+ java-version: 1.8
+
+ - name: Build with Maven
+ run: mvn -B clean package -Dmaven.test.skip
+
+ - name: Set up Apache Maven Central
+ uses: actions/setup-java@v1
+ with: # running setup-java again overwrites the settings.xml
+ java-version: 1.8
+ server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml
+ server-username: MAVEN_USERNAME # env variable for username in deploy
+ server-password: MAVEN_PASSWORD # env variable for token in deploy
+ gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} # Value of the GPG private key to import
+ gpg-passphrase: MAVEN_GPG_PASSPHRASE # env variable for GPG private key passphrase
+
+ - name: Publish to Apache Maven Central
+ run: mvn deploy -Dmaven.test.skip
+ env:
+ MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }}
+ MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }}
+ MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }}
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
index 998ec3c7..5dd802ea 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,7 @@ bin/
target/
test-output/
.idea/
+.classpath
*.class
*.project
@@ -12,6 +13,5 @@ test-output/
*.ear
*.iml
-pom.xml.releaseBackup
-release.properties
-
+*.releaseBackup
+release.properties
\ No newline at end of file
diff --git a/.project b/.project
deleted file mode 100644
index 577a5514..00000000
--- a/.project
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
- jpush-api
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.eclipse.m2e.core.maven2Builder
-
-
-
-
-
- org.eclipse.m2e.core.maven2Nature
- org.eclipse.jdt.core.javanature
-
-
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 7db7478d..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-language: java
-
-jdk:
- - oraclejdk7
- - oraclejdk8
- - openjdk6
- - openjdk7
-
-#branches:
-# only:
-# - master
-
-
diff --git a/README.md b/README.md
index 4f1f4078..185e9c2e 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,15 @@
-[](https://travis-ci.org/jpush/jpush-api-java-client)
-[](https://www.versioneye.com/user/projects/53eff13a13bb06f0bb000518)
+# 新版 SDK
+欢迎使用新一代 [jiguang-sdk-java](https://github.com/jpush/jiguang-sdk-java)!这个 SDK 旨在提供更好的性能、更多功能和更好的用户体验。
+
+为什么升级?
+* 性能优化:新版本经过优化,运行更快,消耗更少的资源。
+* 功能增强:引入了许多新功能和改进,使您的开发工作更加高效。
+* Bug 修复:解决了上个版本存在的问题,提高了稳定性和可靠性。
+
+> 极光已推出新版本的 SDK 供广大用户使用,当前版本后续将不推荐使用,请移步仓库 [jiguang-sdk-java](https://github.com/jpush/jiguang-sdk-java) 了解更多。
+
+# ~~旧版 SDK~~
+
[](http://badge.fury.io/gh/jpush%2Fjpush-api-java-client)
# JPush API Java Library
@@ -8,30 +18,17 @@
这是 JPush REST API 的 Java 版本封装开发包,是由极光推送官方提供的,一般支持最新的 API 功能。
-对应的 REST API 文档:
-
-本开发包 Javadoc:[API Docs](http://jpush.github.io/jpush-api-java-client/apidocs/)
+对应的 REST API 文档:[REST API - Push](https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/), [REST API - Report](https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/).
版本更新:[Release页面](https://github.com/jpush/jpush-api-java-client/releases)。下载更新请到这里。
+> 非常欢迎各位开发者提交代码,贡献一份力量,review过有效的代码将会合入本项目。
-## 安装
-
-### maven 方式
-将下边的依赖条件放到你项目的 maven pom.xml 文件里。
-
-```
-
- cn.jpush.api
- jpush-client
- 3.2.6
-
-```
-### jar 包方式
-请到 [Release页面](https://github.com/jpush/jpush-api-java-client/releases)下载相应版本的发布包。
+## 安装
### 依赖包
+* [jiguang-java-client-common](https://github.com/jpush/jiguang-java-client-common) / 极光 Java client 的公共封装开发包,必须依赖,v1.1.11 为例,查看[最新版本](https://github.com/jpush/jiguang-java-client-common/releases)
* [slf4j](http://www.slf4j.org/) / log4j (Logger)
* [gson](https://code.google.com/p/google-gson/) (Google JSON Utils)
@@ -39,40 +36,64 @@
如果使用 Maven 构建项目,则需要在你的项目 pom.xml 里增加:
-```
-
- com.google.code.gson
- gson
- 2.2.4
-
-
- org.slf4j
- slf4j-api
- 1.7.5
-
-
-
-
- org.slf4j
- slf4j-log4j12
- 1.7.5
-
-
- log4j
- log4j
- 1.2.16
-
-
-
+```Java
+
+ cn.jpush.api
+ jiguang-common
+ 1.1.11
+
+
+ io.netty
+ netty-all
+ 4.1.6.Final
+ compile
+
+
+ com.google.code.gson
+ gson
+ 2.3
+
+
+ org.slf4j
+ slf4j-api
+ 1.7.7
+
+
+
+
+ org.slf4j
+ slf4j-log4j12
+ 1.7.7
+
+
+ log4j
+ log4j
+ 1.2.17
+
```
如果不使用 Maven 构建项目,则项目 libs/ 目录下有依赖的 jar 可复制到你的项目里去。
+## 编译源码
+
+> 如果开发者想基于本项目做一些扩展的开发,或者想了解本项目源码,可以参考此章,否则可略过此章。
+
+### 导入本项目
+
+* 可以采用 `git clone https://github.com/jpush/jpush-api-java-client.git jpush-api-src` 命令下载源码
+* 如果不使用git,请到[Release页面](https://github.com/jpush/jpush-api-java-client/releases)下载源码包并解压
+* 采用eclipse导入下载的源码工程,推荐采用maven的方式,方便依赖包的管理
+* 假如采用导入普通项目的方式,项目报错,检查Build Path,Libraries
+ * 依赖jar包都在libs目录下可以找到,没有加入的请添加到Build Path,Libraries
+ * 默认采用了log4j做日志框架,开发者可根据自己需求替换logback、commons-logging等日志框架
+ * 极个别情况下,如果test目录报错,请手动添加test的依赖jar包mockwebserver-2.0.0.jar、okhttp-2.0.0.jar、okio-1.0.0.jar
+* 开发者需要注意,将本项目的编码格式设置为UTF-8
+
### 构建本项目
可以用 Eclipse 类 IDE 导出 jar 包。建议直接使用 maven,执行命令:
- maven package
+ mvn package
### 自动化测试
@@ -81,13 +102,28 @@
mvn test
## 使用样例
+如果使用 NettyHttpClient(v3.2.15 版本新增),需要在响应返回后手动调用一下 NettyHttpClient 中的 close 方法,否则进程不会退出。代码示例:
+```
+...
+try {
+ PushResult result = jpushClient.sendPush(payload);
+ LOG.info("Got result - " + result);
+ Thread.sleep(5000);
+ // 请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
+ jpushClient.close();
+} catch(InterruptedException e) {
+ e.printStackTrace();
+}
+```
+
+3.2.17 版本后,在 PushClient 中添加了 setHttpClient(IHttpClient client) 方法,用户可以自由切换 ApacheHttpClient,NettyHttpClient 或是 NativeHttpClient。
### 推送样例
> 以下片断来自项目代码里的文件:example / cn.jpush.api.examples.PushExample
```Java
- JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());
// For push, all you need do is to build PushPayload object.
PushPayload payload = buildPushObject_all_all_alert();
@@ -95,7 +131,7 @@
try {
PushResult result = jpushClient.sendPush(payload);
LOG.info("Got result - " + result);
-
+
} catch (APIConnectionException e) {
// Connection error, should retry later
LOG.error("Connection error, should retry later", e);
@@ -143,7 +179,7 @@
}
```
-* 构建推送对象:平台是 iOS,推送目标是 "tag1", "tag_all" 的并集,推送内容同时包括通知与消息 - 通知信息是 ALERT,角标数字为 5,通知声音为 "happy",并且附加字段 from = "JPush";消息内容是 MSG_CONTENT。通知是 APNs 推送通道的,消息是 JPush 应用内消息通道的。APNs 的推送环境是“生产”(如果不显式设置的话,Library 会默认指定为开发)
+* 构建推送对象:平台是 iOS,推送目标是 "tag1", "tag_all" 的交集,推送内容同时包括通知与消息 - 通知信息是 ALERT,角标数字为 5,通知声音为 "happy",并且附加字段 from = "JPush";消息内容是 MSG_CONTENT。通知是 APNs 推送通道的,消息是 JPush 应用内消息通道的。APNs 的推送环境是“生产”(如果不显式设置的话,Library 会默认指定为开发)
```Java
public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
@@ -166,7 +202,7 @@
}
```
-* 构建推送对象:平台是 Andorid 与 iOS,推送目标是 ("tag1" 与 "tag2" 的交集)并("alias1" 与 "alias2" 的交集),推送内容是 - 内容为 MSG_CONTENT 的消息,并且附加字段 from = JPush。
+* 构建推送对象:平台是 Andorid 与 iOS,推送目标是 ("tag1" 与 "tag2" 的并集)交("alias1" 与 "alias2" 的并集),推送内容是 - 内容为 MSG_CONTENT 的消息,并且附加字段 from = JPush。
```Java
public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
@@ -184,6 +220,30 @@
}
```
+* 构建推送对象:推送内容包含SMS信息
+
+```Java
+ public static void testSendWithSMS() {
+ JPushClient jpushClient = new JPushClient(masterSecret, appKey);
+ try {
+ SMS sms = SMS.newBuilder()
+ .setDelayTime(1000)
+ .setTempID(2000)
+ .addPara("Test", 1)
+ .build();
+ PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
+ LOG.info("Got result - " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+```
+
### 统计获取样例
> 以下片断来自项目代码里的文件:example / cn.jpush.api.examples.ReportsExample
@@ -211,6 +271,7 @@
> 以下片断来自项目代码里的文件:example / cn.jpush.api.examples.DeviceExample
+* 获取Tag Alias
```Java
try {
TagAliasResult result = jpushClient.getDeviceTagAlias(REGISTRATION_ID1);
@@ -227,6 +288,22 @@
}
```
+* 绑定手机号
+
+```Java
+ try {
+ DefaultResult result = jpushClient.bindMobile(REGISTRATION_ID1, "13000000000");
+ LOG.info("Got result " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+```
+
### Schedule 样例
> 以下片断来自项目代码里的文件:example / cn.jpush.api.examples.ScheduleExample
@@ -248,3 +325,99 @@
LOG.info("Error Message: " + e.getErrorMessage());
}
```
+
+### Custom Client 样例
+
+> 以下片断来自项目代码里面的文件:example / cn.jpush.api.examples.ClientExample
+
+* 配置的SSLVersion表示指定至少支持的协议版本,也可能支持其他多个协议版本,最终支持的协议版本列表取决于JRE和运行环境
+```Java
+ public static void testCustomClient() {
+ ClientConfig config = ClientConfig.getInstance();
+ config.setMaxRetryTimes(5);
+ config.setConnectionTimeout(10 * 1000); // 10 seconds
+ config.setSSLVersion("TLSv1.1"); // JPush server supports SSLv3, TLSv1, TLSv1.1, TLSv1.2
+
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config);
+ }
+
+ public static void testCustomPushClient() {
+ ClientConfig config = ClientConfig.getInstance();
+ config.setApnsProduction(false); // development env
+ config.setTimeToLive(60 * 60 * 24); // one day
+
+ // config.setGlobalPushSetting(false, 60 * 60 * 24); // development env, one day
+
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config); // JPush client
+
+ // PushClient pushClient = new PushClient(masterSecret, appKey, null, config); // push client only
+
+ }
+```
+
+### Image Client 样例
+
+> 以下片断来自项目代码里面的文件:example / cn.jpush.api.examples.ImageExample
+* 支持通过URL或者文件来上传图片
+```Java
+ public static void testUploadImageByUrl() throws APIConnectionException, APIRequestException {
+ ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
+ ImageUrlPayload payload = ImageUrlPayload.newBuilder()
+ .setImageType(ImageType.LARGE_ICON)
+ .setImageUrl("http://xxx.com/image/a.jpg")
+ .build();
+ ImageUploadResult imageUploadResult = client.uploadImage(payload);
+ String mediaId = imageUploadResult.getMediaId();
+ }
+
+ public static void testUploadImageByFile() {
+ ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
+ ImageFilePayload payload = ImageFilePayload.newBuilder()
+ .setImageType(ImageType.BIG_PICTURE)
+ // 本地文件路径
+ .setOppoFileName("/MyDir/a.jpg")
+ .setXiaomiFileName("/MyDir/a.jpg")
+ .build();
+ ImageUploadResult imageUploadResult = client.uploadImage(payload);
+ String mediaId = imageUploadResult.getMediaId();
+ }
+```
+
+### Weblogic 使用Java SDK
+
+Weblogic在使用jpush-api-java-client时需要注意的一些事项。
+
+#### 注意事项
+
+本文档基于weblogic 10.3.6 版本,12版本请自己对应配置路径。
+
+极个别时候,证书会有版本升级等情况,所以一定要验证当前使用的证书和官方证书的指纹是否一致。
+
+**Weblogic console 设置**
+
++ 【主机名验证】设置为无,否则默认使用weblogic.security.SSL.HostnameVerifier进行主机名验证,导致Hostname验证失败
+ + 配置路径 Weblogic Console > 服务器设置 > SSL > 高级 > 主机名验证
++ 选择【使用 JSSE SSL】,因为Weblogic默认的加密算法和Java标准的加密算法不一样
+ + 配置路径 Weblogic Console > 服务器设置 > SSL > 高级 > 使用 JSSE SSL
+
+**证书配置**
+
++ 检查Weblogic使用的信任密钥库的位置
+ + 默认使用的文件是 JRE目录下面的 jre\lib\security\cacerts 文件
+ + 有些开发者可能会改为自定义的信任密钥库
++ 检查对应的信任库是否包含了Geo Trust的根证书或者Geo Trust SSL二级 证书
+ + 举例:keytool -list -keystore cacerts
+ + 此过程需要信任库的密码(默认changeit)
+ + 如果包含这两个证书中任意一个,调用JPush接口都可以调用通过
++ 如果信任库不包含上述证书,需要导入公钥到对应的信任库
+ + 打开jpush.cn,导出公钥(可以是Geo Trust根证书、Geo Trust SSL 或者 *.jpush.cn 三个任意一个,具体导出方法请百度)
+ + 将导出的公钥证书导入到步骤1对应的信任库
+ + 举例:keytool -import -alias geotrustssl -keystore cacerts -file GeoTrustSSL.cer
+ + 此过程需要信任库的密码(默认changeit)
+
+**证书对比方式**
+
++ 执行 keytool -list -keystore mykey.jks 命令列出信任库里的所有公钥,观察对应证书的指纹
++ 检查官网证书,观察对应证书的指纹
++ 比较两个指纹是否一致,如下图所示
+
diff --git a/example/main/java/cn/jpush/api/examples/ClientExample.java b/example/main/java/cn/jpush/api/examples/ClientExample.java
new file mode 100644
index 00000000..99f1073c
--- /dev/null
+++ b/example/main/java/cn/jpush/api/examples/ClientExample.java
@@ -0,0 +1,52 @@
+package cn.jpush.api.examples;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import cn.jiguang.common.ClientConfig;
+import cn.jpush.api.JPushClient;
+
+public class ClientExample {
+ protected static final Logger LOG = LoggerFactory.getLogger(ClientExample.class);
+
+ private static final String appKey = "dd1066407b044738b6479275";
+ private static final String masterSecret = "e8cc9a76d5b7a580859bcfa7";
+
+ public static void main(String[] args) {
+// testDefaultClient();
+// testCustomClient();
+// testCustomPushClient();
+ }
+
+ public static void testDefaultClient() {
+ JPushClient client = new JPushClient(masterSecret, appKey);
+
+ // JPushClient client1 = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance());
+ }
+
+ public static void testCustomClient() {
+ ClientConfig config = ClientConfig.getInstance();
+ config.setMaxRetryTimes(5);
+ config.setConnectionTimeout(10 * 1000); // 10 seconds
+ config.setSSLVersion("TLSv1.1"); // JPush server supports SSLv3, TLSv1, TLSv1.1, TLSv1.2
+
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config);
+ }
+
+ public static void testCustomPushClient() {
+ ClientConfig config = ClientConfig.getInstance();
+
+ config.setApnsProduction(false); // development env
+ config.setTimeToLive(60 * 60 * 24); // one day
+
+ // config.setGlobalPushSetting(false, 60 * 60 * 24); // development env, one day
+
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey, null, config); // JPush client
+
+ // PushClient pushClient = new PushClient(masterSecret, appKey, null, config); // push client only
+
+ }
+
+}
+
+
diff --git a/example/main/java/cn/jpush/api/examples/DevcieExample.java b/example/main/java/cn/jpush/api/examples/DevcieExample.java
deleted file mode 100644
index 2ad18316..00000000
--- a/example/main/java/cn/jpush/api/examples/DevcieExample.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package cn.jpush.api.examples;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import cn.jpush.api.JPushClient;
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
-import cn.jpush.api.device.TagAliasResult;
-
-public class DevcieExample {
- protected static final Logger LOG = LoggerFactory.getLogger(DevcieExample.class);
-
- private static final String appKey = "dd1066407b044738b6479275";
- private static final String masterSecret = "2b38ce69b1de2a7fa95706ea";
- private static final String TAG1 = "tag1";
- private static final String ALIAS1 = "alias1";
- private static final String ALIAS2 = "alias2";
- private static final String REGISTRATION_ID1 = "0900e8d85ef";
- private static final String REGISTRATION_ID2 = "0a04ad7d8b4";
-
- private static JPushClient jpushClient = new JPushClient(masterSecret, appKey);
-
- public static void main(String[] args) {
- testGetDeviceTagAlias();
- }
-
- public static void testGetDeviceTagAlias() {
- try {
- TagAliasResult result = jpushClient.getDeviceTagAlias(REGISTRATION_ID1);
-
- LOG.info(result.alias);
- LOG.info(result.tags.toString());
-
- } catch (APIConnectionException e) {
- LOG.error("Connection error. Should retry later. ", e);
-
- } catch (APIRequestException e) {
- LOG.error("Error response from JPush server. Should review and fix it. ", e);
- LOG.info("HTTP Status: " + e.getStatus());
- LOG.info("Error Code: " + e.getErrorCode());
- LOG.info("Error Message: " + e.getErrorMessage());
- }
- }
-
-}
-
-
diff --git a/example/main/java/cn/jpush/api/examples/DeviceExample.java b/example/main/java/cn/jpush/api/examples/DeviceExample.java
new file mode 100644
index 00000000..a66bce77
--- /dev/null
+++ b/example/main/java/cn/jpush/api/examples/DeviceExample.java
@@ -0,0 +1,102 @@
+package cn.jpush.api.examples;
+
+import java.util.HashSet;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jiguang.common.resp.DefaultResult;
+import cn.jpush.api.JPushClient;
+import cn.jpush.api.device.OnlineStatus;
+import cn.jpush.api.device.TagAliasResult;
+
+public class DeviceExample {
+ protected static final Logger LOG = LoggerFactory.getLogger(DeviceExample.class);
+
+ private static final String appKey = "7b4b94cca0d185d611e53cca";
+ private static final String masterSecret = "860803cf613ed54aa3b941a8";
+ private static final String TAG1 = "tag1";
+ private static final String ALIAS1 = "alias1";
+ private static final String ALIAS2 = "alias2";
+ private static final String REGISTRATION_ID1 = "160a3797c856951a397";
+ private static final String REGISTRATION_ID2 = "0a04ad7d8b4";
+
+ private static JPushClient jpushClient = new JPushClient(masterSecret, appKey);
+
+ public static void main(String[] args) {
+// testGetDeviceTagAlias();
+// testGetUserOnlineStatus();
+ testUpdateDeviceTagAlias();
+ }
+
+ public static void testUpdateDeviceTagAlias() {
+ HashSet tagSet = new HashSet();
+ tagSet.add("hhh");
+ try {
+ DefaultResult result = jpushClient.updateDeviceTagAlias(REGISTRATION_ID1, null, tagSet, null);
+ LOG.info("Got result " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ public static void testGetDeviceTagAlias() {
+ try {
+ TagAliasResult result = jpushClient.getDeviceTagAlias(REGISTRATION_ID1);
+
+ LOG.info(result.alias);
+ LOG.info(result.tags.toString());
+
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ public static void testGetUserOnlineStatus() {
+ try {
+ Map result = jpushClient.getUserOnlineStatus(REGISTRATION_ID1, REGISTRATION_ID2);
+
+ LOG.info(result.get(REGISTRATION_ID1).toString());
+ LOG.info(result.get(REGISTRATION_ID2).toString());
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ public static void testBindMobile() {
+ try {
+ DefaultResult result = jpushClient.bindMobile(REGISTRATION_ID1, "13000000000");
+ LOG.info("Got result " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+}
+
+
diff --git a/example/main/java/cn/jpush/api/examples/ImageExample.java b/example/main/java/cn/jpush/api/examples/ImageExample.java
new file mode 100644
index 00000000..a29ad866
--- /dev/null
+++ b/example/main/java/cn/jpush/api/examples/ImageExample.java
@@ -0,0 +1,56 @@
+package cn.jpush.api.image;
+
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jpush.api.image.model.ImageFilePayload;
+import cn.jpush.api.image.model.ImageType;
+import cn.jpush.api.image.model.ImageUploadResult;
+import cn.jpush.api.image.model.ImageUrlPayload;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ImageExample {
+ protected static final Logger LOG = LoggerFactory.getLogger(ImageExample.class);
+
+ // demo App defined in resources/jpush-api.conf
+ protected static final String APP_KEY = "e4ceeaf7a53ad745dd4728f2";
+ protected static final String MASTER_SECRET = "1582b986adeaf48ceec1e354";
+ protected static final String GROUP_PUSH_KEY = "2c88a01e073a0fe4fc7b167c";
+ protected static final String GROUP_MASTER_SECRET = "b11314807507e2bcfdeebe2e";
+
+ public static final String TITLE = "Test from API example";
+ public static final String ALERT = "Test from API Example - alert";
+ public static final String MSG_CONTENT = "Test from API Example - msgContent";
+ public static final String REGISTRATION_ID = "0900e8d85ef";
+ public static final String TAG = "tag_api";
+ public static long sendCount = 0;
+ private static long sendTotalTime = 0;
+
+ public static void main(String[] args) throws APIConnectionException, APIRequestException {
+ testUploadImageByFile();
+ testUploadImageByUrl();
+ }
+
+ public static void testUploadImageByUrl() throws APIConnectionException, APIRequestException {
+ ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
+ ImageUrlPayload payload = ImageUrlPayload.newBuilder()
+ .setImageType(ImageType.LARGE_ICON)
+ .setImageUrl("http://xxx.com/image/a.jpg")
+ .build();
+ ImageUploadResult imageUploadResult = client.uploadImage(payload);
+ String mediaId = imageUploadResult.getMediaId();
+ }
+
+ public static void testUploadImageByFile() {
+ ImageClient client = new ImageClient(MASTER_SECRET, APP_KEY);
+ ImageFilePayload payload = ImageFilePayload.newBuilder()
+ .setImageType(ImageType.BIG_PICTURE)
+ // 本地文件路径
+ .setOppoFileName("/MyDir/a.jpg")
+ .setXiaomiFileName("/MyDir/a.jpg")
+ .build();
+ ImageUploadResult imageUploadResult = client.uploadImage(payload);
+ String mediaId = imageUploadResult.getMediaId();
+ }
+}
+
diff --git a/example/main/java/cn/jpush/api/examples/PushExample.java b/example/main/java/cn/jpush/api/examples/PushExample.java
index 77150e42..37a3c9ba 100644
--- a/example/main/java/cn/jpush/api/examples/PushExample.java
+++ b/example/main/java/cn/jpush/api/examples/PushExample.java
@@ -1,69 +1,275 @@
package cn.jpush.api.examples;
-import cn.jpush.api.common.ClientConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+import cn.jiguang.common.ClientConfig;
+import cn.jiguang.common.ServiceHelper;
+import cn.jiguang.common.connection.NativeHttpClient;
+import cn.jiguang.common.connection.NettyHttpClient;
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.JPushClient;
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
+import cn.jpush.api.push.CIDResult;
+import cn.jpush.api.push.GroupPushClient;
+import cn.jpush.api.push.GroupPushResult;
import cn.jpush.api.push.PushResult;
-import cn.jpush.api.push.model.Message;
-import cn.jpush.api.push.model.Options;
-import cn.jpush.api.push.model.Platform;
-import cn.jpush.api.push.model.PushPayload;
+import cn.jpush.api.push.model.*;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
-import cn.jpush.api.push.model.notification.AndroidNotification;
-import cn.jpush.api.push.model.notification.IosNotification;
-import cn.jpush.api.push.model.notification.Notification;
+import cn.jpush.api.push.model.notification.*;
+import cn.jpush.api.report.GroupMessageDetailResult;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import io.netty.handler.codec.http.HttpMethod;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.*;
public class PushExample {
protected static final Logger LOG = LoggerFactory.getLogger(PushExample.class);
- // demo App defined in resources/jpush-api.conf
- private static final String appKey ="e5c0d34f58732cf09b2d4d74";
- private static final String masterSecret = "4cdda6d3c8b029941dbc5cb3";
-
- public static final String TITLE = "Test from API example";
+ /**
+ * Change the app key and master secret to your own account
+ * If you want to use push by group, please enter your own group push key and group master secret.
+ */
+ protected static final String APP_KEY = "8f02a4fa717a6235734d92de";
+ protected static final String MASTER_SECRET = "cf6de29f9e66432ba4ac1c32";
+ protected static final String GROUP_PUSH_KEY = "2c88a01e073a0fe4fc7b167c";
+ protected static final String GROUP_MASTER_SECRET = "b11314807507e2bcfdeebe2e";
+
+ public static final String TITLE = "Test from API example";
public static final String ALERT = "Test from API Example - alert";
public static final String MSG_CONTENT = "Test from API Example - msgContent";
public static final String REGISTRATION_ID = "0900e8d85ef";
public static final String TAG = "tag_api";
+ public static long sendCount = 0;
+ private static long sendTotalTime = 0;
+
+ public static void main(String[] args) {
+
+ // 回调参数可参考下面方法
+// testSendPushWithCustom();
+// testSendPushWithCustomField();
+// testBatchSend();
+// testSendPushWithCustomConfig();
+// testSendIosAlert();
+
+ // 目前推荐这个方法进行测试
+ testSendPush();
+// testSendGroupPush();
+
+
+// testGetCidList();
+// testSendPushes();
+// testSendPush_fromJSON();
+// testSendPushWithCallback();
+// testSendPushWithCid();
+// testSendWithSMS();
+ }
+
+ // 使用 NettyHttpClient 异步接口发送请求
+ public static void testSendPushWithCallback() {
+ ClientConfig clientConfig = ClientConfig.getInstance();
+ String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
+ final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
+ null, clientConfig);
+ try {
+ URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
+ PushPayload payload = buildPushObject_all_alias_alert();
+ client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
+ @Override
+ public void onSucceed(ResponseWrapper responseWrapper) {
+ LOG.info("Got result: " + responseWrapper.responseContent);
+ }
+ });
+ } catch (URISyntaxException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void testSendPush() {
+ ClientConfig clientConfig = ClientConfig.getInstance();
+ final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
+// String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
+ // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
+ // Call setHttpClient to set httpClient,
+ // If you don't invoke this method, default httpClient will use NativeHttpClient.
+
+// ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
+// NettyHttpClient httpClient =new NettyHttpClient(authCode, null, clientConfig);
+// jpushClient.getPushClient().setHttpClient(httpClient);
- public static void main(String[] args) {
- testSendPushWithCustomConfig();
- }
-
-
- public static void testSendPush() {
- // HttpProxy proxy = new HttpProxy("localhost", 3128);
- // Can use this https proxy: https://github.com/Exa-Networks/exaproxy
- JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);
-
// For push, all you need do is to build PushPayload object.
- PushPayload payload = buildPushObject_all_all_alert();
-
+ final PushPayload payload = buildPushObject_android_and_ios();
+
+// PushPayload payload = buildPushObject_all_alias_alert();
+ try {
+ PushResult result = jpushClient.sendPush(payload);
+ LOG.info("Got result - " + result);
+ System.out.println(result);
+ // 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
+ // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
+ // jpushClient.close();
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ LOG.error("Sendno: " + payload.getSendno());
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ LOG.error("Sendno: " + payload.getSendno());
+ }
+ }
+
+ public static void testSendPushWithEncrypt() {
+ ClientConfig clientConfig = ClientConfig.getInstance();
+ clientConfig.setEncryptType(EncryptKeys.ENCRYPT_SMS2_TYPE);
+ final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
+// String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
+ // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
+ // Call setHttpClient to set httpClient,
+ // If you don't invoke this method, default httpClient will use NativeHttpClient.
+
+// ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
+// NettyHttpClient httpClient =new NettyHttpClient(authCode, null, clientConfig);
+// jpushClient.getPushClient().setHttpClient(httpClient);
+ final PushPayload payload = buildPushObject_android_and_ios();
+// // For push, all you need do is to build PushPayload object.
+// PushPayload payload = buildPushObject_all_alias_alert();
try {
PushResult result = jpushClient.sendPush(payload);
LOG.info("Got result - " + result);
-
+ System.out.println(result);
+ // 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
+ // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
+ // jpushClient.close();
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ LOG.error("Sendno: " + payload.getSendno());
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ LOG.error("Sendno: " + payload.getSendno());
+ }
+ }
+
+ //use String to build PushPayload instance
+ public static void testSendPush_fromJSON() {
+ ClientConfig clientConfig = ClientConfig.getInstance();
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
+ Gson gson = new GsonBuilder()
+ .registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter())
+ .create();
+ // Since the type of DeviceType is enum, thus the value should be uppercase, same with the AudienceType.
+ String payloadString = "{\"platform\":{\"all\":false,\"deviceTypes\":[\"IOS\"]},\"audience\":{\"all\":true,\"targets\":[{\"audienceType\":\"TAG_AND\",\"values\":[\"tag1\",\"tag_all\"]}]},\"notification\":{\"notifications\":[{\"soundDisabled\":false,\"badgeDisabled\":false,\"sound\":\"happy\",\"badge\":\"5\",\"contentAvailable\":false,\"alert\":\"Test from API Example - alert\",\"extras\":{\"from\":\"JPush\"},\"type\":\"cn.jpush.api.push.model.notification.IosNotification\"}]},\"message\":{\"msgContent\":\"Test from API Example - msgContent\"},\"options\":{\"sendno\":1429488213,\"overrideMsgId\":0,\"timeToLive\":-1,\"apnsProduction\":true,\"bigPushDuration\":0}}";
+ PushPayload payload = gson.fromJson(payloadString, PushPayload.class);
+ try {
+ PushResult result = jpushClient.sendPush(payloadString);
+ LOG.info("Got result - " + result);
+
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ // LOG.error("Sendno: " + payload.getSendno());
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ //LOG.error("Sendno: " + payload.getSendno());
+ }
+ }
+
+ /**
+ * 测试多线程发送 2000 条推送耗时
+ */
+ public static void testSendPushes() {
+ ClientConfig clientConfig = ClientConfig.getInstance();
+ final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
+ String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
+ // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
+ NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
+ // Call setHttpClient to set httpClient,
+ // If you don't invoke this method, default httpClient will use NativeHttpClient.
+// ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
+ jpushClient.getPushClient().setHttpClient(httpClient);
+ final PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage();
+ for (int i = 0; i < 10; i++) {
+ Thread thread = new Thread() {
+ public void run() {
+ for (int j = 0; j < 200; j++) {
+ long start = System.currentTimeMillis();
+ try {
+ PushResult result = jpushClient.sendPush(payload);
+ LOG.info("Got result - " + result);
+
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ LOG.error("Sendno: " + payload.getSendno());
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ LOG.error("Sendno: " + payload.getSendno());
+ }
+
+ System.out.println("耗时" + (System.currentTimeMillis() - start) + "毫秒 sendCount:" + (++sendCount));
+ }
+ }
+ };
+ thread.start();
+ }
+ }
+
+ public static void testSendGroupPush() {
+ GroupPushClient groupPushClient = new GroupPushClient(GROUP_MASTER_SECRET, GROUP_PUSH_KEY);
+ final PushPayload payload = buildPushObject_android_and_ios();
+ try {
+ GroupPushResult groupPushResult = groupPushClient.sendGroupPush(payload);
+ Map result = groupPushResult.getAppResultMap();
+ for (Map.Entry entry : result.entrySet()) {
+ PushResult pushResult = entry.getValue();
+ PushResult.Error error = pushResult.error;
+ if (error != null) {
+ LOG.info("Group_msgid: " + groupPushResult.getGroupMsgId() + " AppKey: " + entry.getKey() + " error code : " + error.getCode() + " error message: " + error.getMessage());
+ } else {
+ LOG.info("Group_msgid: " + groupPushResult.getGroupMsgId() + " AppKey: " + entry.getKey() + " sendno: " + pushResult.sendno + " msg_id:" + pushResult.msg_id);
+ }
+
+ }
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
-
+ LOG.error("Sendno: " + payload.getSendno());
+
} catch (APIRequestException e) {
LOG.error("Error response from JPush server. Should review and fix it. ", e);
LOG.info("HTTP Status: " + e.getStatus());
LOG.info("Error Code: " + e.getErrorCode());
LOG.info("Error Message: " + e.getErrorMessage());
LOG.info("Msg ID: " + e.getMsgId());
+ LOG.error("Sendno: " + payload.getSendno());
}
- }
-
- public static PushPayload buildPushObject_all_all_alert() {
- return PushPayload.alertAll(ALERT);
- }
-
+ }
+
+ public static PushPayload buildPushObject_all_all_alert() {
+ return PushPayload.alertAll(ALERT);
+ }
+
public static PushPayload buildPushObject_all_alias_alert() {
return PushPayload.newBuilder()
.setPlatform(Platform.all())
@@ -71,7 +277,7 @@ public static PushPayload buildPushObject_all_alias_alert() {
.setNotification(Notification.alert(ALERT))
.build();
}
-
+
public static PushPayload buildPushObject_android_tag_alertWithTitle() {
return PushPayload.newBuilder()
.setPlatform(Platform.android())
@@ -79,23 +285,92 @@ public static PushPayload buildPushObject_android_tag_alertWithTitle() {
.setNotification(Notification.android(ALERT, TITLE, null))
.build();
}
-
+
+ /**
+ * Could modify the contents for pushing
+ * The comments are showing how to use it
+ * @return
+ */
public static PushPayload buildPushObject_android_and_ios() {
+ Map extras = new HashMap();
+ extras.put("test", "https://community.jiguang.cn/push");
+ // you can set anything you want in this builder, read the document to avoid collision.
return PushPayload.newBuilder()
+ .setPlatform(Platform.android_ios())
+ .setAudience(Audience.all())
+// .setMessage(Message.newBuilder()
+// .setMsgContent("Hi, JPush")
+// .build())
+ .setNotification(Notification.newBuilder()
+ .setAlert("testing alert content")
+ .addPlatformNotification(AndroidNotification.newBuilder()
+ .setTitle("Android Title")
+ .addExtras(extras).build())
+ .addPlatformNotification(IosNotification.newBuilder()
+ .incrBadge(1)
+ .addExtra("extra_key", "extra_value").build())
+ .build())
+// .setSMS(SMS.newBuilder()
+// .setDelayTime(1000)
+// .setTempID(2000)
+// .addPara("Test", 1)
+// .setActiveFilter(true)
+// .build())
+// .setNotification3rd(Notification3rd.newBuilder()
+// .setContent("Hi, JPush")
+// .setTitle("msg testing")
+// .setChannelId("channel1001")
+// .setUriActivity("cn.jpush.android.ui.OpenClickActivity")
+// .setUriAction("cn.jpush.android.intent.CONNECTION")
+// .setBadgeAddNum(1)
+// .setBadgeClass("com.test.badge.MainActivity")
+// .setSound("sound")
+// .addExtra("news_id", 124)
+// .addExtra("my_key", "a value")
+// .build())
+ .setOptions(Options.newBuilder()
+ .setApnsProduction(false)
+ .setTimeToLive(43200)
+ .build())
+ .build();
+ }
+
+ public static void buildPushObject_with_extra() {
+
+ JsonObject jsonExtra = new JsonObject();
+ jsonExtra.addProperty("extra1", 1);
+ jsonExtra.addProperty("extra2", false);
+
+ Map extras = new HashMap();
+ extras.put("extra_1", "val1");
+ extras.put("extra_2", "val2");
+
+ PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.tag("tag1"))
.setNotification(Notification.newBuilder()
- .setAlert("alert content")
- .addPlatformNotification(AndroidNotification.newBuilder()
- .setTitle("Android Title").build())
- .addPlatformNotification(IosNotification.newBuilder()
- .incrBadge(1)
- .addExtra("extra_key", "extra_value").build())
- .build())
+ .setAlert("alert content")
+ .addPlatformNotification(AndroidNotification.newBuilder()
+ .setTitle("Android Title")
+ .addExtras(extras)
+ .addExtra("booleanExtra", false)
+ .addExtra("numberExtra", 1)
+ .addExtra("jsonExtra", jsonExtra)
+ .build())
+ .addPlatformNotification(IosNotification.newBuilder()
+ .incrBadge(1)
+ .addExtra("extra_key", "extra_value").build())
+ .build())
.build();
+
+ System.out.println(payload.toJSON());
}
-
+
public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
+ JsonObject sound = new JsonObject();
+ sound.add("critical", new JsonPrimitive(1));
+ sound.add("name", new JsonPrimitive("default"));
+ sound.add("volume", new JsonPrimitive(0.2));
return PushPayload.newBuilder()
.setPlatform(Platform.ios())
.setAudience(Audience.tag_and("tag1", "tag_all"))
@@ -103,17 +378,56 @@ public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage()
.addPlatformNotification(IosNotification.newBuilder()
.setAlert(ALERT)
.setBadge(5)
- .setSound("happy")
+ .setMutableContent(false)
+// .setSound("happy")
+ .setSound(sound)
.addExtra("from", "JPush")
.build())
.build())
- .setMessage(Message.content(MSG_CONTENT))
- .setOptions(Options.newBuilder()
- .setApnsProduction(true)
- .build())
- .build();
+ .setMessage(Message.content(MSG_CONTENT))
+ .setOptions(Options.newBuilder()
+ .setApnsProduction(true)
+ .build())
+ .build();
+ }
+
+ public static PushPayload buildPushObject_android_newly_support() {
+
+ JsonObject inbox = new JsonObject();
+ inbox.add("line1", new JsonPrimitive("line1 string"));
+ inbox.add("line2", new JsonPrimitive("line2 string"));
+ inbox.add("contentTitle", new JsonPrimitive("title string"));
+ inbox.add("summaryText", new JsonPrimitive("+3 more"));
+
+ JsonObject intent = new JsonObject();
+ intent.add("url", new JsonPrimitive("intent:#Intent;component=com.jiguang.push/com.example.jpushdemo.SettingActivity;end"));
+
+ Notification notification = Notification.newBuilder()
+ .addPlatformNotification(AndroidNotification.newBuilder()
+ .setAlert(ALERT)
+ .setBigPicPath("path to big picture")
+ .setBigText("long text")
+ .setBuilderId(1)
+ .setCategory("CATEGORY_SOCIAL")
+ .setInbox(inbox)
+ .setStyle(1)
+ .setTitle("Alert test")
+ .setPriority(1)
+ .setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
+ .setIntent(intent)
+ .build())
+ .build();
+ return PushPayload.newBuilder()
+ .setPlatform(Platform.all())
+ .setAudience(Audience.all())
+ .setNotification(notification)
+ .setOptions(Options.newBuilder()
+ .setApnsProduction(true)
+ .setSendno(ServiceHelper.generateSendno())
+ .build())
+ .build();
}
-
+
public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
@@ -128,12 +442,41 @@ public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
.build();
}
+ public static PushPayload buildPushObject_all_tag_not() {
+ return PushPayload.newBuilder()
+ .setPlatform(Platform.all())
+ .setAudience(Audience.tag_not("abc", "123"))
+ .setNotification(Notification.alert(ALERT))
+ .build();
+ }
+
+ public static PushPayload buildPushObject_android_cid() {
+ Collection list = new LinkedList();
+ list.add("1507bfd3f79558957de");
+ list.add("1507bfd3f79554957de");
+ list.add("1507bfd3f79555957de");
+ list.add("1507bfd3f79556957de");
+ list.add("1507ffd3f79545957de");
+ list.add("1507ffd3f79457957de");
+ list.add("1507ffd3f79456757de");
+ list.add("zzzzzzzz");
+
+
+ return PushPayload.newBuilder()
+ .setPlatform(Platform.android())
+// .setAudience(Audience.registrationId("1507bfd3f79558957de"))
+ .setAudience(Audience.registrationId(list))
+ .setNotification(Notification.alert(ALERT))
+ .setCid("cid")
+ .build();
+ }
+
public static void testSendPushWithCustomConfig() {
ClientConfig config = ClientConfig.getInstance();
// Setup the custom hostname
config.setPushHostName("https://api.jpush.cn");
- JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3, null, config);
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
// For push, all you need do is to build PushPayload object.
PushPayload payload = buildPushObject_all_all_alert();
@@ -154,5 +497,233 @@ public static void testSendPushWithCustomConfig() {
}
}
+ public static void testSendIosAlert() {
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
+
+ IosAlert alert = IosAlert.newBuilder()
+ .setTitleAndBody("test alert", "subtitle", "test ios alert json")
+ .setActionLocKey("PLAY")
+ .build();
+ try {
+ PushResult result = jpushClient.sendIosNotificationWithAlias(alert, new HashMap(), "alias1");
+ LOG.info("Got result - " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ public static void testSendWithSMS() {
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
+ try {
+// SMS sms = SMS.content(1, 10);
+ SMS sms = SMS.newBuilder()
+ .setDelayTime(1000)
+ .setTempID(2000)
+ .addPara("Test", 1)
+ .setActiveFilter(false)
+ .build();
+ PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
+ LOG.info("Got result - " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ public static void testGetCidList() {
+ JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
+ try {
+ CIDResult result = jPushClient.getCidList(3, "push");
+ LOG.info("Got result - " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ public static void testSendPushWithCid() {
+ JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
+ PushPayload pushPayload = buildPushObject_android_cid();
+ try {
+ PushResult result = jPushClient.sendPush(pushPayload);
+ LOG.info("Got result - " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ /**
+ * 批量单推接口
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#vip
+ */
+ public static void testBatchSend() {
+
+ JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
+ try {
+ {
+ List pushPayloadList = new ArrayList<>();
+ PushPayload.Builder builder1 = PushPayload.newBuilder();
+ builder1.setMessage(Message.content("content1 by alias"))
+ .setNotification(Notification.alert(ALERT))
+ .setPlatform(Platform.all())
+ .setAudience(Audience.all())
+ .setOptions(Options.sendno())
+ .setTarget("1507ffd3f79456757de");
+ pushPayloadList.add(builder1.build());
+
+ PushPayload.Builder builder2 = PushPayload.newBuilder();
+ builder2.setMessage(Message.content("content2 by alias"))
+ .setNotification(Notification.alert(ALERT))
+ .setPlatform(Platform.android())
+ .setAudience(Audience.all())
+ .setOptions(Options.sendno())
+ .setTarget("1507ffd3f79456757de");
+ pushPayloadList.add(builder2.build());
+
+ BatchPushResult result = jPushClient.batchSendPushByAlias(pushPayloadList);
+ LOG.info("batchSendPushByAlias param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
+ }
+
+// {
+// List pushPayloadList = new ArrayList<>();
+// PushPayload.Builder builder1 = PushPayload.newBuilder();
+// builder1.setMessage(Message.content("content1 by regId"))
+// .setNotification(Notification.alert(ALERT))
+// .setPlatform(Platform.android())
+// .setAudience(Audience.all())
+// .setOptions(Options.sendno())
+// .setTarget("1507ffd3f79456757de");
+// pushPayloadList.add(builder1.build());
+//
+// PushPayload.Builder builder2 = PushPayload.newBuilder();
+// builder2.setMessage(Message.content("content2 by regId"))
+// .setNotification(Notification.alert(ALERT))
+// .setAudience(Audience.all())
+// .setPlatform(Platform.ios())
+// .setOptions(Options.sendno())
+// .setTarget("1507ffd3f79456757de");
+// pushPayloadList.add(builder2.build());
+//
+// BatchPushResult result = jPushClient.batchSendPushByRegId(pushPayloadList);
+// LOG.info("batchSendPushByRegId param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
+// }
+
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ /**
+ * 自定义发送参数名称, 华为客户可参考该方法
+ */
+ public static void testSendPushWithCustomField() {
+
+ ClientConfig config = ClientConfig.getInstance();
+ // Setup the custom hostname
+ config.setPushHostName("https://api.jpush.cn");
+
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
+
+ Notification notification = Notification.newBuilder()
+ .addPlatformNotification(AndroidNotification.newBuilder()
+ .setAlert(ALERT)
+ .setTitle("Alert test")
+ .setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
+ .addCustom("uri_activity", "uri_activity")
+ .addCustom("uri_flag", "uri_flag")
+ .addCustom("uri_action", "uri_action")
+ .build())
+ .build();
+
+ PushPayload.Builder payloadBuilder = new PushPayload.Builder()
+ .setPlatform(Platform.all())
+ .setAudience(Audience.all())
+ .setNotification(notification);
+
+ try {
+ PushResult result = jpushClient.sendPush(payloadBuilder.build());
+ LOG.info("Got result - " + result);
+
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ }
+ }
+
+ /**
+ * 回调参数示例
+ */
+ public static void testSendPushWithCustom() {
+
+ ClientConfig config = ClientConfig.getInstance();
+ // Setup the custom hostname
+ config.setPushHostName("https://api.jpush.cn");
+
+ JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
+
+ Notification notification = Notification.newBuilder()
+ .addPlatformNotification(AndroidNotification.newBuilder()
+ .setAlert(ALERT)
+ .setTitle("Alert test")
+ .build())
+ .build();
+
+ JsonObject callback = new JsonObject();
+ callback.addProperty("url", "https://www.jiguagn.cn/callback");
+ JsonObject params = new JsonObject();
+ params.addProperty("name", "joe");
+ params.addProperty("age", 26);
+ callback.add("params", params);
+ callback.addProperty("type", 3);
+
+ PushPayload.Builder payloadBuilder = new PushPayload.Builder()
+ .setPlatform(Platform.all())
+ .setAudience(Audience.all())
+ .setNotification(notification)
+ .addCustom("callback", callback);
+
+ try {
+ PushResult result = jpushClient.sendPush(payloadBuilder.build());
+ LOG.info("Got result - " + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ }
+ }
+
}
diff --git a/example/main/java/cn/jpush/api/examples/ReportsExample.java b/example/main/java/cn/jpush/api/examples/ReportsExample.java
index 2482f7bb..e97cf3f3 100644
--- a/example/main/java/cn/jpush/api/examples/ReportsExample.java
+++ b/example/main/java/cn/jpush/api/examples/ReportsExample.java
@@ -1,35 +1,52 @@
package cn.jpush.api.examples;
+import cn.jiguang.common.TimeUnit;
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jpush.api.JPushClient;
+import cn.jpush.api.report.*;
+import cn.jpush.api.report.model.CheckMessagePayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import cn.jpush.api.JPushClient;
-import cn.jpush.api.common.TimeUnit;
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
-import cn.jpush.api.report.MessagesResult;
-import cn.jpush.api.report.ReceivedsResult;
-import cn.jpush.api.report.UsersResult;
+import java.util.Map;
public class ReportsExample {
protected static final Logger LOG = LoggerFactory.getLogger(ReportsExample.class);
- // demo App defined in resources/jpush-api.conf
- private static final String appKey = "dd1066407b044738b6479275";
- private static final String masterSecret = "2b38ce69b1de2a7fa95706ea";
+
+ /**
+ * Change the app key and master secret to your own account
+ * If you want to use push by group, please enter your own group push key and group master secret.
+ */
+ protected static final String appKey = "8f02a4fa717a6235734d92de";
+ protected static final String masterSecret = "cf6de29f9e66432ba4ac1c32";
+ protected static final String GROUP_PUSH_KEY = "2c88a01e073a0fe4fc7b167c";
+ protected static final String GROUP_MASTER_SECRET = "b11314807507e2bcfdeebe2e";
+
+
+ public static final String REGISTRATION_ID1 = "0900e8d85ef";
+ public static final String REGISTRATION_ID2 = "0a04ad7d8b4";
+ public static final String REGISTRATION_ID3 = "18071adc030dcba91c0";
public static void main(String[] args) {
- testGetReport();
- testGetMessages();
- testGetUsers();
+
+// testGetReceivedDetail();
+// testGetMessagesDetail();
+// testGetReport();
+// testGetMessages();
+// testGetUsers();
+// testGetMessageStatus();
+ testGetGroupMessagesDetail();
+// testGetGroupUsers();
}
public static void testGetReport() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
try {
- ReceivedsResult result = jpushClient.getReportReceiveds("1942377665");
- LOG.debug("Got result - " + result);
+ ReceivedsResult result = jpushClient.getReportReceiveds("2252035206045707");
+ LOG.info("Got result - " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
@@ -42,11 +59,15 @@ public static void testGetReport() {
}
}
+ /**
+ * 用户统计
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#vip_2
+ */
public static void testGetUsers() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
try {
UsersResult result = jpushClient.getReportUsers(TimeUnit.DAY, "2014-06-10", 3);
- LOG.debug("Got result - " + result);
+ LOG.info("Got result - " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
@@ -76,5 +97,114 @@ public static void testGetMessages() {
}
}
+ public static void testGetMessageStatus() {
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey);
+ CheckMessagePayload payload = CheckMessagePayload.newBuilder()
+ .setMsgId(3993287034L)
+ .addRegistrationIds(REGISTRATION_ID1, REGISTRATION_ID2, REGISTRATION_ID3)
+ .setDate("2017-08-08")
+ .build();
+ try {
+ Map map = jPushClient.getMessageStatus(payload);
+ for (Map.Entry entry : map.entrySet()) {
+ LOG.info("registrationId: " + entry.getKey() + " status: " + entry.getValue().getStatus());
+ }
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ /**
+ * 消息统计
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#vip
+ */
+ public static void testGetMessagesDetail() {
+
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey);
+// String msgIds = "3993287034,3993287035,3993287036";
+ String msgIds = "38280839685161019";
+ try {
+ MessageDetailResult result = jPushClient.getMessagesDetail(msgIds);
+ LOG.info("msgIds: {}, MessageDetail: {}", msgIds, result.received_list);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+
+ }
+
+ /**
+ * 送达详情
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#_7
+ */
+ public static void testGetReceivedDetail() {
+
+ JPushClient jPushClient = new JPushClient(masterSecret, appKey);
+ String msgIds = "3993287034,3993287035,3993287036";
+ try {
+ ReceivedsResult result = jPushClient.getReceivedsDetail(msgIds);
+ LOG.info("msgIds: {}, ReceivedsDetail: {}", msgIds, result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
+ /**
+ * 分组统计-消息统计
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#-vip
+ */
+ public static void testGetGroupMessagesDetail() {
+
+ JPushClient jPushClient = new JPushClient(GROUP_MASTER_SECRET, GROUP_PUSH_KEY);
+ String groupMsgIds = "c4hmbne09s6bbaca91vg";
+ try {
+ GroupMessageDetailResult result = jPushClient.getGroupMessagesDetail(groupMsgIds);
+ LOG.info("group_msgIds: {}, MessageDetail: {}", groupMsgIds, result.received_list);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+
+ }
+
+ /**
+ * 分组统计-用户统计
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_report/#-vip_1
+ */
+ public static void testGetGroupUsers() {
+ JPushClient jpushClient = new JPushClient(GROUP_MASTER_SECRET, GROUP_PUSH_KEY);
+ try {
+ GroupUsersResult result = jpushClient.getGroupReportUsers(TimeUnit.DAY, "2021-08-21", 3);
+ LOG.debug("Got result - " + result);
+
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
+
}
diff --git a/example/main/java/cn/jpush/api/examples/ScheduleExample.java b/example/main/java/cn/jpush/api/examples/ScheduleExample.java
index de4df8c4..80bde327 100644
--- a/example/main/java/cn/jpush/api/examples/ScheduleExample.java
+++ b/example/main/java/cn/jpush/api/examples/ScheduleExample.java
@@ -1,40 +1,49 @@
package cn.jpush.api.examples;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import cn.jiguang.common.TimeUnit;
+import cn.jiguang.common.Week;
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
-import cn.jpush.api.common.TimeUnit;
-import cn.jpush.api.common.Week;
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.schedule.ScheduleListResult;
+import cn.jpush.api.schedule.ScheduleMsgIdsResult;
import cn.jpush.api.schedule.ScheduleResult;
import cn.jpush.api.schedule.model.SchedulePayload;
import cn.jpush.api.schedule.model.TriggerPayload;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
public class ScheduleExample {
protected static final Logger LOG = LoggerFactory.getLogger(ScheduleExample.class);
- private static final String appKey ="e5c0d34f58732cf09b2d4d74";
- private static final String masterSecret = "4cdda6d3c8b029941dbc5cb3";
- public static void main(String[] args) {
+ /**
+ * Change it to your own appKey and masterSecret if you want to try the demo
+ */
+ private static final String appKey ="7b4b94cca0d185d611e53cca";
+ private static final String masterSecret = "860803cf613ed54aa3b941a8";
+
+ public static void main(String[] args) {
+ testCreateSingleSchedule();
+// testCreateDailySchedule();
// testDeleteSchedule();
- testGetScheduleList();
+// testGetScheduleList();
// testUpdateSchedule();
- testGetSchedule();
+// testGetSchedule();
+// testGetScheduleMsgIds();
}
public static void testCreateSingleSchedule() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
String name = "test_schedule_example";
- String time = "2016-07-30 12:30:25";
- PushPayload push = PushPayload.alertAll("test schedule example.");
+ String time = "2021-08-11 15:36:10";
+ PushPayload push = PushPayload.alertAll("test schedule example");
try {
- ScheduleResult result = jpushClient.createSingleSchedule(name, time, push);
+ ScheduleResult result = jpushClient.createSingleSchedule(name, time, push, masterSecret, appKey);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
@@ -49,12 +58,12 @@ public static void testCreateSingleSchedule() {
public static void testCreateDailySchedule() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
String name = "test_daily_schedule";
- String start = "2015-08-06 12:16:13";
- String end = "2115-08-06 12:16:13";
+ String start = "2019-08-06 12:16:13";
+ String end = "2020-08-06 12:16:13";
String time = "14:00:00";
PushPayload push = PushPayload.alertAll("test daily example.");
try {
- ScheduleResult result = jPushClient.createDailySchedule(name, start, end, time, push);
+ ScheduleResult result = jPushClient.createDailySchedule(name, start, end, time, push, masterSecret, appKey);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
@@ -75,7 +84,7 @@ public static void testCreateWeeklySchedule() {
Week[] days = {Week.MON, Week.FRI};
PushPayload push = PushPayload.alertAll("test weekly example.");
try {
- ScheduleResult result = jPushClient.createWeeklySchedule(name, start, end, time, days, push);
+ ScheduleResult result = jPushClient.createWeeklySchedule(name, start, end, time, days, push, masterSecret, appKey);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later. ", e);
@@ -96,7 +105,7 @@ public static void testCreateMonthlySchedule() {
String[] points = {"01", "02"};
PushPayload push = PushPayload.alertAll("test monthly example.");
try {
- ScheduleResult result = jPushClient.createMonthlySchedule(name, start, end, time, points, push);
+ ScheduleResult result = jPushClient.createMonthlySchedule(name, start, end, time, points, push, masterSecret, appKey);
LOG.info("schedule result is " + result);
} catch (APIConnectionException e) {
LOG.error("Connection error. Should retry later.", e);
@@ -170,7 +179,7 @@ public static void testUpdateSchedule() {
}
public static void testGetSchedule() {
- String scheduleId = "95bbd066-3a88-11e5-8e62-0021f652c102";
+ String scheduleId = "13573bfa-cf5a-11e8-bd7f-0021f6b55802";
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
try {
@@ -185,6 +194,23 @@ public static void testGetSchedule() {
LOG.info("Error Message: " + e.getErrorMessage());
}
}
+
+ public static void testGetScheduleMsgIds() {
+ String scheduleId = "63db10a0-cf5b-11e8-ac2f-0021f6b55802";
+ JPushClient jpushClient = new JPushClient(masterSecret, appKey);
+
+ try {
+ ScheduleMsgIdsResult result = jpushClient.getScheduleMsgIds(scheduleId);
+ LOG.info("scheduleMsgIds :" + result);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ }
+ }
}
diff --git a/example/main/java/cn/jpush/api/examples/adminExample.java b/example/main/java/cn/jpush/api/examples/adminExample.java
new file mode 100644
index 00000000..a6f5bd86
--- /dev/null
+++ b/example/main/java/cn/jpush/api/examples/adminExample.java
@@ -0,0 +1,43 @@
+package cn.jpush.api.examples;
+
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jpush.api.admin.AdminClient;
+import cn.jpush.api.file.model.FileType;
+import cn.jpush.api.file.model.FileUploadResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class adminExample {
+
+ protected static final Logger LOG = LoggerFactory.getLogger(DeviceExample.class);
+
+
+ /**
+ * Change the Dev key and Dev secret to your own account
+ * base64_auth_string 生成规则是:base64(dev_key:dev_secret), dev_key 及 dev_secret 请登录官网在开发者帐号页面获取;
+ */
+ protected static final String DEV_KEY = "b924003f73a21f28b238fb12";
+ protected static final String DEV_SECRET = "666a4a8284e62eef3b7aaf51";
+ protected static final String APP_KEY = "e9fcfcf59eb3adb7e4dda56d";
+
+ public static void main(String[] args) {
+ testUploadCertificate();
+ }
+
+ public static void testUploadCertificate() {
+ AdminClient adminClient = new AdminClient(DEV_KEY, DEV_SECRET);
+
+ try {
+ adminClient.uploadCertificate(APP_KEY, "test_push_cert.p12", "123456", null, null);
+ } catch (APIConnectionException e) {
+ LOG.error("Connection error. Should retry later. ", e);
+ } catch (APIRequestException e) {
+ LOG.error("Error response from JPush server. Should review and fix it. ", e);
+ LOG.info("HTTP Status: " + e.getStatus());
+ LOG.info("Error Code: " + e.getErrorCode());
+ LOG.info("Error Message: " + e.getErrorMessage());
+ LOG.info("Msg ID: " + e.getMsgId());
+ }
+ }
+}
diff --git a/pom.xml b/pom.xml
index 5dd458ea..7a3330df 100644
--- a/pom.xml
+++ b/pom.xml
@@ -3,20 +3,12 @@
cn.jpush.apijpush-client
- 3.2.6-SNAPSHOT
+ 3.7.8jarhttps://github.com/jpush/jpush-api-java-clientJPush API Java ClientJPush's officially supported Java client library for accessing JPush APIs.
-
-
- The Apache Software License, Version 2.0
- http://www.apache.org/licenses/LICENSE-2.0.txt
- repo
-
-
-
githubUTF-8
@@ -35,11 +27,37 @@
https://github.com/jpush/jpush-api-java-clientscm:git:git@github.com:jpush/jpush-api-java-client.gitscm:git:git@github.com:jpush/jpush-api-java-client.git
- v3.1.1
+ v3.3.12
+
+
+
+ org.projectlombok
+ lombok
+ 1.18.6
+ provided
+
+
+
+ cn.jpush.api
+ jiguang-common
+ 1.2.7
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.3
+ compile
+
+
+ io.netty
+ netty-all
+ 4.1.6.Final
+ compile
+
+ com.google.code.gsongson2.3
@@ -67,10 +85,22 @@
test
-
+
+ org.bouncycastle
+ bcprov-jdk15on
+ 1.60
+
+
+ org.bouncycastle
+ bcpkix-jdk15on
+ 1.60
+
+
+
+ junitjunit
- 4.11
+ 4.13.1test
@@ -79,147 +109,18 @@
2.0.0test
+
+ org.mockito
+ mockito-core
+ 1.10.19
+ test
+
+
+ org.hamcrest
+ hamcrest-core
+ 2.2
+ test
+
-
-
-
- maven-compiler-plugin
- 3.1
-
- ${jdkVersion}
- ${jdkVersion}
- 1.5
- true
- true
- true
- true
-
- -Xlint:unchecked
-
-
-
-
-
- org.apache.maven.plugins
- maven-release-plugin
- 2.5.1
-
-
- org.apache.maven.plugins
- maven-scm-plugin
- 1.9.2
-
-
-
- deploy,site
- false
- true
- true
- v@{project.version}
-
-
-
-
- com.github.github
- site-maven-plugin
- 0.9
-
- Creating site for ${project.version}
- github
-
-
-
-
- site
-
- site
-
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- 2.17
-
- UTF-8
- cn.jpush.api.FastTests
- -Dfile.encoding=UTF-8
-
- **/mock/*Test.java
-
-
-
-
- org.apache.maven.surefire
- surefire-junit47
- 2.17
-
-
-
-
-
- org.apache.maven.plugins
- maven-failsafe-plugin
- 2.17
-
- UTF-8
- cn.jpush.api.SlowTests
- -Dfile.encoding=UTF-8
-
- **/mock/*Test.java
-
-
-
-
-
- integration-test
- verify
-
-
-
- **/*.class
-
-
-
-
-
-
- org.apache.maven.surefire
- surefire-junit47
- 2.17
-
-
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-project-info-reports-plugin
- 2.7
-
-
-
- dependencies
- license
- scm
-
-
-
-
-
- org.apache.maven.plugins
- maven-javadoc-plugin
- 2.9.1
-
- resources/javadoc-overview.html
-
-
-
-
-
diff --git a/src/main/java/cn/jpush/api/JPushClient.java b/src/main/java/cn/jpush/api/JPushClient.java
index 270df3b1..e0b132b7 100644
--- a/src/main/java/cn/jpush/api/JPushClient.java
+++ b/src/main/java/cn/jpush/api/JPushClient.java
@@ -1,67 +1,100 @@
package cn.jpush.api;
+import java.util.List;
import java.util.Map;
import java.util.Set;
-import cn.jpush.api.common.ClientConfig;
-import cn.jpush.api.common.TimeUnit;
-import cn.jpush.api.common.Week;
-import cn.jpush.api.common.connection.HttpProxy;
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
-import cn.jpush.api.common.resp.BooleanResult;
-import cn.jpush.api.common.resp.DefaultResult;
+import cn.jiguang.common.resp.*;
+import cn.jpush.api.push.CIDResult;
+import cn.jpush.api.push.model.*;
+import cn.jpush.api.push.model.live_activity.LiveActivity;
+import cn.jpush.api.report.*;
+import cn.jpush.api.report.model.CheckMessagePayload;
+import com.google.gson.JsonObject;
+
+import cn.jiguang.common.ClientConfig;
+import cn.jiguang.common.TimeUnit;
+import cn.jiguang.common.Week;
+import cn.jiguang.common.utils.Preconditions;
+import cn.jiguang.common.connection.HttpProxy;
import cn.jpush.api.device.AliasDeviceListResult;
import cn.jpush.api.device.DeviceClient;
+import cn.jpush.api.device.OnlineStatus;
import cn.jpush.api.device.TagAliasResult;
import cn.jpush.api.device.TagListResult;
import cn.jpush.api.push.PushClient;
import cn.jpush.api.push.PushResult;
-import cn.jpush.api.push.model.Message;
-import cn.jpush.api.push.model.Platform;
-import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
+import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.Notification;
-import cn.jpush.api.report.MessagesResult;
-import cn.jpush.api.report.ReceivedsResult;
-import cn.jpush.api.report.ReportClient;
-import cn.jpush.api.report.UsersResult;
import cn.jpush.api.schedule.ScheduleClient;
import cn.jpush.api.schedule.ScheduleListResult;
+import cn.jpush.api.schedule.ScheduleMsgIdsResult;
import cn.jpush.api.schedule.ScheduleResult;
import cn.jpush.api.schedule.model.SchedulePayload;
import cn.jpush.api.schedule.model.TriggerPayload;
-import cn.jpush.api.utils.Preconditions;
/**
* The global entrance of JPush API library.
*/
public class JPushClient {
private final PushClient _pushClient;
- private final ReportClient _reportClient;
- private final DeviceClient _deviceClient;
+ private final ReportClient _reportClient;
+ private final DeviceClient _deviceClient;
private final ScheduleClient _scheduleClient;
-
- /**
- * Create a JPush Client.
- *
- * @param masterSecret API access secret of the appKey.
- * @param appKey The KEY of one application on JPush.
- */
- public JPushClient(String masterSecret, String appKey) {
- _pushClient = new PushClient(masterSecret, appKey);
- _reportClient = new ReportClient(masterSecret, appKey);
- _deviceClient = new DeviceClient(masterSecret, appKey);
+
+ /**
+ * Create a JPush Client.
+ *
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ */
+ public JPushClient(String masterSecret, String appKey) {
+ _pushClient = new PushClient(masterSecret, appKey);
+ _reportClient = new ReportClient(masterSecret, appKey);
+ _deviceClient = new DeviceClient(masterSecret, appKey);
_scheduleClient = new ScheduleClient(masterSecret, appKey);
- }
-
- public JPushClient(String masterSecret, String appKey, int maxRetryTimes) {
+ }
+
+ /**
+ * Create a JPush Client by custom Client configuration.
+ *
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param proxy The proxy, if there is no proxy, should be null.
+ * @param conf The client configuration. Can use ClientConfig.getInstance() as default.
+ */
+ public JPushClient(String masterSecret, String appKey, HttpProxy proxy, ClientConfig conf) {
+ _pushClient = new PushClient(masterSecret, appKey, proxy, conf);
+ _reportClient = new ReportClient(masterSecret, appKey, proxy, conf);
+ _deviceClient = new DeviceClient(masterSecret, appKey, proxy, conf);
+ _scheduleClient = new ScheduleClient(masterSecret, appKey, proxy, conf);
+ }
+
+ /**
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
+ *
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param maxRetryTimes The max retry times.
+ */
+ @Deprecated
+ public JPushClient(String masterSecret, String appKey, int maxRetryTimes) {
_pushClient = new PushClient(masterSecret, appKey, maxRetryTimes);
_reportClient = new ReportClient(masterSecret, appKey, maxRetryTimes);
_deviceClient = new DeviceClient(masterSecret, appKey, maxRetryTimes);
_scheduleClient = new ScheduleClient(masterSecret, appKey, maxRetryTimes);
- }
-
+ }
+
+ /**
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
+ *
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param maxRetryTimes The max retry times.
+ * @param proxy The proxy, if there is no proxy, should be null.
+ */
+ @Deprecated
public JPushClient(String masterSecret, String appKey, int maxRetryTimes, HttpProxy proxy) {
_pushClient = new PushClient(masterSecret, appKey, maxRetryTimes, proxy);
_reportClient = new ReportClient(masterSecret, appKey, maxRetryTimes, proxy);
@@ -71,148 +104,231 @@ public JPushClient(String masterSecret, String appKey, int maxRetryTimes, HttpPr
/**
* Create a JPush Client by custom Client configuration.
- *
+ *
* If you are using JPush privacy cloud, maybe this constructor is what you needed.
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
*
- * @param masterSecret API access secret of the appKey.
- * @param appKey The KEY of one application on JPush.
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
* @param maxRetryTimes Client request retry times.
- * @param proxy The proxy, if there is no proxy, should be null.
- * @param conf The client configuration. Can use ClientConfig.getInstance() as default.
+ * @param proxy The proxy, if there is no proxy, should be null.
+ * @param conf The client configuration. Can use ClientConfig.getInstance() as default.
*/
+ @Deprecated
public JPushClient(String masterSecret, String appKey, int maxRetryTimes, HttpProxy proxy, ClientConfig conf) {
- _pushClient = new PushClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _reportClient = new ReportClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _deviceClient = new DeviceClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _scheduleClient = new ScheduleClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
+ conf.setMaxRetryTimes(maxRetryTimes);
+
+ _pushClient = new PushClient(masterSecret, appKey, proxy, conf);
+ _reportClient = new ReportClient(masterSecret, appKey, proxy, conf);
+ _deviceClient = new DeviceClient(masterSecret, appKey, proxy, conf);
+ _scheduleClient = new ScheduleClient(masterSecret, appKey, proxy, conf);
+
}
/**
* Create a JPush Client by custom Client configuration with global settings.
- *
+ *
* If you are using JPush privacy cloud, and you want different settings from default globally,
* maybe this constructor is what you needed.
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setGlobalPushSetting} instead of this constructor.
*
- * @param masterSecret API access secret of the appKey.
- * @param appKey The KEY of one application on JPush.
- * @param maxRetryTimes Client request retry times.
- * @param proxy The proxy, if there is no proxy, should be null.
- * @param conf The client configuration. Can use ClientConfig.getInstance() as default.
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param maxRetryTimes Client request retry times.
+ * @param proxy The proxy, if there is no proxy, should be null.
+ * @param conf The client configuration. Can use ClientConfig.getInstance() as default.
* @param apnsProduction Global APNs environment setting. It will override PushPayload Options.
- * @param timeToLive Global time_to_live setting. It will override PushPayload Options.
+ * @param timeToLive Global time_to_live setting. It will override PushPayload Options.
*/
+ @Deprecated
public JPushClient(String masterSecret, String appKey, int maxRetryTimes, HttpProxy proxy, ClientConfig conf,
boolean apnsProduction, long timeToLive) {
- _pushClient = new PushClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _reportClient = new ReportClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _deviceClient = new DeviceClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _scheduleClient = new ScheduleClient(masterSecret, appKey, maxRetryTimes, proxy, conf);
- _pushClient.setDefaults(apnsProduction, timeToLive);
- }
-
- /**
- * Create a JPush Client with global settings.
- *
- * If you want different settings from default globally, this constructor is what you needed.
- *
- * @param masterSecret API access secret of the appKey.
- * @param appKey The KEY of one application on JPush.
- * @param apnsProduction Global APNs environment setting. It will override PushPayload Options.
- * @param timeToLive Global time_to_live setting. It will override PushPayload Options.
- */
+ conf.setMaxRetryTimes(maxRetryTimes);
+ conf.setApnsProduction(apnsProduction);
+ conf.setTimeToLive(timeToLive);
+ _pushClient = new PushClient(masterSecret, appKey, proxy, conf);
+ _reportClient = new ReportClient(masterSecret, appKey, proxy, conf);
+ _deviceClient = new DeviceClient(masterSecret, appKey, proxy, conf);
+ _scheduleClient = new ScheduleClient(masterSecret, appKey, proxy, conf);
+ }
+
+ /**
+ * Create a JPush Client with global settings.
+ *
+ * If you want different settings from default globally, this constructor is what you needed.
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setGlobalPushSetting} instead of this constructor.
+ *
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param apnsProduction Global APNs environment setting. It will override PushPayload Options.
+ * @param timeToLive Global time_to_live setting. It will override PushPayload Options.
+ */
+ @Deprecated
public JPushClient(String masterSecret, String appKey, boolean apnsProduction, long timeToLive) {
- _pushClient = new PushClient(masterSecret, appKey, apnsProduction, timeToLive);
+ ClientConfig conf = ClientConfig.getInstance();
+ conf.setApnsProduction(apnsProduction);
+ conf.setTimeToLive(timeToLive);
+ _pushClient = new PushClient(masterSecret, appKey);
_reportClient = new ReportClient(masterSecret, appKey);
_deviceClient = new DeviceClient(masterSecret, appKey);
_scheduleClient = new ScheduleClient(masterSecret, appKey);
}
-
-
+
+ public PushClient getPushClient() {
+ return _pushClient;
+ }
+
// ----------------------------- Push API
/**
* Send a push with PushPayload object.
- *
- * @param pushPayload payload object of a push.
+ *
+ * @param pushPayload payload object of a push.
* @return PushResult The result object of a Push. Can be printed to a JSON.
- * @throws APIConnectionException
- * @throws APIRequestException
- */
- public PushResult sendPush(PushPayload pushPayload) throws APIConnectionException, APIRequestException {
- return _pushClient.sendPush(pushPayload);
- }
-
- /**
- * Send a push with JSON string.
- *
- * You can send a push JSON string directly with this method.
- *
- * Attention: globally settings cannot be affect this type of Push.
- *
- * @param payloadString payload of a push.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendPush(PushPayload pushPayload) throws APIConnectionException, APIRequestException {
+ return _pushClient.sendPush(pushPayload);
+ }
+
+ /**
+ * Send a push with JSON string.
+ *
+ * You can send a push JSON string directly with this method.
+ *
+ * Attention: globally settings cannot be affect this type of Push.
+ *
+ * @param payloadString payload of a push.
* @return PushResult. Can be printed to a JSON.
- * @throws APIConnectionException
- * @throws APIRequestException
- */
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
public PushResult sendPush(String payloadString) throws APIConnectionException, APIRequestException {
return _pushClient.sendPush(payloadString);
}
-
+
+ /**
+ * Send a file push with PushPayload object.
+ *
+ * @param pushPayload payload object of a push.
+ * @return PushResult The result object of a Push. Can be printed to a JSON.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendFilePush(PushPayload pushPayload) throws APIConnectionException, APIRequestException {
+ return _pushClient.sendFilePush(pushPayload);
+ }
+
/**
* Validate a push action, but do NOT send it actually.
- *
- * @param paylaod
- * @return
- * @throws APIConnectionException
- * @throws APIRequestException
+ *
+ * @param payload payload of a push.
+ * @return PushResult. Can be printed to a JSON.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendPushValidate(PushPayload paylaod) throws APIConnectionException, APIRequestException {
- return _pushClient.sendPushValidate(paylaod);
+ public PushResult sendPushValidate(PushPayload payload) throws APIConnectionException, APIRequestException {
+ return _pushClient.sendPushValidate(payload);
}
public PushResult sendPushValidate(String payloadString) throws APIConnectionException, APIRequestException {
- return _pushClient.sendPushValidate(payloadString);
+ return _pushClient.sendPushValidate(payloadString);
+ }
+
+ public BatchPushResult batchSendPushByRegId(List pushPayloadList) throws APIConnectionException, APIRequestException {
+ return _pushClient.batchSendPushByRegId(pushPayloadList);
}
-
+ public BatchPushResult batchSendPushByAlias(List pushPayloadList) throws APIConnectionException, APIRequestException {
+ return _pushClient.batchSendPushByAlias(pushPayloadList);
+ }
+
+ /**
+ * Get cid list, the data form of cid is appKey-uuid.
+ *
+ * @param count the count of cid list, from 1 to 1000. default is 1.
+ * @param type default is push, option: schedule
+ * @return CIDResult, an array of cid
+ * @throws APIConnectionException connect exception
+ * @throws APIRequestException request exception
+ */
+ public CIDResult getCidList(int count, String type) throws APIConnectionException, APIRequestException {
+ return _pushClient.getCidList(count, type);
+ }
+
+
// ------------------------------- Report API
/**
- * Get received report.
- *
+ * Get received report.
+ *
* @param msgIds 100 msgids to batch getting is supported.
* @return ReceivedResult. Can be printed to JSON.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ReceivedsResult getReportReceiveds(String msgIds) throws APIConnectionException, APIRequestException {
- return _reportClient.getReceiveds(msgIds);
- }
-
+ return _reportClient.getReceiveds(msgIds);
+ }
+
public UsersResult getReportUsers(TimeUnit timeUnit, String start, int duration) throws APIConnectionException, APIRequestException {
return _reportClient.getUsers(timeUnit, start, duration);
}
-
+
public MessagesResult getReportMessages(String msgIds) throws APIConnectionException, APIRequestException {
return _reportClient.getMessages(msgIds);
}
-
-
+
+ public Map getMessageStatus(CheckMessagePayload payload)
+ throws APIConnectionException, APIRequestException {
+ return _reportClient.getMessagesStatus(payload);
+ }
+
+ public ReceivedsResult getReceivedsDetail(String msgIds)
+ throws APIConnectionException, APIRequestException {
+ return _reportClient.getReceivedsDetail(msgIds);
+ }
+
+ public MessageDetailResult getMessagesDetail(String msgIds)
+ throws APIConnectionException, APIRequestException {
+ return _reportClient.getMessagesDetail(msgIds);
+ }
+
+ public GroupMessageDetailResult getGroupMessagesDetail(String groupMsgIds)
+ throws APIConnectionException, APIRequestException {
+ return _reportClient.getGroupMessagesDetail(groupMsgIds);
+ }
+
+ public GroupUsersResult getGroupReportUsers(TimeUnit timeUnit, String start, int duration) throws APIConnectionException,
+ APIRequestException {
+ return _reportClient.getGroupUsers(timeUnit, start, duration);
+ }
+
// ------------------------------ Shortcuts - notification
-
- /**
- * Shortcut
- */
+
public PushResult sendNotificationAll(String alert) throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.alertAll(alert);
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send a notification to all.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The notification content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @return push result
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendAndroidNotificationWithAlias(String title, String alert,
- Map extras, String... alias)
+ public PushResult sendNotificationAll(String alert, SMS sms) throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.alertAll(alert, sms);
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendAndroidNotificationWithAlias(String title, String alert,
+ Map extras, String... alias)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android())
@@ -221,26 +337,163 @@ public PushResult sendAndroidNotificationWithAlias(String title, String alert,
.build();
return _pushClient.sendPush(payload);
}
-
+
+ /**
+ * Send a notification to Android with alias.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The notification title.
+ * @param alert The notification content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra parameter.
+ * @param alias The users' alias.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendAndroidNotificationWithAlias(String title, String alert, SMS sms,
+ Map extras, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.android())
+ .setAudience(Audience.alias(alias))
+ .setNotification(Notification.android(alert, title, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendAndroidNotificationWithRegistrationID(String title, String alert,
+ Map extras, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.android())
+ .setAudience(Audience.registrationId(registrationID))
+ .setNotification(Notification.android(alert, title, extras))
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
/**
- * Shortcut
+ * Send a notification to Android with RegistrationID.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The notification title.
+ * @param alert The notification content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra parameter.
+ * @param registrationID The registration id generated by JPush.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendAndroidNotificationWithRegistrationID(String title, String alert,
- Map extras, String... registrationID)
+ public PushResult sendAndroidNotificationWithRegistrationID(String title, String alert, SMS sms,
+ Map extras, String... registrationID)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android())
.setAudience(Audience.registrationId(registrationID))
.setNotification(Notification.android(alert, title, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendIosNotificationWithAlias(String alert,
+ Map extras, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.alias(alias))
+ .setNotification(Notification.ios(alert, extras))
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send a notification to iOS with alias.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The notification content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra parameter.
+ * @param alias The users' alias.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithAlias(String alert, SMS sms,
+ Map extras, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.alias(alias))
+ .setNotification(Notification.ios(alert, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS notification with alias.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ *
+ * @param alert The wrapper of APNs alert.
+ * @param extras The extra params.
+ * @param alias The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithAlias(IosAlert alert,
+ Map extras, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.alias(alias))
+ .setNotification(Notification.ios(alert, extras))
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS notification with alias.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The wrapper of APNs alert.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra params.
+ * @param alias The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithAlias(IosAlert alert, SMS sms,
+ Map extras, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.alias(alias))
+ .setNotification(Notification.ios(alert, extras))
+ .setSMS(sms)
.build();
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send an iOS notification with alias.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ *
+ * @param alert The JSON object of APNs alert.
+ * @param extras The extra params.
+ * @param alias The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendIosNotificationWithAlias(String alert,
- Map extras, String... alias)
+ public PushResult sendIosNotificationWithAlias(JsonObject alert,
+ Map extras, String... alias)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.ios())
@@ -249,12 +502,80 @@ public PushResult sendIosNotificationWithAlias(String alert,
.build();
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send an iOS notification with alias.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The JSON object of APNs alert.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra params.
+ * @param alias The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendIosNotificationWithRegistrationID(String alert,
- Map extras, String... registrationID)
+ public PushResult sendIosNotificationWithAlias(JsonObject alert, SMS sms,
+ Map extras, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.alias(alias))
+ .setNotification(Notification.ios(alert, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendIosNotificationWithRegistrationID(String alert,
+ Map extras, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setNotification(Notification.ios(alert, extras))
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS notification with registrationIds.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The notification content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra params.
+ * @param registrationID The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithRegistrationID(String alert, SMS sms,
+ Map extras, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setNotification(Notification.ios(alert, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS notification with registrationIds.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ *
+ * @param alert The wrapper of APNs alert.
+ * @param extras The extra params.
+ * @param registrationID The registration ids.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithRegistrationID(IosAlert alert,
+ Map extras, String... registrationID)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.ios())
@@ -264,21 +585,102 @@ public PushResult sendIosNotificationWithRegistrationID(String alert,
return _pushClient.sendPush(payload);
}
-
- // ---------------------- shortcuts - message
-
/**
- * Shortcut
+ * Send an iOS notification with registrationIds.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The wrapper of APNs alert.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra params.
+ * @param registrationID The registration ids.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
+ public PushResult sendIosNotificationWithRegistrationID(IosAlert alert, SMS sms,
+ Map extras, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setNotification(Notification.ios(alert, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS notification with registrationIds.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ *
+ * @param alert The wrapper of APNs alert.
+ * @param extras The extra params.
+ * @param registrationID The registration ids.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithRegistrationID(JsonObject alert,
+ Map extras, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setNotification(Notification.ios(alert, extras))
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS notification with registrationIds.
+ * If you want to send alert as a Json object, maybe this method is what you needed.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param alert The JSON object of APNs alert.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param extras The extra params.
+ * @param registrationID The registration ids.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosNotificationWithRegistrationID(JsonObject alert, SMS sms,
+ Map extras, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setNotification(Notification.ios(alert, extras))
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+
+ // ---------------------- shortcuts - message
+
public PushResult sendMessageAll(String msgContent) throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.messageAll(msgContent);
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send a message to all
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param msgContent The message content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendAndroidMessageWithAlias(String title, String msgContent, String... alias)
+ public PushResult sendMessageAll(String msgContent, SMS sms) throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.messageAll(msgContent, sms);
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendAndroidMessageWithAlias(String title, String msgContent, String... alias)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android())
@@ -290,11 +692,34 @@ public PushResult sendAndroidMessageWithAlias(String title, String msgContent, S
.build();
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send an Android message with alias.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The message title.
+ * @param msgContent The message content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param alias The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendAndroidMessageWithRegistrationID(String title, String msgContent, String... registrationID)
+ public PushResult sendAndroidMessageWithAlias(String title, String msgContent, SMS sms, String... alias)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.android())
+ .setAudience(Audience.alias(alias))
+ .setMessage(Message.newBuilder()
+ .setTitle(title)
+ .setMsgContent(msgContent)
+ .build())
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendAndroidMessageWithRegistrationID(String title, String msgContent, String... registrationID)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android())
@@ -306,11 +731,34 @@ public PushResult sendAndroidMessageWithRegistrationID(String title, String msgC
.build();
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send an Android message with registration id.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The message title.
+ * @param msgContent The message content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param registrationID The registration id list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendIosMessageWithAlias(String title, String msgContent, String... alias)
+ public PushResult sendAndroidMessageWithRegistrationID(String title, String msgContent, SMS sms, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.android())
+ .setAudience(Audience.registrationId(registrationID))
+ .setMessage(Message.newBuilder()
+ .setTitle(title)
+ .setMsgContent(msgContent)
+ .build())
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendIosMessageWithAlias(String title, String msgContent, String... alias)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.ios())
@@ -322,14 +770,76 @@ public PushResult sendIosMessageWithAlias(String title, String msgContent, Strin
.build();
return _pushClient.sendPush(payload);
}
-
+
/**
- * Shortcut
+ * Send an iOS message with alias.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The message title.
+ * @param msgContent The message content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param alias The alias list.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendIosMessageWithRegistrationID(String title, String msgContent, String... registrationID)
+ public PushResult sendIosMessageWithAlias(String title, String msgContent, SMS sms, String... alias)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.ios())
+ .setAudience(Audience.alias(alias))
+ .setMessage(Message.newBuilder()
+ .setTitle(title)
+ .setMsgContent(msgContent)
+ .build())
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendIosMessageWithRegistrationID(String title, String msgContent, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setMessage(Message.newBuilder()
+ .setTitle(title)
+ .setMsgContent(msgContent)
+ .build())
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ /**
+ * Send an iOS message with registration id.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The message title.
+ * @param msgContent The message content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param registrationID The registrationIds generated by JPush.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public PushResult sendIosMessageWithRegistrationID(String title, String msgContent, SMS sms, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.ios())
+ .setAudience(Audience.registrationId(registrationID))
+ .setMessage(Message.newBuilder()
+ .setTitle(title)
+ .setMsgContent(msgContent)
+ .build())
+ .setSMS(sms)
+ .build();
+ return _pushClient.sendPush(payload);
+ }
+
+ public PushResult sendMessageWithRegistrationID(String title, String msgContent, String... registrationID)
+ throws APIConnectionException, APIRequestException {
+ PushPayload payload = PushPayload.newBuilder()
+ .setPlatform(Platform.all())
.setAudience(Audience.registrationId(registrationID))
.setMessage(Message.newBuilder()
.setTitle(title)
@@ -340,9 +850,18 @@ public PushResult sendIosMessageWithRegistrationID(String title, String msgConte
}
/**
- * Shortcut
+ * Send a message with registrationIds.
+ * If it doesn't received within the delay time,JPush will send a SMS to the corresponding users.
+ *
+ * @param title The message title.
+ * @param msgContent The message content.
+ * @param sms The SMS content and delay time. If null, sms doesn't work, no effect on Push feature.
+ * @param registrationID The registrationIds generated by JPush.
+ * @return push result.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public PushResult sendMessageWithRegistrationID(String title, String msgContent, String... registrationID)
+ public PushResult sendMessageWithRegistrationID(String title, String msgContent, SMS sms, String... registrationID)
throws APIConnectionException, APIRequestException {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.all())
@@ -351,74 +870,105 @@ public PushResult sendMessageWithRegistrationID(String title, String msgContent,
.setTitle(title)
.setMsgContent(msgContent)
.build())
+ .setSMS(sms)
.build();
return _pushClient.sendPush(payload);
}
+ /**
+ * Delete a push by msgId.
+ *
+ * @param msgId The message id
+ * @return delete result
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs
+ */
+ public DefaultResult deletePush(String msgId) throws APIConnectionException, APIRequestException {
+ return _pushClient.deletePush(msgId);
+ }
+
-
// ----------------------- Device
-
- public TagAliasResult getDeviceTagAlias(String registrationId)
- throws APIConnectionException, APIRequestException {
- return _deviceClient.getDeviceTagAlias(registrationId);
+
+ public TagAliasResult getDeviceTagAlias(String registrationId)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.getDeviceTagAlias(registrationId);
}
public DefaultResult updateDeviceTagAlias(String registrationId, boolean clearAlias, boolean clearTag)
- throws APIConnectionException, APIRequestException {
- return _deviceClient.updateDeviceTagAlias(registrationId, clearAlias, clearTag);
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.updateDeviceTagAlias(registrationId, clearAlias, clearTag);
+ }
+
+ public DefaultResult updateDeviceTagAlias(String registrationId, String alias,
+ Set tagsToAdd, Set tagsToRemove)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.updateDeviceTagAlias(registrationId, alias, tagsToAdd, tagsToRemove);
+ }
+
+ public TagListResult getTagList()
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.getTagList();
}
-
- public DefaultResult updateDeviceTagAlias(String registrationId, String alias,
- Set tagsToAdd, Set tagsToRemove)
+
+ public BooleanResult isDeviceInTag(String theTag, String registrationID)
throws APIConnectionException, APIRequestException {
- return _deviceClient.updateDeviceTagAlias(registrationId, alias, tagsToAdd, tagsToRemove);
+ return _deviceClient.isDeviceInTag(theTag, registrationID);
}
- public TagListResult getTagList()
- throws APIConnectionException, APIRequestException {
- return _deviceClient.getTagList();
- }
+ public DefaultResult addRemoveDevicesFromTag(String theTag,
+ Set toAddUsers, Set toRemoveUsers)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.addRemoveDevicesFromTag(theTag, toAddUsers,
+ toRemoveUsers);
+ }
- public BooleanResult isDeviceInTag(String theTag, String registrationID)
- throws APIConnectionException, APIRequestException {
- return _deviceClient.isDeviceInTag(theTag, registrationID);
- }
+ public DefaultResult deleteTag(String theTag, String platform)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.deleteTag(theTag, platform);
+ }
- public DefaultResult addRemoveDevicesFromTag(String theTag,
- Set toAddUsers, Set toRemoveUsers)
- throws APIConnectionException, APIRequestException {
- return _deviceClient.addRemoveDevicesFromTag(theTag, toAddUsers,
- toRemoveUsers);
- }
+ public AliasDeviceListResult getAliasDeviceList(String alias,
+ String platform) throws APIConnectionException, APIRequestException {
+ return _deviceClient.getAliasDeviceList(alias, platform);
+ }
- public DefaultResult deleteTag(String theTag, String platform)
- throws APIConnectionException, APIRequestException {
- return _deviceClient.deleteTag(theTag, platform);
- }
+ public DefaultResult deleteAlias(String alias, String platform)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.deleteAlias(alias, platform);
+ }
- public AliasDeviceListResult getAliasDeviceList(String alias,
- String platform) throws APIConnectionException, APIRequestException {
- return _deviceClient.getAliasDeviceList(alias, platform);
- }
+ public DefaultResult removeDevicesFromAlias(String alias, Set toRemoveDevice)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.removeDevicesFromAlias(alias, toRemoveDevice);
+ }
- public DefaultResult deleteAlias(String alias, String platform)
- throws APIConnectionException, APIRequestException {
- return _deviceClient.deleteAlias(alias, platform);
- }
+ public Map getUserOnlineStatus(String... registrationIds)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.getUserOnlineStatus(registrationIds);
+ }
+
+ public DefaultResult bindMobile(String registrationId, String mobile)
+ throws APIConnectionException, APIRequestException {
+ return _deviceClient.bindMobile(registrationId, mobile);
+ }
// ----------------------- Schedule
/**
* Create a single schedule.
- * @param name The schedule name.
- * @param time The push time, format is 'yyyy-MM-dd HH:mm:ss'
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param time The push time, format is 'yyyy-MM-dd HH:mm:ss'
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createSingleSchedule(String name, String time, PushPayload push)
+ public ScheduleResult createSingleSchedule(String name, String time, PushPayload push, String masterSecret,
+ String appKey)
throws APIConnectionException, APIRequestException {
TriggerPayload trigger = TriggerPayload.newBuilder()
.setSingleTime(time)
@@ -430,143 +980,185 @@ public ScheduleResult createSingleSchedule(String name, String time, PushPayload
.setPush(push)
.build();
- return _scheduleClient.createSchedule(payload);
+ return _scheduleClient.createSchedule(payload, masterSecret, appKey);
}
/**
* Create a daily schedule push everyday.
- * @param name The schedule name.
- * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param time The push time, format 'HH:mm:ss'
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param time The push time, format 'HH:mm:ss'
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createDailySchedule(String name, String start, String end, String time, PushPayload push)
+ public ScheduleResult createDailySchedule(String name, String start, String end, String time, PushPayload push,
+ String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
- return createPeriodicalSchedule(name, start, end, time, TimeUnit.DAY, 1, null, push);
+ return createPeriodicalSchedule(name, start, end, time, TimeUnit.DAY, 1, null, push,
+ masterSecret, appKey);
}
/**
* Create a daily schedule push with a custom frequency.
- * @param name The schedule name.
- * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param time The push time, format 'HH:mm:ss'
- * @param frequency The custom frequency.
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param time The push time, format 'HH:mm:ss'
+ * @param frequency The custom frequency.
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createDailySchedule(String name, String start, String end, String time, int frequency, PushPayload push)
+ public ScheduleResult createDailySchedule(String name, String start, String end, String time, int frequency,
+ PushPayload push, String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
- return createPeriodicalSchedule(name, start, end, time, TimeUnit.DAY, frequency, null, push);
+ return createPeriodicalSchedule(name, start, end, time, TimeUnit.DAY, frequency, null, push,
+ masterSecret, appKey);
}
/**
* Create a weekly schedule push every week at the appointed days.
- * @param name The schedule name.
- * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param time The push time, format 'HH:mm:ss'
- * @param days The appointed days.
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param time The push time, format 'HH:mm:ss'
+ * @param days The appointed days.
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createWeeklySchedule(String name, String start, String end, String time, Week[] days, PushPayload push)
+ public ScheduleResult createWeeklySchedule(String name, String start, String end, String time, Week[] days,
+ PushPayload push, String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(null != days && days.length > 0, "The days must not be empty.");
String[] points = new String[days.length];
- for(int i = 0 ; i < days.length; i++) {
+ for (int i = 0; i < days.length; i++) {
points[i] = days[i].name();
}
- return createPeriodicalSchedule(name, start, end, time, TimeUnit.WEEK, 1, points, push);
+ return createPeriodicalSchedule(name, start, end, time, TimeUnit.WEEK, 1, points, push,
+ masterSecret, appKey);
}
/**
* Create a weekly schedule push with a custom frequency at the appointed days.
- * @param name The schedule name.
- * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param time The push time, format 'HH:mm:ss'.
- * @param frequency The custom frequency.
- * @param days The appointed days.
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param time The push time, format 'HH:mm:ss'.
+ * @param frequency The custom frequency.
+ * @param days The appointed days.
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createWeeklySchedule(String name, String start, String end, String time, int frequency, Week[] days, PushPayload push)
+ public ScheduleResult createWeeklySchedule(String name, String start, String end, String time, int frequency,
+ Week[] days, PushPayload push, String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(null != days && days.length > 0, "The days must not be empty.");
String[] points = new String[days.length];
- for(int i = 0 ; i < days.length; i++) {
+ for (int i = 0; i < days.length; i++) {
points[i] = days[i].name();
}
- return createPeriodicalSchedule(name, start, end, time, TimeUnit.WEEK, frequency, points, push);
+ return createPeriodicalSchedule(name, start, end, time, TimeUnit.WEEK, frequency, points, push, masterSecret, appKey);
}
/**
* Create a monthly schedule push every month at the appointed days.
- * @param name The schedule name.
- * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param time The push time, format 'HH:mm:ss'.
- * @param points The appointed days.
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param time The push time, format 'HH:mm:ss'.
+ * @param points The appointed days.
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createMonthlySchedule(String name, String start, String end, String time, String[] points, PushPayload push)
+ public ScheduleResult createMonthlySchedule(String name, String start, String end, String time, String[] points,
+ PushPayload push, String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(null != points && points.length > 0, "The points must not be empty.");
- return createPeriodicalSchedule(name, start, end, time, TimeUnit.MONTH, 1, points, push);
+ return createPeriodicalSchedule(name, start, end, time, TimeUnit.MONTH, 1, points, push, masterSecret, appKey);
}
/**
* Create a monthly schedule push with a custom frequency at the appointed days.
- * @param name The schedule name.
- * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
- * @param time The push time, format 'HH:mm:ss'.
- * @param frequency The custom frequency.
- * @param points The appointed days.
- * @param push The push payload.
+ *
+ * @param name The schedule name.
+ * @param start The schedule comes into effect date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param end The schedule expiration date, format 'yyyy-MM-dd HH:mm:ss'.
+ * @param time The push time, format 'HH:mm:ss'.
+ * @param frequency The custom frequency.
+ * @param points The appointed days.
+ * @param push The push payload.
+ * @param masterSecret master secret
+ * @param appKey app key
* @return The created scheduleResult instance.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
- public ScheduleResult createMonthlySchedule(String name, String start, String end, String time, int frequency, String[] points, PushPayload push)
+ public ScheduleResult createMonthlySchedule(String name, String start, String end, String time, int frequency, String[] points,
+ PushPayload push, String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(null != points && points.length > 0, "The points must not be empty.");
- return createPeriodicalSchedule(name, start, end, time, TimeUnit.MONTH, frequency, points, push);
+ return createPeriodicalSchedule(name, start, end, time, TimeUnit.MONTH, frequency, points, push, masterSecret, appKey);
}
/**
* Get the schedule information by the schedule id.
+ *
* @param scheduleId The schedule id.
* @return The schedule information.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult getSchedule(String scheduleId)
throws APIConnectionException, APIRequestException {
- return _scheduleClient.getSchedule(scheduleId);
+ return _scheduleClient.getSchedule(scheduleId);
+ }
+
+ /**
+ * Get the message id by the schedule id.
+ *
+ * @param scheduleId The schedule id.
+ * @return The message id list.
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
+ */
+ public ScheduleMsgIdsResult getScheduleMsgIds(String scheduleId)
+ throws APIConnectionException, APIRequestException {
+ return _scheduleClient.getScheduleMsgIds(scheduleId);
}
/**
* Get the schedule list size and the first page.
+ *
* @return The schedule list size and the first page.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleListResult getScheduleList()
throws APIConnectionException, APIRequestException {
@@ -575,10 +1167,11 @@ public ScheduleListResult getScheduleList()
/**
* Get the schedule list by the page.
+ *
* @param page The page to search.
* @return The schedule list of the appointed page.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleListResult getScheduleList(int page)
throws APIConnectionException, APIRequestException {
@@ -587,11 +1180,12 @@ public ScheduleListResult getScheduleList(int page)
/**
* Update the schedule name
+ *
* @param scheduleId The schedule id.
- * @param name The new name.
+ * @param name The new name.
* @return The schedule information after updated.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult updateScheduleName(String scheduleId, String name)
throws APIConnectionException, APIRequestException {
@@ -604,10 +1198,11 @@ public ScheduleResult updateScheduleName(String scheduleId, String name)
/**
* Enable the schedule.
+ *
* @param scheduleId The schedule id.
* @return The schedule information after updated.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult enableSchedule(String scheduleId)
throws APIConnectionException, APIRequestException {
@@ -620,10 +1215,11 @@ public ScheduleResult enableSchedule(String scheduleId)
/**
* Disable the schedule.
+ *
* @param scheduleId The schedule id.
* @return The schedule information after updated.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult disableSchedule(String scheduleId)
throws APIConnectionException, APIRequestException {
@@ -635,11 +1231,12 @@ public ScheduleResult disableSchedule(String scheduleId)
/**
* Update the trigger of the schedule.
+ *
* @param scheduleId The schedule id.
- * @param trigger The new trigger.
+ * @param trigger The new trigger.
* @return The schedule information after updated.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult updateScheduleTrigger(String scheduleId, TriggerPayload trigger)
throws APIConnectionException, APIRequestException {
@@ -652,11 +1249,12 @@ public ScheduleResult updateScheduleTrigger(String scheduleId, TriggerPayload tr
/**
* Update the push content of the schedule.
+ *
* @param scheduleId The schedule id.
- * @param push The new push payload.
+ * @param push The new push payload.
* @return The schedule information after updated.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult updateSchedulePush(String scheduleId, PushPayload push)
throws APIConnectionException, APIRequestException {
@@ -669,11 +1267,12 @@ public ScheduleResult updateSchedulePush(String scheduleId, PushPayload push)
/**
* Update a schedule by the id.
+ *
* @param scheduleId The schedule id to update.
- * @param payload The new schedule payload.
+ * @param payload The new schedule payload.
* @return The new schedule information.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public ScheduleResult updateSchedule(String scheduleId, SchedulePayload payload)
throws APIConnectionException, APIRequestException {
@@ -682,9 +1281,10 @@ public ScheduleResult updateSchedule(String scheduleId, SchedulePayload payload)
/**
* Delete a schedule by id.
+ *
* @param scheduleId The schedule id.
- * @throws APIConnectionException
- * @throws APIRequestException
+ * @throws APIConnectionException if a remote or network exception occurs.
+ * @throws APIRequestException if a request exception occurs.
*/
public void deleteSchedule(String scheduleId)
throws APIConnectionException, APIRequestException {
@@ -692,11 +1292,12 @@ public void deleteSchedule(String scheduleId)
}
private ScheduleResult createPeriodicalSchedule(String name, String start, String end, String time,
- TimeUnit timeUnit, int frequency, String[] point, PushPayload push)
+ TimeUnit timeUnit, int frequency, String[] point, PushPayload push,
+ String masterSecret, String appKey)
throws APIConnectionException, APIRequestException {
TriggerPayload trigger = TriggerPayload.newBuilder()
.setPeriodTime(start, end, time)
- .setTimeFrequency(timeUnit, frequency, point )
+ .setTimeFrequency(timeUnit, frequency, point)
.buildPeriodical();
SchedulePayload payload = SchedulePayload.newBuilder()
.setName(name)
@@ -705,8 +1306,17 @@ private ScheduleResult createPeriodicalSchedule(String name, String start, Strin
.setPush(push)
.build();
- return _scheduleClient.createSchedule(payload);
+ return _scheduleClient.createSchedule(payload, masterSecret, appKey);
}
+ public PushResult sendLiveActivity(LiveActivity liveActivity) throws APIConnectionException, APIRequestException {
+ return _pushClient.sendLiveActivity(liveActivity);
+ }
+
+ public void close() {
+ _pushClient.close();
+ }
+
+
}
diff --git a/src/main/java/cn/jpush/api/JPushConfig.java b/src/main/java/cn/jpush/api/JPushConfig.java
new file mode 100644
index 00000000..930e1e72
--- /dev/null
+++ b/src/main/java/cn/jpush/api/JPushConfig.java
@@ -0,0 +1,39 @@
+package cn.jpush.api;
+
+import cn.jiguang.common.ClientConfig;
+
+public class JPushConfig {
+
+ private static ClientConfig clientConfig = ClientConfig.getInstance();
+
+ private static JPushConfig instance = new JPushConfig();
+
+ public static final String ADMIN_HOST_NAME = "api.admin.host.name";
+ public static final String V1_APP_PATH = "jpush.v1.app.path";
+
+ private JPushConfig() {
+ clientConfig.put(ADMIN_HOST_NAME, "https://admin.jpush.cn");
+ clientConfig.put(V1_APP_PATH, "/v1/app");
+ }
+
+ public static JPushConfig getInstance() {
+ return instance;
+ }
+
+ public ClientConfig getClientConfig() {
+ return clientConfig;
+ }
+
+ public JPushConfig setAdminHostName(String hostName) {
+ clientConfig.put(ADMIN_HOST_NAME, hostName);
+ return this;
+ }
+
+ public void put(String key, Object value) {
+ clientConfig.put(key, value);
+ }
+
+ public Object get(String key) {
+ return clientConfig.get(key);
+ }
+}
diff --git a/src/main/java/cn/jpush/api/admin/AdminClient.java b/src/main/java/cn/jpush/api/admin/AdminClient.java
new file mode 100644
index 00000000..57bce1c2
--- /dev/null
+++ b/src/main/java/cn/jpush/api/admin/AdminClient.java
@@ -0,0 +1,134 @@
+package cn.jpush.api.admin;
+
+import cn.jiguang.common.ServiceHelper;
+import cn.jiguang.common.connection.HttpProxy;
+import cn.jiguang.common.connection.IHttpClient;
+import cn.jiguang.common.connection.NativeHttpClient;
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jiguang.common.resp.DefaultResult;
+import cn.jiguang.common.resp.ResponseWrapper;
+import cn.jiguang.common.utils.Preconditions;
+import cn.jpush.api.JPushConfig;
+import cn.jpush.api.file.FileClient;
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Admin APIs
+ * https://docs.jiguang.cn/jpush/server/push/rest_api_admin_api_v1/
+ */
+public class AdminClient {
+
+ protected static final Logger LOG = LoggerFactory.getLogger(FileClient.class);
+
+
+ private IHttpClient mHttpClient;
+ private String mBasePath;
+ private String mV1AppPath;
+ private Gson mGson = new Gson();
+
+ /**
+ * Create a Push Client.
+ *
+ * @param appKey The KEY of one application on JPush.
+ * @param masterSecret API access secret of the appKey.
+ */
+ public AdminClient(String appKey, String masterSecret) {
+ this(appKey, masterSecret, null, JPushConfig.getInstance());
+ }
+
+ public AdminClient(String appKey, String masterSecret, HttpProxy proxy) {
+ this(appKey, masterSecret, proxy, JPushConfig.getInstance());
+ }
+
+
+ public AdminClient(String appKey, String masterSecret, HttpProxy proxy, JPushConfig conf) {
+ ServiceHelper.checkBasic(appKey, masterSecret);
+ mBasePath = (String) conf.get(JPushConfig.ADMIN_HOST_NAME);
+ mV1AppPath = (String) conf.get(JPushConfig.V1_APP_PATH);
+ String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
+ this.mHttpClient = new NativeHttpClient(authCode, proxy, conf.getClientConfig());
+ }
+
+ public void setHttpClient(IHttpClient client) {
+ this.mHttpClient = client;
+ }
+
+ /**
+ * Create an app under developer account
+ * @param appName app name
+ * @param packageName android package name
+ * @param groupName developer app group name
+ * @return {@link CreateAppResult}
+ * @throws APIConnectionException connect exception
+ * @throws APIRequestException request exception
+ */
+ public CreateAppResult createApp(String appName, String packageName, String groupName)
+ throws APIConnectionException, APIRequestException {
+ Preconditions.checkArgument(null != appName, "app name should not be null");
+ Preconditions.checkArgument(null != packageName, "package name should not be null");
+ JsonObject jsonObject = new JsonObject();
+ jsonObject.addProperty("app_name", appName);
+ jsonObject.addProperty("android_package", packageName);
+ if (null != groupName) {
+ jsonObject.addProperty("group_name", groupName);
+ }
+ ResponseWrapper responseWrapper = mHttpClient.sendPost(mBasePath + mV1AppPath, mGson.toJson(jsonObject));
+ return CreateAppResult.fromResponse(responseWrapper, CreateAppResult.class);
+ }
+
+ /**
+ * Delete app by app key
+ * @param appKey app key
+ * @return {@link AppResult}
+ * @throws APIConnectionException connect exception
+ * @throws APIRequestException request exception
+ */
+ public AppResult deleteApp(String appKey) throws APIConnectionException, APIRequestException {
+ ResponseWrapper responseWrapper = mHttpClient.sendDelete(mBasePath + mV1AppPath + "/" + appKey + "/delete");
+ return DefaultResult.fromResponse(responseWrapper, AppResult.class);
+ }
+
+ /**
+ * Upload certificate
+ * @param appKey app key
+ * @param devCertificatePassword dev certificate password
+ * @param proCertificatePassword pro certificate password
+ * @param devCertificateFile dev certificate file
+ * @param proCertificateFile pro certificate file
+ * @throws APIConnectionException connect exception
+ * @throws APIRequestException request exception
+ */
+ public void uploadCertificate(String appKey, String devCertificateFile, String devCertificatePassword,
+ String proCertificateFile, String proCertificatePassword)
+ throws APIConnectionException, APIRequestException {
+
+ Preconditions.checkArgument(devCertificateFile != null || proCertificateFile != null,
+ "dev certificate file or pro certificate file should not be null");
+
+ NativeHttpClient client = (NativeHttpClient) mHttpClient;
+ String url = mBasePath + mV1AppPath + "/" + appKey + "/certificate";
+
+ Map fileMap = new HashMap();
+ Map textMap = new HashMap();
+
+ if(devCertificateFile != null) {
+ textMap.put("devCertificatePassword", devCertificatePassword);
+ fileMap.put("devCertificateFile", devCertificateFile);
+ }
+
+ if(proCertificateFile != null) {
+ textMap.put("proCertificatePassword", proCertificatePassword);
+ fileMap.put("proCertificateFile", proCertificateFile);
+ }
+
+ String response = client.formUploadByPost(url, textMap, fileMap, null);
+ LOG.info("uploadFile:{}", response);
+ }
+}
diff --git a/src/main/java/cn/jpush/api/admin/AppResult.java b/src/main/java/cn/jpush/api/admin/AppResult.java
new file mode 100644
index 00000000..8b22e585
--- /dev/null
+++ b/src/main/java/cn/jpush/api/admin/AppResult.java
@@ -0,0 +1,13 @@
+package cn.jpush.api.admin;
+
+import cn.jiguang.common.resp.BaseResult;
+import com.google.gson.annotations.Expose;
+
+public class AppResult extends BaseResult {
+
+ @Expose private String success;
+
+ public String getSuccess() {
+ return success;
+ }
+}
diff --git a/src/main/java/cn/jpush/api/admin/CreateAppResult.java b/src/main/java/cn/jpush/api/admin/CreateAppResult.java
new file mode 100644
index 00000000..64846452
--- /dev/null
+++ b/src/main/java/cn/jpush/api/admin/CreateAppResult.java
@@ -0,0 +1,22 @@
+package cn.jpush.api.admin;
+
+import cn.jiguang.common.resp.BaseResult;
+import com.google.gson.annotations.Expose;
+
+public class CreateAppResult extends BaseResult {
+ @Expose private String app_key;
+ @Expose private boolean is_new_created;
+ @Expose private String android_package;
+
+ public String getApp_key() {
+ return app_key;
+ }
+
+ public boolean is_new_created() {
+ return is_new_created;
+ }
+
+ public String getAndroid_package() {
+ return android_package;
+ }
+}
diff --git a/src/main/java/cn/jpush/api/common/ClientConfig.java b/src/main/java/cn/jpush/api/common/ClientConfig.java
deleted file mode 100644
index 97eaf9de..00000000
--- a/src/main/java/cn/jpush/api/common/ClientConfig.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package cn.jpush.api.common;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class ClientConfig extends HashMap {
-
- private static ClientConfig instance = new ClientConfig();
-
- public static final String DEVICE_HOST_NAME = "device.host.name";
- public static final Object DEVICE_HOST_NAME_SCHEMA = String.class;
-
- public static final String DEVICES_PATH = "devices.path";
- public static final Object DEVICES_PATH_SCHEMA = String.class;
-
- public static final String TAGS_PATH = "tags.path";
- public static final Object TAGS_PATH_SCHEMA = String.class;
-
- public static final String ALIASES_PATH = "aliases.path";
- public static final Object ALIASES_PATH_SCHEMA = String.class;
-
- public static final String PUSH_HOST_NAME = "push.host.name";
- public static final Object PUSH_HOST_NAME_SCHEMA = String.class;
-
- public static final String PUSH_PATH = "push.path";
- public static final Object PUSH_PATH_SCHEMA = String.class;
-
- public static final String PUSH_VALIDATE_PATH = "push.validate.path";
- public static final Object PUSH_VALIDATE_PATH_SCHMEA = String.class;
-
- public static final String REPORT_HOST_NAME = "report.host.name";
- public static final Object REPORT_HOST_NAME_SCHEMA = String.class;
-
- public static final String REPORT_RECEIVE_PATH = "report.receive.path";
- public static final Object REPORT_RECEIVE_PATH_SCHEMA = String.class;
-
- public static final String REPORT_USER_PATH = "report.user.path";
- public static final Object REPORT_USER_PATH_SCHEMA = String.class;
-
- public static final String REPORT_MESSAGE_PATH = "report.message.path";
- public static final Object REPORT_MESSAGE_PATH_SCHEMA = String.class;
-
- public static final String SCHEDULE_HOST_NAME = "schedule.host.name";
- public static final Object SCHEDULE_HOST_NAME_SCHEMA = String.class;
-
- public static final String SCHEDULE_PATH = "schedule.path";
- public static final Object SCHEDULE_PATH_SCHEMA = String.class;
-
- private ClientConfig() {
- super(12);
- this.put(DEVICE_HOST_NAME, "https://device.jpush.cn");
- this.put(DEVICES_PATH, "/v3/devices");
- this.put(TAGS_PATH, "/v3/tags");
- this.put(ALIASES_PATH, "/v3/aliases");
-
- this.put(PUSH_HOST_NAME, "https://api.jpush.cn");
- this.put(PUSH_PATH, "/v3/push");
- this.put(PUSH_VALIDATE_PATH, "/v3/push/validate");
-
- this.put(REPORT_HOST_NAME, "https://report.jpush.cn");
- this.put(REPORT_RECEIVE_PATH, "/v3/received");
- this.put(REPORT_USER_PATH, "/v3/users");
- this.put(REPORT_MESSAGE_PATH, "/v3/messages");
-
- this.put(SCHEDULE_HOST_NAME, "https://api.jpush.cn");
- this.put(SCHEDULE_PATH, "/v3/schedules");
- }
-
- public static ClientConfig getInstance() {
- return instance;
- }
-
- public static void setDeviceHostName(Map conf, String hostName) {
- conf.put(DEVICE_HOST_NAME, hostName);
- }
-
- /**
- * Setup custom device api host name, if using the JPush privacy cloud.
- * @param hostName the custom api host name, default is JPush domain name
- */
- public void setDeviceHostName(String hostName) {
- setDeviceHostName(this, hostName);
- }
-
- public static void setPushHostName(Map conf, String hostName) {
- conf.put(PUSH_HOST_NAME, hostName);
- }
-
- /**
- * Setup custom push api host name, if using the JPush privacy cloud.
- * @param hostName the custom api host name, default is JPush domain name
- */
- public void setPushHostName(String hostName) {
- setPushHostName(this, hostName);
- }
-
- public static void setReportHostName(Map conf, String hostName) {
- conf.put(REPORT_HOST_NAME, hostName);
- }
-
- /**
- * Setup custom report api host name, if using the JPush privacy cloud.
- * @param hostName the custom api host name, default is JPush domain name
- */
- public void setReportHostName(String hostName) {
- setReportHostName(this, hostName);
- }
-
- public static void setScheduleHostName(Map conf, String hostName) {
- conf.put(SCHEDULE_HOST_NAME, hostName);
- }
-
- public void setScheduleHostName(String hostName) {
- setScheduleHostName(this, hostName);
- }
-
-}
diff --git a/src/main/java/cn/jpush/api/common/DeviceType.java b/src/main/java/cn/jpush/api/common/DeviceType.java
deleted file mode 100644
index 1170fd14..00000000
--- a/src/main/java/cn/jpush/api/common/DeviceType.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package cn.jpush.api.common;
-
-public enum DeviceType {
-
- Android("android"),
- IOS("ios"),
- WinPhone("winphone");
-
- private final String value;
-
- private DeviceType(final String value) {
- this.value = value;
- }
-
- public String value() {
- return this.value;
- }
-
-}
diff --git a/src/main/java/cn/jpush/api/common/ServiceHelper.java b/src/main/java/cn/jpush/api/common/ServiceHelper.java
deleted file mode 100644
index ad905d14..00000000
--- a/src/main/java/cn/jpush/api/common/ServiceHelper.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package cn.jpush.api.common;
-
-import java.text.SimpleDateFormat;
-import java.util.Random;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import cn.jpush.api.utils.Base64;
-import cn.jpush.api.utils.StringUtils;
-
-import com.google.gson.JsonArray;
-import com.google.gson.JsonPrimitive;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ServiceHelper {
-
- private static final Logger LOG = LoggerFactory.getLogger(ServiceHelper.class);
- private final static Pattern PUSH_PATTERNS = Pattern.compile("[^a-zA-Z0-9]");
- private final static String BASIC_PREFIX = "Basic";
-
- private static final Random RANDOM = new Random(System.currentTimeMillis());
- private static final int MIN = 100000;
- private static final int MAX = Integer.MAX_VALUE;
-
- private static final int MAX_BADGE_NUMBER = 99999;
-
- private static final Pattern USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z_0-9.、。@,-]*");
- private static final Pattern DATE_PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
- private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
-
- static {
- DATE_FORMAT.setLenient(false);
- }
-
- public static boolean isValidIntBadge(int intBadge) {
- if (intBadge >= 0 && intBadge <= MAX_BADGE_NUMBER) {
- return true;
- }
- return false;
- }
-
- public static int generateSendno() {
- return RANDOM.nextInt((MAX - MIN) + 1) + MIN;
- }
-
- public static String getBasicAuthorization(String username, String password) {
- String encodeKey = username + ":" + password;
- return BASIC_PREFIX + " " + String.valueOf(Base64.encode(encodeKey.getBytes()));
- }
-
- public static void checkBasic(String appKey, String masterSecret) {
- if (StringUtils.isEmpty(appKey)
- || StringUtils.isEmpty(masterSecret)) {
- throw new IllegalArgumentException("appKey and masterSecret are both required.");
- }
- if (appKey.length() != 24
- || masterSecret.length() != 24
- || PUSH_PATTERNS.matcher(appKey).find()
- || PUSH_PATTERNS.matcher(masterSecret).find()) {
- throw new IllegalArgumentException("appKey and masterSecret format is incorrect. "
- + "They should be 24 size, and be composed with alphabet and numbers. "
- + "Please confirm that they are coming from JPush Web Portal.");
- }
- }
-
- public static JsonArray fromSet(Set sets) {
- JsonArray array = new JsonArray();
- if (null != sets && sets.size() > 0) {
- for (String item : sets) {
- array.add(new JsonPrimitive(item));
- }
- }
- return array;
- }
-
- public static boolean checkUsername(String username) {
- return USERNAME_PATTERN.matcher(username).matches();
- }
-
- public static boolean isValidBirthday( String birthday) {
- try {
- if( ! DATE_PATTERN.matcher(birthday).matches() ) {
- return false;
- }
- DATE_FORMAT.parse(birthday);
- } catch (Exception e) {
- LOG.error("incorrect date format. " + birthday, e);
- return false;
- }
- return true;
- }
-
-}
diff --git a/src/main/java/cn/jpush/api/common/TimeUnit.java b/src/main/java/cn/jpush/api/common/TimeUnit.java
deleted file mode 100644
index 7d6ca3b8..00000000
--- a/src/main/java/cn/jpush/api/common/TimeUnit.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package cn.jpush.api.common;
-
-public enum TimeUnit {
-
- HOUR,
- DAY,
- MONTH,
- WEEK
-
-}
diff --git a/src/main/java/cn/jpush/api/common/Week.java b/src/main/java/cn/jpush/api/common/Week.java
deleted file mode 100644
index df04313a..00000000
--- a/src/main/java/cn/jpush/api/common/Week.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package cn.jpush.api.common;
-
-public enum Week {
- MON,
- TUE,
- WED,
- THU,
- FRI,
- SAT,
- SUN
-}
diff --git a/src/main/java/cn/jpush/api/common/connection/HttpProxy.java b/src/main/java/cn/jpush/api/common/connection/HttpProxy.java
deleted file mode 100644
index 376eec70..00000000
--- a/src/main/java/cn/jpush/api/common/connection/HttpProxy.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package cn.jpush.api.common.connection;
-
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import cn.jpush.api.common.ServiceHelper;
-import cn.jpush.api.utils.Preconditions;
-
-public class HttpProxy {
- private static final Logger LOG = LoggerFactory.getLogger(HttpProxy.class);
-
- private String host;
- private int port;
- private String username;
- private String password;
-
- private boolean authenticationNeeded = false;
-
- public HttpProxy(String host, int port) {
- this.host = host;
- this.port = port;
- }
-
- public HttpProxy(String host, int port, String username, String password) {
- this(host, port);
-
- Preconditions.checkArgument(! (null == username), "username should not be null");
- Preconditions.checkArgument(! (null == password), "password should not be null");
-
- this.username = username;
- this.password = password;
- authenticationNeeded = true;
-
- LOG.info("Http Proxy - host:" + host + ", port:" + port
- + ", username:" + username + ", password:" + password);
- }
-
-
- public Proxy getNetProxy() {
- return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
- }
-
- public boolean isAuthenticationNeeded() {
- return this.authenticationNeeded;
- }
-
- public String getProxyAuthorization() {
- return ServiceHelper.getBasicAuthorization(username, password);
- }
-
- public String getUsername() {
- return this.username;
- }
-
- public String getPassword() {
- return this.password;
- }
-}
diff --git a/src/main/java/cn/jpush/api/common/connection/IHttpClient.java b/src/main/java/cn/jpush/api/common/connection/IHttpClient.java
deleted file mode 100644
index 38f33629..00000000
--- a/src/main/java/cn/jpush/api/common/connection/IHttpClient.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package cn.jpush.api.common.connection;
-
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
-import cn.jpush.api.common.resp.ResponseWrapper;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public interface IHttpClient {
-
- public static final String CHARSET = "UTF-8";
- public static final String CONTENT_TYPE_JSON = "application/json";
- public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
-
- public static final String RATE_LIMIT_QUOTA = "X-Rate-Limit-Limit";
- public static final String RATE_LIMIT_Remaining = "X-Rate-Limit-Remaining";
- public static final String RATE_LIMIT_Reset = "X-Rate-Limit-Reset";
- public static final String JPUSH_USER_AGENT = "JPush-API-Java-Client";
-
- public static final int RESPONSE_OK = 200;
-
- public enum RequestMethod {
- GET,
- POST,
- PUT,
- DELETE
- }
-
- public static final String IO_ERROR_MESSAGE = "Connection IO error. \n"
- + "Can not connect to JPush Server. "
- + "Please ensure your internet connection is ok. \n"
- + "If the problem persists, please let us know at support@jpush.cn.";
-
- public static final String CONNECT_TIMED_OUT_MESSAGE = "connect timed out. \n"
- + "Connect to JPush Server timed out, and already retried some times. \n"
- + "Please ensure your internet connection is ok. \n"
- + "If the problem persists, please let us know at support@jpush.cn.";
-
- public static final String READ_TIMED_OUT_MESSAGE = "Read timed out. \n"
- + "Read response from JPush Server timed out. \n"
- + "If this is a Push action, you may not want to retry. \n"
- + "It may be due to slowly response from JPush server, or unstable connection. \n"
- + "If the problem persists, please let us know at support@jpush.cn.";
-
- public static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
-
-
- //设置连接超时时间
- public static final int DEFAULT_CONNECTION_TIMEOUT = (5 * 1000); // milliseconds
-
- //设置读取超时时间
- public static final int DEFAULT_READ_TIMEOUT = (30 * 1000); // milliseconds
-
- public static final int DEFAULT_MAX_RETRY_TIMES = 3;
-
- public ResponseWrapper sendGet(String url)
- throws APIConnectionException, APIRequestException;
-
- public ResponseWrapper sendDelete(String url)
- throws APIConnectionException, APIRequestException;
-
- public ResponseWrapper sendPost(String url, String content)
- throws APIConnectionException, APIRequestException;
-
-
- public ResponseWrapper sendPut(String url, String content)
- throws APIConnectionException, APIRequestException;
-}
diff --git a/src/main/java/cn/jpush/api/common/connection/NativeHttpClient.java b/src/main/java/cn/jpush/api/common/connection/NativeHttpClient.java
deleted file mode 100644
index eb52944d..00000000
--- a/src/main/java/cn/jpush/api/common/connection/NativeHttpClient.java
+++ /dev/null
@@ -1,324 +0,0 @@
-package cn.jpush.api.common.connection;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.Authenticator;
-import java.net.HttpURLConnection;
-import java.net.PasswordAuthentication;
-import java.net.SocketTimeoutException;
-import java.net.URL;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
-import cn.jpush.api.common.resp.ResponseWrapper;
-
-/**
- * The implementation has no connection pool mechanism, used origin java connection.
- *
- * 本实现没有连接池机制,基于 Java 原始的 HTTP 连接实现。
- *
- * 遇到连接超时,会自动重连指定的次数(默认为 3);如果是读取超时,则不会自动重连。
- *
- * 可选支持 HTTP 代理,同时支持 2 种方式:1) HTTP 头上加上 Proxy-Authorization 信息;2)全局配置 Authenticator.setDefault;
- */
-public class NativeHttpClient implements IHttpClient {
- private static final Logger LOG = LoggerFactory.getLogger(NativeHttpClient.class);
- private static final String KEYWORDS_CONNECT_TIMED_OUT = "connect timed out";
- private static final String KEYWORDS_READ_TIMED_OUT = "Read timed out";
-
- private int _maxRetryTimes = 0;
- private String _authCode;
- private HttpProxy _proxy;
-
- /**
- * 默认的重连次数是 3
- */
- public NativeHttpClient(String authCode) {
- this(authCode, DEFAULT_MAX_RETRY_TIMES, null);
- }
-
- public NativeHttpClient(String authCode, int maxRetryTimes, HttpProxy proxy) {
- this._maxRetryTimes = maxRetryTimes;
- LOG.info("Created instance with _maxRetryTimes = " + _maxRetryTimes);
-
- this._authCode = authCode;
- this._proxy = proxy;
-
- if ( null != _proxy && _proxy.isAuthenticationNeeded()) {
- Authenticator.setDefault(new SimpleProxyAuthenticator(
- _proxy.getUsername(), _proxy.getPassword()));
- }
-
- initSSL();
- }
-
- public ResponseWrapper sendGet(String url)
- throws APIConnectionException, APIRequestException {
- return doRequest(url, null, RequestMethod.GET);
- }
-
- public ResponseWrapper sendDelete(String url)
- throws APIConnectionException, APIRequestException {
- return doRequest(url, null, RequestMethod.DELETE);
- }
-
- public ResponseWrapper sendPost(String url, String content)
- throws APIConnectionException, APIRequestException {
- return doRequest(url, content, RequestMethod.POST);
- }
-
- public ResponseWrapper sendPut(String url, String content)
- throws APIConnectionException, APIRequestException {
- return doRequest(url, content, RequestMethod.PUT);
- }
-
- public ResponseWrapper doRequest(String url, String content,
- RequestMethod method) throws APIConnectionException, APIRequestException {
- ResponseWrapper response = null;
- for (int retryTimes = 0; ; retryTimes++) {
- try {
- response = _doRequest(url, content, method);
- break;
- } catch (SocketTimeoutException e) {
- if (KEYWORDS_READ_TIMED_OUT.equals(e.getMessage())) {
- // Read timed out. For push, maybe should not re-send.
- throw new APIConnectionException(READ_TIMED_OUT_MESSAGE, e, true);
- } else { // connect timed out
- if (retryTimes >= _maxRetryTimes) {
- throw new APIConnectionException(CONNECT_TIMED_OUT_MESSAGE, e, retryTimes);
- } else {
- LOG.debug("connect timed out - retry again - " + (retryTimes + 1));
- }
- }
- }
- }
- return response;
- }
-
- private ResponseWrapper _doRequest(String url, String content,
- RequestMethod method) throws APIConnectionException, APIRequestException,
- SocketTimeoutException {
-
- LOG.debug("Send request - " + method.toString() + " "+ url);
- if (null != content) {
- LOG.debug("Request Content - " + content);
- }
-
- HttpURLConnection conn = null;
- OutputStream out = null;
- StringBuffer sb = new StringBuffer();
- ResponseWrapper wrapper = new ResponseWrapper();
-
- try {
- URL aUrl = new URL(url);
-
- if (null != _proxy) {
- conn = (HttpURLConnection) aUrl.openConnection(_proxy.getNetProxy());
- if (_proxy.isAuthenticationNeeded()) {
- conn.setRequestProperty("Proxy-Authorization", _proxy.getProxyAuthorization());
- }
- } else {
- conn = (HttpURLConnection) aUrl.openConnection();
- }
-
- conn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
- conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
- conn.setUseCaches(false);
- conn.setRequestMethod(method.name());
- conn.setRequestProperty("User-Agent", JPUSH_USER_AGENT);
- conn.setRequestProperty("Connection", "Keep-Alive");
- conn.setRequestProperty("Accept-Charset", CHARSET);
- conn.setRequestProperty("Charset", CHARSET);
- conn.setRequestProperty("Authorization", _authCode);
- conn.setRequestProperty("Content-Type", CONTENT_TYPE_JSON);
-
- if (RequestMethod.GET == method) {
- conn.setDoOutput(false);
- } else if (RequestMethod.DELETE == method) {
- conn.setDoOutput(false);
- } else if (RequestMethod.POST == method || RequestMethod.PUT == method) {
- conn.setDoOutput(true);
- byte[] data = content.getBytes(CHARSET);
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- out = conn.getOutputStream();
- out.write(data);
- out.flush();
- }
-
- int status = conn.getResponseCode();
- InputStream in = null;
- if (status / 100 == 2) {
- in = conn.getInputStream();
- } else {
- in = conn.getErrorStream();
- }
-
- if (null != in) {
- InputStreamReader reader = new InputStreamReader(in, CHARSET);
- char[] buff = new char[1024];
- int len;
- while ((len = reader.read(buff)) > 0) {
- sb.append(buff, 0, len);
- }
- }
-
- String responseContent = sb.toString();
- wrapper.responseCode = status;
- wrapper.responseContent = responseContent;
-
- String quota = conn.getHeaderField(RATE_LIMIT_QUOTA);
- String remaining = conn.getHeaderField(RATE_LIMIT_Remaining);
- String reset = conn.getHeaderField(RATE_LIMIT_Reset);
- wrapper.setRateLimit(quota, remaining, reset);
-
- if (status >= 200 && status < 300) {
- LOG.debug("Succeed to get response OK - responseCode:" + status);
- LOG.debug("Response Content - " + responseContent);
-
- } else if (status >= 300 && status < 400) {
- LOG.warn("Normal response but unexpected - responseCode:" + status + ", responseContent:" + responseContent);
-
- } else {
- LOG.warn("Got error response - responseCode:" + status + ", responseContent:" + responseContent);
-
- switch (status) {
- case 400:
- LOG.error("Your request params is invalid. Please check them according to error message.");
- wrapper.setErrorObject();
- break;
- case 401:
- LOG.error("Authentication failed! Please check authentication params according to docs.");
- wrapper.setErrorObject();
- break;
- case 403:
- LOG.error("Request is forbidden! Maybe your appkey is listed in blacklist or your params is invalid.");
- wrapper.setErrorObject();
- break;
- case 404:
- LOG.error("Request page is not found! Maybe your params is invalid.");
- wrapper.setErrorObject();
- break;
- case 410:
- LOG.error("Request resource is no longer in service. Please according to notice on official website.");
- wrapper.setErrorObject();
- case 429:
- LOG.error("Too many requests! Please review your appkey's request quota.");
- wrapper.setErrorObject();
- break;
- case 500:
- case 502:
- case 503:
- case 504:
- LOG.error("Seems encountered server error. Maybe JPush is in maintenance? Please retry later.");
- break;
- default:
- LOG.error("Unexpected response.");
- }
-
- throw new APIRequestException(wrapper);
- }
-
- } catch (SocketTimeoutException e) {
- if (e.getMessage().contains(KEYWORDS_CONNECT_TIMED_OUT)) {
- throw e;
- } else if (e.getMessage().contains(KEYWORDS_READ_TIMED_OUT)) {
- throw new SocketTimeoutException(KEYWORDS_READ_TIMED_OUT);
- }
- LOG.debug(IO_ERROR_MESSAGE, e);
- throw new APIConnectionException(IO_ERROR_MESSAGE, e);
-
- } catch (IOException e) {
- LOG.debug(IO_ERROR_MESSAGE, e);
- throw new APIConnectionException(IO_ERROR_MESSAGE, e);
-
- } finally {
- if (null != out) {
- try {
- out.close();
- } catch (IOException e) {
- LOG.error("Failed to close stream.", e);
- }
- }
- if (null != conn) {
- conn.disconnect();
- }
- }
-
- return wrapper;
- }
-
- protected void initSSL() {
- TrustManager[] tmCerts = new javax.net.ssl.TrustManager[1];
- tmCerts[0] = new SimpleTrustManager();
- try {
- SSLContext sslContext = SSLContext.getInstance("SSL");
- sslContext.init(null, tmCerts, null);
- HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
-
- HostnameVerifier hostnameVerifier = new SimpleHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
- } catch (Exception e) {
- LOG.error("Init SSL error", e);
- }
- }
-
-
- private static class SimpleHostnameVerifier implements HostnameVerifier {
-
- @Override
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
-
- }
-
- private static class SimpleTrustManager implements TrustManager, X509TrustManager {
-
- @Override
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- return;
- }
-
- @Override
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- return;
- }
-
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- }
-
- private static class SimpleProxyAuthenticator extends java.net.Authenticator {
- private String username;
- private String password;
-
- public SimpleProxyAuthenticator(String username, String password) {
- this.username = username;
- this.password = password;
- }
-
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(
- this.username,
- this.password.toCharArray());
- }
- }
-}
diff --git a/src/main/java/cn/jpush/api/common/resp/APIConnectionException.java b/src/main/java/cn/jpush/api/common/resp/APIConnectionException.java
deleted file mode 100644
index ac000006..00000000
--- a/src/main/java/cn/jpush/api/common/resp/APIConnectionException.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package cn.jpush.api.common.resp;
-
-/**
- * Should retry for encountering this exception basically.
- * Normally it is due to:
- * 1. Connect timed out.
- * 2. Read timed out.
- * 3. Cannot parse domain.
- *
- * For Push action, if the exception is "Read timed out" you may not want to retry it.
- */
-public class APIConnectionException extends Exception {
- private static final long serialVersionUID = -2615370590441195647L;
- private boolean readTimedout = false;
- private int doneRetriedTimes = 0;
-
- public APIConnectionException(String message, Throwable e) {
- super(message, e);
- }
-
- public APIConnectionException(String message, Throwable e, int doneRetriedTimes) {
- super(message, e);
- this.doneRetriedTimes = doneRetriedTimes;
- }
-
- public APIConnectionException(String message, Throwable e, boolean readTimedout) {
- super(message, e);
- this.readTimedout = readTimedout;
- }
-
- public boolean isReadTimedout() {
- return readTimedout;
- }
-
- public int getDoneRetriedTimes() {
- return this.doneRetriedTimes;
- }
-}
-
-
diff --git a/src/main/java/cn/jpush/api/common/resp/APIRequestException.java b/src/main/java/cn/jpush/api/common/resp/APIRequestException.java
deleted file mode 100644
index 341e436b..00000000
--- a/src/main/java/cn/jpush/api/common/resp/APIRequestException.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package cn.jpush.api.common.resp;
-
-import cn.jpush.api.common.resp.ResponseWrapper.ErrorObject;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public class APIRequestException extends Exception implements IRateLimiting {
- private static final long serialVersionUID = -3921022835186996212L;
-
- protected static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
-
- private final ResponseWrapper responseWrapper;
-
- public APIRequestException(ResponseWrapper responseWrapper) {
- super(responseWrapper.responseContent);
- this.responseWrapper = responseWrapper;
- }
-
- public int getStatus() {
- return this.responseWrapper.responseCode;
- }
-
- public long getMsgId() {
- ErrorObject eo = getErrorObject();
- if (null != eo) {
- return eo.msg_id;
- }
- return 0;
- }
-
- public int getErrorCode() {
- ErrorObject eo = getErrorObject();
- if (null != eo && null != eo.error) {
- return eo.error.code;
- }
- return -1;
- }
-
- public String getErrorMessage() {
- ErrorObject eo = getErrorObject();
- if (null != eo && null != eo.error) {
- return eo.error.message;
- }
- return null;
- }
-
- @Override
- public String toString() {
- return _gson.toJson(this);
- }
-
- private ErrorObject getErrorObject() {
- return this.responseWrapper.error;
- }
-
-
- @Override
- public int getRateLimitQuota() {
- return responseWrapper.rateLimitQuota;
- }
-
- @Override
- public int getRateLimitRemaining() {
- return responseWrapper.rateLimitRemaining;
- }
-
- @Override
- public int getRateLimitReset() {
- return responseWrapper.rateLimitReset;
- }
-
-}
-
diff --git a/src/main/java/cn/jpush/api/common/resp/BaseResult.java b/src/main/java/cn/jpush/api/common/resp/BaseResult.java
deleted file mode 100644
index b980fdd5..00000000
--- a/src/main/java/cn/jpush/api/common/resp/BaseResult.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package cn.jpush.api.common.resp;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public abstract class BaseResult implements IRateLimiting {
- public static final int ERROR_CODE_NONE = -1;
- public static final int ERROR_CODE_OK = 0;
- public static final String ERROR_MESSAGE_NONE = "None error message.";
-
- protected static final int RESPONSE_OK = 200;
- protected static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
-
- private ResponseWrapper responseWrapper;
-
- public void setResponseWrapper(ResponseWrapper responseWrapper) {
- this.responseWrapper = responseWrapper;
- }
-
- public String getOriginalContent() {
- if (null != responseWrapper) {
- return responseWrapper.responseContent;
- }
- return null;
- }
-
- public boolean isResultOK() {
- return RESPONSE_OK == responseWrapper.responseCode;
- }
-
- public static T fromResponse(
- ResponseWrapper responseWrapper, Class clazz) {
- T result = null;
-
- if (responseWrapper.isServerResponse()) {
- result = _gson.fromJson(responseWrapper.responseContent, clazz);
- } else {
- try {
- result = clazz.newInstance();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
-
- result.setResponseWrapper(responseWrapper);
-
- return result;
- }
-
-
- @Override
- public int getRateLimitQuota() {
- if (null != responseWrapper) {
- return responseWrapper.rateLimitQuota;
- }
- return 0;
- }
-
- @Override
- public int getRateLimitRemaining() {
- if (null != responseWrapper) {
- return responseWrapper.rateLimitRemaining;
- }
- return 0;
- }
-
- @Override
- public int getRateLimitReset() {
- if (null != responseWrapper) {
- return responseWrapper.rateLimitReset;
- }
- return 0;
- }
-
- @Override
- public String toString() {
- return _gson.toJson(this);
- }
-
-
-}
diff --git a/src/main/java/cn/jpush/api/common/resp/BooleanResult.java b/src/main/java/cn/jpush/api/common/resp/BooleanResult.java
deleted file mode 100644
index 8487577c..00000000
--- a/src/main/java/cn/jpush/api/common/resp/BooleanResult.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package cn.jpush.api.common.resp;
-
-import com.google.gson.annotations.Expose;
-
-public class BooleanResult extends DefaultResult {
-
- @Expose public boolean result;
-
-}
diff --git a/src/main/java/cn/jpush/api/common/resp/DefaultResult.java b/src/main/java/cn/jpush/api/common/resp/DefaultResult.java
deleted file mode 100644
index 951b9e73..00000000
--- a/src/main/java/cn/jpush/api/common/resp/DefaultResult.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package cn.jpush.api.common.resp;
-
-public class DefaultResult extends BaseResult {
-
- public static DefaultResult fromResponse(ResponseWrapper responseWrapper) {
- DefaultResult result = null;
-
- if (responseWrapper.isServerResponse()) {
- result = new DefaultResult();
- }
-
- result.setResponseWrapper(responseWrapper);
-
- return result;
- }
-
-}
diff --git a/src/main/java/cn/jpush/api/common/resp/IRateLimiting.java b/src/main/java/cn/jpush/api/common/resp/IRateLimiting.java
deleted file mode 100644
index 4d91dd82..00000000
--- a/src/main/java/cn/jpush/api/common/resp/IRateLimiting.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package cn.jpush.api.common.resp;
-
-public interface IRateLimiting {
-
- public int getRateLimitQuota();
-
- public int getRateLimitRemaining();
-
- public int getRateLimitReset();
-
-}
-
diff --git a/src/main/java/cn/jpush/api/common/resp/ResponseWrapper.java b/src/main/java/cn/jpush/api/common/resp/ResponseWrapper.java
deleted file mode 100644
index 40fd1d9d..00000000
--- a/src/main/java/cn/jpush/api/common/resp/ResponseWrapper.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package cn.jpush.api.common.resp;
-
-import com.google.gson.Gson;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ResponseWrapper {
- private static final Logger LOG = LoggerFactory.getLogger(ResponseWrapper.class);
- private static final int RESPONSE_CODE_NONE = -1;
-
- private static Gson _gson = new Gson();
- private static JsonParser jsonParser = new JsonParser();
-
- public int responseCode = RESPONSE_CODE_NONE;
- public String responseContent;
-
- public ErrorObject error; // error for non-200 response, used by new API
-
- public int rateLimitQuota;
- public int rateLimitRemaining;
- public int rateLimitReset;
-
- public void setRateLimit(String quota, String remaining, String reset) {
- if (null == quota) return;
-
- try {
- rateLimitQuota = Integer.parseInt(quota);
- rateLimitRemaining = Integer.parseInt(remaining);
- rateLimitReset = Integer.parseInt(reset);
-
- LOG.debug("JPush API Rate Limiting params - quota:" + quota + ", remaining:" + remaining + ", reset:" + reset);
- } catch (NumberFormatException e) {
- LOG.debug("Unexpected - parse rate limiting headers error.");
- }
- }
-
- public void setErrorObject() {
- error = new ErrorObject();
- error.error = new ErrorEntity();
- try {
- JsonElement element = jsonParser.parse(responseContent);
- JsonObject errorObj = null;
- if( element instanceof JsonArray) {
- JsonArray array = (JsonArray) element;
- for(int i = 0; i < array.size(); i++) {
- if(array.get(i).getAsJsonObject().has("error")) {
- errorObj = array.get(i).getAsJsonObject();
- break;
- }
- }
- } else if(element instanceof JsonObject) {
- errorObj = (JsonObject) element;
- } else {
- // nothing
- }
- if(null != errorObj) {
- JsonObject errorMsg = errorObj;
- if(errorObj.has("msg_id")) {
- error.msg_id = errorObj.get("msg_id").getAsLong();
- }
- if (errorObj.has("error")) {
- errorMsg = (JsonObject) errorObj.get("error");
- }
- if(errorMsg.has("code")) {
- error.error.code = errorMsg.get("code").getAsInt();
- }
- if(errorMsg.has("message")) {
- error.error.message = errorMsg.get("message").getAsString();
- }
- }
- } catch(JsonSyntaxException e) {
- LOG.error("Unexpected - responseContent:" + responseContent, e);
- } catch (Exception e) {
- LOG.error("Unexpected - responseContent:" + responseContent, e);
- }
- }
-
- public boolean isServerResponse() {
- if (responseCode / 100 == 2) return true;
- if (responseCode > 0 && null != error && error.error.code > 0) return true;
- return false;
- }
-
- @Override
- public String toString() {
- return _gson.toJson(this);
- }
-
- public static class ErrorObject {
- public long msg_id;
- public ErrorEntity error;
- }
-
- public static class ErrorEntity {
- public int code;
- public String message;
-
- @Override
- public String toString() {
- return _gson.toJson(this);
- }
- }
-
-}
diff --git a/src/main/java/cn/jpush/api/device/AliasDeviceListResult.java b/src/main/java/cn/jpush/api/device/AliasDeviceListResult.java
index be960e8b..259971b4 100644
--- a/src/main/java/cn/jpush/api/device/AliasDeviceListResult.java
+++ b/src/main/java/cn/jpush/api/device/AliasDeviceListResult.java
@@ -3,10 +3,10 @@
import java.util.ArrayList;
import java.util.List;
-import cn.jpush.api.common.resp.BaseResult;
-
import com.google.gson.annotations.Expose;
+import cn.jiguang.common.resp.BaseResult;
+
public class AliasDeviceListResult extends BaseResult {
@Expose public List registration_ids = new ArrayList();
diff --git a/src/main/java/cn/jpush/api/device/DeviceClient.java b/src/main/java/cn/jpush/api/device/DeviceClient.java
index 0f4d1edf..c834a7a4 100644
--- a/src/main/java/cn/jpush/api/device/DeviceClient.java
+++ b/src/main/java/cn/jpush/api/device/DeviceClient.java
@@ -1,23 +1,27 @@
package cn.jpush.api.device;
+import java.lang.reflect.Type;
+import java.util.Map;
import java.util.Set;
-import cn.jpush.api.common.ClientConfig;
-import cn.jpush.api.common.ServiceHelper;
-import cn.jpush.api.common.connection.HttpProxy;
-import cn.jpush.api.common.connection.IHttpClient;
-import cn.jpush.api.common.connection.NativeHttpClient;
-import cn.jpush.api.common.resp.APIConnectionException;
-import cn.jpush.api.common.resp.APIRequestException;
-import cn.jpush.api.common.resp.BaseResult;
-import cn.jpush.api.common.resp.BooleanResult;
-import cn.jpush.api.common.resp.DefaultResult;
-import cn.jpush.api.common.resp.ResponseWrapper;
-import cn.jpush.api.utils.Preconditions;
-
+import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
+import com.google.gson.reflect.TypeToken;
+
+import cn.jiguang.common.ClientConfig;
+import cn.jiguang.common.ServiceHelper;
+import cn.jiguang.common.utils.Preconditions;
+import cn.jiguang.common.utils.StringUtils;
+import cn.jiguang.common.connection.HttpProxy;
+import cn.jiguang.common.connection.NativeHttpClient;
+import cn.jiguang.common.resp.APIConnectionException;
+import cn.jiguang.common.resp.APIRequestException;
+import cn.jiguang.common.resp.BaseResult;
+import cn.jiguang.common.resp.BooleanResult;
+import cn.jiguang.common.resp.DefaultResult;
+import cn.jiguang.common.resp.ResponseWrapper;
public class DeviceClient {
@@ -28,26 +32,54 @@ public class DeviceClient {
private String aliasesPath;
public DeviceClient(String masterSecret, String appKey) {
- this(masterSecret, appKey, IHttpClient.DEFAULT_MAX_RETRY_TIMES);
+ this(masterSecret, appKey, null, ClientConfig.getInstance());
}
-
+
+ /**
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param maxRetryTimes The max retry times.
+ *
+ */
+ @Deprecated
public DeviceClient(String masterSecret, String appKey, int maxRetryTimes) {
this(masterSecret, appKey, maxRetryTimes, null);
}
-
+
+ /**
+ * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
+ * @param masterSecret API access secret of the appKey.
+ * @param appKey The KEY of one application on JPush.
+ * @param maxRetryTimes The max retry times.
+ * @param proxy The HTTP proxy.
+ *
+ */
+ @Deprecated
public DeviceClient(String masterSecret, String appKey, int maxRetryTimes, HttpProxy proxy) {
- this(masterSecret, appKey, maxRetryTimes, proxy, ClientConfig.getInstance());
+ ClientConfig conf = ClientConfig.getInstance();
+ conf.setMaxRetryTimes(maxRetryTimes);
+ ServiceHelper.checkBasic(appKey, masterSecret);
+
+ hostName = (String) conf.get(ClientConfig.DEVICE_HOST_NAME);
+ devicesPath = (String) conf.get(ClientConfig.DEVICES_PATH);
+ tagsPath = (String) conf.get(ClientConfig.TAGS_PATH);
+ aliasesPath = (String) conf.get(ClientConfig.ALIASES_PATH);
+
+ String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
+ _httpClient = new NativeHttpClient(authCode, proxy, conf);
+
}
/**
+ * Create a Device Client by client configuration.
*
* @param masterSecret API access secret of the appKey.
* @param appKey The KEY of one application on JPush.
- * @param maxRetryTimes Max retry times
* @param proxy The proxy, if there is no proxy, should be null.
* @param conf The client configuration. Can use ClientConfig.getInstance() as default.
*/
- public DeviceClient(String masterSecret, String appKey, int maxRetryTimes, HttpProxy proxy, ClientConfig conf) {
+ public DeviceClient(String masterSecret, String appKey, HttpProxy proxy, ClientConfig conf) {
ServiceHelper.checkBasic(appKey, masterSecret);
hostName = (String) conf.get(ClientConfig.DEVICE_HOST_NAME);
@@ -56,7 +88,7 @@ public DeviceClient(String masterSecret, String appKey, int maxRetryTimes, HttpP
aliasesPath = (String) conf.get(ClientConfig.ALIASES_PATH);
String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
- _httpClient = new NativeHttpClient(authCode, maxRetryTimes, proxy);
+ _httpClient = new NativeHttpClient(authCode, proxy, conf);
}
// -------------- device
@@ -116,6 +148,22 @@ public DefaultResult updateDeviceTagAlias(String registrationId, String alias,
return DefaultResult.fromResponse(response);
}
+ public DefaultResult bindMobile(String registrationId, String mobile)
+ throws APIConnectionException, APIRequestException {
+ if ( StringUtils.isEmpty(mobile) ) {
+ // delete bind while mobile is empty.
+ mobile = "";
+ } else {
+// Preconditions.checkArgument(StringUtils.isMobileNumber(mobile), "The mobile format is incorrect. " + mobile);
+ }
+
+ String url = hostName + devicesPath + "/" + registrationId;
+ JsonObject top = new JsonObject();
+ top.addProperty("mobile", mobile);
+ ResponseWrapper response = _httpClient.sendPost(url, top.toString());
+ return DefaultResult.fromResponse(response);
+ }
+
// ------------- tags
public TagListResult getTagList() throws APIConnectionException, APIRequestException {
@@ -196,6 +244,50 @@ public DefaultResult deleteAlias(String alias, String platform) throws APIConnec
return DefaultResult.fromResponse(response);
}
+
+ public DefaultResult removeDevicesFromAlias(String alias, Set toRemoveDevice) throws APIConnectionException, APIRequestException {
+ String url = hostName + aliasesPath + "/" + alias;
+
+ JsonObject top = new JsonObject();
+ JsonObject registrationIds = new JsonObject();
+
+ if (null != toRemoveDevice && toRemoveDevice.size() > 0) {
+ JsonArray array = new JsonArray();
+ for (String device : toRemoveDevice) {
+ array.add(new JsonPrimitive(device));
+ }
+ registrationIds.add("remove", array);
+ }
+
+ top.add("registration_ids", registrationIds);
+
+ ResponseWrapper response = _httpClient.sendPost(url, top.toString());
+
+ return DefaultResult.fromResponse(response);
+ }
+
+ // -------------- devices status
+
+ public Map getUserOnlineStatus(String... registrationIds)
+ throws APIConnectionException, APIRequestException
+ {
+ Preconditions.checkArgument((null != registrationIds ),
+ "The registration id list should not be null.");
+ Preconditions.checkArgument(registrationIds.length > 0 && registrationIds.length <= 1000,
+ "The length of registration id list should between 1 and 1000.");
+
+ String url = hostName + devicesPath + "/status";
+ JsonObject json = new JsonObject();
+ JsonArray array = new JsonArray();
+ for(int i = 0; i < registrationIds.length; i++) {
+ array.add(new JsonPrimitive(registrationIds[i]));
+ }
+ json.add("registration_ids", array);
+ Type type = new TypeToken