From d4b2ddb04a627a7a967326d14cc565852ba7b7fc Mon Sep 17 00:00:00 2001 From: Cedric Mailleux Date: Wed, 28 Feb 2024 14:34:22 -0500 Subject: [PATCH] BACKLOG-22437: Refactor code to remove some complexities and bad log formatting --- .../htmlfiltering/HTMLFilteringInterface.java | 18 +-- .../HtmlFilteringInterceptor.java | 108 +++++++++--------- .../configuration/HTMLFiltering.java | 45 +++++--- .../configuration/parse/Parser.java | 61 +++++----- .../parse/PropsToJsonParser.java | 2 - .../models/HTMLFilteringConfigInterface.java | 8 +- ...GqlHTMLFilterConfigurationingMutation.java | 2 +- .../GqlHtmlFilteringMutation.java | 32 +++--- .../GqlHTMLFilteringConfigurationQuery.java | 2 +- .../GqlHtmlFilteringQuery.java | 55 ++++----- 10 files changed, 174 insertions(+), 159 deletions(-) rename src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/{htmlFiltering => html_filtering}/GqlHtmlFilteringMutation.java (86%) rename src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/{htmlFiltering => html_filtering}/GqlHtmlFilteringQuery.java (80%) diff --git a/src/main/java/org/jahia/modules/htmlfiltering/HTMLFilteringInterface.java b/src/main/java/org/jahia/modules/htmlfiltering/HTMLFilteringInterface.java index 7b53e6d..f59d634 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/HTMLFilteringInterface.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/HTMLFilteringInterface.java @@ -20,21 +20,21 @@ public interface HTMLFilteringInterface { - public static String DEFAULT_POLICY_KEY = "default"; + String DEFAULT_POLICY_KEY = "default"; - public String getCKEditor5Config(String siteKey); + String getCKEditor5Config(String siteKey); - public String getCKEditor4Config(String siteKey); + String getCKEditor4Config(String siteKey); - public PolicyFactory getOwaspPolicyFactory(String siteKey); + PolicyFactory getOwaspPolicyFactory(String siteKey); - public PolicyFactory getDefaultOwaspPolicyFactory(); + PolicyFactory getDefaultOwaspPolicyFactory(); - public PolicyFactory getMergedOwaspPolicyFactory(String... siteKeys); + PolicyFactory getMergedOwaspPolicyFactory(String... siteKeys); - public JSONObject getMergedJSONPolicy(String... siteKeys); + JSONObject getMergedJSONPolicy(String... siteKeys); - public boolean configExists(String siteKey); + boolean configExists(String siteKey); - public boolean htmlSanitizerDryRun(String siteKey); + boolean htmlSanitizerDryRun(String siteKey); } diff --git a/src/main/java/org/jahia/modules/htmlfiltering/HtmlFilteringInterceptor.java b/src/main/java/org/jahia/modules/htmlfiltering/HtmlFilteringInterceptor.java index ed94fae..d5c0f78 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/HtmlFilteringInterceptor.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/HtmlFilteringInterceptor.java @@ -22,6 +22,7 @@ import org.jahia.services.content.decorator.JCRSiteNode; import org.jahia.services.content.interceptor.BaseInterceptor; import org.jahia.services.content.nodetypes.ExtendedPropertyDefinition; +import org.jetbrains.annotations.NotNull; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; @@ -34,11 +35,8 @@ import javax.annotation.Nullable; import javax.jcr.RepositoryException; import javax.jcr.Value; -import javax.jcr.ValueFormatException; -import javax.jcr.lock.LockException; -import javax.jcr.nodetype.ConstraintViolationException; -import javax.jcr.version.VersionException; import java.util.Collections; +import java.util.Objects; @Component(immediate = true) public class HtmlFilteringInterceptor extends BaseInterceptor { @@ -66,26 +64,14 @@ public void setJcrStoreService(JCRStoreService jcrStoreService) { @Override public Value beforeSetValue(JCRNodeWrapper node, String name, - ExtendedPropertyDefinition definition, Value originalValue) - throws ValueFormatException, VersionException, LockException, - ConstraintViolationException, RepositoryException { + ExtendedPropertyDefinition definition, Value originalValue) + throws RepositoryException { - String content = originalValue.getString(); - if (StringUtils.isEmpty(content) || !content.contains("<")) { - if (logger.isDebugEnabled()) { - logger.debug("The value does not contain any HTML tags. Skip filtering."); - } - return originalValue; - } + if (valueIsEmpty(originalValue)) return originalValue; JCRSiteNode resolveSite = node.getResolveSite(); - if (!resolveSite.isHtmlMarkupFilteringEnabled()) { - return originalValue; - } - HTMLFilteringInterface filteringConfig = BundleUtils.getOsgiService(HTMLFilteringInterface.class, null); - - if (filteringConfig == null) { + if (!resolveSite.isHtmlMarkupFilteringEnabled() || filteringConfig == null) { return originalValue; } @@ -95,66 +81,84 @@ public Value beforeSetValue(JCRNodeWrapper node, String name, return originalValue; } - Value modifiedValue = originalValue; - if (logger.isDebugEnabled()) { - logger.debug("Performing HTML tag filtering for " + node.getPath() + "/" + name); + logger.debug("Performing HTML tag filtering for {}/{}", node.getPath(), name); if (logger.isTraceEnabled()) { - logger.trace("Original value: " + content); + logger.trace("Original value: {}", originalValue.getString()); } } - + String content = originalValue.getString(); String propInfo = node.hasProperty(definition.getName()) ? node.getProperty(definition.getName()).getRealProperty().getPath() : node.getPath(); - if (filteringConfig.htmlSanitizerDryRun(resolveSite.getSiteKey())) { - logger.info(String.format("Dry run: Skipping Sanitization of [%s]", propInfo)); - - policyFactory.sanitize(content, new HtmlChangeListener() { - @Override - public void discardedTag(@Nullable Object o, String tag) { - logger.info(String.format("Removed tag: %s", tag)); - } - - @Override - public void discardedAttributes(@Nullable Object o, String tag, String... strings) { - logger.info(String.format("Removed attributes %s for tag %s", String.join(", ", strings), tag)); - } - }, null); - - return originalValue; - } + if (dryRun(filteringConfig, resolveSite, propInfo, policyFactory, content)) return originalValue; String result = policyFactory.sanitize(content); - logger.warn(String.format("Sanitized [%s]", propInfo)); + logger.warn("Sanitized [{}]", propInfo); + return getModifiedValue(node, preservePlaceholders(result), content, originalValue); + } + + @NotNull + private static String preservePlaceholders(String result) { // Preserve URL context placeholders that might've been encoded by the sanitizer result = result.replace("%7bmode%7d", "{mode}"); result = result.replace("%7blang%7d", "{lang}"); result = result.replace("%7bworkspace%7d", "{workspace}"); + return result; + } - if (result != content && !result.equals(content)) { - modifiedValue = node.getSession().getValueFactory().createValue(result); + private static Value getModifiedValue(JCRNodeWrapper node, String result, String content, Value originalValue) throws RepositoryException { + if (!result.equals(content)) { + Value modifiedValue = node.getSession().getValueFactory().createValue(result); if (logger.isDebugEnabled()) { logger.debug("Done filtering of \"unwanted\" HTML tags."); if (logger.isTraceEnabled()) { - logger.trace("Modified value: " + result); + logger.trace("Modified value: {}", result); } } - } else { + return modifiedValue; + } else if (logger.isDebugEnabled()) { + logger.debug("The value does not contain HTML tags that needs to be removed. The content remains unchanged."); + } + return originalValue; + } + + private static boolean valueIsEmpty(Value originalValue) throws RepositoryException { + if (StringUtils.isEmpty(originalValue.getString()) || !originalValue.getString().contains("<")) { if (logger.isDebugEnabled()) { - logger.debug("The value does not contain HTML tags that needs to be removed. The content remains unchanged."); + logger.debug("The value does not contain any HTML tags. Skip filtering."); } + return true; } + return false; + } + + private static boolean dryRun(HTMLFilteringInterface filteringConfig, JCRSiteNode resolveSite, String propInfo, PolicyFactory policyFactory, String content) { + if (filteringConfig.htmlSanitizerDryRun(resolveSite.getSiteKey())) { + logger.info("Dry run: Skipping Sanitization of [{}]", propInfo); - return modifiedValue; + policyFactory.sanitize(content, new HtmlChangeListener() { + @Override + public void discardedTag(@Nullable Object o, String tag) { + logger.info(String.format("Removed tag: %s", tag)); + } + + @Override + public void discardedAttributes(@Nullable Object o, String tag, String... strings) { + logger.info(String.format("Removed attributes %s for tag %s", String.join(", ", strings), tag)); + } + }, null); + + return true; + } + return false; } @Override public Value[] beforeSetValues(JCRNodeWrapper node, String name, - ExtendedPropertyDefinition definition, Value[] originalValues) - throws ValueFormatException, VersionException, LockException, - ConstraintViolationException, RepositoryException { + ExtendedPropertyDefinition definition, Value[] originalValues) + throws RepositoryException { Value[] res = new Value[originalValues.length]; for (int i = 0; i < originalValues.length; i++) { diff --git a/src/main/java/org/jahia/modules/htmlfiltering/configuration/HTMLFiltering.java b/src/main/java/org/jahia/modules/htmlfiltering/configuration/HTMLFiltering.java index 0f25a0f..d306fbf 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/configuration/HTMLFiltering.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/configuration/HTMLFiltering.java @@ -16,7 +16,6 @@ package org.jahia.modules.htmlfiltering.configuration; import org.apache.commons.lang.StringUtils; -import org.jahia.api.settings.SettingsBean; import org.jahia.modules.htmlfiltering.HTMLFilteringInterface; import org.jahia.modules.htmlfiltering.configuration.parse.Parser; import org.jahia.modules.htmlfiltering.configuration.parse.PropsToJsonParser; @@ -69,9 +68,9 @@ public void updated(String pid, Dictionary dictionary) throws Configu if (!dictCopy.isEmpty()) { configs.put(pid, new PropsToJsonParser().parse(dictCopy)); siteKeyToPid.put(siteKey, pid); - logger.info(String.format("Setting htmlFiltering config for site %s: %s", siteKey, configs.get(pid).toString())); + logger.info("Setting htmlFiltering config for site {}: {}", siteKey, configs.get(pid)); } else { - logger.warn(String.format("Could not find htmlFiltering object for site: %s", siteKey)); + logger.warn("Could not find htmlFiltering object for site: {}", siteKey); } } @@ -121,7 +120,7 @@ public JSONObject getMergedJSONPolicy(String... siteKeys) { for (String key : siteKeys) { if (configExists(key)) { - mergeJsonObject(mergedPolicy, configs.get(siteKeyToPid.get(key))); + mergeJSONObject(mergedPolicy, configs.get(siteKeyToPid.get(key))); } } @@ -150,27 +149,35 @@ public boolean htmlSanitizerDryRun(String siteKey) { return f.has("htmlSanitizerDryRun") && f.getBoolean("htmlSanitizerDryRun"); } - private void mergeJsonObject(JSONObject target, JSONObject source) { + private void mergeJSONObject(JSONObject target, JSONObject source) { for (String key : source.keySet()) { if (source.get(key) instanceof JSONObject) { - if (target.has(key) && target.get(key) instanceof JSONObject) { - mergeJsonObject(target.getJSONObject(key), source.getJSONObject(key)); - } else { - target.put(key, new JSONObject(source.getJSONObject(key).toString())); - } + mergeSubJSONObject(target, source, key); } else if (source.get(key) instanceof JSONArray) { - if (target.has(key) && target.get(key) instanceof JSONArray) { - JSONArray targetArray = target.getJSONArray(key); - JSONArray sourceArray = source.getJSONArray(key); - for (int i = 0; i < sourceArray.length(); i++) { - targetArray.put(sourceArray.get(i)); - } - } else { - target.put(key, new JSONArray(source.getJSONArray(key).toString())); - } + mergeJSONArray(target, source, key); } else { target.put(key, source.get(key)); } } } + + private static void mergeJSONArray(JSONObject target, JSONObject source, String key) { + if (target.has(key) && target.get(key) instanceof JSONArray) { + JSONArray targetArray = target.getJSONArray(key); + JSONArray sourceArray = source.getJSONArray(key); + for (int i = 0; i < sourceArray.length(); i++) { + targetArray.put(sourceArray.get(i)); + } + } else { + target.put(key, new JSONArray(source.getJSONArray(key).toString())); + } + } + + private void mergeSubJSONObject(JSONObject target, JSONObject source, String key) { + if (target.has(key) && target.get(key) instanceof JSONObject) { + mergeJSONObject(target.getJSONObject(key), source.getJSONObject(key)); + } else { + target.put(key, new JSONObject(source.getJSONObject(key).toString())); + } + } } diff --git a/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/Parser.java b/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/Parser.java index 084b2e8..5110c4d 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/Parser.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/Parser.java @@ -15,6 +15,7 @@ */ package org.jahia.modules.htmlfiltering.configuration.parse; +import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONObject; import org.owasp.html.HtmlPolicyBuilder; @@ -26,28 +27,30 @@ public abstract class Parser { + public static final String ELEMENTS = "elements"; + private enum PolicyType { - ALLOW, DISALLOW; + ALLOW, DISALLOW } - private static Map PATTERNS; + private static final Map PATTERNS; static { PATTERNS = new HashMap<>(); String onsiteUrl = "(?:[\\p{L}\\p{N}\\\\\\.\\#@\\$%\\+&;\\-_~,\\?=/!{}:]+|\\#(\\w)+)"; String offsiteUrl = "(\\s*(?:(?:ht|f)tps?://|mailto:)[\\p{L}\\p{N}][\\p{L}\\p{N}\\p{Zs}\\.\\#@\\$%\\+&;:\\-_~,\\?=/!\\(\\)" + "]*+\\s*)"; - PATTERNS.put("NUMBER_OR_PERCENT", Pattern.compile("[0-9]+%?")); + PATTERNS.put("NUMBER_OR_PERCENT", Pattern.compile("\\d+%?")); PATTERNS.put("ONSITE_URL", Pattern.compile(onsiteUrl)); PATTERNS.put("OFFSITE_URL", Pattern.compile(onsiteUrl)); PATTERNS.put("LINKS_URL", Pattern.compile(String.format("(?:%s|%s)", onsiteUrl, offsiteUrl))); PATTERNS.put("HTML_ID", Pattern.compile("[a-zA-Z0-9\\:\\-_\\.]+")); PATTERNS.put("HTML_CLASS", Pattern.compile("[a-zA-Z0-9\\s,\\-_]+")); - PATTERNS.put("NUMBER", Pattern.compile("[+-]?(?:(?:[0-9]+(?:\\.[0-9]*)?)|\\.[0-9]+)")); + PATTERNS.put("NUMBER", Pattern.compile("[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)")); PATTERNS.put("NAME", Pattern.compile("[a-zA-Z0-9\\-_\\$]+")); PATTERNS.put("ALIGN", Pattern.compile("(?i)center|left|right|justify|char")); PATTERNS.put("VALIGN", Pattern.compile("(?i)baseline|bottom|middle|top")); - PATTERNS.put("PARAGRAPH", Pattern.compile("(?:[\\p{L}\\p{N},'\\.\\s\\-_\\(\\)]|&[0-9]{2};)*")); + PATTERNS.put("PARAGRAPH", Pattern.compile("(?:[\\p{L}\\p{N},'\\.\\s\\-_\\(\\)]|&\\d{2};)*")); } public abstract String parseToJsonString(JSONObject json); @@ -81,9 +84,7 @@ private static void handleProtocols(JSONObject filtering, HtmlPolicyBuilder buil if (filtering.has("protocols")) { Object p = filtering.get("protocols"); - if (!(p instanceof JSONArray)) { - p = new JSONArray(new String[]{(String) p}); - } + p = convertToJSONArray(p); if (policyType == PolicyType.ALLOW) { builder.allowUrlProtocols(jsonArrayToArray((JSONArray) p)); @@ -94,15 +95,13 @@ private static void handleProtocols(JSONObject filtering, HtmlPolicyBuilder buil } private static void handleElements(JSONObject filtering, HtmlPolicyBuilder builder, PolicyType policyType) { - if (filtering.has("elements")) { - JSONArray elems = filtering.getJSONArray("elements"); + if (filtering.has(ELEMENTS)) { + JSONArray elems = filtering.getJSONArray(ELEMENTS); elems.forEach(jsonObject -> { Object name = ((JSONObject)jsonObject).get("name"); - if (!(name instanceof JSONArray)) { - name = new JSONArray(new String[]{(String) name}); - } + name = convertToJSONArray(name); if (policyType == PolicyType.ALLOW) { builder.allowElements(jsonArrayToArray((JSONArray) name)); @@ -118,12 +117,10 @@ private static void handleAttributes(JSONObject filtering, HtmlPolicyBuilder bui JSONArray attr = filtering.getJSONArray("attributes"); attr.forEach(jsonObject -> { - boolean isGlobal = !((JSONObject)jsonObject).has("elements"); + boolean isGlobal = !((JSONObject)jsonObject).has(ELEMENTS); Object name = ((JSONObject)jsonObject).get("name"); - if (!(name instanceof JSONArray)) { - name = new JSONArray(new String[]{(String) name}); - } + name = convertToJSONArray(name); HtmlPolicyBuilder.AttributeBuilder attrBuilder; @@ -139,19 +136,29 @@ private static void handleAttributes(JSONObject filtering, HtmlPolicyBuilder bui attrBuilder.matching(p); } - if (isGlobal) { - attrBuilder.globally(); - } else { - Object elems = ((JSONObject)jsonObject).get("elements"); + handleGlobal((JSONObject) jsonObject, isGlobal, attrBuilder); + }); + } + } - if (!(elems instanceof JSONArray)) { - elems = new JSONArray(new String[]{(String) elems}); - } + private static void handleGlobal(JSONObject jsonObject, boolean isGlobal, HtmlPolicyBuilder.AttributeBuilder attrBuilder) { + if (isGlobal) { + attrBuilder.globally(); + } else { + Object elems = jsonObject.get(ELEMENTS); - attrBuilder.onElements(jsonArrayToArray((JSONArray) elems)); - } - }); + elems = convertToJSONArray(elems); + + attrBuilder.onElements(jsonArrayToArray((JSONArray) elems)); + } + } + + @NotNull + private static Object convertToJSONArray(Object name) { + if (!(name instanceof JSONArray)) { + name = new JSONArray(new String[]{(String) name}); } + return name; } private static String[] jsonArrayToArray(JSONArray array) { diff --git a/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/PropsToJsonParser.java b/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/PropsToJsonParser.java index 0605c32..a192339 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/PropsToJsonParser.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/configuration/parse/PropsToJsonParser.java @@ -22,7 +22,6 @@ /** * Given a flat map of this kind: - * * Map flatMap = new HashMap<>(); * flatMap.put("name", "John Doe"); * flatMap.put("age", 30); @@ -39,7 +38,6 @@ * flatMap.put("contacts[2].sub[0].value", "123-456-7890"); * flatMap.put("jcrestapi.grants[0].node.withPermission", "my-access"); * flatMap.put("jcrestapi.grants[1].node.withPermission", "api-access"); - * * it produces a json object. */ public class PropsToJsonParser { diff --git a/src/main/java/org/jahia/modules/htmlfiltering/graphql/models/HTMLFilteringConfigInterface.java b/src/main/java/org/jahia/modules/htmlfiltering/graphql/models/HTMLFilteringConfigInterface.java index 2c4a31d..8b815f6 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/graphql/models/HTMLFilteringConfigInterface.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/graphql/models/HTMLFilteringConfigInterface.java @@ -20,7 +20,9 @@ public interface HTMLFilteringConfigInterface { - public Set getProtocols(); - public Set getElements(); - public List getAttributes(); + Set getProtocols(); + + Set getElements(); + + List getAttributes(); } diff --git a/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/GqlHTMLFilterConfigurationingMutation.java b/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/GqlHTMLFilterConfigurationingMutation.java index 8057870..6a320a2 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/GqlHTMLFilterConfigurationingMutation.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/GqlHTMLFilterConfigurationingMutation.java @@ -18,7 +18,7 @@ import graphql.annotations.annotationTypes.GraphQLDescription; import graphql.annotations.annotationTypes.GraphQLField; import graphql.annotations.annotationTypes.GraphQLName; -import org.jahia.modules.htmlfiltering.graphql.mutation.impl.htmlFiltering.GqlHtmlFilteringMutation; +import org.jahia.modules.htmlfiltering.graphql.mutation.impl.html_filtering.GqlHtmlFilteringMutation; @GraphQLName("HTMLFilteringMutation") @GraphQLDescription("HTML Filtering mutations entry point") diff --git a/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/htmlFiltering/GqlHtmlFilteringMutation.java b/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/html_filtering/GqlHtmlFilteringMutation.java similarity index 86% rename from src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/htmlFiltering/GqlHtmlFilteringMutation.java rename to src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/html_filtering/GqlHtmlFilteringMutation.java index 677143b..eabfae9 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/htmlFiltering/GqlHtmlFilteringMutation.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/graphql/mutation/impl/html_filtering/GqlHtmlFilteringMutation.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jahia.modules.htmlfiltering.graphql.mutation.impl.htmlFiltering; +package org.jahia.modules.htmlfiltering.graphql.mutation.impl.html_filtering; import graphql.annotations.annotationTypes.GraphQLDescription; import graphql.annotations.annotationTypes.GraphQLField; @@ -46,15 +46,12 @@ public class GqlHtmlFilteringMutation { public Boolean getEnableFiltering(@GraphQLNonNull @GraphQLName("siteKey") @GraphQLDescription("Site key for the affected site") String siteKey) { try { - return JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback() { - @Override - public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { - JCRNodeWrapper siteNode = session.getNode("/sites/" + siteKey); - siteNode.setProperty("j:doTagFiltering", true); - session.save(); - - return true; - } + return JCRTemplate.getInstance().doExecuteWithSystemSession(session -> { + JCRNodeWrapper siteNode = session.getNode("/sites/" + siteKey); + siteNode.setProperty("j:doTagFiltering", true); + session.save(); + + return true; }); } catch (RepositoryException e) { throw new DataFetchingException(e); @@ -67,15 +64,12 @@ public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { public Boolean getDisableFiltering(@GraphQLNonNull @GraphQLName("siteKey") @GraphQLDescription("Site key for the affected site") String siteKey) { try { - return JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback() { - @Override - public Boolean doInJCR(JCRSessionWrapper session) throws RepositoryException { - JCRNodeWrapper siteNode = session.getNode("/sites/" + siteKey); - siteNode.setProperty("j:doTagFiltering", false); - session.save(); - - return true; - } + return JCRTemplate.getInstance().doExecuteWithSystemSession(session -> { + JCRNodeWrapper siteNode = session.getNode("/sites/" + siteKey); + siteNode.setProperty("j:doTagFiltering", false); + session.save(); + + return true; }); } catch (RepositoryException e) { throw new DataFetchingException(e); diff --git a/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/GqlHTMLFilteringConfigurationQuery.java b/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/GqlHTMLFilteringConfigurationQuery.java index 6556249..4938ee0 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/GqlHTMLFilteringConfigurationQuery.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/GqlHTMLFilteringConfigurationQuery.java @@ -18,7 +18,7 @@ import graphql.annotations.annotationTypes.GraphQLDescription; import graphql.annotations.annotationTypes.GraphQLField; import graphql.annotations.annotationTypes.GraphQLName; -import org.jahia.modules.htmlfiltering.graphql.query.impl.htmlFiltering.GqlHtmlFilteringQuery; +import org.jahia.modules.htmlfiltering.graphql.query.impl.html_filtering.GqlHtmlFilteringQuery; @GraphQLName("HTMLFilteringConfigurationQuery") @GraphQLDescription("Entry point for site HTML Filtering queries") diff --git a/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/htmlFiltering/GqlHtmlFilteringQuery.java b/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/html_filtering/GqlHtmlFilteringQuery.java similarity index 80% rename from src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/htmlFiltering/GqlHtmlFilteringQuery.java rename to src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/html_filtering/GqlHtmlFilteringQuery.java index 869006d..f17a3e9 100644 --- a/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/htmlFiltering/GqlHtmlFilteringQuery.java +++ b/src/main/java/org/jahia/modules/htmlfiltering/graphql/query/impl/html_filtering/GqlHtmlFilteringQuery.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.jahia.modules.htmlfiltering.graphql.query.impl.htmlFiltering; +package org.jahia.modules.htmlfiltering.graphql.query.impl.html_filtering; import graphql.annotations.annotationTypes.GraphQLDescription; import graphql.annotations.annotationTypes.GraphQLField; @@ -42,22 +42,21 @@ @GraphQLDescription("Query for html filtering settings") public class GqlHtmlFilteringQuery { + public static final String TAG_FILTERING = "j:doTagFiltering"; + public static final String ELEMENTS = "elements"; + @GraphQLField @GraphQLName("filteringSettings") @GraphQLDescription("HTML filtering settings for a site") public GqlHTMLFiltering getFilteringSettings(@GraphQLNonNull @GraphQLName("siteKey") @GraphQLDescription("Site key for the affected site") String siteKey) { - GqlHTMLFiltering filtering = null; + GqlHTMLFiltering filtering; try { - filtering = JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback() { - - @Override - public GqlHTMLFiltering doInJCR(JCRSessionWrapper session) throws RepositoryException { - JCRNodeWrapper siteNode = session.getNode("/sites/" + siteKey); - boolean enabled = siteNode.hasProperty("j:doTagFiltering") && siteNode.getProperty("j:doTagFiltering").getBoolean(); + filtering = JCRTemplate.getInstance().doExecuteWithSystemSession(session -> { + JCRNodeWrapper siteNode = session.getNode("/sites/" + siteKey); + boolean enabled = siteNode.hasProperty(TAG_FILTERING) && siteNode.getProperty(TAG_FILTERING).getBoolean(); - return new GqlHTMLFiltering(siteKey, enabled); - } + return new GqlHTMLFiltering(siteKey, enabled); }); } catch (RepositoryException e) { throw new DataFetchingException(e); @@ -76,7 +75,7 @@ public List getSitesWithActiveFiltering() { List siteNodes = JahiaSitesService.getInstance().getSitesNodeList(); for (JCRSiteNode siteNode : siteNodes) { - if (siteNode.hasProperty("j:doTagFiltering") && siteNode.getProperty("j:doTagFiltering").getBoolean()) { + if (siteNode.hasProperty(TAG_FILTERING) && siteNode.getProperty(TAG_FILTERING).getBoolean()) { enabled.add(siteNode.getSiteKey()); } } @@ -124,8 +123,8 @@ private void getProtocols(JSONObject config, HTMLFilteringConfigInterface gqlHTM } private void getElements(JSONObject config, HTMLFilteringConfigInterface gqlHTMLFilteringConfig) { - if (config.has("elements")) { - JSONArray elements = config.getJSONArray("elements"); + if (config.has(ELEMENTS)) { + JSONArray elements = config.getJSONArray(ELEMENTS); elements.forEach(e -> { if (((JSONObject)e).get("name") instanceof JSONArray) { ((JSONObject)e).getJSONArray("name").forEach(el -> gqlHTMLFilteringConfig.getElements().add((String) el)); @@ -150,22 +149,26 @@ private void getAttributes(JSONObject config, HTMLFilteringConfigInterface gqlHT toHandle.add(((JSONObject) attr).getString("name")); } - for (String s : toHandle) { - GqlHTMLFilteringConfigAttribute at = findOrCreateAttributesByAttribute(a, s); + handleAttributes((JSONObject) attr, toHandle, a); + }); + } + } - if (((JSONObject) attr).has("pattern")) { - at.setPattern(((JSONObject) attr).getString("pattern")); - } + private void handleAttributes(JSONObject attr, List toHandle, List a) { + for (String s : toHandle) { + GqlHTMLFilteringConfigAttribute at = findOrCreateAttributesByAttribute(a, s); - if (((JSONObject) attr).has("elements")) { - if (((JSONObject) attr).get("elements") instanceof JSONArray) { - ((JSONObject) attr).getJSONArray("elements").forEach(e -> at.getElements().add((String) e)); - } else { - at.getElements().add(((JSONObject) attr).getString("elements")); - } - } + if (attr.has("pattern")) { + at.setPattern(attr.getString("pattern")); + } + + if (attr.has(ELEMENTS)) { + if (attr.get(ELEMENTS) instanceof JSONArray) { + attr.getJSONArray(ELEMENTS).forEach(e -> at.getElements().add((String) e)); + } else { + at.getElements().add(attr.getString(ELEMENTS)); } - }); + } } }