From e4fa7b5ed06f0e5dcb0297dd6544b5aa8d450b39 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Thu, 22 Jun 2023 16:59:17 +0530 Subject: [PATCH 1/8] Attributes support added --- README.md | 147 ++++++++++-------- .../utils/render/DefaultOption.java | 84 +++++++--- .../utils/DefaultOptionClass.java | 48 ++++++ .../com/contentstack/utils/UtilTests.java | 38 +++-- src/test/resources/issue/newline.json | 8 +- 5 files changed, 215 insertions(+), 110 deletions(-) create mode 100644 src/test/java/com/contentstack/utils/DefaultOptionClass.java diff --git a/README.md b/README.md index 11e6f74..2208b35 100644 --- a/README.md +++ b/README.md @@ -12,23 +12,25 @@ This guide will help you get started with Contentstack Java Utils SDK to build a ### SDK Installation and Setup -To setup [Utils SDK](https://mvnrepository.com/artifact/com.contentstack.sdk/utils) in your Java project, add the following dependency in the pom.xml file +To setup [Utils SDK](https://mvnrepository.com/artifact/com.contentstack.sdk/utils) in your Java project, add the +following dependency in the pom.xml file ```java - com.contentstack.sdk - util - {latest} +com.contentstack.sdk +util +{latest} ``` -If you are using Contentstack Java SDK, then the Utils SDK is already imported into your project, and the dependency snippet will look as below +If you are using Contentstack Java SDK, then the Utils SDK is already imported into your project, and the dependency +snippet will look as below ```java - com.contentstack.sdk - java - {latest} +com.contentstack.sdk +java +{latest} ``` @@ -40,18 +42,20 @@ Let’s learn how you can use Utils SDK to render embedded items. ### Create Render Option -To render embedded items on the front-end, use the renderContents function, and define the UI elements you want to show in the front-end of your website, as shown in the example code below: +To render embedded items on the front-end, use the renderContents function, and define the UI elements you want to show +in the front-end of your website, as shown in the example code below: ```java package com.contentstack.utils; + import com.contentstack.utils.helper.Metadata; import com.contentstack.utils.interfaces.NodeCallback; -import com.contentstack.utils.interfaces.Option; import com.contentstack.utils.node.MarkType; +import com.contentstack.utils.render.DefaultOption; import org.json.JSONObject; -public class DefaultOptionClass implements Option { +public class DefaultOptionClass extends DefaultOption { @Override public String renderOptions(JSONObject embeddedObject, Metadata metadata) { @@ -69,7 +73,7 @@ public class DefaultOptionClass implements Option { return "

" + embeddedObject.getString("someTitle") + "

" + embeddedObject.getString("multi") + ""; default: - return null; + return super.renderOptions(embeddedObject, metadata); } } @@ -78,7 +82,7 @@ public class DefaultOptionClass implements Option { if (markType == MarkType.BOLD) { return "" + renderText + ""; } - return null; + return super.renderMark(markType, renderText); } @Override @@ -88,94 +92,99 @@ public class DefaultOptionClass implements Option { return "

" + children + "

