Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>


<groupId>com.contentstack.sdk</groupId>
<artifactId>utils</artifactId>
<version>1.2.4-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Contentstack-utils</name>
<version>1.2.3</version>
<description>Java Utils SDK for Contentstack Content Delivery API, Contentstack is a headless CMS
</description>
<description>Java Utils SDK for Contentstack Content Delivery API, Contentstack is a headless CMS</description>
<url>https://www.contentstack.com</url>

<properties>
Expand Down Expand Up @@ -233,7 +230,7 @@
<configuration>
<source>1.8</source>
<target>1.8</target>
<executable>${JAVA_HOME}/bin/javac</executable>
<!-- <executable>${JAVA_HOME}/bin/javac</executable>-->
</configuration>
</plugin>
<plugin>
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/contentstack/utils/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public static void jsonToHTML(@NotNull JSONObject entry, @NotNull String[] keyPa
* @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.
* @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.
*/
Expand All @@ -219,7 +219,7 @@ public static String jsonToHTML(@NotNull JSONObject jsonRTE, Option renderOption
* @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.
* @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.
*/
Expand Down
73 changes: 63 additions & 10 deletions src/main/java/com/contentstack/utils/render/DefaultOption.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
import org.apache.commons.text.StringEscapeUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;


public class DefaultOption implements Option {
Expand Down Expand Up @@ -55,6 +54,8 @@ public String renderOptions(JSONObject embeddedObject, Metadata metadata) {
*/
@Override
public String renderMark(MarkType markType, String text) {
// Replace "\n" with "<br/>" tags
text = renderHtmlWithLineBreaks(text);
switch (markType) {
case SUPERSCRIPT:
return "<sup>" + text + "</sup>";
Expand Down Expand Up @@ -94,8 +95,7 @@ private String escapeInjectHtml(JSONObject nodeObj, String nodeType) {
* 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
* 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`.
*/
Expand All @@ -105,11 +105,12 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca
String strAttrs = strAttrs(nodeObject);

String children = callback.renderChildren(nodeObject.optJSONArray("children"));

switch (nodeType) {
case "p":
return "<p" + strAttrs + ">" + children + "</p>";
case "a":
return "<a" + strAttrs + "href=\"" + escapeInjectHtml(nodeObject, "href") + "\">" + children + "</a>";
return "<a" + strAttrs + " href=\"" + escapeInjectHtml(nodeObject, "href") + "\">" + children + "</a>";
case "img":
String assetLink = getNodeStr(nodeObject, "asset-link");
if (!assetLink.isEmpty()) {
Expand Down Expand Up @@ -164,6 +165,28 @@ public String renderNode(String nodeType, JSONObject nodeObject, NodeCallback ca
}


/**
* Returns the string replacing </n> is with the <br/> tags
*
* @param content the content
* @return string with br tags
* @apiNote the support for the br tags are included
* @since v1.3.0
*/
private String renderHtmlWithLineBreaks(String content) {
// Replace "\n" with "<br/>" tags
String htmlContent = content.replaceAll("\\n", "<br />");

// Now, you can render the HTML content
// (You can use your rendering method here, e.g., send it to a WebView or display it in a GUI component)

// For demonstration purposes, let's just print it
System.out.println(htmlContent);

return htmlContent;
}


/**
* The function takes a JSONObject as input and returns a string containing the attributes and
* their values, excluding certain keys.
Expand All @@ -178,12 +201,18 @@ String strAttrs(JSONObject nodeObject) {
JSONObject attrsObject = nodeObject.optJSONObject("attrs");
if (attrsObject != null && !attrsObject.isEmpty()) {
for (String key : attrsObject.keySet()) {
Object objValue = attrsObject.opt(key);
Object objValue = attrsObject.opt(key);
String value = objValue.toString();
String[] ignoreKeys = {"href", "asset-link", "src", "url"};
ArrayList<String> ignoreKeysList = new ArrayList<>(Arrays.asList(ignoreKeys));
if (!ignoreKeysList.contains(key)) {
result.append(" ").append(key).append("=\"").append(value).append("\"");
// If style is available, do styling calculations
if (Objects.equals(key, "style")) {
String resultStyle = stringifyStyles(attrsObject.optJSONObject("style"));
result.append(" ").append(key).append("=\"").append(resultStyle).append("\"");
} else {
String[] ignoreKeys = {"href", "asset-link", "src", "url"};
ArrayList<String> ignoreKeysList = new ArrayList<>(Arrays.asList(ignoreKeys));
if (!ignoreKeysList.contains(key)) {
result.append(" ").append(key).append("=\"").append(value).append("\"");
}
}
}
}
Expand All @@ -192,6 +221,30 @@ String strAttrs(JSONObject nodeObject) {
}


private String stringifyStyles(JSONObject style) {
Map<String, String> styleMap = new HashMap<>();

// Convert JSONObject to a Map
Iterator<String> keys = style.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = style.getString(key);
styleMap.put(key, value);
}

StringBuilder styleString = new StringBuilder();

for (Map.Entry<String, String> entry : styleMap.entrySet()) {
String property = entry.getKey();
String value = entry.getValue();

styleString.append(property).append(": ").append(value).append("; ");
}

return styleString.toString();
}


/**
* 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.
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/com/contentstack/utils/RTEResult.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class RTEResult {
public static String kH4Html = "<h4><strong><em><u><sub>MaNullam feugiat turpis quis elit interdum, vitae laoreet quam viverra</sub></u></em></strong></h4>";
public static String kH5Html = "<h5>Mauris venenatis dui id massa sollicitudin, non bibendum nunc dictum.</h5>";
public static String kH6Html = "<h6>Nunc porta diam vitae purus semper, ut consequat lorem vehicula.</h6>";
public static String kOrderListHtml = "<ol><li redactor-attributes=\"{}\" style=\"{\"text-align\":\"justify\"}\">Morbi in quam molestie, fermentum diam vitae, bibendum ipsum.</li><li redactor-attributes=\"{}\" style=\"{\"text-align\":\"justify\"}\">Pellentesque mattis lacus in quam aliquam congue</li><li redactor-attributes=\"{}\" style=\"{\"text-align\":\"justify\"}\">Integer feugiat leo dignissim, lobortis enim vitae, mollis lectus.</li><li redactor-attributes=\"{}\" style=\"{\"text-align\":\"justify\"}\">Sed in ante lacinia, molestie metus eu, fringilla sapien.</li></ol>";
public static String kOrderListHtml = "<ol><li redactor-attributes=\"{}\" style=\"text-align: justify; \">Morbi in quam molestie, fermentum diam vitae, bibendum ipsum.</li><li redactor-attributes=\"{}\" style=\"text-align: justify; \">Pellentesque mattis lacus in quam aliquam congue</li><li redactor-attributes=\"{}\" style=\"text-align: justify; \">Integer feugiat leo dignissim, lobortis enim vitae, mollis lectus.</li><li redactor-attributes=\"{}\" style=\"text-align: justify; \">Sed in ante lacinia, molestie metus eu, fringilla sapien.</li></ol>";
public static String kIUnorderListHtml = "<ul><li>Sed quis metus sed mi hendrerit mollis vel et odio.</li><li>Integer vitae sem dignissim, elementum libero vel, fringilla massa.</li><li>Integer imperdiet arcu sit amet tortor faucibus aliquet.</li><li>Aenean scelerisque velit vitae dui vehicula, at congue massa sagittis.</li></ul>";
public static String kImgHtml = "<img redactor-attributes=\"{\"asset_uid\":\"47f1aa5ae422cd1\"}\" width=\"33.69418132611637\" height=\"auto\" src=\"https://images.contentstack.com/v3/assets/UID_13/Donald.jog.png\" />";
public static String kTableHtml = "<table><thead><tr><th><p>Header 1</p></th><th><p>Header 2</p></th></tr></thead><tbody><tr><td><p>Body row 1 data 1</p></td><td><p>Body row 1 data 2</p></td></tr><tr><td><p>Body row 2 data 1</p></td><td><p>Body row 2 data 2</p></td></tr></tbody></table>";
Expand Down
28 changes: 18 additions & 10 deletions src/test/resources/asset_displayable.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[{
[
{
"title": "New entry with figure tag",
"rich_text_editor": [
"<p> Block embedded entry </p><p><figure type=\"entry\" class=\"embedded-entry block-entry\" data-sys-entry-uid=\"55f6d8cbd7e03a1f\" data-sys-content-type-uid=\"article\" style=\"display:block;\" sys-style-type=\"block\"><span>{{title}}</span></figure></p>"
"<p> Block embedded entry </p><p><figure type=\"entry\" class=\"embedded-entry block-entry\" data-sys-entry-uid=\"55f6d8cbd7e03a1f\" data-sys-content-type-uid=\"article\" style=\"display:block;\" sys-style-type=\"block\"><span>{{title}}</span></figure></p>"
],
"tags": [],
"locale": "en-us",
Expand All @@ -13,20 +14,25 @@
"ACL": {},
"_version": 1,
"_in_progress": false,
"_embedded_entries": [{
"_embedded_entries": [
{
"title": "Why are Indian rating agency heads being sent on 'leave'?",
"multi_line": "If you have watched the film The Big Short, you might remember a scene in which Mark Baum, the fund manager, asks the lady at the ratings agency, “Why did you rate this?” And she says, otherwise they will go to another agency two blocks down the road.\n\nDid rating agencies in India fall for the same logic? Only time will tell.\n\nFor now, the heads of two Indian rating agencies, CARE Ltd and ICRA Ltd, have been sent on leave. On Wednesday evening, CARE Ratings Ltd announced to the stock exchanges that it has sent its managing director and CEO, Rajesh Mokashi on leave with immediate effect. It comes on the back of an anonymous complaint that was sent to the markets regulator, which was then forwarded to CARE, and the ratings firm is now examining the complaint.\n\nJust a fortnight ago, the same pattern followed when concerns were raised in an anonymous representation to the securities and exchange board of India (Sebi) regarding another agency, ICRA Ltd. The markets regulator had promptly sent it forward to ICRA which then sent its managing director, Naresh Takkar, on immediate leave, until further notice.\n\nThese are two incidents just this month, and more heads are expected to roll. Ratings agencies have come under the scanner since the debacle of shadow banking firm IL&FS Ltd. Three agencies that rated the company include India Ratings & Research, ICRA and CARE. The markets regulator in December last year had said it will investigate the matter.\n\nIn fact, one look at ICRA’s website shows that on August 6, 2018, the firm had given an A+ rating to IL&FS Financial Services Ltd’s (IFIN’s) commercial paper, worth Rs 4,000 crore. Interestingly, a closer look at the document showcases problems galore.",
"header_ref": [{
"header_ref": [
{
"uid": "dd96bf9df1e109cd",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

replace uid value with fake values

"_content_type_uid": "header"
}],
}
],
"footer_ref": [
"a8d1c04adeca1cd1"
"a8d1c04adeca1cd1"
],
"reference": [{
"reference": [
{
"uid": "35f57d9211b3d430",
"_content_type_uid": "author"
}],
}
],
"tags": [],
"locale": "en-us",
"uid": "55f6d8cbd7e03a1f",
Expand All @@ -41,5 +47,7 @@
"number": null,
"url": "/why-are-indian-rating-agency-heads-being-sent-on-leave-",
"_in_progress": false
}]
}]
}
]
}
]
Loading