-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.java
More file actions
482 lines (447 loc) · 22.2 KB
/
Utils.java
File metadata and controls
482 lines (447 loc) · 22.2 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package com.contentstack.utils;
import com.contentstack.utils.helper.Metadata;
import com.contentstack.utils.interfaces.ContentCallback;
import com.contentstack.utils.interfaces.MetaToEmbedCallback;
import com.contentstack.utils.interfaces.Option;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.StreamSupport;
import static com.contentstack.utils.AutomateCommon.*;
public class Utils {
/**
* The `render` function takes a JSON object, an array of path strings, and an
* option object, and
* renders the contents of the JSON object based on the provided paths and
* options.
*
* @param entryObj The entryObj parameter is a JSONObject that represents an
* entry or a data
* object. It contains various properties and values.
* @param pathString An array of strings representing the paths to the content
* in the JSON object.
* @param renderObject The `renderObject` parameter is an object of type
* `Option`. It is used to
* specify rendering options for the content.
*/
public static void render(JSONObject entryObj, String[] pathString, Option renderObject) {
ContentCallback callback = content -> {
if (content instanceof JSONArray) {
JSONArray contentArray = (JSONArray) content;
return renderContents(contentArray, entryObj, renderObject);
} else if (content instanceof String) {
String contentString = (String) content;
return renderContent(contentString, entryObj, renderObject);
}
return null;
};
if (entryObj != null && entryObj.has("_embedded_items")) {
// when pathString is provided by user
if (pathString != null && pathString.length > 0) {
for (String path : pathString) {
findContent(entryObj, path, callback);
}
} else {
// if pathString is not given, extract all available pathString from
// _embedded_items
JSONObject embedKeys = entryObj.getJSONObject("_embedded_items");
ArrayList<String> pathKeys = new ArrayList<>(embedKeys.keySet());
for (String path : pathKeys) {
findContent(entryObj, path, callback);
}
}
}
}
/**
* The function takes a string, a JSON object, and an option, and replaces
* certain elements in the
* string with values from the JSON object based on the option.
*
* @param rteStringify The `rteStringify` parameter is a string representation
* of the content to be
* rendered. It is passed to the `Jsoup.parse()` method to
* create a `Document` object.
* @param embedObject The `embedObject` parameter is a JSONObject that contains
* embedded items. It
* may have a key "_embedded_items" which holds a JSONObject
* of embedded items.
* @param option The "option" parameter is of type "Option". It is an
* object that represents a
* specific option for rendering the content. The exact
* structure and properties of the "Option"
* object are not provided in the code snippet, so it would
* be necessary to refer to the
* documentation or other parts of the code
* @return The method is returning the modified RTE (Rich Text Editor) content
* as a string.
*/
public static String renderContent(String rteStringify, JSONObject embedObject, Option option) {
final String[] sReplaceRTE = { rteStringify };
Document html = Jsoup.parse(rteStringify);
getEmbeddedObjects(html, metadata -> {
Optional<JSONObject> filteredContent = Optional.empty();
boolean available = embedObject.has("_embedded_items");
if (available) {
JSONObject jsonArray = embedObject.optJSONObject("_embedded_items");
filteredContent = findEmbeddedItems(jsonArray, metadata);
}
if (filteredContent.isPresent()) {
JSONObject contentToPass = filteredContent.get();
String stringOption = getStringOption(option, metadata, contentToPass);
sReplaceRTE[0] = html.body().html().replace(metadata.getOuterHTML(), stringOption);
}
});
return sReplaceRTE[0];
}
/**
* The function takes an array of strings, an object, and an option, and returns
* a new array with the
* rendered contents of each string.
*
* @param rteArray An array of RTE (Rich Text Editor) content strings.
* @param entryObject The `entryObject` parameter is a JSONObject that contains
* the data needed for
* rendering the content. It likely contains key-value pairs
* representing different properties or
* attributes of the content.
* @param option The "option" parameter is an object of type "Option". It
* is used as an argument in the
* "renderContent" method.
* @return The method is returning a JSONArray object.
*/
public static JSONArray renderContents(JSONArray rteArray, JSONObject entryObject, Option option) {
JSONArray jsonArrayRTEContent = new JSONArray();
for (Object RTE : rteArray) {
String stringify = (String) RTE;
String renderContent = renderContent(stringify, entryObject, option);
jsonArrayRTEContent.put(renderContent);
}
return jsonArrayRTEContent;
}
private static Optional<JSONObject> findEmbeddedItems(JSONObject jsonObject, Metadata metadata) {
Set<String> allKeys = jsonObject.keySet();
for (String key : allKeys) {
JSONArray jsonArray = jsonObject.optJSONArray(key);
Optional<JSONObject> filteredContent = StreamSupport.stream(jsonArray.spliterator(), false)
.map(val -> (JSONObject) val)
.filter(val -> val.optString("uid").equalsIgnoreCase(metadata.getItemUid())).findFirst();
if (filteredContent.isPresent()) {
return filteredContent;
}
}
return Optional.empty();
}
/**
* The function converts a JSONArray to HTML using a specified key path and
* options.
*
* @param entryArray A JSONArray containing JSON objects.
* @param keyPath The keyPath parameter is an array of strings that
* represents the path to a specific
* key in a JSON object. Each string in the array represents a
* key in the path. For example, if the
* keyPath is ["person", "name"], it means that we want to
* access the value of the "
* @param option The "option" parameter is an object of type "Option". It is
* used to specify additional
* options or settings for the JSON to HTML conversion
* process.
*/
public static void jsonToHTML(@NotNull JSONArray entryArray, @NotNull String[] keyPath, @NotNull Option option) {
entryArray.forEach(jsonObj -> jsonToHTML((JSONObject) jsonObj, keyPath, option));
}
/**
* The function `jsonToHTML` converts a JSON object to HTML using a specified
* key path and
* rendering options.
*
* @param entry The `entry` parameter is a `JSONObject` that represents
* the JSON data that you want
* to convert to HTML. It contains the data that you want to
* render as HTML.
* @param keyPath The keyPath parameter is an array of strings that
* represents the path to the
* desired content in the JSON object. Each string in the
* array represents a key in the JSON object
* hierarchy. The method will traverse the JSON object using
* the keys in the keyPath array to find
* the desired content.
* @param renderOption The renderOption parameter is an option that determines
* how the content
* should be rendered. It is of type Option, which is likely
* an enum or a class with different
* rendering options. The specific options available and
* their meanings would depend on the
* implementation of the Option class.
*/
public static void jsonToHTML(@NotNull JSONObject entry, @NotNull String[] keyPath, Option renderOption) {
MetaToEmbedCallback converter = metadata -> {
boolean available = entry.has("_embedded_items");
if (available) {
JSONObject jsonArray = entry.optJSONObject("_embedded_items");
return findEmbeddedItems(jsonArray, metadata);
}
return Optional.empty();
};
ContentCallback callback = content -> {
if (content instanceof JSONArray) {
JSONArray contentArray = (JSONArray) content;
return enumerateContents(contentArray, renderOption, converter);
} else if (content instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) content;
return enumerateContent(jsonObject, renderOption, converter);
}
return null;
};
for (String path : keyPath) {
findContent(entry, path, callback);
}
}
/**
* The function converts a JSON object to HTML using a specified rendering
* option and optional embedded
* items.
*
* @param jsonRTE A JSONObject representing the JSON data to be converted
* to HTML.
* @param renderOption The `renderOption` parameter is an option that
* determines how the JSON content
* should be rendered as HTML. It could be an enum or a
* class that defines different rendering options.
* @param embeddeditems The `embedded-items` parameter is a `JSONObject` that
* contains embedded items.
* It is used to find and retrieve embedded items based on
* their metadata.
* @return The method is returning a String.
*/
public static String jsonToHTML(@NotNull JSONObject jsonRTE, Option renderOption, JSONObject embeddeditems) {
MetaToEmbedCallback converter = metadata -> {
if (embeddeditems != null && !embeddeditems.isEmpty()) {
return findEmbeddedItems(embeddeditems, metadata);
}
return Optional.empty();
};
return enumerateContent(jsonRTE, renderOption, converter);
}
/**
* The function `jsonToHTML` converts a JSON array to HTML using a specified
* rendering option and
* optional embedded items.
*
* @param jsonRTE A JSONArray object containing the JSON data to be
* converted to HTML.
* @param renderOption The `renderOption` parameter is an option that
* determines how the JSON data
* should be rendered as HTML. It could be an enum or a
* custom class that defines different rendering
* options.
* @param embeddeditems The `embedded-items` parameter is a `JSONObject` that
* contains embedded items.
* It is used to find and retrieve embedded items based on
* the metadata provided.
* @return The method is returning an Object.
*/
public static Object jsonToHTML(@NotNull JSONArray jsonRTE, Option renderOption, JSONObject embeddeditems) {
MetaToEmbedCallback converter = metadata -> {
if (embeddeditems != null && !embeddeditems.isEmpty()) {
return findEmbeddedItems(embeddeditems, metadata);
}
return Optional.empty();
};
return enumerateContents(jsonRTE, renderOption, converter);
}
/**
* The function takes a JSONArray, a keyPath array, and an Option object, and
* iterates over each
* JSONObject in the JSONArray to call another render function.
*
* @param jsonArray A JSONArray object that contains a collection of JSON
* objects.
* @param keyPath The `keyPath` parameter is an array of strings that
* represents the path to a specific
* key in a JSON object. Each string in the array represents
* a key in the path. For example, if the key
* path is `["foo", "bar", "baz"]`, it means that you want
* @param renderObject The `renderObject` parameter is an object of type
* `Option`.
*/
public void render(@NotNull JSONArray jsonArray, @NotNull String[] keyPath, @NotNull Option renderObject) {
jsonArray.forEach(jsonObj -> render((JSONObject) jsonObj, keyPath, renderObject));
}
public static JSONObject getVariantAliases(JSONObject entry, String contentTypeUid) {
if (contentTypeUid == null || contentTypeUid.isEmpty()) {
throw new IllegalArgumentException("ContentType is required.");
}
if (entry == null) {
throw new IllegalArgumentException("Entry must not be null.");
}
if (!entry.has("uid") || entry.isNull("uid")) {
throw new IllegalArgumentException("Entry must contain uid.");
}
String entryUid = entry.optString("uid", "");
JSONArray variantsArray = extractVariantAliasesFromEntry(entry);
JSONObject result = new JSONObject();
result.put("entry_uid", entryUid);
result.put("contenttype_uid", contentTypeUid);
result.put("variants", variantsArray);
return result;
}
public static JSONArray getVariantAliases(JSONArray entries, String contentTypeUid) {
if (contentTypeUid == null || contentTypeUid.isEmpty()) {
throw new IllegalArgumentException("ContentType is required.");
}
if (entries == null) {
return new JSONArray();
}
JSONArray variantResults = new JSONArray();
for (int i = 0; i < entries.length(); i++) {
JSONObject entry = entries.optJSONObject(i);
if (entry != null && entry.has("uid")) {
JSONObject singleResult = getVariantAliases(entry, contentTypeUid);
variantResults.put(singleResult);
}
}
return variantResults;
}
public static JSONObject getDataCsvariantsAttribute(JSONObject entry, String contentTypeUid) {
if (entry == null) {
JSONObject result = new JSONObject();
result.put("data-csvariants", "[]");
return result;
}
JSONArray entries = new JSONArray();
entries.put(entry);
return getDataCsvariantsAttribute(entries, contentTypeUid);
}
public static JSONObject getDataCsvariantsAttribute(JSONArray entries, String contentTypeUid) {
JSONObject result = new JSONObject();
if (entries == null) {
result.put("data-csvariants", "[]");
return result;
}
if (contentTypeUid == null || contentTypeUid.isEmpty()) {
throw new IllegalArgumentException("ContentType is required.");
}
JSONArray variantResults = getVariantAliases(entries, contentTypeUid);
String resultString = variantResults.toString();
result.put("data-csvariants", resultString);
return result;
}
private static JSONArray extractVariantAliasesFromEntry(JSONObject entry) {
JSONArray variantArray = new JSONArray();
JSONObject publishDetails = entry.optJSONObject("publish_details");
if (publishDetails == null) {
return new JSONArray();
}
JSONObject variants = publishDetails.optJSONObject("variants");
if (variants == null) {
return new JSONArray();
}
for (String key : variants.keySet()) {
Object value = variants.get(key);
if (value instanceof JSONObject) {
String alias = ((JSONObject) value).optString("alias", "");
if (alias != null && !alias.isEmpty()) {
variantArray.put(alias.trim());
}
}
}
return variantArray;
}
// update assetURL in json of GQL response
public static void UpdateAssetURLForGQL(JSONObject entryJson) {
Map<String, String> assetUrls = new HashMap<>();
if (entryJson.has("data")) {
JSONObject data = entryJson.optJSONObject("data");
for (String key : data.keySet()) {
Object value = data.get(key);
if (value instanceof JSONObject) {
JSONObject contentTypeObj = (JSONObject) value;
Iterator<String> keys = contentTypeObj.keys();
while (keys.hasNext()) {
String mainKey = keys.next();
Object embeddedItem = contentTypeObj.get(mainKey);
if (embeddedItem instanceof JSONObject) {
JSONObject jsonRteObj = (JSONObject) embeddedItem;
if (jsonRteObj.has("embedded_itemsConnection")) {
JSONObject embeddedConnection = jsonRteObj.getJSONObject("embedded_itemsConnection");
if (embeddedConnection.has("edges")) {
JSONArray embeddedItems = embeddedConnection.getJSONArray("edges");
for (int i = 0; i < embeddedItems.length(); i++) {
JSONObject item = embeddedItems.getJSONObject(i);
if (item.has("node")) {
JSONObject nodeList = item.getJSONObject("node");
if (nodeList.has("url")) {
String url = nodeList.getString("url");
if (nodeList.has("system")) {
JSONObject systemList = nodeList.getJSONObject("system");
if ("sys_assets".equals(systemList.optString("content_type_uid"))
&& systemList.has("uid")) {
String uid = systemList.getString("uid");
assetUrls.put(uid, url);
updateChildObjects(entryJson, assetUrls);
}
}
}
}
}
}
} else {
throw new IllegalArgumentException(
"_embedded_items not present in entry. Call includeEmbeddedItems() before fetching entry.");
}
}
}
}
}
}
}
private static void updateChildObjects(JSONObject entryJson, Map<String, String> assetUrls) {
if (entryJson.has("data")) {
JSONObject dataObject = entryJson.getJSONObject("data");
for (String key : dataObject.keySet()) {
Object value = dataObject.get(key);
if (value instanceof JSONObject) {
JSONObject contentTypeObj = (JSONObject) value;
Iterator<String> keys = contentTypeObj.keys();
while (keys.hasNext()) {
String mainKey = keys.next();
Object embeddedItem = contentTypeObj.get(mainKey);
if (embeddedItem instanceof JSONObject) {
JSONObject jsonRteObj = (JSONObject) embeddedItem;
if (jsonRteObj.has("json")) {
JSONObject jsonValue = jsonRteObj.getJSONObject("json");
if (jsonValue.has("children")) {
JSONArray childrenArray = jsonValue.getJSONArray("children");
updateChildrenArray(childrenArray, assetUrls);
}
}
}
}
}
}
}
}
private static void updateChildrenArray(JSONArray childrenArray, Map<String, String> assetUrls) {
for (int i = 0; i < childrenArray.length(); i++) {
JSONObject child = childrenArray.getJSONObject(i);
if (child.has("attrs")) {
JSONObject attrsObject = child.getJSONObject("attrs");
if (attrsObject.has("asset-uid") && attrsObject.has("asset-link")) {
String assetUid = attrsObject.getString("asset-uid");
if (assetUrls.containsKey(assetUid)) {
attrsObject.put("asset-link", assetUrls.get(assetUid));
}
}
}
}
}
}