"; } - return null; + return super.renderNode(nodeType, nodeObject, callback); } } + ``` ### Basic Queries -Contentstack Utils SDK lets you interact with the Content Delivery APIs and retrieve embedded items from the RTE field of an entry. +Contentstack Utils SDK lets you interact with the Content Delivery APIs and retrieve embedded items from the RTE field +of an entry. #### Fetch Embedded Item(s) from a Single Entry -To get an embedded item of a single entry, you need to provide the stack API key, environment name, delivery token, content type’s UID and entry’s UID. Then, use the includeEmbeddedItems function as shown below: +To get an embedded item of a single entry, you need to provide the stack API key, environment name, delivery token, +content type’s UID and entry’s UID. Then, use the includeEmbeddedItems function as shown below: ```java import Contentstack -Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment_name"); -ContentType contentType = stack.contentType("content_type_uid"); -Entry entry = contentType.entry("entry_uid"); -entry.includeEmbeddedItems(); -entry.fetch(new EntryResultCallBack() { - @Override - public void onCompletion(ResponseType responseType, Error error) { - if (error == null) { - // [Success block] - String[] keyPath = { - "rich_text_editor", "global_rich_multiple.group.rich_text_editor" - }; - JSONObject jsonObject = entry.toJSON(); - Utils.render(jsonObject, keyPath, new Option()); - } else { - [Error block] // handle your error +Stack stack=Contentstack.stack("apiKey","deliveryToken","environment_name"); + ContentType contentType=stack.contentType("content_type_uid"); + Entry entry=contentType.entry("entry_uid"); + entry.includeEmbeddedItems(); + entry.fetch(new EntryResultCallBack(){ +@Override +public void onCompletion(ResponseType responseType,Error error){ + if(error==null){ + // [Success block] + String[]keyPath={ + "rich_text_editor","global_rich_multiple.group.rich_text_editor" + }; + JSONObject jsonObject=entry.toJSON(); + Utils.render(jsonObject,keyPath,new Option()); + }else{ + [Error block] // handle your error }} -}); + }); ``` #### Fetch Embedded Item(s) from Multiple Entries -To get embedded items from multiple entries, you need to provide the stack API key, environment name, delivery token, and content type’s UID. +To get embedded items from multiple entries, you need to provide the stack API key, environment name, delivery token, +and content type’s UID. ```java import Contentstack -Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment_name"); -Query query = stack.contentType("content_type_uid").query(); -query.includeEmbeddedItems(); -query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - String[] keyPath = { - "rich_text_editor", "global_rich_multiple.group.rich_text_editor" - }; - for (Entry entry : entries) { - JSONObject jsonObject = entry.toJSON(); - Utils.render(jsonObject, keyPath, new Option()); - } +Stack stack=Contentstack.stack("apiKey","deliveryToken","environment_name"); + Query query=stack.contentType("content_type_uid").query(); + query.includeEmbeddedItems(); + query.find(new QueryResultsCallBack(){ +@Override +public void onCompletion(ResponseType responseType,QueryResult queryResult,Error error){ + if(error==null){ + List entries=queryresult.getResultObjects(); + String[]keyPath={ + "rich_text_editor","global_rich_multiple.group.rich_text_editor" + }; + for(Entry entry:entries){ + JSONObject jsonObject=entry.toJSON(); + Utils.render(jsonObject,keyPath,new Option()); + } }else{ - [Error block] // handle your error - }} -}); + [Error block] // handle your error + }} + }); ``` #### Render JSON RTE Contents -To get multiple entries, you need to provide the stack API key, environment name, delivery token, content type and entry UID. Then, use the Utils.jsonToHTML function as shown below: +To get multiple entries, you need to provide the stack API key, environment name, delivery token, content type and entry +UID. Then, use the Utils.jsonToHTML function as shown below: ```java import Contentstack -Stack stack = Contentstack.stack("apiKey", "deliveryToken", "environment_name"); -Query query = stack.contentType("content_type_uid").query(); -query.includeEmbeddedItems(); // include embedded items -query.find(new QueryResultsCallBack() { - @Override - public void onCompletion(ResponseType responseType, QueryResult queryResult, Error error) { - if (error == null) { - List entries = queryresult.getResultObjects(); - String[] keyPath = { - "rte_fieldUid", "group.rteFieldUID" - }; - for (Entry entry : entries) { - JSONObject jsonObject = entry.toJSON(); - Utils.jsonToHTML(jsonObject, keyPath, new Option()); - } +Stack stack=Contentstack.stack("apiKey","deliveryToken","environment_name"); + Query query=stack.contentType("content_type_uid").query(); + query.includeEmbeddedItems(); // include embedded items + query.find(new QueryResultsCallBack(){ +@Override +public void onCompletion(ResponseType responseType,QueryResult queryResult,Error error){ + if(error==null){ + List entries=queryresult.getResultObjects(); + String[]keyPath={ + "rte_fieldUid","group.rteFieldUID" + }; + for(Entry entry:entries){ + JSONObject jsonObject=entry.toJSON(); + Utils.jsonToHTML(jsonObject,keyPath,new Option()); + } }} -}); + }); ``` diff --git a/src/main/java/com/contentstack/utils/render/DefaultOption.java b/src/main/java/com/contentstack/utils/render/DefaultOption.java index a38a654..b20cb3b 100644 --- a/src/main/java/com/contentstack/utils/render/DefaultOption.java +++ b/src/main/java/com/contentstack/utils/render/DefaultOption.java @@ -7,6 +7,9 @@ import org.apache.commons.text.StringEscapeUtils; import org.json.JSONObject; +import java.util.ArrayList; +import java.util.Arrays; + public class DefaultOption implements Option { @@ -66,58 +69,71 @@ private String escapeInjectHtml(JSONObject nodeObj, String nodeType) { @Override public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback callback) { + + // Get attributes from the nodeObject and render/stringfy using for look by extracting the attributes using key-value pair + // Like below + // attributes = + // + // + // + + // output nodeObject = attributes + + String strAttrs = strAttrs(nodeObject); + + String children = callback.renderChildren(nodeObject.optJSONArray("children")); switch (nodeType) { case "p": - return "

" + children + "

"; + return "" + children + "

"; case "a": - return "" + children + ""; + return "" + children + ""; case "img": String assetLink = getNodeStr(nodeObject, "asset-link"); if (!assetLink.isEmpty()) { - return "" + children; + return "" + children; } - return "" + children; + return "" + children; case "embed": - return ""; case "h1": - return "

" + children + "

"; + return "" + children + ""; case "h2": - return "

" + children + "

"; + return "" + children + ""; case "h3": - return "

" + children + "

"; + return "" + children + ""; case "h4": - return "

" + children + "

"; + return "" + children + ""; case "h5": - return "
" + children + "
"; + return "" + children + ""; case "h6": - return "
" + children + "
"; + return "" + children + ""; case "ol": - return "
    " + children + "
"; + return "" + children + ""; case "ul": - return "
    " + children + "
"; + return "" + children + ""; case "li": - return "
  • " + children + "
  • "; + return "" + children + ""; case "hr": - return "
    "; + return ""; case "table": - return "" + children + "
    "; + return "" + children + "
    "; case "thead": - return "" + children + ""; + return "" + children + ""; case "tbody": - return "" + children + ""; + return "" + children + ""; case "tfoot": - return "" + children + ""; + return "" + children + ""; case "tr": - return "" + children + ""; + return "" + children + ""; case "th": - return "" + children + ""; + return "" + children + ""; case "td": - return "" + children + ""; + return "" + children + ""; case "blockquote": - return "
    " + children + "
    "; + return "" + children + ""; case "code": - return "" + children + ""; + return "" + children + ""; case "reference": return ""; default: @@ -126,6 +142,25 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca } + String strAttrs(JSONObject nodeObject) { + StringBuilder result = new StringBuilder(); + if (nodeObject.has("attrs")) { + JSONObject attrsObject = nodeObject.optJSONObject("attrs"); + if (attrsObject != null && attrsObject.length() > 0) { + for (String key : attrsObject.keySet()) { + String value = attrsObject.getString(key); + String[] ignoreKeys = {"href", "asset-link", "src", "url"}; + ArrayList ignoreKeysList = new ArrayList<>(Arrays.asList(ignoreKeys)); + if (!ignoreKeysList.contains(key)) { + result.append(" ").append(key).append("=\"").append(value).append("\""); + } + } + } + } + return result.toString(); + } + + private String getNodeStr(JSONObject nodeObject, String key) { String herf = nodeObject.optJSONObject("attrs").optString(key); // key might be [href/src] if (herf == null || herf.isEmpty()) { @@ -143,7 +178,6 @@ private String getNodeStr(JSONObject nodeObject, String key) { * @return String */ protected String findTitleOrUid(JSONObject embeddedObject) { - String _title = ""; if (embeddedObject != null) { if (embeddedObject.has("title") && !embeddedObject.optString("title").isEmpty()) { diff --git a/src/test/java/com/contentstack/utils/DefaultOptionClass.java b/src/test/java/com/contentstack/utils/DefaultOptionClass.java new file mode 100644 index 0000000..a8303ff --- /dev/null +++ b/src/test/java/com/contentstack/utils/DefaultOptionClass.java @@ -0,0 +1,48 @@ +package com.contentstack.utils; + +import com.contentstack.utils.helper.Metadata; +import com.contentstack.utils.interfaces.NodeCallback; +import com.contentstack.utils.node.MarkType; +import com.contentstack.utils.render.DefaultOption; +import org.json.JSONObject; + +public class DefaultOptionClass extends DefaultOption { + + @Override + public String renderOptions(JSONObject embeddedObject, Metadata metadata) { + switch (metadata.getStyleType()) { + case BLOCK: + return "

    " + embeddedObject.getString("title") + "

    " + + embeddedObject.getString("multi") + ""; + case INLINE: + return "

    " + embeddedObject.getString("title") + "

    " + + embeddedObject.getString("line") + ""; + case LINK: + return "

    " + embeddedObject.getString("title") + "

    " + + embeddedObject.getString("key") + ""; + case DISPLAY: + return "

    " + embeddedObject.getString("someTitle") + "

    " + + embeddedObject.getString("multi") + ""; + default: + return super.renderOptions(embeddedObject, metadata); + } + } + + @Override + public String renderMark(MarkType markType, String renderText) { + if (markType == MarkType.BOLD) { + return "" + renderText + ""; + } + return super.renderMark(markType, renderText); + } + + @Override + public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback callback) { + if (nodeType.equalsIgnoreCase("paragraph")) { + String children = callback.renderChildren(nodeObject.optJSONArray("children")); + return "

    " + children + "

    "; + } + + return super.renderNode(nodeType, nodeObject, callback); + } +} diff --git a/src/test/java/com/contentstack/utils/UtilTests.java b/src/test/java/com/contentstack/utils/UtilTests.java index 75a7539..fd15c16 100644 --- a/src/test/java/com/contentstack/utils/UtilTests.java +++ b/src/test/java/com/contentstack/utils/UtilTests.java @@ -1,9 +1,7 @@ package com.contentstack.utils; -import com.contentstack.utils.embedded.StyleType; import com.contentstack.utils.render.DefaultOption; import org.json.JSONObject; -import org.json.simple.JSONArray; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; @@ -13,8 +11,6 @@ import java.util.logging.Level; import java.util.logging.Logger; -import static com.contentstack.utils.embedded.StyleType.*; - @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UtilTests { @@ -41,14 +37,14 @@ public void testRenderFunction() { Utils.render(localJsonObj, keys, new DefaultOption()); } - @Test - public void testWithoutKeyPath() { - String[] keys = new String[2]; - keys[0] = "global_rich_multiple.group.rich_text_editor"; - keys[1] = "global_rich_multiple.group.rich_text_editor_multiple"; - Utils.render(localJsonObj, null, new DefaultOption()); - } - +// @Test +// public void testWithoutKeyPath() { +// String[] keys = new String[2]; +// keys[0] = "global_rich_multiple.group.rich_text_editor"; +// keys[1] = "global_rich_multiple.group.rich_text_editor_multiple"; +// Utils.render(localJsonObj, null, new DefaultOption()); +// } +// // @Test // public void testEmbeddedBlockEntry() { // JSONArray rteArray = null; @@ -107,7 +103,7 @@ public void testWithoutKeyPath() { // } // }); // } -// + // @Test // public void testEmbeddedLinkEntry() { // JSONArray rteArray = null; @@ -159,4 +155,20 @@ public void testWithoutKeyPath() { // }); // } + + @Test + public void testCustomJSONRTE() { + + + JSONObject rteObject = new JSONObject(); + String[] keyPath = { + "rich_text_editor", "global_rich_multiple.group.rich_text_editor" + }; + Utils.jsonToHTML(rteObject, keyPath, new DefaultOptionClass()); + } + + } + + + diff --git a/src/test/resources/issue/newline.json b/src/test/resources/issue/newline.json index 994916c..8fd0a76 100644 --- a/src/test/resources/issue/newline.json +++ b/src/test/resources/issue/newline.json @@ -8,8 +8,10 @@ "text": "First Heading" } ], - "type": "p", - "attrs": {} + "type": "hangout-chat", + "attrs": { + "from": "Paul, Addy" + } }, { "uid": "3c5625fac71c42a7b22b82f7d2370b77", @@ -18,7 +20,7 @@ "text": "This is the article text" } ], - "type": "p", + "type": "hangout-discussion", "attrs": {} }, { From 47fcf8c31811d662233d27fea229eceedfbf4023 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Mon, 31 Jul 2023 23:52:18 +0530 Subject: [PATCH 2/8] Update pom.xml --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 09a6217..258a951 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ com.contentstack.sdk utils - 1.2.2 + 1.2.3 jar Contentstack-utils Java Utils SDK for Contentstack Content Delivery API, Contentstack is a headless CMS @@ -237,4 +237,4 @@ - \ No newline at end of file + From fdc2e43f0ff8be21b8a0d529857772fa06390c43 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Wed, 2 Aug 2023 12:58:09 +0530 Subject: [PATCH 3/8] removed secrets-scan.yml support --- .github/workflows/secrets-scan.yml | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 .github/workflows/secrets-scan.yml diff --git a/.github/workflows/secrets-scan.yml b/.github/workflows/secrets-scan.yml deleted file mode 100644 index 1e8f176..0000000 --- a/.github/workflows/secrets-scan.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: Secrets Scan -on: - pull_request: - types: [opened, synchronize, reopened] -jobs: - security: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Gittyleaks - uses: gupy-io/gittyleaks-action@v0.1 \ No newline at end of file From dc012354bdbdfce404a68807fc1b375676706612 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Wed, 2 Aug 2023 16:45:46 +0530 Subject: [PATCH 4/8] removed comment from DefaultOption --- .idea/.gitignore | 8 ++++++++ .../com/contentstack/utils/AutomateCommon.java | 18 ++++++------------ .../utils/render/DefaultOption.java | 11 +---------- 3 files changed, 15 insertions(+), 22 deletions(-) create mode 100644 .idea/.gitignore diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/src/main/java/com/contentstack/utils/AutomateCommon.java b/src/main/java/com/contentstack/utils/AutomateCommon.java index e9d6c17..d34dc4f 100644 --- a/src/main/java/com/contentstack/utils/AutomateCommon.java +++ b/src/main/java/com/contentstack/utils/AutomateCommon.java @@ -31,12 +31,9 @@ private AutomateCommon() { /** * Find dot separated keys * - * @param entryObj - * Json Object - * @param path - * keyPath - * @param contentCallback - * content callback + * @param entryObj Json Object + * @param path keyPath + * @param contentCallback content callback */ protected static void findContent(JSONObject entryObj, String path, ContentCallback contentCallback) { String[] arrayString = path.split("\\."); @@ -45,12 +42,9 @@ protected static void findContent(JSONObject entryObj, String path, ContentCallb /** - * @param arrayString - * list of keys available - * @param entryObj - * entry object - * @param contentCallback - * content callback + * @param arrayString list of keys available + * @param entryObj entry object + * @param contentCallback content callback */ private static void getContent(String[] arrayString, JSONObject entryObj, ContentCallback contentCallback) { if (arrayString != null && arrayString.length != 0) { diff --git a/src/main/java/com/contentstack/utils/render/DefaultOption.java b/src/main/java/com/contentstack/utils/render/DefaultOption.java index b20cb3b..8368321 100644 --- a/src/main/java/com/contentstack/utils/render/DefaultOption.java +++ b/src/main/java/com/contentstack/utils/render/DefaultOption.java @@ -70,15 +70,6 @@ private String escapeInjectHtml(JSONObject nodeObj, String nodeType) { @Override public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback callback) { - // Get attributes from the nodeObject and render/stringfy using for look by extracting the attributes using key-value pair - // Like below - // attributes = - // - // - // - - // output nodeObject = attributes - String strAttrs = strAttrs(nodeObject); @@ -146,7 +137,7 @@ String strAttrs(JSONObject nodeObject) { StringBuilder result = new StringBuilder(); if (nodeObject.has("attrs")) { JSONObject attrsObject = nodeObject.optJSONObject("attrs"); - if (attrsObject != null && attrsObject.length() > 0) { + if (attrsObject != null && !attrsObject.isEmpty()) { for (String key : attrsObject.keySet()) { String value = attrsObject.getString(key); String[] ignoreKeys = {"href", "asset-link", "src", "url"}; From 6ab4a6b5edfe56e11296d3d44c72b94eefff0105 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Mon, 7 Aug 2023 15:12:11 +0530 Subject: [PATCH 5/8] document formated --- pom.xml | 2 +- .../contentstack/utils/AutomateCommon.java | 98 +++++++++++- src/main/java/com/contentstack/utils/GQL.java | 45 +++--- .../java/com/contentstack/utils/Utils.java | 144 ++++++++++-------- .../contentstack/utils/embedded/ItemType.java | 8 +- .../utils/embedded/StyleType.java | 4 +- .../contentstack/utils/helper/Metadata.java | 63 +++++--- .../utils/interfaces/ContentCallback.java | 9 +- .../utils/interfaces/MetaToEmbedCallback.java | 10 +- .../utils/interfaces/MetadataCallback.java | 7 +- .../utils/interfaces/NodeCallback.java | 10 +- .../contentstack/utils/interfaces/Option.java | 53 ++++--- .../com/contentstack/utils/node/MarkType.java | 7 +- .../contentstack/utils/node/NodeToHTML.java | 19 ++- .../utils/render/DefaultOption.java | 81 ++++++++-- .../com/contentstack/utils/AssetLinkTest.java | 2 - .../utils/DefaultOptionClass.java | 1 - .../utils/DefaultOptionTests.java | 1 - .../utils/EmbeddedModelTests.java | 1 - .../java/com/contentstack/utils/TestRte.java | 18 +-- 20 files changed, 388 insertions(+), 195 deletions(-) diff --git a/pom.xml b/pom.xml index 258a951..6cce317 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ 2.5.3 2.0.1.Final 20230227 - 6.0.7 + 6.0.11 1.10.0 diff --git a/src/main/java/com/contentstack/utils/AutomateCommon.java b/src/main/java/com/contentstack/utils/AutomateCommon.java index d34dc4f..4927b06 100644 --- a/src/main/java/com/contentstack/utils/AutomateCommon.java +++ b/src/main/java/com/contentstack/utils/AutomateCommon.java @@ -29,11 +29,16 @@ private AutomateCommon() { } /** - * Find dot separated keys + * The function "findContent" splits a given path string into an array of strings, and then calls the + * "getContent" function with the array, a JSONObject, and a contentCallback as parameters. * - * @param entryObj Json Object - * @param path keyPath - * @param contentCallback content callback + * @param entryObj A JSONObject that contains the data you want to search through. + * @param path The `path` parameter is a string that represents the path to a specific content in a + * JSON object. It is used to navigate through the JSON object and find the desired content. + * @param contentCallback The `contentCallback` parameter is an instance of the `ContentCallback` + * interface. It is used to provide a callback mechanism for handling the content found during the + * search process. The `ContentCallback` interface typically defines a method that will be called with + * the content found at each step of the search. */ protected static void findContent(JSONObject entryObj, String path, ContentCallback contentCallback) { String[] arrayString = path.split("\\."); @@ -42,9 +47,15 @@ protected static void findContent(JSONObject entryObj, String path, ContentCallb /** - * @param arrayString list of keys available - * @param entryObj entry object - * @param contentCallback content callback + * The function `getContent` recursively traverses a JSON object and modifies its content based on + * a callback function. + * + * @param arrayString An array of strings representing the path to the content in the JSON object. + * @param entryObj The `entryObj` parameter is a JSONObject that contains the data to be processed. + * @param contentCallback The `contentCallback` parameter is an instance of the `ContentCallback` + * interface. This interface defines a method called `contentObject()` which takes an object as + * input and returns a modified version of that object. The purpose of this callback is to allow + * the caller of the `getContent()` method to customize */ private static void getContent(String[] arrayString, JSONObject entryObj, ContentCallback contentCallback) { if (arrayString != null && arrayString.length != 0) { @@ -71,6 +82,20 @@ private static void getContent(String[] arrayString, JSONObject entryObj, Conten } + /** + * The function returns a string representation of an option by rendering it with the provided + * content and metadata, falling back to default options if necessary. + * + * @param option The "option" parameter is an object of type Option, which represents a specific + * option that can be rendered. It likely has properties and methods that allow it to generate the + * desired output based on the provided content and metadata. + * @param metadata Metadata is an object that contains additional information about the option. It + * may include details such as the option's label, description, and any other relevant information. + * @param contentToPass The `contentToPass` parameter is a `JSONObject` that contains the data or + * content that needs to be passed to the `renderOptions` method of the `Option` or `DefaultOption` + * class. This data or content is used to generate the string representation of the option. + * @return The method is returning a string value. + */ protected static String getStringOption(Option option, Metadata metadata, JSONObject contentToPass) { String stringOption = option.renderOptions(contentToPass, metadata); if (stringOption == null) { @@ -81,6 +106,17 @@ protected static String getStringOption(Option option, Metadata metadata, JSONOb } + /** + * The function retrieves embedded objects from an HTML document and passes them to a callback + * function for further processing. + * + * @param html The "html" parameter is a Document object that represents an HTML document. It is + * used to extract embedded objects from the HTML document. + * @param metadataCallback The `metadataCallback` parameter is an instance of a class that + * implements the `MetadataCallback` interface. This interface defines a method called + * `embeddedObject` which is called for each embedded object found in the HTML document. The + * `embeddedObject` method takes a `Metadata` object as a parameter, + */ protected static void getEmbeddedObjects(Document html, MetadataCallback metadataCallback) { Elements embeddedEntries = html.body().getElementsByClass("embedded-entry"); Elements embeddedAssets = html.body().getElementsByClass("embedded-asset"); @@ -107,6 +143,16 @@ protected static void getEmbeddedObjects(Document html, MetadataCallback metadat } + /** + * The function takes a JSONArray of content, iterates through each element, and calls another + * function to render and enumerate the content, returning a JSONArray of the rendered content. + * + * @param contentArray A JSONArray containing the content to be enumerated. + * @param renderObject The renderObject parameter is an instance of the Option class. + * @param item The "item" parameter is a callback function that takes in a "Meta" object and + * returns a value to be embedded in the rendered content. + * @return The method is returning a JSONArray object. + */ protected static Object enumerateContents(JSONArray contentArray, Option renderObject, MetaToEmbedCallback item) { JSONArray jsonArrayRTEContent = new JSONArray(); for (Object RTE : contentArray) { @@ -117,8 +163,19 @@ protected static Object enumerateContents(JSONArray contentArray, Option renderO return jsonArrayRTEContent; } + /** + * The function checks if a JSON object has a specific type and children, and if so, it performs + * some processing on the children. + * + * @param jsonObject A JSONObject that contains the content to be enumerated. + * @param renderObject The `renderObject` parameter is of type `Option`. It is used as an argument + * in the `doRawProcessing` method. + * @param item The "item" parameter is a callback function that takes in a "Meta" object and returns + * a string. + * @return An empty string. + */ protected static String enumerateContent(JSONObject jsonObject, Option renderObject, MetaToEmbedCallback item) { - if (jsonObject.length() > 0 && jsonObject.has("type") && jsonObject.has("children")) { + if (!jsonObject.isEmpty() && jsonObject.has("type") && jsonObject.has("children")) { if (jsonObject.opt("type").equals("doc")) { return doRawProcessing(jsonObject.optJSONArray("children"), renderObject, item); } @@ -127,6 +184,17 @@ protected static String enumerateContent(JSONObject jsonObject, Option renderObj } + /** + * The function `doRawProcessing` processes a JSONArray of children, extracting keys from each + * child and appending the results to a StringBuilder, then returns the final string. + * + * @param children A JSONArray containing the children items to process. + * @param renderObject The parameter "renderObject" is of type "Option". It is used as an option to + * specify how the keys should be rendered during processing. + * @param embedItem The `embedItem` parameter is a callback function that takes a `Meta` object as + * input and returns an embedded representation of that object. + * @return The method is returning a string. + */ private static String doRawProcessing(@NotNull JSONArray children, Option renderObject, MetaToEmbedCallback embedItem) { StringBuilder stringBuilder = new StringBuilder(); children.forEach(item -> { @@ -140,6 +208,20 @@ private static String doRawProcessing(@NotNull JSONArray children, Option render } + /** + * The function extracts keys from a JSON object and returns a string based on the type of the + * node. + * + * @param jsonNode The `jsonNode` parameter is a `JSONObject` that represents a node in a JSON + * structure. It is used to extract information from the node and perform certain operations based + * on its properties. + * @param renderObject The `renderObject` parameter is an object of type `Option`. It is used to + * specify rendering options for the extracted keys. + * @param embedItem The `embedItem` parameter is a callback function that takes a `Metadata` object + * as input and returns an optional `JSONObject`. This callback is used to embed metadata into the + * rendered content. + * @return The method is returning a String. + */ private static String extractKeys(@NotNull JSONObject jsonNode, Option renderObject, MetaToEmbedCallback embedItem) { if (!jsonNode.has("type") && jsonNode.has("text")) { diff --git a/src/main/java/com/contentstack/utils/GQL.java b/src/main/java/com/contentstack/utils/GQL.java index 71fb2f8..9a439b9 100644 --- a/src/main/java/com/contentstack/utils/GQL.java +++ b/src/main/java/com/contentstack/utils/GQL.java @@ -12,28 +12,35 @@ import static com.contentstack.utils.AutomateCommon.*; -/** - * The type Gql. - */ + public class GQL { + // The `private GQL() throws IllegalAccessException` is a private constructor of the `GQL` class. It is +// throwing an `IllegalAccessException` with a message "Invalid Access! Could not create instance of +// GQL". private GQL() throws IllegalAccessException { throw new IllegalAccessException("Invalid Access! Could not create instance of GQL"); } + // The line `static JSONArray embeddedItems = null` declares a static variable named + // `embeddedItems` of type `JSONArray` and initializes it with a value of `null`. This + // variable is used to store the embedded items extracted from the GraphQL entry object + // during the conversion process. private static JSONArray embeddedItems = null; + /** - * Json to html. + * The function `jsonToHTML` converts a JSON object to HTML based on a given path and render + * option. * - * @param gqlEntry - * the gql entry is entry @{@link JSONObject} - * @param path - * the path is array of @{@link String} - * @param renderOption - * the render option is instance of @{@link DefaultOption} + * @param gqlEntry The `gqlEntry` parameter is a JSONObject that represents the GraphQL entry + * object. It contains the data that needs to be converted to HTML. + * @param path An array of strings representing the path to the desired content in the JSON object. + * @param renderOption The `renderOption` parameter is of type `DefaultOption` and is used to + * specify the rendering options for the HTML output. It is an enum that contains different options + * for rendering the content. */ public static void jsonToHTML(@NotNull JSONObject gqlEntry, @NotNull String[] path, @NotNull DefaultOption renderOption) { @@ -49,16 +56,14 @@ public static void jsonToHTML(@NotNull JSONObject gqlEntry, @NotNull String[] pa if (contentDict.has("json")) { MetaToEmbedCallback converter = metadata -> { if (embeddedItems != null) { - Optional filteredContent = StreamSupport.stream(embeddedItems.spliterator(), false) - .map(JSONObject.class::cast) - .filter(itemDict -> { - JSONObject nodeObject = itemDict.optJSONObject("node"); - if (nodeObject.has("uid")) { - String uid = nodeObject.optString("uid"); - return uid.equals(metadata.getItemUid()); - } - return false; - }).findFirst(); + Optional filteredContent = StreamSupport.stream(embeddedItems.spliterator(), false).map(JSONObject.class::cast).filter(itemDict -> { + JSONObject nodeObject = itemDict.optJSONObject("node"); + if (nodeObject.has("uid")) { + String uid = nodeObject.optString("uid"); + return uid.equals(metadata.getItemUid()); + } + return false; + }).findFirst(); if (filteredContent.isPresent()) { return filteredContent; } diff --git a/src/main/java/com/contentstack/utils/Utils.java b/src/main/java/com/contentstack/utils/Utils.java index aa19971..aa41786 100644 --- a/src/main/java/com/contentstack/utils/Utils.java +++ b/src/main/java/com/contentstack/utils/Utils.java @@ -13,30 +13,23 @@ import java.util.ArrayList; import java.util.Optional; import java.util.Set; -import java.util.logging.Logger; import java.util.stream.StreamSupport; import static com.contentstack.utils.AutomateCommon.*; -/** - * The Utils Class enables few functions like render, renderContent, jsonToHtml, RTE and SRTE to process the entry data - * and converts in html format. - */ public class Utils { - static final Logger logger = Logger.getLogger(Utils.class.getName()); - /** - * Render. + * 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 entry obj - * @param pathString - * the key path - * @param renderObject - * the render object + * @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) { @@ -70,15 +63,18 @@ public static void render(JSONObject entryObj, String[] pathString, Option rende /** - * Render content string. + * 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 rte stringify - * @param embedObject - * the embed object - * @param option - * the option - * @return the string + * @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}; @@ -99,6 +95,18 @@ public static String renderContent(String rteStringify, JSONObject embedObject, 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) { @@ -113,9 +121,7 @@ private static Optional findEmbeddedItems(JSONObject jsonObject, Met Set allKeys = jsonObject.keySet(); for (String key : allKeys) { JSONArray jsonArray = jsonObject.optJSONArray(key); - Optional filteredContent = StreamSupport.stream(jsonArray.spliterator(), false) - .map(val -> (JSONObject) val) - .filter(val -> val.optString("uid").equalsIgnoreCase(metadata.getItemUid())).findFirst(); + Optional filteredContent = StreamSupport.stream(jsonArray.spliterator(), false).map(val -> (JSONObject) val).filter(val -> val.optString("uid").equalsIgnoreCase(metadata.getItemUid())).findFirst(); if (filteredContent.isPresent()) { return filteredContent; } @@ -124,14 +130,14 @@ private static Optional findEmbeddedItems(JSONObject jsonObject, Met } /** - * Json to html. + * The function converts a JSONArray to HTML using a specified key path and options. * - * @param entryArray - * the entry array - * @param keyPath - * the key path - * @param option - * the render option + * @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)); @@ -139,14 +145,19 @@ public static void jsonToHTML(@NotNull JSONArray entryArray, @NotNull String[] k /** - * Json to html. + * The function `jsonToHTML` converts a JSON object to HTML using a specified key path and + * rendering options. * - * @param entry - * the entry - * @param keyPath - * the key path - * @param renderOption - * the render object + * @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) { @@ -172,25 +183,22 @@ public static void jsonToHTML(@NotNull JSONObject entry, @NotNull String[] keyPa return null; }; - if (keyPath.length > 0) { - for (String path : keyPath) { - logger.info(path); - findContent(entry, path, callback); - } + for (String path : keyPath) { + findContent(entry, path, callback); } } /** - * Converts jsonRTE to String + * The function converts a JSON object to HTML using a specified rendering option and optional embedded + * items. * - * @param jsonRTE - * The JsonRTE object {@link JSONObject} - * @param renderOption - * The Option Interface - * @param embeddeditems - * The Embedded Objects {@link JSONObject} - * @return String + * @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 `embeddeditems` 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 -> { @@ -202,14 +210,18 @@ public static String jsonToHTML(@NotNull JSONObject jsonRTE, Option renderOption return enumerateContent(jsonRTE, renderOption, converter); } + /** - * @param jsonRTE - * The JsonRTE Array {@link JSONArray} - * @param renderOption - * The Option Interface - * @param embeddeditems - * The Embedded Objects {@link JSONObject} - * @return String + * 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 `embeddeditems` 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 -> { @@ -223,14 +235,14 @@ public static Object jsonToHTML(@NotNull JSONArray jsonRTE, Option renderOption, /** - * Render. + * 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 - * the json array - * @param keyPath - * the key path - * @param renderObject - * the render object + * @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)); diff --git a/src/main/java/com/contentstack/utils/embedded/ItemType.java b/src/main/java/com/contentstack/utils/embedded/ItemType.java index 410c751..f190aeb 100644 --- a/src/main/java/com/contentstack/utils/embedded/ItemType.java +++ b/src/main/java/com/contentstack/utils/embedded/ItemType.java @@ -1,9 +1,9 @@ package com.contentstack.utils.embedded; -/** - * ItemType: there are two types of Item - * Which is ENTRY and ASSET - */ + +// The code snippet is defining an enumeration called `ItemType` with two possible values: `ENTRY` and +// `ASSET`. This enum is used to represent different types of items, specifically in the context of the +// `com.contentstack.utils.embedded` package. public enum ItemType { ENTRY, ASSET } diff --git a/src/main/java/com/contentstack/utils/embedded/StyleType.java b/src/main/java/com/contentstack/utils/embedded/StyleType.java index aa4d546..863046c 100644 --- a/src/main/java/com/contentstack/utils/embedded/StyleType.java +++ b/src/main/java/com/contentstack/utils/embedded/StyleType.java @@ -15,8 +15,8 @@ *

    * [`Example`]: *

    - * For `Entry`: StyleType.BLOCK, StyleType.INLINE, StyleType.LINKED, For `Assets`: StyleType. DISPLAY and StyleType. - * DOWNLOAD + * For `Entry`: StyleType.BLOCK, StyleType.INLINE, StyleType.LINKED, + * For `Assets`: StyleType. DISPLAY and StyleType.DOWNLOAD */ public enum StyleType { BLOCK, INLINE, LINK, DISPLAY, DOWNLOAD, diff --git a/src/main/java/com/contentstack/utils/helper/Metadata.java b/src/main/java/com/contentstack/utils/helper/Metadata.java index 6d184b7..bf77828 100644 --- a/src/main/java/com/contentstack/utils/helper/Metadata.java +++ b/src/main/java/com/contentstack/utils/helper/Metadata.java @@ -14,24 +14,9 @@ public class Metadata { String outerHTML; Attributes attributes; - /** - * Instantiates a new Metadata. - * - * @param text - * the text - * @param itemType - * the item type - * @param itemUid - * the item uid - * @param contentTypeUid - * the content type uid - * @param styleType - * the style type - * @param outerHTML - * the outer html - * @param attributes - * the attributes - */ + + // The `public Metadata` constructor is initializing the values of the `Metadata` class with the + // provided parameters. public Metadata(String text, String itemType, String itemUid, String contentTypeUid, String styleType, String outerHTML, Attributes attributes) { this.text = text; @@ -43,6 +28,13 @@ public Metadata(String text, String itemType, String itemUid, String contentType this.attributes = attributes; } + /** + * The toString() function returns a string representation of the EmbeddedObject object. + * + * @return The `toString()` method is returning a string representation of an `EmbeddedObject` object. + * The returned string includes the values of the `text`, `itemType`, `itemUid`, `contentTypeUid`, + * `styleType`, `outerHTML`, and `attributes` properties of the object. + */ @Override public String toString() { return "EmbeddedObject{" + @@ -56,30 +48,65 @@ public String toString() { '}'; } + /** + * The getText() function returns the value of the text variable. + * + * @return The method is returning a String value. + */ public String getText() { return text; } + /** + * The getItemType() function returns the type of an item. + * + * @return The method is returning the value of the variable "itemType". + */ public String getItemType() { return itemType; } + /** + * The function returns the attributes of an object. + * + * @return The method is returning an object of type Attributes. + */ public Attributes getAttributes() { return attributes; } + /** + * The getItemUid() function returns the itemUid value. + * + * @return The method is returning the value of the variable "itemUid". + */ public String getItemUid() { return itemUid; } + /** + * The function returns the content type UID as a string. + * + * @return The method is returning the value of the variable "contentTypeUid". + */ public String getContentTypeUid() { return contentTypeUid; } + /** + * The function returns the value of the styleType variable. + * + * @return The method is returning the value of the variable "styleType" of type StyleType. + */ public StyleType getStyleType() { return styleType; } + /** + * The getOuterHTML() function returns the outer HTML of an element. + * + * @return The method is returning the value of the variable "outerHTML". + */ public String getOuterHTML() { return outerHTML; } diff --git a/src/main/java/com/contentstack/utils/interfaces/ContentCallback.java b/src/main/java/com/contentstack/utils/interfaces/ContentCallback.java index e2ccd28..713a5db 100644 --- a/src/main/java/com/contentstack/utils/interfaces/ContentCallback.java +++ b/src/main/java/com/contentstack/utils/interfaces/ContentCallback.java @@ -5,12 +5,13 @@ * The interface Content. */ public interface ContentCallback { + /** - * Content object object. + * The function contentObject takes an object as input and returns an object as output. * - * @param content - * the content - * @return the object + * @param content The content parameter is an object that represents the content to be passed to + * the contentObject function. + * @return The contentObject is being returned. */ Object contentObject(Object content); } diff --git a/src/main/java/com/contentstack/utils/interfaces/MetaToEmbedCallback.java b/src/main/java/com/contentstack/utils/interfaces/MetaToEmbedCallback.java index d6d8c65..13cbedc 100644 --- a/src/main/java/com/contentstack/utils/interfaces/MetaToEmbedCallback.java +++ b/src/main/java/com/contentstack/utils/interfaces/MetaToEmbedCallback.java @@ -10,12 +10,14 @@ * The interface Meta to embed. */ public interface MetaToEmbedCallback { + /** - * To embed optional. + * The function "toEmbed" takes in a Metadata object and returns an Optional object containing a + * JSONObject. * - * @param metadata - * the metadata - * @return the optional + * @param metadata The metadata parameter is an object that contains information about a resource, + * such as its title, description, and URL. + * @return The method is returning an Optional object that contains a JSONObject. */ Optional toEmbed(Metadata metadata); } diff --git a/src/main/java/com/contentstack/utils/interfaces/MetadataCallback.java b/src/main/java/com/contentstack/utils/interfaces/MetadataCallback.java index 3232760..f2f99e6 100644 --- a/src/main/java/com/contentstack/utils/interfaces/MetadataCallback.java +++ b/src/main/java/com/contentstack/utils/interfaces/MetadataCallback.java @@ -7,11 +7,12 @@ * The interface Metadata callback. */ public interface MetadataCallback { + /** - * Embedded object. + * The function "embeddedObject" takes a Metadata object as a parameter. * - * @param metadata - * the metadata + * @param metadata The metadata parameter is an object of type Metadata. It is used to pass + * additional information or data to the embeddedObject function. */ void embeddedObject(Metadata metadata); } diff --git a/src/main/java/com/contentstack/utils/interfaces/NodeCallback.java b/src/main/java/com/contentstack/utils/interfaces/NodeCallback.java index caf04eb..891a588 100644 --- a/src/main/java/com/contentstack/utils/interfaces/NodeCallback.java +++ b/src/main/java/com/contentstack/utils/interfaces/NodeCallback.java @@ -6,12 +6,14 @@ * The interface Node callback. */ public interface NodeCallback { + /** - * Render children string. + * The function takes a JSONArray of nodes and returns a string representation of their children. * - * @param nodeJsonArray - * the node json array - * @return the string + * @param nodeJsonArray The `nodeJsonArray` parameter is a JSONArray object that contains a + * collection of JSON objects representing nodes. Each JSON object represents a node and contains + * information about the node's properties and children. + * @return The method is returning a String. */ String renderChildren(JSONArray nodeJsonArray); } diff --git a/src/main/java/com/contentstack/utils/interfaces/Option.java b/src/main/java/com/contentstack/utils/interfaces/Option.java index 2dca2d1..cccd1c3 100644 --- a/src/main/java/com/contentstack/utils/interfaces/Option.java +++ b/src/main/java/com/contentstack/utils/interfaces/Option.java @@ -5,42 +5,49 @@ import org.json.JSONObject; -/** - * The interface Option. - */ +// The `Option` interface defines a set of methods that can be implemented by classes to provide +// rendering options for different types of content. public interface Option { + /** - * Render options string. + * The function takes in a JSON object and metadata, and returns a string representation of the + * options rendered from the embedded object. * - * @param embeddedObject - * the embedded object - * @param metadata - * the metadata - * @return the string + * @param embeddedObject The embeddedObject parameter is a JSONObject that contains the data to be + * rendered. It can be any valid JSON object that you want to render or display in some way. + * @param metadata Metadata is an object that contains additional information about the embedded + * object. It can include properties such as the object's type, size, creation date, and any other + * relevant information. + * @return The method is returning a String. */ String renderOptions(JSONObject embeddedObject, Metadata metadata); + /** - * Render mark string. + * The function "renderMark" takes a MarkType and a String as input and returns a formatted version + * of the String based on the MarkType. * - * @param markType - * the mark type - * @param renderText - * the render text - * @return the string + * @param markType The markType parameter is of type MarkType, which is an enumeration representing + * different types of marks that can be applied to a text. + * @param renderText The `renderText` parameter is a string that represents the text that needs to + * be rendered. + * @return The renderMark method returns a string. */ String renderMark(MarkType markType, String renderText); + /** - * Render node string. + * The function "renderNode" takes in a node type, a JSON object representing the node, and a + * callback function, and returns a string. * - * @param nodeType - * the node type - * @param nodeObject - * the node object - * @param callback - * the callback - * @return the string + * @param nodeType A string representing the type of the node. This could be any valid string value + * that identifies the type of the node, such as "div", "span", "p", etc. + * @param nodeObject The `nodeObject` parameter is a JSONObject that represents a node in a tree + * structure. It contains information about the node, such as its properties and children. + * @param callback The callback parameter is a function that will be called after the node has been + * rendered. It allows you to perform additional actions or manipulate the rendered node in some + * way. + * @return The method is returning a String. */ String renderNode(String nodeType, JSONObject nodeObject, NodeCallback callback); } diff --git a/src/main/java/com/contentstack/utils/node/MarkType.java b/src/main/java/com/contentstack/utils/node/MarkType.java index 4c94b3a..421fbd3 100644 --- a/src/main/java/com/contentstack/utils/node/MarkType.java +++ b/src/main/java/com/contentstack/utils/node/MarkType.java @@ -1,8 +1,9 @@ package com.contentstack.utils.node; -/** - * The enum Mark type. - */ + +// The code snippet is defining an enumeration called `MarkType`. An enumeration is a special type in +// Java that represents a fixed set of constants. In this case, the `MarkType` enumeration represents +// different types of text formatting marks. public enum MarkType { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH, INLINECODE, SUBSCRIPT, SUPERSCRIPT, BREAK, } diff --git a/src/main/java/com/contentstack/utils/node/NodeToHTML.java b/src/main/java/com/contentstack/utils/node/NodeToHTML.java index da05ee8..0c0df09 100644 --- a/src/main/java/com/contentstack/utils/node/NodeToHTML.java +++ b/src/main/java/com/contentstack/utils/node/NodeToHTML.java @@ -3,8 +3,10 @@ import com.contentstack.utils.interfaces.Option; import org.json.JSONObject; + /** - * The type Node to html. + * The NodeToHTML class provides a method to convert a text node in JSON format to an HTML string, + * applying various rendering options. */ public class NodeToHTML { @@ -13,14 +15,17 @@ private NodeToHTML() { throw new IllegalStateException("Could not create instance of NodeToHTML"); } + /** - * Text node to html string. + * The function converts a JSON object representing a text node into HTML, applying various + * formatting options based on the provided renderOption. * - * @param nodeText - * the node text - * @param renderOption - * the render option - * @return the string + * @param nodeText The `nodeText` parameter is a JSONObject that represents a text node. It + * contains various options for rendering the text, such as superscript, subscript, inline code, + * strikethrough, underline, italic, bold, and line break. + * @param renderOption The renderOption parameter is an object of type Option. It is used to + * specify the rendering options for the text node. + * @return The method returns the modified text after applying the specified rendering options. */ public static String textNodeToHTML(JSONObject nodeText, Option renderOption) { String text = nodeText.optString("text"); diff --git a/src/main/java/com/contentstack/utils/render/DefaultOption.java b/src/main/java/com/contentstack/utils/render/DefaultOption.java index 8368321..8009a08 100644 --- a/src/main/java/com/contentstack/utils/render/DefaultOption.java +++ b/src/main/java/com/contentstack/utils/render/DefaultOption.java @@ -14,13 +14,16 @@ public class DefaultOption implements Option { /** - * Accepts below params to provide defaults options + * The function `renderOptions` takes in a JSON object and metadata and returns a string based on the + * style type of the metadata. * - * @param embeddedObject - * entry embedded object - * @param metadata - * for of the entry object - * @return String as a result + * @param embeddedObject The embeddedObject parameter is a JSONObject that contains the data of the + * embedded object. It may have different properties depending on the type of object being embedded. + * @param metadata The `metadata` parameter is an object of type `Metadata` which contains information + * about the style type of the embedded object. It has a method `getStyleType()` which returns the + * style type of the embedded object. + * @return The method is returning a string based on the value of the `metadata.getStyleType()` + * parameter. The returned string depends on the style type and the content of the `embeddedObject`. */ @Override public String renderOptions(JSONObject embeddedObject, Metadata metadata) { @@ -38,6 +41,18 @@ public String renderOptions(JSONObject embeddedObject, Metadata metadata) { } } + /** + * The function takes a mark type and text as input and returns the text wrapped in HTML tags based on + * the mark type. + * + * @param markType The `markType` parameter is of type `MarkType` and represents the type of formatting + * to be applied to the `text` parameter. The `MarkType` enum contains the following values: + * @param text The `text` parameter is a string that represents the content that needs to be rendered + * with the specified mark type. + * @return The method returns a string that represents the given text with the specified mark type + * applied. If the mark type is not recognized, the method returns the original text without any + * modifications. + */ @Override public String renderMark(MarkType markType, String text) { switch (markType) { @@ -67,6 +82,23 @@ private String escapeInjectHtml(JSONObject nodeObj, String nodeType) { return StringEscapeUtils.escapeHtml4(injectedHtml); } + /** + * The function takes in a node type and a JSON object representing a node, and returns the + * corresponding HTML string representation of the node. + * + * @param nodeType The `nodeType` parameter is a String that represents the type of HTML element to + * be rendered. It can have values such as "p", "a", "img", "embed", "h1", "h2", "h3", "h4", "h5", + * "h + * @param nodeObject The `nodeObject` parameter is a JSONObject that contains the properties and + * values of a node in a tree structure. It represents a specific node in the tree that needs to be + * rendered. + * @param callback The `callback` parameter is an instance of the `NodeCallback` interface. It is + * used to render the children of the current node. The `renderChildren` method of the `callback` + * is called with the `children` JSON array of the current node as the argument. The + * `renderChildren + * @return The method `renderNode` returns a string representation of an HTML element based on the + * given `nodeType` and `nodeObject`. + */ @Override public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback callback) { @@ -133,6 +165,14 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca } + /** + * The function takes a JSONObject as input and returns a string containing the attributes and + * their values, excluding certain keys. + * + * @param nodeObject A JSONObject representing a node in a tree structure. + * @return The method is returning a string representation of the attributes (key-value pairs) in + * the given JSONObject, excluding certain keys specified in the ignoreKeys array. + */ String strAttrs(JSONObject nodeObject) { StringBuilder result = new StringBuilder(); if (nodeObject.has("attrs")) { @@ -152,6 +192,17 @@ String strAttrs(JSONObject nodeObject) { } + /** + * The function retrieves the value of a specified key from a JSONObject, and if it is empty or + * null, it retrieves the value of the "url" key instead. + * + * @param nodeObject A JSONObject representing a node in a data structure. + * @param key The "key" parameter is a string that represents the key to be used to retrieve a + * value from the "attrs" JSONObject. It could be either "href" or "src". + * @return The method is returning the value of the "href" or "src" key from the "attrs" JSONObject + * of the given "nodeObject". If the value is null or empty, it will return the value of the "url" + * key from the "attrs" JSONObject. + */ private String getNodeStr(JSONObject nodeObject, String key) { String herf = nodeObject.optJSONObject("attrs").optString(key); // key might be [href/src] if (herf == null || herf.isEmpty()) { @@ -162,11 +213,12 @@ private String getNodeStr(JSONObject nodeObject, String key) { /** - * Returns Title From The Embedded Object of type entry + * The function finds the title or uid value from a given JSONObject. * - * @param embeddedObject - * JSONObject - * @return String + * @param embeddedObject The embeddedObject parameter is a JSONObject that contains data. + * @return The method is returning a String value, which is either the value of the "title" key in + * the embeddedObject JSONObject, or the value of the "uid" key if the "title" key is not present + * or is empty. */ protected String findTitleOrUid(JSONObject embeddedObject) { String _title = ""; @@ -180,12 +232,13 @@ protected String findTitleOrUid(JSONObject embeddedObject) { return _title; } + /** - * Returns Title From The Embedded Object of type asset + * The function finds the title of an asset from a given JSON object. * - * @param embeddedObject - * JSONObject - * @return String + * @param embeddedObject The embeddedObject parameter is a JSONObject that contains information + * about an asset. + * @return The method is returning a String value, which is the title of the asset. */ protected String findAssetTitle(JSONObject embeddedObject) { String _title = ""; diff --git a/src/test/java/com/contentstack/utils/AssetLinkTest.java b/src/test/java/com/contentstack/utils/AssetLinkTest.java index 6a33e60..7fcc493 100644 --- a/src/test/java/com/contentstack/utils/AssetLinkTest.java +++ b/src/test/java/com/contentstack/utils/AssetLinkTest.java @@ -10,10 +10,8 @@ public class AssetLinkTest { - private static JSONObject assetLink = null; - @BeforeClass public static void startUtilTests() throws IOException { final String ASSERT_LINK = "src/test/resources/issue/jsonfile.json"; diff --git a/src/test/java/com/contentstack/utils/DefaultOptionClass.java b/src/test/java/com/contentstack/utils/DefaultOptionClass.java index a8303ff..0cbe5e1 100644 --- a/src/test/java/com/contentstack/utils/DefaultOptionClass.java +++ b/src/test/java/com/contentstack/utils/DefaultOptionClass.java @@ -42,7 +42,6 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca String children = callback.renderChildren(nodeObject.optJSONArray("children")); return "

    " + children + "

    "; } - return super.renderNode(nodeType, nodeObject, callback); } } diff --git a/src/test/java/com/contentstack/utils/DefaultOptionTests.java b/src/test/java/com/contentstack/utils/DefaultOptionTests.java index 1f918d4..c25da3b 100644 --- a/src/test/java/com/contentstack/utils/DefaultOptionTests.java +++ b/src/test/java/com/contentstack/utils/DefaultOptionTests.java @@ -16,7 +16,6 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DefaultOptionTests { - private static final Logger logger = Logger.getLogger(UtilTests.class.getName()); private static JSONObject localJsonObj; diff --git a/src/test/java/com/contentstack/utils/EmbeddedModelTests.java b/src/test/java/com/contentstack/utils/EmbeddedModelTests.java index 1b71fc9..6fb3c40 100644 --- a/src/test/java/com/contentstack/utils/EmbeddedModelTests.java +++ b/src/test/java/com/contentstack/utils/EmbeddedModelTests.java @@ -13,7 +13,6 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EmbeddedModelTests { - private static final Logger logger = Logger.getLogger(UtilTests.class.getName()); private static JSONObject localJsonObj; diff --git a/src/test/java/com/contentstack/utils/TestRte.java b/src/test/java/com/contentstack/utils/TestRte.java index a1ec91c..7f7a975 100644 --- a/src/test/java/com/contentstack/utils/TestRte.java +++ b/src/test/java/com/contentstack/utils/TestRte.java @@ -19,56 +19,56 @@ public static void startTestEmbedItemType() { } @Test - public void testkBlankDocument() { + public void testsBlankDocument() { JSONObject rteObject = new JSONObject(kPlainTextJson); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kPlainTextHtml, result); } @Test - public void testkH1Json() { + public void testsH1Json() { JSONObject rteObject = new JSONObject(kH1Json); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kH1Html, result); } @Test - public void testkH2Json() { + public void testsH2Json() { JSONObject rteObject = new JSONObject(kH2Json); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kH2Html, result); } @Test - public void testkH3Json() { + public void testsH3Json() { JSONObject rteObject = new JSONObject(kH3Json); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kH3Html, result); } @Test - public void testkH4Json() { + public void testH4Json() { JSONObject rteObject = new JSONObject(kH4Json); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kH4Html, result); } @Test - public void testkH5Json() { + public void testsH5Json() { JSONObject rteObject = new JSONObject(kH5Json); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kH5Html, result); } @Test - public void testkH6Json() { + public void testH6Json() { JSONObject rteObject = new JSONObject(kH6Json); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kH6Html, result); } @Test - public void testkOrderListJson() { + public void testOrderListJson() { JSONObject rteObject = new JSONObject(kOrderListJson); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kOrderListHtml, result); @@ -82,7 +82,7 @@ public void testKCodeHtmlTypes() { } @Test - public void testkImgJson() { + public void testsImgJson() { JSONObject rteObject = new JSONObject(kImgJson); String result = Utils.jsonToHTML(rteObject, new DefaultOption(), null); Assert.assertEquals(kImgHtml, result); From ce7b1596bb3f8c03f5f05cf43131a91341b90dc9 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Mon, 7 Aug 2023 17:38:09 +0530 Subject: [PATCH 6/8] changelog added --- Changelog.md | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/Changelog.md b/Changelog.md index cb0ea42..c8957db 100644 --- a/Changelog.md +++ b/Changelog.md @@ -3,40 +3,43 @@ A brief description of what changes project contains +## Aug 8, 2023 +#### v1.2.3 +- Attribute support added + + +## Jun 7un 26, 2023 +#### v1.2.2 +- Added Support For Nested Assets +- General Code Improvement ## Jun 26, 2023 #### v1.2.1 -##### Jun 26, 2023 -New Line Issues while rendering Json object To HTML +- New Line Issues while rendering Json object To HTML ## Updated Jsoup vulnerable dependency #### v1.2.0 -##### Oct 6, 2022 - Updated Jsoup vulnerable dependency - jsonToHTML function support added ## Fixed compile Issue #### v1.1.2 -##### Jun 16, 2022 -Fixed compile Issue +- Fixed compile Issue ## Transitive dependencies updated #### v1.1.1 -##### Apr-06-2021 -Updated transitive dependencies to pom.xml +- Updated transitive dependencies to pom.xml ## JSON RTE Feature Support #### v1.1.0 -##### Jun 1, 2022 -JSON RTE Feature Support +- JSON RTE Feature Support ## Introducing Release Of Java Utils SDK #### v1.0.0 -##### Apr 6, 2021 -Initial release for Utils SDK +- Initial release for Utils SDK ## Support -For support, email fake@fake.com or join our Slack channel. +- For support, email fake@fake.com or join our Slack channel. From 7c79a04bd1b670ca684a0581dbde1cd9b4112c97 Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Tue, 8 Aug 2023 13:07:19 +0530 Subject: [PATCH 7/8] removed comment from DefaultOption --- .../java/com/contentstack/utils/render/DefaultOption.java | 8 ++++---- src/test/java/com/contentstack/utils/AssetLinkTest.java | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/contentstack/utils/render/DefaultOption.java b/src/main/java/com/contentstack/utils/render/DefaultOption.java index 8009a08..d18eb39 100644 --- a/src/main/java/com/contentstack/utils/render/DefaultOption.java +++ b/src/main/java/com/contentstack/utils/render/DefaultOption.java @@ -104,7 +104,6 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca String strAttrs = strAttrs(nodeObject); - String children = callback.renderChildren(nodeObject.optJSONArray("children")); switch (nodeType) { case "p": @@ -114,9 +113,9 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca case "img": String assetLink = getNodeStr(nodeObject, "asset-link"); if (!assetLink.isEmpty()) { - return "" + children; + return "" + children; } - return "" + children; + return "" + children; case "embed": return ""; case "h1": @@ -179,7 +178,8 @@ String strAttrs(JSONObject nodeObject) { JSONObject attrsObject = nodeObject.optJSONObject("attrs"); if (attrsObject != null && !attrsObject.isEmpty()) { for (String key : attrsObject.keySet()) { - String value = attrsObject.getString(key); + Object objValue = attrsObject.opt(key); + String value = objValue.toString(); String[] ignoreKeys = {"href", "asset-link", "src", "url"}; ArrayList ignoreKeysList = new ArrayList<>(Arrays.asList(ignoreKeys)); if (!ignoreKeysList.contains(key)) { diff --git a/src/test/java/com/contentstack/utils/AssetLinkTest.java b/src/test/java/com/contentstack/utils/AssetLinkTest.java index 7fcc493..6198c61 100644 --- a/src/test/java/com/contentstack/utils/AssetLinkTest.java +++ b/src/test/java/com/contentstack/utils/AssetLinkTest.java @@ -24,6 +24,6 @@ public void testRenderFunction() { keys[0] = "assetlink"; Utils.jsonToHTML(assetLink, keys, new DefaultOption()); System.out.println(assetLink); - Assert.assertEquals("", assetLink.opt("assetlink").toString()); + Assert.assertEquals("", assetLink.opt("assetlink").toString()); } } From 5b7ff7c3cfde704099ada9c0e0bc599df8c583de Mon Sep 17 00:00:00 2001 From: Shailesh Mishra Date: Tue, 8 Aug 2023 13:15:30 +0530 Subject: [PATCH 8/8] deleted support from workflow: .github/workflows/sast-scan.yml --- .github/workflows/sast-scan.yml | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 .github/workflows/sast-scan.yml diff --git a/.github/workflows/sast-scan.yml b/.github/workflows/sast-scan.yml deleted file mode 100644 index f931630..0000000 --- a/.github/workflows/sast-scan.yml +++ /dev/null @@ -1,11 +0,0 @@ -name: SAST Scan -on: - pull_request: - types: [opened, synchronize, reopened] -jobs: - security: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Horusec Scan - run: docker run -v /var/run/docker.sock:/var/run/docker.sock -v $(pwd):/src horuszup/horusec-cli:latest horusec start -p /src -P $(pwd) \ No newline at end of file