Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 123 additions & 46 deletions example/main/java/cn/jpush/api/examples/PushExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.push.CIDResult;
import cn.jpush.api.push.GroupPushClient;
import cn.jpush.api.push.model.notification.*;
import com.google.gson.*;
import io.netty.handler.codec.http.HttpMethod;
Expand All @@ -34,11 +36,10 @@ 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 ="dd1066407b044738b6479275";
private static final String masterSecret = "e8cc9a76d5b7a580859bcfa7";

protected static final String APP_KEY ="d4ee2375846bc30fa51334f5";
protected static final String MASTER_SECRET = "2bf52ee46fdeaadb8718fc15";
protected static final String MASTER_SECRET = "61807e56ddaebf2e47172159";
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";
Expand Down Expand Up @@ -85,9 +86,74 @@ public static void testSendPush() {
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 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<PlatformNotification>())
.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\":false,\"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(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());
}
}

/**
* 测试多线程发送 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_android_newly_support();
final PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage();
for(int i=0;i<10;i++) {
Thread thread = new Thread() {
public void run() {
Expand Down Expand Up @@ -116,41 +182,13 @@ public void run() {
};
thread.start();
}

// // 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);
// // 如果使用 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(masterSecret, appKey, null, clientConfig);
Gson gson = new GsonBuilder()
.registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter<PlatformNotification>())
.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\":false,\"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);
public static void testSendGroupPush() {
GroupPushClient groupPushClient = new GroupPushClient(GROUP_MASTER_SECRET, GROUP_PUSH_KEY);
final PushPayload payload = buildPushObject_android_and_ios();
try {
PushResult result = jpushClient.sendPush(payload);
PushResult result = groupPushClient.sendGroupPush(payload);
LOG.info("Got result - " + result);

} catch (APIConnectionException e) {
Expand All @@ -165,10 +203,6 @@ public static void testSendPush_fromJSON() {
LOG.info("Msg ID: " + e.getMsgId());
LOG.error("Sendno: " + payload.getSendno());
}
}

public static void testSendPushes() {

}

public static PushPayload buildPushObject_all_all_alert() {
Expand Down Expand Up @@ -277,9 +311,12 @@ public static PushPayload buildPushObject_android_newly_support() {
.build();
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.registrationId("18071adc030dcba91c0"))
.setAudience(Audience.all())
.setNotification(notification)
.setOptions(Options.sendno())
.setOptions(Options.newBuilder()
.setApnsProduction(true)
.setSendno(ServiceHelper.generateSendno())
.build())
.build();
}

Expand All @@ -305,12 +342,21 @@ public static PushPayload buildPushObject_all_tag_not() {
.build();
}

public static PushPayload buildPushObject_android_cid() {
return PushPayload.newBuilder()
.setPlatform(Platform.android())
.setAudience(Audience.registrationId("18071adc030dcba91c0"))
.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, 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();
Expand All @@ -332,7 +378,7 @@ public static void testSendPushWithCustomConfig() {
}

public static void testSendIosAlert() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);

IosAlert alert = IosAlert.newBuilder()
.setTitleAndBody("test alert", "subtitle", "test ios alert json")
Expand All @@ -352,7 +398,7 @@ public static void testSendIosAlert() {
}

public static void testSendWithSMS() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
try {
SMS sms = SMS.content("Test SMS", 10);
PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
Expand All @@ -367,5 +413,36 @@ public static void testSendWithSMS() {
}
}

public static void testGetCidList() {
JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
try {
CIDResult result = jPushClient.getCidList(3, 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 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());
}
}

}

6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.2.21-SNAPSHOT</version>
<version>3.3.0-SNAPSHOT</version>
<packaging>jar</packaging>
<url>https://github.com/jpush/jpush-api-java-client</url>
<name>JPush API Java Client</name>
Expand Down Expand Up @@ -35,14 +35,14 @@
<url>https://github.com/jpush/jpush-api-java-client</url>
<connection>scm:git:git@github.com:jpush/jpush-api-java-client.git</connection>
<developerConnection>scm:git:git@github.com:jpush/jpush-api-java-client.git</developerConnection>
<tag>v3.2.20</tag>
<tag>v3.3.0</tag>
</scm>

<dependencies>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.0.6</version>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/cn/jpush/api/JPushClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.Map;
import java.util.Set;

import cn.jpush.api.push.CIDResult;
import com.google.gson.JsonObject;

import cn.jiguang.common.ClientConfig;
Expand Down Expand Up @@ -226,6 +227,18 @@ public PushResult sendPushValidate(String payloadString) throws APIConnectionExc
return _pushClient.sendPushValidate(payloadString);
}

/**
* 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

Expand Down
12 changes: 12 additions & 0 deletions src/main/java/cn/jpush/api/push/CIDResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package cn.jpush.api.push;

import cn.jiguang.common.resp.BaseResult;
import com.google.gson.annotations.Expose;

import java.util.ArrayList;
import java.util.List;

public class CIDResult extends BaseResult {

@Expose public List<String> cidlist = new ArrayList<String>();
}
44 changes: 44 additions & 0 deletions src/main/java/cn/jpush/api/push/GroupPushClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package cn.jpush.api.push;

import cn.jiguang.common.ClientConfig;
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.BaseResult;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jiguang.common.utils.Preconditions;
import cn.jpush.api.push.model.PushPayload;

/**
* Created by caiyaoguan on 2017/7/4.
*/
public class GroupPushClient {

private IHttpClient _httpClient;
private String _baseUrl;
private String _groupPushPath;

public GroupPushClient(String groupMasterSecret, String groupKey) {
this(groupMasterSecret, groupKey, null, ClientConfig.getInstance());
}

public GroupPushClient(String groupMasterSecret, String groupKey, HttpProxy proxy, ClientConfig conf) {
ServiceHelper.checkBasic(groupKey, groupMasterSecret);
this._baseUrl = (String) conf.get(ClientConfig.PUSH_HOST_NAME);
this._groupPushPath = (String) conf.get(ClientConfig.GROUP_PUSH_PATH);
String authCode = ServiceHelper.getBasicAuthorization("group-" + groupKey, groupMasterSecret);
this._httpClient = new NativeHttpClient(authCode, proxy, conf);
}

public PushResult sendGroupPush(PushPayload pushPayload) throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(! (null == pushPayload), "pushPayload should not be null");

ResponseWrapper response = _httpClient.sendPost(_baseUrl + _groupPushPath, pushPayload.toString());

return BaseResult.fromResponse(response, PushResult.class);
}

}
20 changes: 20 additions & 0 deletions src/main/java/cn/jpush/api/push/PushClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,26 @@ public PushResult sendPushValidate(String payloadString) throws APIConnectionExc
return BaseResult.fromResponse(response, PushResult.class);
}

/**
* 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 {
Preconditions.checkArgument(count >= 1 && count <= 1000, "count should not less than 1 or larger than 1000");
Preconditions.checkArgument(type == null || type.equals("push") || type.equals("schedule"), "type should be \"push\" or \"schedule\"");
ResponseWrapper responseWrapper;
if (type != null) {
responseWrapper = _httpClient.sendGet(_baseUrl + _pushPath + "/cid?count=" + count + "&type=" + type);
} else {
responseWrapper = _httpClient.sendGet(_baseUrl + _pushPath + "/cid?count=" + count);
}
return BaseResult.fromResponse(responseWrapper, CIDResult.class);
}

public void setHttpClient(IHttpClient client) {
this._httpClient = client;
}
Expand Down
Loading