Skip to content

Commit ad10278

Browse files
author
Javen
committed
Refine code - can use msgResult / receivedsResult to get all response info by hand.
1 parent 2201512 commit ad10278

File tree

12 files changed

+211
-89
lines changed

12 files changed

+211
-89
lines changed

resources/jpush-api.conf

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ masterSecret=2b38ce69b1de2a7fa95706ea
77

88
alias=alias_api
99
tag=tag_api
10+
registrationID=0900e8d85ef

src/cn/jpush/api/common/BaseHttpClient.java

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ public class BaseHttpClient {
3535
private static final String RATE_LIMIT_Remaining = "X-Rate-Limit-Remaining";
3636
private static final String RATE_LIMIT_Reset = "X-Rate-Limit-Reset";
3737

38+
protected static final int RESPONSE_OK = 200;
3839
protected static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
3940

4041
//设置连接超时时间
@@ -108,33 +109,31 @@ protected ResponseResult sendRequest(String url, final boolean enableSSL,
108109
String reset = conn.getHeaderField(RATE_LIMIT_Reset);
109110
result.setRateLimit(quota, remaining, reset);
110111

111-
LOG.debug("JPush API Rate Limiting params - quota:" + quota + ", remaining:" + remaining + ", reset:" + reset);
112-
113112
if (status == 200) {
114-
LOG.debug("Succeed to get response - 200 OK - " + responseContent);
113+
LOG.debug("Succeed to get response - 200 OK");
115114

116115
} else {
117116
LOG.warn("Got error response - responseCode:" + status + ", responseContent:" + responseContent);
118117

119118
switch (status) {
120119
case 400:
121-
LOG.info("Your request params is invalid. Please check them according to docs.");
120+
LOG.warn("Your request params is invalid. Please check them according to docs.");
122121
result.setErrorObject();
123122
break;
124123
case 403:
125-
LOG.info("Request is forbidden! Maybe your appkey is listed in blacklist?");
124+
LOG.warn("Request is forbidden! Maybe your appkey is listed in blacklist?");
126125
result.setErrorObject();
127126
break;
128127
case 401:
129-
LOG.info("Authentication failed! Please check authentication params according to docs.");
128+
LOG.warn("Authentication failed! Please check authentication params according to docs.");
130129
result.setErrorObject();
131130
break;
132131
case 429:
133-
LOG.info("Too many requests! Please review your appkey's request quota.");
132+
LOG.warn("Too many requests! Please review your appkey's request quota.");
134133
result.setErrorObject();
135134
break;
136135
case 500:
137-
LOG.info("Seems encountered server error. Please retry later.");
136+
LOG.warn("Seems encountered server error. Please retry later.");
138137
break;
139138
default:
140139
}
@@ -143,19 +142,19 @@ protected ResponseResult sendRequest(String url, final boolean enableSSL,
143142

144143
} catch (SocketTimeoutException e) {
145144
result.exceptionString = e.getMessage();
146-
LOG.warn("Request timeout. Retry later.", e);
145+
LOG.error("Request timeout. Retry later.", e);
147146
} catch (ConnectException e) {
148147
result.exceptionString = e.getMessage();
149-
LOG.warn("Connnect error. ", e);
148+
LOG.error("Connnect error. ", e);
150149
} catch (UnknownHostException e) {
151150
result.exceptionString = e.getMessage();
152-
LOG.warn("Unknown host. Please check the DNS configuration of your server.", e);
151+
LOG.error("Unknown host. Please check the DNS configuration of your server.", e);
153152
} catch (IOException e) {
154153
result.exceptionString = e.getMessage();
155-
LOG.warn("IO error. ", e);
154+
LOG.error("IO error. ", e);
156155
} catch (Exception e) {
157156
result.exceptionString = e.getMessage();
158-
LOG.warn("Unknown exception. ", e);
157+
LOG.error("Unknown exception. ", e);
159158
} finally {
160159
if (null != out) {
161160
try {

src/cn/jpush/api/common/BaseResult.java

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
package cn.jpush.api.common;
22

3-
import cn.jpush.api.common.ResponseResult.ErrorObject;
4-
53
import com.google.gson.Gson;
64
import com.google.gson.GsonBuilder;
75

8-
public class BaseResult {
9-
6+
public abstract class BaseResult {
7+
public static final int ERROR_CODE_NONE = -1;
8+
public static final int ERROR_CODE_OK = 0;
9+
public static final String ERROR_MESSAGE_NONE = "None error message.";
10+
11+
protected static final int RESPONSE_OK = 200;
1012
protected static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
1113

1214
public ResponseResult responseResult;
1315

14-
public ErrorObject getErrorObject() {
15-
if (null != responseResult) {
16-
return responseResult.error;
17-
}
18-
return null;
19-
}
16+
public abstract boolean isResultOK();
17+
18+
public abstract int getErrorCode();
19+
20+
public abstract String getErrorMessage();
2021

2122
public int getRateLimitQuota() {
2223
if (null != responseResult) {

src/cn/jpush/api/common/ResponseResult.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66
import com.google.gson.Gson;
77

88
public class ResponseResult {
9-
protected static final Logger LOG = LoggerFactory.getLogger(ResponseResult.class);
10-
protected static Gson _gson = new Gson();
9+
private static final Logger LOG = LoggerFactory.getLogger(ResponseResult.class);
10+
private static final int RESPONSE_CODE_NONE = -1;
1111

12-
public int responseCode;
12+
private static Gson _gson = new Gson();
13+
14+
public int responseCode = RESPONSE_CODE_NONE;
1315
public String responseContent;
1416

1517
public ErrorObject error; // error for non-200 response, used by new API
@@ -24,12 +26,16 @@ public ResponseResult() {
2426
}
2527

2628
public void setRateLimit(String quota, String remaining, String reset) {
29+
if (null == quota) return;
30+
2731
try {
2832
rateLimitQuota = Integer.parseInt(quota);
2933
rateLimitRemaining = Integer.parseInt(remaining);
3034
rateLimitReset = Integer.parseInt(reset);
35+
36+
LOG.debug("JPush API Rate Limiting params - quota:" + quota + ", remaining:" + remaining + ", reset:" + reset);
3137
} catch (NumberFormatException e) {
32-
LOG.error("Unexpected - parse rate limiting headers error.");
38+
LOG.debug("Unexpected - parse rate limiting headers error.");
3339
}
3440
}
3541

src/cn/jpush/api/common/ValidateRequestParams.java

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,30 +5,60 @@
55
import cn.jpush.api.utils.StringUtils;
66

77
public class ValidateRequestParams {
8-
private final static int sendNo = -1;
9-
private final static Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
8+
private final static Pattern PUSH_PATTERNS = Pattern.compile("[^a-zA-Z0-9]");
9+
private final static Pattern MSGID_PATTERNS = Pattern.compile("[^0-9, ]");
1010

11-
public static void checkBasic(String appkey, String masterSecret) {
12-
if (StringUtils.isEmpty(appkey)
11+
public static void checkBasic(String appKey, String masterSecret) {
12+
if (StringUtils.isEmpty(appKey)
1313
|| StringUtils.isEmpty(masterSecret)) {
1414
throw new IllegalArgumentException("appKey and masterSecret are both required.");
1515
}
16-
if (appkey.length() != 24
16+
if (appKey.length() != 24
1717
|| masterSecret.length() != 24
18-
|| pattern.matcher(appkey).find()
19-
|| pattern.matcher(masterSecret).find()) {
20-
throw new IllegalArgumentException("appKey and masterSecret format is incorrect.");
18+
|| PUSH_PATTERNS.matcher(appKey).find()
19+
|| PUSH_PATTERNS.matcher(masterSecret).find()) {
20+
throw new IllegalArgumentException("appKey and masterSecret format is incorrect. "
21+
+ "They should be 24 size, and be composed with alphabet and numbers. "
22+
+ "Please confirm that they are coming from JPush Web Portal.");
2123
}
2224

2325
}
2426

2527
public static void checkPushParams(MessageParams params) {
2628
checkBasic(params.getAppKey(), params.getMasterSecret());
2729

30+
2831
}
2932

30-
public static void checkReportParams() {
33+
public static void checkReportParams(String appKey, String masterSecret, String msgIds) {
34+
checkBasic(appKey, masterSecret);
35+
36+
if (StringUtils.isTrimedEmpty(msgIds)) {
37+
throw new IllegalArgumentException("msgIds param is required.");
38+
}
39+
40+
if (MSGID_PATTERNS.matcher(msgIds).find()) {
41+
throw new IllegalArgumentException("msgIds param format is incorrect. "
42+
+ "It should be msg_id (number) which response from JPush Push API. "
43+
+ "If there are many, use ',' as interval. ");
44+
}
45+
46+
msgIds = msgIds.trim();
47+
if (msgIds.endsWith(",")) {
48+
msgIds = msgIds.substring(0, msgIds.length() - 1);
49+
}
3150

51+
String[] splits = msgIds.split(",");
52+
try {
53+
for (String s : splits) {
54+
s = s.trim();
55+
if (!StringUtils.isEmpty(s)) {
56+
Integer.parseInt(s);
57+
}
58+
}
59+
} catch (NumberFormatException e) {
60+
throw new IllegalArgumentException("Every msg_id should be valid Integer number which splits by ','");
61+
}
3262
}
3363
}
3464

src/cn/jpush/api/examples/JPushClientExample.java

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,32 +17,63 @@ public class JPushClientExample {
1717
private static final String appKey ="dd1066407b044738b6479275";
1818
private static final String masterSecret = "2b38ce69b1de2a7fa95706ea";
1919

20-
private static final String msgTitle = "Test from API example";
21-
private static final String msgContent = "Test Test";
22-
private static final String registrationID = "0900e8d85ef";
20+
public static final String msgTitle = "Test from API example";
21+
public static final String msgContent = "Test Test";
22+
public static final String registrationID = "0900e8d85ef";
23+
public static final String tag = "tag_api";
2324

2425
private static JPushClient jpushClient = null;
2526

2627
public static void main(String[] args) {
2728
jpushClient = new JPushClient(masterSecret, appKey, 0, DeviceEnum.Android, false);
2829

2930
testSend();
31+
testGetReport();
3032
}
3133

3234
private static void testSend() {
3335
CustomMessageParams params = new CustomMessageParams();
34-
params.setReceiverType(ReceiverTypeEnum.REGISTRATION_ID);
35-
params.setReceiverValue(registrationID);
36-
MessageResult msgResult = jpushClient.sendCustomMessage(msgTitle, msgContent, params, null);
36+
//params.setReceiverType(ReceiverTypeEnum.REGISTRATION_ID);
37+
//params.setReceiverValue(registrationID);
38+
params.setReceiverType(ReceiverTypeEnum.TAG);
39+
params.setReceiverValue(tag);
3740

38-
if (null != msgResult) {
39-
LOG.info("responseContent - " + msgResult.responseResult.responseContent);
40-
LOG.info("msgResult - " + msgResult);
41+
MessageResult msgResult = jpushClient.sendCustomMessage(msgTitle, msgContent, params, null);
42+
LOG.debug("responseContent - " + msgResult.responseResult.responseContent);
43+
if (msgResult.isResultOK()) {
44+
LOG.info("msgResult - " + msgResult);
45+
LOG.info("messageId - " + msgResult.getMessageId());
46+
} else {
47+
if (msgResult.getErrorCode() > 0) {
48+
// 业务异常
49+
LOG.warn("Service error - ErrorCode: "
50+
+ msgResult.getErrorCode() + ", ErrorMessage: "
51+
+ msgResult.getErrorMessage());
52+
} else {
53+
// 未到达 JPush
54+
LOG.error("Other excepitons - "
55+
+ msgResult.responseResult.exceptionString);
56+
}
57+
}
58+
}
59+
60+
public static void testGetReport() {
61+
ReceivedsResult receivedsResult = jpushClient.getReportReceiveds("1708010723,1774452771");
62+
LOG.debug("responseContent - " + receivedsResult.responseResult.responseContent);
63+
if (receivedsResult.isResultOK()) {
64+
LOG.info("Receiveds - " + receivedsResult);
65+
} else {
66+
if (receivedsResult.getErrorCode() > 0) {
67+
// 业务异常
68+
LOG.warn("Service error - ErrorCode: "
69+
+ receivedsResult.getErrorCode() + ", ErrorMessage: "
70+
+ receivedsResult.getErrorMessage());
71+
} else {
72+
// 未到达 JPush
73+
LOG.error("Other excepitons - "
74+
+ receivedsResult.responseResult.exceptionString);
75+
}
4176
}
42-
43-
ReceivedsResult rrr = jpushClient.getReportReceiveds("1708010723,1774452771");
44-
LOG.info("content - " + rrr.responseResult.responseContent);
45-
LOG.debug("Received - " + rrr);
4677
}
4778

4879
}

src/cn/jpush/api/push/MessageResult.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,33 @@
77
public class MessageResult extends BaseResult {
88
@Expose public Long msg_id;
99
@Expose public int sendno;
10-
@Expose public int errcode = -1;
10+
@Expose public int errcode = ERROR_CODE_NONE;
1111
@Expose public String errmsg;
1212

1313
public MessageResult() {
1414
}
1515

16-
public int getErrcode() {
16+
public long getMessageId() {
17+
return this.msg_id;
18+
}
19+
20+
public int getSendNo() {
21+
return this.sendno;
22+
}
23+
24+
public int getErrorCode() {
1725
return this.errcode;
1826
}
1927

28+
public String getErrorMessage() {
29+
return this.errmsg;
30+
}
31+
32+
public boolean isResultOK() {
33+
if (responseResult.responseCode == RESPONSE_OK && this.errcode == ERROR_CODE_OK) return true;
34+
return false;
35+
}
36+
2037
@Override
2138
public String toString() {
2239
return _gson.toJson(this);

src/cn/jpush/api/push/PushClient.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,16 @@
1212
import cn.jpush.api.utils.StringUtils;
1313

1414
public class PushClient extends BaseHttpClient {
15-
public String appKey;
16-
public String masterSecret;
17-
public long timeToLive = -1;
18-
public boolean enableSSL = false;
19-
public boolean apnsProduction = false;
15+
private static final String HOST_NAME_SSL = "https://api.jpush.cn";
16+
private static final String HOST_NAME = "http://api.jpush.cn:8800";
17+
private static final String PUSH_PATH = "/v2/push";
2018

21-
public Set<DeviceEnum> devices = new HashSet<DeviceEnum>(); //默认发送所有平台
19+
private String appKey;
20+
private String masterSecret;
21+
private long timeToLive = -1;
22+
private boolean enableSSL = false;
23+
private boolean apnsProduction = false;
24+
private Set<DeviceEnum> devices = new HashSet<DeviceEnum>();
2225

2326
public PushClient(String masterSecret, String appKey, long timeToLive, DeviceEnum device, boolean apnsProduction) {
2427
this.masterSecret = masterSecret;
@@ -65,18 +68,14 @@ private MessageResult sendMessage(String content, MessageParams params) {
6568
return sendPush(enableSSL, params);
6669
}
6770

68-
public static String HOST_NAME_SSL = "https://api.jpush.cn:443";
69-
public static String HOST_NAME = "http://api.jpush.cn:8800";
70-
public static final String PUSH_PATH = "/v2/push";
71-
7271
public MessageResult sendPush(final boolean enableSSL, final MessageParams params) {
7372
ValidateRequestParams.checkPushParams(params);
7473
String url = enableSSL ? HOST_NAME_SSL : HOST_NAME;
7574
url += PUSH_PATH;
7675

7776
ResponseResult result = sendPost(url, enableSSL, parse(params), null);
7877
MessageResult rr = null;
79-
if (result.responseCode == 200) {
78+
if (result.responseCode == RESPONSE_OK) {
8079
rr = _gson.fromJson(result.responseContent, MessageResult.class);
8180
} else {
8281
rr = new MessageResult();

0 commit comments

Comments
 (0)