Skip to content

Commit a4a6569

Browse files
author
Javen
committed
Refactoring:
1) use composite to replace inherit for push client; 2) prepare for adding more http client implementaiton.
1 parent d733e71 commit a4a6569

File tree

10 files changed

+134
-93
lines changed

10 files changed

+134
-93
lines changed

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

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,15 @@ public abstract class BaseResult {
1313
protected static final int RESPONSE_OK = 200;
1414
protected static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
1515

16-
public ResponseWrapper responseResult;
16+
private ResponseWrapper responseWrapper;
1717

18+
public void setResponseWrapper(ResponseWrapper responseWrapper) {
19+
this.responseWrapper = responseWrapper;
20+
}
21+
1822
protected ErrorObject getErrorObject() {
19-
if (null != responseResult) {
20-
return responseResult.error;
23+
if (null != responseWrapper) {
24+
return responseWrapper.error;
2125
}
2226
return null;
2327
}
@@ -27,8 +31,8 @@ public int getErrorCode() {
2731
if (null != eo) {
2832
return eo.error.code;
2933
}
30-
if (null != responseResult) {
31-
if (responseResult.responseCode == RESPONSE_OK) {
34+
if (null != responseWrapper) {
35+
if (responseWrapper.responseCode == RESPONSE_OK) {
3236
return ERROR_CODE_OK;
3337
}
3438
}
@@ -43,35 +47,42 @@ public String getErrorMessage() {
4347
return ERROR_MESSAGE_NONE;
4448
}
4549

46-
public String getOriginalError() {
47-
if (null != responseResult) {
48-
return responseResult.responseContent;
50+
public String getOriginalContent() {
51+
if (null != responseWrapper) {
52+
return responseWrapper.responseContent;
53+
}
54+
return null;
55+
}
56+
57+
public String getExceptionString() {
58+
if (null != responseWrapper) {
59+
return responseWrapper.exceptionString;
4960
}
5061
return null;
5162
}
5263

5364
public boolean isResultOK() {
54-
if (responseResult.responseCode == RESPONSE_OK) return true;
65+
if (responseWrapper.responseCode == RESPONSE_OK) return true;
5566
return false;
5667
}
5768

5869
public int getRateLimitQuota() {
59-
if (null != responseResult) {
60-
return responseResult.rateLimitQuota;
70+
if (null != responseWrapper) {
71+
return responseWrapper.rateLimitQuota;
6172
}
6273
return 0;
6374
}
6475

6576
public int getRateLimitRemaining() {
66-
if (null != responseResult) {
67-
return responseResult.rateLimitRemaining;
77+
if (null != responseWrapper) {
78+
return responseWrapper.rateLimitRemaining;
6879
}
6980
return 0;
7081
}
7182

7283
public int getRateLimitReset() {
73-
if (null != responseResult) {
74-
return responseResult.rateLimitReset;
84+
if (null != responseWrapper) {
85+
return responseWrapper.rateLimitReset;
7586
}
7687
return 0;
7788
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package cn.jpush.api.common;
2+
3+
public interface IHttpClient {
4+
5+
public static final String CHARSET = "UTF-8";
6+
public static final String RATE_LIMIT_QUOTA = "X-Rate-Limit-Limit";
7+
public static final String RATE_LIMIT_Remaining = "X-Rate-Limit-Remaining";
8+
public static final String RATE_LIMIT_Reset = "X-Rate-Limit-Reset";
9+
10+
public static final int RESPONSE_OK = 200;
11+
public static final String METHOD_POST = "POST";
12+
public static final String METHOD_GET = "GET";
13+
14+
//设置连接超时时间
15+
public final int DEFAULT_CONNECTION_TIMEOUT = (20 * 1000); // milliseconds
16+
17+
//设置读取超时时间
18+
public final int DEFAULT_SOCKET_TIMEOUT = (30 * 1000); // milliseconds
19+
20+
public ResponseWrapper sendGet(String url, String params, String authCode);
21+
22+
public ResponseWrapper sendPost(String url, String content, String authCode);
23+
24+
25+
}

src/cn/jpush/api/common/BaseHttpClient.java renamed to src/cn/jpush/api/common/NativeHttpClient.java

Lines changed: 12 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import java.net.UnknownHostException;
1212
import java.security.cert.CertificateException;
1313
import java.security.cert.X509Certificate;
14-
import java.util.regex.Pattern;
1514

1615
import javax.net.ssl.HostnameVerifier;
1716
import javax.net.ssl.HttpsURLConnection;
@@ -22,39 +21,26 @@
2221
import org.slf4j.Logger;
2322
import org.slf4j.LoggerFactory;
2423

25-
import cn.jpush.api.utils.Base64;
2624
import cn.jpush.api.utils.StringUtils;
2725

2826
import com.google.gson.Gson;
2927
import com.google.gson.GsonBuilder;
3028

31-
public class BaseHttpClient {
32-
private static final Logger LOG = LoggerFactory.getLogger(BaseHttpClient.class);
29+
public class NativeHttpClient implements IHttpClient {
30+
private static final Logger LOG = LoggerFactory.getLogger(NativeHttpClient.class);
3331

34-
private static final String CHARSET = "UTF-8";
35-
private static final String RATE_LIMIT_QUOTA = "X-Rate-Limit-Limit";
36-
private static final String RATE_LIMIT_Remaining = "X-Rate-Limit-Remaining";
37-
private static final String RATE_LIMIT_Reset = "X-Rate-Limit-Reset";
38-
39-
protected static final int RESPONSE_OK = 200;
4032
protected static Gson _gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
41-
42-
//设置连接超时时间
43-
private final int DEFAULT_CONNECTION_TIMEOUT = (20 * 1000); // milliseconds
44-
45-
//设置读取超时时间
46-
private final int DEFAULT_SOCKET_TIMEOUT = (30 * 1000); // milliseconds
4733

4834

49-
protected ResponseWrapper sendGet(String url, String params, String authCode) {
50-
return sendRequest(url, params, "GET", authCode);
35+
public ResponseWrapper sendGet(String url, String params, String authCode) {
36+
return sendRequest(url, params, METHOD_GET, authCode);
5137
}
5238

53-
protected ResponseWrapper sendPost(String url, String content, String authCode) {
54-
return sendRequest(url, content, "POST", authCode);
39+
public ResponseWrapper sendPost(String url, String content, String authCode) {
40+
return sendRequest(url, content, METHOD_POST, authCode);
5541
}
5642

57-
protected ResponseWrapper sendRequest(String url, String content, String method, String authCode) {
43+
public ResponseWrapper sendRequest(String url, String content, String method, String authCode) {
5844
LOG.debug("Send request to - " + url + ", with content - " + content);
5945
HttpURLConnection conn = null;
6046
OutputStream out = null;
@@ -77,7 +63,7 @@ protected ResponseWrapper sendRequest(String url, String content, String method,
7763
conn.setRequestProperty("Authorization", authCode);
7864
}
7965

80-
if (method.equals("POST")) {
66+
if (METHOD_POST.equals(method)) {
8167
conn.setDoOutput(true); //POST Request
8268
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
8369
byte[] data = content.getBytes(CHARSET);
@@ -188,31 +174,9 @@ protected void initSSL() {
188174
LOG.error("", e);
189175
}
190176
}
191-
192-
public static String getAuthorizationBase64(String appKey, String masterSecret) {
193-
String encodeKey = appKey + ":" + masterSecret;
194-
return String.valueOf(Base64.encode(encodeKey.getBytes()));
195-
}
196-
197-
private final static Pattern PUSH_PATTERNS = Pattern.compile("[^a-zA-Z0-9]");
198-
199-
public static void checkBasic(String appKey, String masterSecret) {
200-
if (StringUtils.isEmpty(appKey)
201-
|| StringUtils.isEmpty(masterSecret)) {
202-
throw new IllegalArgumentException("appKey and masterSecret are both required.");
203-
}
204-
if (appKey.length() != 24
205-
|| masterSecret.length() != 24
206-
|| PUSH_PATTERNS.matcher(appKey).find()
207-
|| PUSH_PATTERNS.matcher(masterSecret).find()) {
208-
throw new IllegalArgumentException("appKey and masterSecret format is incorrect. "
209-
+ "They should be 24 size, and be composed with alphabet and numbers. "
210-
+ "Please confirm that they are coming from JPush Web Portal.");
211-
}
212-
}
213-
214-
215-
public class SimpleHostnameVerifier implements HostnameVerifier {
177+
178+
179+
public static class SimpleHostnameVerifier implements HostnameVerifier {
216180

217181
@Override
218182
public boolean verify(String hostname, SSLSession session) {
@@ -221,7 +185,7 @@ public boolean verify(String hostname, SSLSession session) {
221185

222186
}
223187

224-
public class SimpleTrustManager implements TrustManager, X509TrustManager {
188+
public static class SimpleTrustManager implements TrustManager, X509TrustManager {
225189

226190
@Override
227191
public void checkClientTrusted(X509Certificate[] chain, String authType)

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

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@ public class ResponseWrapper {
2222

2323
public String exceptionString;
2424

25-
public ResponseWrapper() {
26-
}
2725

2826
public void setRateLimit(String quota, String remaining, String reset) {
2927
if (null == quota) return;
@@ -42,7 +40,13 @@ public void setRateLimit(String quota, String remaining, String reset) {
4240
public void setErrorObject() {
4341
error = _gson.fromJson(responseContent, ErrorObject.class);
4442
}
45-
43+
44+
public boolean isServerResonse() {
45+
if (responseCode == 200) return true;
46+
if (responseCode > 0 && null != error && error.error.code > 0) return true;
47+
return false;
48+
}
49+
4650
@Override
4751
public String toString() {
4852
return _gson.toJson(this);
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package cn.jpush.api.common;
2+
3+
import java.util.regex.Pattern;
4+
5+
import cn.jpush.api.utils.Base64;
6+
import cn.jpush.api.utils.StringUtils;
7+
8+
public class ServiceHelper {
9+
10+
private final static Pattern PUSH_PATTERNS = Pattern.compile("[^a-zA-Z0-9]");
11+
12+
13+
public static String getAuthorizationBase64(String appKey, String masterSecret) {
14+
String encodeKey = appKey + ":" + masterSecret;
15+
return String.valueOf(Base64.encode(encodeKey.getBytes()));
16+
}
17+
18+
public static void checkBasic(String appKey, String masterSecret) {
19+
if (StringUtils.isEmpty(appKey)
20+
|| StringUtils.isEmpty(masterSecret)) {
21+
throw new IllegalArgumentException("appKey and masterSecret are both required.");
22+
}
23+
if (appKey.length() != 24
24+
|| masterSecret.length() != 24
25+
|| PUSH_PATTERNS.matcher(appKey).find()
26+
|| PUSH_PATTERNS.matcher(masterSecret).find()) {
27+
throw new IllegalArgumentException("appKey and masterSecret format is incorrect. "
28+
+ "They should be 24 size, and be composed with alphabet and numbers. "
29+
+ "Please confirm that they are coming from JPush Web Portal.");
30+
}
31+
}
32+
33+
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ private static void testSendNotification() {
3636
LOG.debug(result.toString());
3737
} else {
3838
if (result.getErrorCode() > 0) {
39-
LOG.warn(result.getOriginalError());
39+
LOG.warn(result.getOriginalContent());
4040
} else {
4141
LOG.debug("Maybe connect error. Retry laster. ");
4242
}
@@ -52,7 +52,7 @@ private static void testSendMesasge() {
5252
public static void testGetReport() {
5353
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
5454
ReceivedsResult receivedsResult = jpushClient.getReportReceiveds("1708010723,1774452771");
55-
LOG.debug("responseContent - " + receivedsResult.responseResult.responseContent);
55+
LOG.debug("responseContent - " + receivedsResult.getOriginalContent());
5656
if (receivedsResult.isResultOK()) {
5757
LOG.info("Receiveds - " + receivedsResult);
5858
} else {
@@ -64,7 +64,7 @@ public static void testGetReport() {
6464
} else {
6565
// 未到达 JPush
6666
LOG.error("Other excepitons - "
67-
+ receivedsResult.responseResult.exceptionString);
67+
+ receivedsResult.getExceptionString());
6868
}
6969
}
7070
}

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
package cn.jpush.api.push;
22

3-
import cn.jpush.api.common.BaseHttpClient;
3+
import cn.jpush.api.common.NativeHttpClient;
44
import cn.jpush.api.common.ResponseWrapper;
5+
import cn.jpush.api.common.ServiceHelper;
56
import cn.jpush.api.push.model.PushPayload;
67

78
/**
@@ -14,10 +15,12 @@
1415
*
1516
* Can be used directly.
1617
*/
17-
public class PushClient extends BaseHttpClient {
18+
public class PushClient {
1819
private static String HOST_NAME_SSL = "https://api.jpush.cn";
1920
private static final String PUSH_PATH = "/v3/push";
2021

22+
private NativeHttpClient _httpClient = new NativeHttpClient();;
23+
2124
// The API secret of the appKey. Please get it from JPush Web Portal
2225
private final String _masterSecret;
2326

@@ -40,8 +43,8 @@ public class PushClient extends BaseHttpClient {
4043
public PushClient(String masterSecret, String appKey) {
4144
this._masterSecret = masterSecret;
4245
this._appKey = appKey;
43-
this._authCode = getAuthorizationBase64(_appKey, _masterSecret);
44-
checkBasic(appKey, masterSecret);
46+
this._authCode = ServiceHelper.getAuthorizationBase64(_appKey, _masterSecret);
47+
ServiceHelper.checkBasic(appKey, masterSecret);
4548
}
4649

4750
public PushClient(String masterSecret, String appKey, boolean apnsProduction, long timeToLive) {
@@ -58,14 +61,14 @@ public PushResult sendPush(PushPayload pushPayload) {
5861
}
5962

6063
String url = HOST_NAME_SSL + PUSH_PATH;
61-
ResponseWrapper response = sendPost(url, pushPayload.toString(), _authCode);
64+
ResponseWrapper response = _httpClient.sendPost(url, pushPayload.toString(), _authCode);
6265

6366
return PushResult.fromResponse(response);
6467
}
6568

6669
public PushResult sendPush(String payloadString) {
6770
String url = HOST_NAME_SSL + PUSH_PATH;
68-
ResponseWrapper response = sendPost(url, payloadString, _authCode);
71+
ResponseWrapper response = _httpClient.sendPost(url, payloadString, _authCode);
6972

7073
return PushResult.fromResponse(response);
7174
}

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,18 @@ public class PushResult extends BaseResult {
1010
@Expose public long msg_id;
1111
@Expose public int sendno;
1212

13-
public static PushResult fromResponse(ResponseWrapper response) {
13+
public static PushResult fromResponse(ResponseWrapper responseWrapper) {
1414
PushResult pushResult = null;
15-
if (response.responseCode == RESPONSE_OK) {
16-
pushResult = _gson.fromJson(response.responseContent, PushResult.class);
15+
16+
if (responseWrapper.isServerResonse()) {
17+
pushResult = _gson.fromJson(responseWrapper.responseContent, PushResult.class);
1718
} else {
1819
pushResult = new PushResult();
1920
}
20-
pushResult.responseResult = response;
21+
22+
pushResult.setResponseWrapper(responseWrapper);
23+
2124
return pushResult;
2225
}
23-
2426
}
2527

src/cn/jpush/api/report/ReceivedsResult.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,13 @@ public List<Received> getReceivedList() {
2626
return this.received_list;
2727
}
2828

29-
public static ReceivedsResult fromResponse(ResponseWrapper wrapper) {
29+
public static ReceivedsResult fromResponse(ResponseWrapper responseWrapper) {
3030
ReceivedsResult receivedsResult = new ReceivedsResult();
31-
if (wrapper.responseCode == RESPONSE_OK) {
32-
receivedsResult.received_list = _gson.fromJson(wrapper.responseContent, RECEIVED_TYPE);
31+
if (responseWrapper.isServerResonse()) {
32+
receivedsResult.received_list = _gson.fromJson(responseWrapper.responseContent, RECEIVED_TYPE);
3333
}
3434

35-
receivedsResult.responseResult = wrapper;
35+
receivedsResult.setResponseWrapper(responseWrapper);
3636
return receivedsResult;
3737
}
3838

0 commit comments

Comments
 (0)