forked from ringcentral/pubnub-jtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEndpoint.java
More file actions
298 lines (230 loc) · 10.7 KB
/
Copy pathEndpoint.java
File metadata and controls
298 lines (230 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package com.pubnub.api.endpoints;
import com.pubnub.api.PubNub;
import com.pubnub.api.PubNubException;
import com.pubnub.api.builder.PubNubErrorBuilder;
import com.pubnub.api.callbacks.PNCallback;
import com.pubnub.api.enums.PNLogVerbosity;
import com.pubnub.api.enums.PNOperationType;
import com.pubnub.api.enums.PNStatusCategory;
import com.pubnub.api.models.consumer.PNErrorData;
import com.pubnub.api.models.consumer.PNStatus;
import lombok.AccessLevel;
import lombok.Getter;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public abstract class Endpoint<Input, Output> {
@Getter(AccessLevel.PROTECTED)
private PubNub pubnub;
@Getter(AccessLevel.NONE)
private PNCallback<Output> cachedCallback;
@Getter(AccessLevel.NONE)
private Call<Input> call;
/**
* If the endpoint failed to execute and we do not want to alert the user, flip this to true
* This operation is handy if we internally cancelled the endpoint.
*/
@Getter(AccessLevel.NONE)
private boolean silenceFailures;
private static final int SERVER_RESPONSE_SUCCESS = 200;
private static final int SERVER_RESPONSE_FORBIDDEN = 403;
private static final int SERVER_RESPONSE_BAD_REQUEST = 400;
public Endpoint(final PubNub pubnubInstance) {
this.pubnub = pubnubInstance;
}
public final Output sync() throws PubNubException {
this.validateParams();
call = doWork(createBaseParams());
Response<Input> serverResponse;
Output response;
try {
serverResponse = call.execute();
} catch (IOException e) {
throw PubNubException.builder()
.pubnubError(PubNubErrorBuilder.PNERROBJ_PARSING_ERROR)
.errormsg(e.toString())
.affectedCall(call)
.build();
}
if (!serverResponse.isSuccessful() || serverResponse.code() != SERVER_RESPONSE_SUCCESS) {
String responseBodyText;
try {
responseBodyText = serverResponse.errorBody().string();
} catch (IOException e) {
responseBodyText = "N/A";
}
throw PubNubException.builder()
.pubnubError(PubNubErrorBuilder.PNERROBJ_HTTP_ERROR)
.errormsg(responseBodyText)
.statusCode(serverResponse.code())
.affectedCall(call)
.build();
}
response = createResponse(serverResponse);
return response;
}
public final void async(final PNCallback<Output> callback) {
cachedCallback = callback;
try {
call = doWork(createBaseParams());
} catch (PubNubException e) {
PubNubException pubnubException = PubNubException.builder()
.pubnubError(PubNubErrorBuilder.PNERROBJ_HTTP_ERROR)
.errormsg(e.getMessage())
.build();
callback.onResponse(null, createStatusResponse(PNStatusCategory.PNBadRequestCategory, null, pubnubException));
return;
}
call.enqueue(new retrofit2.Callback<Input>() {
@Override
public void onResponse(final Call<Input> performedCall, final Response<Input> response) {
Output callbackResponse;
if (!response.isSuccessful() || response.code() != SERVER_RESPONSE_SUCCESS) {
String responseBodyText;
try {
responseBodyText = response.errorBody().string();
} catch (IOException e) {
responseBodyText = "N/A";
}
PNStatusCategory pnStatusCategory = PNStatusCategory.PNUnknownCategory;
PubNubException ex = PubNubException.builder()
.pubnubError(PubNubErrorBuilder.PNERROBJ_HTTP_ERROR)
.errormsg(responseBodyText)
.statusCode(response.code())
.build();
if (response.code() == SERVER_RESPONSE_FORBIDDEN) {
pnStatusCategory = PNStatusCategory.PNAccessDeniedCategory;
}
if (response.code() == SERVER_RESPONSE_BAD_REQUEST) {
pnStatusCategory = PNStatusCategory.PNBadRequestCategory;
}
callback.onResponse(null, createStatusResponse(pnStatusCategory, response, ex));
return;
}
try {
callbackResponse = createResponse(response);
} catch (PubNubException e) {
PubNubException pubnubException = PubNubException.builder()
.pubnubError(PubNubErrorBuilder.PNERROBJ_PARSING_ERROR)
.errormsg(e.getMessage())
.statusCode(response.code())
.build();
callback.onResponse(null, createStatusResponse(PNStatusCategory.PNMalformedResponseCategory, response, pubnubException));
return;
}
callback.onResponse(callbackResponse, createStatusResponse(PNStatusCategory.PNAcknowledgmentCategory, response, null));
}
@Override
public void onFailure(final Call<Input> performedCall, final Throwable throwable) {
if (silenceFailures) {
return;
}
PNStatusCategory pnStatusCategory = PNStatusCategory.PNBadRequestCategory;
PubNubException.PubNubExceptionBuilder pubnubException = PubNubException.builder()
.errormsg(throwable.getMessage());
try {
throw throwable;
} catch (UnknownHostException networkException) {
pubnubException.pubnubError(PubNubErrorBuilder.PNERROBJ_CONNECTION_NOT_SET);
pnStatusCategory = PNStatusCategory.PNUnexpectedDisconnectCategory;
} catch (ConnectException connectException) {
pubnubException.pubnubError(PubNubErrorBuilder.PNERROBJ_CONNECT_EXCEPTION);
pnStatusCategory = PNStatusCategory.PNUnexpectedDisconnectCategory;
} catch (SocketTimeoutException socketTimeoutException) {
pubnubException.pubnubError(PubNubErrorBuilder.PNERROBJ_SUBSCRIBE_TIMEOUT);
pnStatusCategory = PNStatusCategory.PNTimeoutCategory;
} catch (Throwable throwable1) {
pubnubException.pubnubError(PubNubErrorBuilder.PNERROBJ_HTTP_ERROR);
}
callback.onResponse(null, createStatusResponse(pnStatusCategory, null, pubnubException.build()));
}
});
}
public void retry() {
silenceFailures = false;
async(cachedCallback);
};
/**
* cancel the operation but do not alert anybody, useful for restarting the heartbeats and subscribe loops.
*/
public void silentCancel() {
if (call != null && !call.isCanceled()) {
this.silenceFailures = true;
call.cancel();
}
}
private PNStatus createStatusResponse(PNStatusCategory category, Response<Input> response, Exception throwable) {
PNStatus.PNStatusBuilder pnStatus = PNStatus.builder();
pnStatus.executedEndpoint(this);
if (response == null || throwable != null) {
pnStatus.error(true);
}
if (throwable != null) {
PNErrorData pnErrorData = new PNErrorData(throwable.getMessage(), throwable);
pnStatus.errorData(pnErrorData);
}
if (response != null) {
pnStatus.statusCode(response.code());
pnStatus.tlsEnabled(response.raw().request().url().isHttps());
pnStatus.origin(response.raw().request().url().host());
pnStatus.uuid(response.raw().request().url().queryParameter("uuid"));
pnStatus.authKey(response.raw().request().url().queryParameter("auth"));
pnStatus.clientRequest(response.raw().request());
}
pnStatus.operation(getOperationType());
pnStatus.category(category);
pnStatus.affectedChannels(getAffectedChannels());
pnStatus.affectedChannelGroups(getAffectedChannelGroups());
return pnStatus.build();
}
protected final Retrofit createRetrofit() {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(this.getRequestTimeout(), TimeUnit.SECONDS);
httpClient.connectTimeout(this.getConnectTimeout(), TimeUnit.SECONDS);
if (pubnub.getConfiguration().getLogVerbosity() == PNLogVerbosity.BODY) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}
return new Retrofit.Builder()
.baseUrl(pubnub.getBaseUrl())
.addConverterFactory(JacksonConverterFactory.create())
.client(httpClient.build())
.build();
}
protected final Map<String, String> createBaseParams() {
Map<String, String> params = new HashMap<>();
params.put("pnsdk", "Java/" + this.pubnub.getVersion());
params.put("uuid", this.pubnub.getConfiguration().getUuid());
// add the auth key for publish and subscribe.
if (this.pubnub.getConfiguration().getAuthKey() != null && isAuthRequired()) {
params.put("auth", pubnub.getConfiguration().getAuthKey());
}
return params;
}
protected List<String> getAffectedChannels() {
return null;
}
protected List<String> getAffectedChannelGroups() {
return null;
}
protected abstract void validateParams() throws PubNubException;
protected abstract Call<Input> doWork(Map<String, String> baseParams) throws PubNubException;
protected abstract Output createResponse(Response<Input> input) throws PubNubException;
// add hooks for timeout
protected abstract int getConnectTimeout();
protected abstract int getRequestTimeout();
protected abstract PNOperationType getOperationType();
protected abstract boolean isAuthRequired();
}