-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCSHttpConnection.java
More file actions
372 lines (330 loc) · 14.4 KB
/
Copy pathCSHttpConnection.java
File metadata and controls
372 lines (330 loc) · 14.4 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package com.contentstack.sdk;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.IntStream;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import retrofit2.Call;
import retrofit2.Response;
import static com.contentstack.sdk.Constants.*;
public class CSHttpConnection implements IURLRequestHTTP {
protected static final Logger logger = Logger.getLogger(CSHttpConnection.class.getName());
private final String urlPath;
private final IRequestModelHTTP connectionRequest;
private String controller;
private LinkedHashMap<String, Object> headers;
private String info;
private APIService service;
private Config config;
private Stack stackInstance;
private ResultCallBack callBackObject;
private JSONObject responseJSON;
private HashMap<String, Object> formParams;
private final String utfType = String.valueOf(StandardCharsets.UTF_8);
public CSHttpConnection(String urlToCall, IRequestModelHTTP csConnectionRequest) {
this.urlPath = urlToCall;
this.connectionRequest = csConnectionRequest;
}
public void setFormParams(HashMap<String, Object> formParams) {
this.formParams = formParams;
}
@Override
public String getController() {
return controller;
}
@Override
public void setController(String controller) {
this.controller = controller;
}
@Override
public void setHeaders(LinkedHashMap<String, Object> headers) {
this.headers = headers;
}
@Override
public LinkedHashMap<String, Object> getHeaders() {
return this.headers;
}
@Override
public String getInfo() {
return info;
}
@Override
public void setInfo(String info) {
this.info = info;
}
@Override
public ResultCallBack getCallBackObject() {
return callBackObject;
}
@Override
public void setCallBackObject(ResultCallBack callBackObject) {
this.callBackObject = callBackObject;
}
@Override
public JSONObject getResponse() {
return responseJSON;
}
public String setFormParamsGET(HashMap<String, Object> params) {
if (params != null && params.size() > 0) {
String urlParams = null;
urlParams = info.equalsIgnoreCase(Constants.REQUEST_CONTROLLER.QUERY.name())
|| info.equalsIgnoreCase(Constants.REQUEST_CONTROLLER.ENTRY.name())
|| info.equalsIgnoreCase(Constants.REQUEST_CONTROLLER.ASSET.name())
|| info.equalsIgnoreCase(Constants.REQUEST_CONTROLLER.ASSETLIBRARY.name()) ? getParams(params) : null;
if (urlParams == null) {
for (Map.Entry<String, Object> e : params.entrySet()) {
if (urlParams == null) {
urlParams = "?" + e.getKey() + "=" + e.getValue();
} else {
urlParams += "&" + e.getKey() + "=" + e.getValue();
}
}
}
return urlParams;
}
return null;
}
private String getParams(HashMap<String, Object> params) {
String urlParams = "?";
for (Map.Entry<String, Object> e : params.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
try {
if (key.equalsIgnoreCase("include[]") || key.equalsIgnoreCase("only[BASE][]")
|| key.equalsIgnoreCase("except[BASE][]") || key.equalsIgnoreCase("asset_fields[]")) {
urlParams = convertUrlParam(urlParams, value, key);
} else if (key.equalsIgnoreCase("only")) {
JSONObject onlyJSON = (JSONObject) value;
Iterator<String> itrString = onlyJSON.keys();
while (itrString.hasNext()) {
String innerKey = itrString.next();
JSONArray array = onlyJSON.optJSONArray(innerKey);
innerKey = URLEncoder.encode("only[" + innerKey + "][]", utfType);
for (int i = 0; i < array.length(); i++) {
urlParams += urlParams.equals("?") ? innerKey + "=" + array.opt(i)
: "&" + innerKey + "=" + array.opt(i);
}
}
} else if (key.equalsIgnoreCase("except")) {
JSONObject onlyJSON = (JSONObject) value;
Iterator<String> iter = onlyJSON.keys();
while (iter.hasNext()) {
String innerKey = iter.next();
JSONArray array = onlyJSON.optJSONArray(innerKey);
innerKey = URLEncoder.encode("except[" + innerKey + "][]", utfType);
for (int i = 0; i < array.length(); i++) {
urlParams += urlParams.equals("?") ? innerKey + "=" + array.opt(i)
: "&" + innerKey + "=" + array.opt(i);
}
}
} else if (key.equalsIgnoreCase("query")) {
JSONObject queryJSON = (JSONObject) value;
urlParams += urlParams.equals("?") ? key + "=" + URLEncoder.encode(queryJSON.toString(), utfType)
: "&" + key + "=" + URLEncoder.encode(queryJSON.toString(), utfType);
} else {
urlParams += urlParams.equals("?") ? key + "=" + value : "&" + key + "=" + value;
}
} catch (Exception e1) {
logger.log(Level.SEVERE, ErrorMessages.URL_PARAMETER_ENCODING_FAILED, e1);
}
}
return urlParams;
}
private String convertUrlParam(String urlParams, Object value, String key) throws UnsupportedEncodingException {
key = URLEncoder.encode(key, utfType);
JSONArray array = (JSONArray) value;
for (int i = 0; i < array.length(); i++) {
urlParams += urlParams.equals("?") ? key + "=" + array.opt(i) : "&" + key + "=" + array.opt(i);
}
return urlParams;
}
@Override
public void send() {
String url = "";
String params = setFormParamsGET(formParams);
if (params != null) {
url = urlPath + params;
} else {
url = urlPath;
}
try {
getService(url);
} catch (IOException | JSONException e) {
logger.log(Level.SEVERE, ErrorMessages.URL_PARAMETER_ENCODING_FAILED, e);
}
}
private JSONObject createOrderedJSONObject(Map<String, Object> map) {
JSONObject json = new JSONObject();
for (Map.Entry<String, Object> entry : map.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
return json;
}
/**
* Recursively converts a parsed {@link JSONObject} into plain Java collections that
* mirror what the response models expect: JSON objects become {@link LinkedHashMap}
* (preserving key order) and JSON arrays become {@link ArrayList}.
*/
private static Map<String, Object> jsonToOrderedMap(JSONObject object) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
for (String key : object.keySet()) {
map.put(key, convertJsonValue(object.get(key)));
}
return map;
}
private static Object convertJsonValue(Object value) {
if (value == null || value == JSONObject.NULL) {
return null;
}
if (value instanceof JSONObject) {
return jsonToOrderedMap((JSONObject) value);
}
if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
ArrayList<Object> list = new ArrayList<>(array.length());
for (int i = 0; i < array.length(); i++) {
list.add(convertJsonValue(array.get(i)));
}
return list;
}
// Normalize floating-point numbers to Double to match the previous parser's output.
if (value instanceof BigDecimal) {
return ((BigDecimal) value).doubleValue();
}
return value;
}
private void getService(String requestUrl) throws IOException {
this.headers.put(X_USER_AGENT_KEY, "contentstack-delivery-java/" + SDK_VERSION);
this.headers.put(USER_AGENT_KEY, USER_AGENT);
this.headers.put(CONTENT_TYPE, APPLICATION_JSON);
Request request = null;
if (this.config.plugins != null) {
request = pluginRequestImp(requestUrl);
this.headers.clear();
Request finalRequest = request;
request.headers().names().forEach(key -> {
this.headers.put(key, finalRequest.headers().get(key));
});
requestUrl = request.url().toString();
}
try {
Response<ResponseBody> response = this.service.getRequest(requestUrl, this.headers).execute();
if (response.isSuccessful()) {
assert response.body() != null;
if (request != null) {
response = pluginResponseImp(request, response);
}
try {
// Parse the JSON into ordered maps/lists using org.json. Nested objects
// become LinkedHashMap and arrays become ArrayList, matching the shape
// the response models expect.
Map<String, Object> responseMap = jsonToOrderedMap(new JSONObject(response.body().string()));
// Use the custom method to create an ordered JSONObject
responseJSON = createOrderedJSONObject(responseMap);
if (this.config.livePreviewEntry != null && !this.config.livePreviewEntry.isEmpty()) {
handleJSONArray();
}
connectionRequest.onRequestFinished(CSHttpConnection.this);
} catch (JSONException e) {
// Handle non-JSON response
setError(ErrorMessages.INVALID_JSON_RESPONSE);
}
} else {
assert response.errorBody() != null;
setError(response.errorBody().string());
}
} catch (SocketTimeoutException e) {
// Handle timeout
setError("Request timed out: " + e.getMessage());
} catch (IOException e) {
// Handle other IO exceptions
setError("IO error occurred: " + e.getMessage());
}
}
private Request pluginRequestImp(String requestUrl) {
Call<ResponseBody> call = this.service.getRequest(requestUrl, this.headers);
Request request = call.request();
this.config.plugins.forEach(plugin -> plugin.onRequest(this.stackInstance, request));
return request;
}
private Response<ResponseBody> pluginResponseImp(Request request, Response<ResponseBody> response) {
this.config.plugins.forEach(plugin -> plugin.onResponse(this.stackInstance, request, response));
return response;
}
void handleJSONArray() {
JSONArray entriesArray = responseJSON.optJSONArray("entries");
if (responseJSON.has("entries") && entriesArray != null && !entriesArray.isEmpty()) {
JSONArray finalEntries = entriesArray;
IntStream.range(0, finalEntries.length()).forEach(idx -> {
JSONObject objJSON = (JSONObject) finalEntries.get(idx);
handleJSONObject(finalEntries, objJSON, idx);
});
}
JSONObject entryObj = responseJSON.optJSONObject("entry");
if (responseJSON.has("entry") && entryObj != null && !entryObj.isEmpty()) {
JSONObject entry = entryObj;
if (!entry.isEmpty() && this.config.livePreviewEntry != null) {
Object entryUid = entry.opt("uid");
Object previewUid = this.config.livePreviewEntry.opt("uid");
if (entryUid != null && java.util.Objects.equals(entryUid, previewUid)) {
responseJSON = new JSONObject().put("entry", this.config.livePreviewEntry);
}
}
}
}
void handleJSONObject(JSONArray arrayEntry, JSONObject jsonObj, int idx) {
if (!jsonObj.isEmpty() && this.config.livePreviewEntry != null) {
Object entryUid = jsonObj.opt("uid");
Object previewUid = this.config.livePreviewEntry.opt("uid");
if (entryUid != null && java.util.Objects.equals(entryUid, previewUid)) {
arrayEntry.put(idx, this.config.livePreviewEntry);
}
}
responseJSON = new JSONObject().put("entries", arrayEntry);
}
void setError(String errResp) {
if (errResp == null || errResp.trim().isEmpty()) {
errResp = "Unexpected error: No response received from server.";
}
try {
responseJSON = new JSONObject(errResp);
} catch (JSONException e) {
// If errResp is not valid JSON, create a new JSONObject with the error message
responseJSON = new JSONObject();
responseJSON.put(ERROR_MESSAGE, errResp);
}
responseJSON.put(ERROR_MESSAGE, responseJSON.optString(ERROR_MESSAGE, "An unknown error occurred."));
responseJSON.put(ERROR_CODE, responseJSON.optString(ERROR_CODE, "0"));
responseJSON.put(ERRORS, responseJSON.optString(ERRORS, "No additional error details available."));
int errCode = 0;
try {
errCode = Integer.parseInt(responseJSON.optString(ERROR_CODE, "0"));
} catch (NumberFormatException e) {
// Default error code remains 0 if parsing fails
}
connectionRequest.onRequestFailed(responseJSON, errCode, callBackObject);
}
public void setAPIService(APIService service) {
this.service = service;
}
public void setConfig(Config config) {
this.config = config;
}
public void setStack(Stack stackInstance) {
this.stackInstance = stackInstance;
}
}