You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by dk...@apache.org on 2019/07/02 18:43:51 UTC

[sling-org-apache-sling-app-cms] branch master updated (b158fac -> 860c28e)

This is an automated email from the ASF dual-hosted git repository.

dklco pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-app-cms.git.


    from b158fac  Merge branch 'master' of git@github.com:apache/sling-org-apache-sling-app-cms.git
     new 2167c18  Adding a servlet to download files rather than just linking to them
     new 860c28e  Adding a number of Sonar fixes and improvements

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../providers/HTMLValdiatorInsightProvider.java    |  54 ++++++-----
 .../impl/providers/ReadabilityInsightProvider.java |  97 ++++++++++---------
 .../core/internal/filters/EditIncludeFilter.java   | 107 ++++++++++++---------
 .../internal/operations/BulkReplaceOperation.java  |   2 +
 .../operations/UpdateReferencesPostOperation.java  |  81 ++++++++--------
 .../core/internal/rewriter/HTML5Serializer.java    |  56 +++++------
 .../internal/servlets/DownloadFileServlet.java     |  28 +++++-
 .../libs/sling-cms/content/file/download.json      |   4 +
 .../libs/sling-cms/content/site/content.json       |   6 +-
 .../libs/sling-cms/content/static/content.json     |   6 +-
 10 files changed, 253 insertions(+), 188 deletions(-)
 create mode 100644 ui/src/main/resources/jcr_root/libs/sling-cms/content/file/download.json


[sling-org-apache-sling-app-cms] 02/02: Adding a number of Sonar fixes and improvements

Posted by dk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dklco pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-app-cms.git

commit 860c28e1cabd8f65b21765b4fe6fed0124407191
Author: Dan Klco <dk...@apache.org>
AuthorDate: Tue Jul 2 14:43:45 2019 -0400

    Adding a number of Sonar fixes and improvements
---
 .../providers/HTMLValdiatorInsightProvider.java    |  54 ++++++-----
 .../impl/providers/ReadabilityInsightProvider.java |  97 ++++++++++---------
 .../core/internal/filters/EditIncludeFilter.java   | 107 ++++++++++++---------
 .../internal/operations/BulkReplaceOperation.java  |   2 +
 .../operations/UpdateReferencesPostOperation.java  |  81 ++++++++--------
 .../core/internal/rewriter/HTML5Serializer.java    |  56 +++++------
 6 files changed, 214 insertions(+), 183 deletions(-)

diff --git a/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/HTMLValdiatorInsightProvider.java b/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/HTMLValdiatorInsightProvider.java
index 53c72ec..cbc541e 100644
--- a/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/HTMLValdiatorInsightProvider.java
+++ b/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/HTMLValdiatorInsightProvider.java
@@ -19,6 +19,7 @@
 package org.apache.sling.cms.core.insights.impl.providers;
 
 import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
 import java.nio.charset.StandardCharsets;
 import java.util.HashSet;
@@ -126,30 +127,7 @@ public class HTMLValdiatorInsightProvider extends BaseInsightProvider {
                     }
                 }
             }
-            double score = 0.0;
-            if (errors > 5) {
-                insight.setPrimaryMessage(Message
-                        .danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_DANGER, new Object[] { errors, warnings })));
-                score = 0.2;
-            } else if (errors > 0) {
-                insight.setPrimaryMessage(Message
-                        .danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_DANGER, new Object[] { errors, warnings })));
-                score = 0.4;
-            } else if (warnings > 5) {
-                insight.setPrimaryMessage(
-                        Message.danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_WARN, new Object[] { warnings })));
-                score = 0.6;
-            } else if (warnings > 0) {
-                insight.setPrimaryMessage(
-                        Message.danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_WARN, new Object[] { warnings })));
-                score = 0.8;
-            } else {
-                insight.setPrimaryMessage(Message.danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_SUCCESS)));
-                score = 1.0;
-            }
-            insight.setScore(score);
-            insight.setMoreDetailsLink("https://validator.w3.org/nu/?doc="
-                    + URLEncoder.encode(pageRequest.getPage().getPublishedUrl(), StandardCharsets.UTF_8.toString()));
+            updateInsight(insight, pageRequest, dictionary, errors, warnings);
         } finally {
             if (reader != null) {
                 reader.close();
@@ -159,6 +137,34 @@ public class HTMLValdiatorInsightProvider extends BaseInsightProvider {
         return insight;
     }
 
+    private void updateInsight(Insight insight, PageInsightRequest pageRequest, I18NDictionary dictionary, int errors,
+            int warnings) throws UnsupportedEncodingException {
+        double score = 0.0;
+        if (errors > 5) {
+            insight.setPrimaryMessage(Message
+                    .danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_DANGER, new Object[] { errors, warnings })));
+            score = 0.2;
+        } else if (errors > 0) {
+            insight.setPrimaryMessage(Message
+                    .danger(dictionary.get(I18N_KEY_HTMLVALIDATOR_DANGER, new Object[] { errors, warnings })));
+            score = 0.4;
+        } else if (warnings > 5) {
+            insight.setPrimaryMessage(
+                    Message.warn(dictionary.get(I18N_KEY_HTMLVALIDATOR_WARN, new Object[] { warnings })));
+            score = 0.6;
+        } else if (warnings > 0) {
+            insight.setPrimaryMessage(
+                    Message.warn(dictionary.get(I18N_KEY_HTMLVALIDATOR_WARN, new Object[] { warnings })));
+            score = 0.8;
+        } else {
+            insight.setPrimaryMessage(Message.success(dictionary.get(I18N_KEY_HTMLVALIDATOR_SUCCESS)));
+            score = 1.0;
+        }
+        insight.setScore(score);
+        insight.setMoreDetailsLink("https://validator.w3.org/nu/?doc="
+                + URLEncoder.encode(pageRequest.getPage().getPublishedUrl(), StandardCharsets.UTF_8.toString()));
+    }
+
     @Override
     public String getId() {
         return "htmlvalidator";
diff --git a/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/ReadabilityInsightProvider.java b/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/ReadabilityInsightProvider.java
index 72e8b86..b24dde4 100644
--- a/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/ReadabilityInsightProvider.java
+++ b/core/src/main/java/org/apache/sling/cms/core/insights/impl/providers/ReadabilityInsightProvider.java
@@ -97,52 +97,7 @@ public class ReadabilityInsightProvider extends BaseInsightProvider {
 
         I18NDictionary dictionary = i18nProvider.getDictionary(request.getResource().getResourceResolver());
         if (site != null && config != null) {
-            ReadabilityService svc = factory.getReadabilityService(site.getLocale());
-
-            double score = svc.calculateAverageGradeLevel(text);
-            String scoreStr = new DecimalFormat("##0.00").format(score);
-
-            insight.setScored(true);
-
-            log.debug("Calculating readability of page {}", pageRequest.getPage());
-
-            if (score > config.getMaxGradeLevel() || score < config.getMinGradeLevel()) {
-                log.debug("Retrieved out of bounds readability {} based on range {}-{}", score,
-                        config.getMinGradeLevel(), config.getMaxGradeLevel());
-
-                StandardDeviation sd = new StandardDeviation(false);
-                double stddev = sd.evaluate(new double[] { config.getMinGradeLevel(), config.getMaxGradeLevel() });
-                double dev;
-                if (score > config.getMaxGradeLevel()) {
-                    dev = score - config.getMaxGradeLevel();
-                } else {
-                    dev = config.getMinGradeLevel() - score;
-                }
-                double calcScore = 1 - (dev / stddev) * .5;
-                if (calcScore > 0) {
-                    insight.setScore(calcScore);
-                } else {
-                    insight.setScore(0.0);
-                }
-                insight.setPrimaryMessage(Message.warn(dictionary.get(I18N_KEY_READABILITY_RESULT_WARN,
-                        new Object[] { config.getMinGradeLevel(), config.getMaxGradeLevel(), scoreStr })));
-            } else {
-                log.debug("Retrieved in bounds readability {} based on range {}-{}", score, config.getMinGradeLevel(),
-                        config.getMaxGradeLevel());
-                insight.setScore(1.0);
-                insight.setPrimaryMessage(Message.success(dictionary.get(I18N_KEY_READABILITY_RESULT_SUCCESS,
-                        new Object[] { config.getMinGradeLevel(), config.getMaxGradeLevel(), scoreStr })));
-            }
-            Text t = svc.extractSentences(text);
-
-            insight.getScoreDetails().add(Message.defaultMsg(dictionary.get(I18N_KEY_READABILITY_STATS,
-                    new Object[] { t.getSentences().size(), t.getWordCount(), t.getComplexWordCount() })));
-            addDetail(insight, svc.calculateARI(t), "ARI");
-            addDetail(insight, svc.calculateColemanLiauIndex(t), "Coleman-Liau Index");
-            addDetail(insight, svc.calculateFleschKincaidGradeLevel(t), "Flesch-Kincaid Grade Level");
-            addDetail(insight, svc.calculateFleschReadingEase(t), "Flesch-Kincaid Reading Ease");
-            addDetail(insight, svc.calculateGunningFog(t), "Gunning Fog");
-            addDetail(insight, svc.calculateSMOG(t), "SMOG");
+            executeReadabilityCheck(insight, pageRequest, text, site, config, dictionary);
 
         } else {
             log.warn("Failed to get readability for resource {} site or config were null",
@@ -156,6 +111,56 @@ public class ReadabilityInsightProvider extends BaseInsightProvider {
         return insight;
     }
 
+    private void executeReadabilityCheck(Insight insight, PageInsightRequest pageRequest, String text, Site site,
+            ReadabilitySiteConfig config, I18NDictionary dictionary) {
+        ReadabilityService svc = factory.getReadabilityService(site.getLocale());
+
+        double score = svc.calculateAverageGradeLevel(text);
+        String scoreStr = new DecimalFormat("##0.00").format(score);
+
+        insight.setScored(true);
+
+        log.debug("Calculating readability of page {}", pageRequest.getPage());
+
+        if (score > config.getMaxGradeLevel() || score < config.getMinGradeLevel()) {
+            log.debug("Retrieved out of bounds readability {} based on range {}-{}", score,
+                    config.getMinGradeLevel(), config.getMaxGradeLevel());
+
+            StandardDeviation sd = new StandardDeviation(false);
+            double stddev = sd.evaluate(new double[] { config.getMinGradeLevel(), config.getMaxGradeLevel() });
+            double dev;
+            if (score > config.getMaxGradeLevel()) {
+                dev = score - config.getMaxGradeLevel();
+            } else {
+                dev = config.getMinGradeLevel() - score;
+            }
+            double calcScore = 1 - (dev / stddev) * .5;
+            if (calcScore > 0) {
+                insight.setScore(calcScore);
+            } else {
+                insight.setScore(0.0);
+            }
+            insight.setPrimaryMessage(Message.warn(dictionary.get(I18N_KEY_READABILITY_RESULT_WARN,
+                    new Object[] { config.getMinGradeLevel(), config.getMaxGradeLevel(), scoreStr })));
+        } else {
+            log.debug("Retrieved in bounds readability {} based on range {}-{}", score, config.getMinGradeLevel(),
+                    config.getMaxGradeLevel());
+            insight.setScore(1.0);
+            insight.setPrimaryMessage(Message.success(dictionary.get(I18N_KEY_READABILITY_RESULT_SUCCESS,
+                    new Object[] { config.getMinGradeLevel(), config.getMaxGradeLevel(), scoreStr })));
+        }
+        Text t = svc.extractSentences(text);
+
+        insight.getScoreDetails().add(Message.defaultMsg(dictionary.get(I18N_KEY_READABILITY_STATS,
+                new Object[] { t.getSentences().size(), t.getWordCount(), t.getComplexWordCount() })));
+        addDetail(insight, svc.calculateARI(t), "ARI");
+        addDetail(insight, svc.calculateColemanLiauIndex(t), "Coleman-Liau Index");
+        addDetail(insight, svc.calculateFleschKincaidGradeLevel(t), "Flesch-Kincaid Grade Level");
+        addDetail(insight, svc.calculateFleschReadingEase(t), "Flesch-Kincaid Reading Ease");
+        addDetail(insight, svc.calculateGunningFog(t), "Gunning Fog");
+        addDetail(insight, svc.calculateSMOG(t), "SMOG");
+    }
+
     @Override
     public String getId() {
         return READABILITY_CA_CONFIG;
diff --git a/core/src/main/java/org/apache/sling/cms/core/internal/filters/EditIncludeFilter.java b/core/src/main/java/org/apache/sling/cms/core/internal/filters/EditIncludeFilter.java
index b8e9993..2527f10 100644
--- a/core/src/main/java/org/apache/sling/cms/core/internal/filters/EditIncludeFilter.java
+++ b/core/src/main/java/org/apache/sling/cms/core/internal/filters/EditIncludeFilter.java
@@ -18,7 +18,9 @@ package org.apache.sling.cms.core.internal.filters;
 
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.util.Collections;
 import java.util.Iterator;
+import java.util.Optional;
 
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
@@ -47,7 +49,7 @@ public class EditIncludeFilter implements Filter {
     public static final String ENABLED_ATTR_NAME = "cmsEditEnabled";
 
     @Override
-    public void init(FilterConfig filterConfig) throws ServletException {
+    public void destroy() {
         // Nothing required
     }
 
@@ -59,33 +61,8 @@ public class EditIncludeFilter implements Filter {
         boolean includeEnd = false;
 
         if (enabled) {
-
-            String editPath = null;
-            Resource resource = ((SlingHttpServletRequest) request).getResource();
-
-            EditableResource editableResource = new EditableResourceImpl(resource);
-            Component component = editableResource.getComponent();
-            if (component != null && !component.isType(CMSConstants.COMPONENT_TYPE_PAGE)) {
-                editPath = component.getEditPath();
-            }
-
             writer = response.getWriter();
-
-            if (StringUtils.isNotEmpty(editPath)) {
-                includeEnd = true;
-                writeEditorMarkup(resource, writer);
-            } else if (component != null && !component.isEditable()) {
-                includeEnd = true;
-                EditableResource er = resource.adaptTo(EditableResource.class);
-                if (er != null) {
-                    component = er.getComponent();
-                }
-                writer = response.getWriter();
-                writer.write("<div class=\"sling-cms-component\" data-sling-cms-title=\""
-                        + (component != null ? component.getTitle() : "") + "\" data-sling-cms-resource-path=\""
-                        + resource.getPath() + "\" data-sling-cms-resource-type=\"" + resource.getResourceType()
-                        + "\">");
-            }
+            includeEnd = writeHeader(request, writer, includeEnd);
         }
         chain.doFilter(request, response);
         if (enabled && writer != null && includeEnd) {
@@ -93,15 +70,30 @@ public class EditIncludeFilter implements Filter {
         }
     }
 
-    private void writeEditorMarkup(Resource resource, PrintWriter writer) {
+    private Iterator<Resource> getSiblings(Resource resource) {
+        return Optional.ofNullable(resource.getParent()).map(p -> p.listChildren()).orElse(Collections.emptyIterator());
+    }
 
-        boolean last = false;
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+        // Nothing required
+    }
+
+    private boolean isFirst(Resource resource) {
         boolean first = false;
         if (resource != null && resource.getParent() != null) {
-            Iterator<Resource> children = resource.getParent().listChildren();
+            Iterator<Resource> children = getSiblings(resource);
             if (!children.hasNext() || children.next().getPath().equals(resource.getPath())) {
                 first = true;
             }
+        }
+        return first;
+    }
+
+    private boolean isLast(Resource resource) {
+        boolean last = false;
+        if (resource != null && resource.getParent() != null) {
+            Iterator<Resource> children = getSiblings(resource);
             if (children.hasNext()) {
                 while (children.hasNext()) {
                     if (children.next().getPath().equals(resource.getPath()) && !children.hasNext()) {
@@ -112,19 +104,22 @@ public class EditIncludeFilter implements Filter {
                 last = true;
             }
         }
+        return last;
+    }
+
+    private void writeEditorMarkup(Resource resource, PrintWriter writer) {
+
         boolean exists = resource.getResourceResolver().getResource(resource.getPath()) != null;
+        boolean last = isFirst(resource);
+        boolean first = isLast(resource);
 
-        Component component = null;
         EditableResource er = new EditableResourceImpl(resource);
-        String editPath = "";
-        if (er != null) {
-            component = er.getComponent();
-            editPath = component.getEditPath();
-        }
-        String title = component != null ? component.getTitle()
+        Component component = er.getComponent();
+        String editPath = component.getEditPath();
+        String title = StringUtils.isNotEmpty(component.getTitle()) ? component.getTitle()
                 : StringUtils.substringAfterLast(resource.getResourceType(), "/");
-        writer.write("<div class=\"sling-cms-component\" data-component=\"" + component.getResource().getPath() + "\" data-sling-cms-title=\""
-                + title + "\" data-sling-cms-resource-path=\"" + resource.getPath()
+        writer.write("<div class=\"sling-cms-component\" data-component=\"" + component.getResource().getPath()
+                + "\" data-sling-cms-title=\"" + title + "\" data-sling-cms-resource-path=\"" + resource.getPath()
                 + "\" data-sling-cms-resource-type=\"" + resource.getResourceType() + "\" data-sling-cms-edit=\""
                 + editPath + "\"><div class=\"sling-cms-editor\">");
         writer.write(
@@ -147,16 +142,36 @@ public class EditIncludeFilter implements Filter {
         }
 
         writer.write("</div></div>");
-        if (component != null) {
-            writer.write(
-                    "<div class=\"level-right\"><div class=\"level-item has-text-light\">" + title + "</div></div>");
-        }
+        writer.write("<div class=\"level-right\"><div class=\"level-item has-text-light\">" + title + "</div></div>");
         writer.write("</div></div>");
     }
 
-    @Override
-    public void destroy() {
-        // Nothing required
+    private boolean writeHeader(ServletRequest request, PrintWriter writer, boolean includeEnd) {
+        String editPath = null;
+        Resource resource = ((SlingHttpServletRequest) request).getResource();
+
+        EditableResource editableResource = new EditableResourceImpl(resource);
+        Component component = editableResource.getComponent();
+        if (component != null && !component.isType(CMSConstants.COMPONENT_TYPE_PAGE)) {
+            editPath = component.getEditPath();
+        }
+
+
+        if (StringUtils.isNotEmpty(editPath)) {
+            includeEnd = true;
+            writeEditorMarkup(resource, writer);
+        } else if (component != null && !component.isEditable()) {
+            includeEnd = true;
+            EditableResource er = resource.adaptTo(EditableResource.class);
+            if (er != null) {
+                component = er.getComponent();
+            }
+            writer.write("<div class=\"sling-cms-component\" data-sling-cms-title=\""
+                    + (component != null ? component.getTitle() : "") + "\" data-sling-cms-resource-path=\""
+                    + resource.getPath() + "\" data-sling-cms-resource-type=\"" + resource.getResourceType()
+                    + "\">");
+        }
+        return includeEnd;
     }
 
 }
diff --git a/core/src/main/java/org/apache/sling/cms/core/internal/operations/BulkReplaceOperation.java b/core/src/main/java/org/apache/sling/cms/core/internal/operations/BulkReplaceOperation.java
index 2e40792..ca1f708 100644
--- a/core/src/main/java/org/apache/sling/cms/core/internal/operations/BulkReplaceOperation.java
+++ b/core/src/main/java/org/apache/sling/cms/core/internal/operations/BulkReplaceOperation.java
@@ -56,6 +56,7 @@ public class BulkReplaceOperation implements PostOperation {
     public static final String PN_REPLACE = "replace";
     public static final String PN_MODE = "mode";
 
+    @SuppressWarnings("javasecurity:S2631") // ignoring warning since this servlet can only be executed by privileged users
     @Override
     public void run(SlingHttpServletRequest request, PostResponse response, SlingPostProcessor[] processors) {
 
@@ -73,6 +74,7 @@ public class BulkReplaceOperation implements PostOperation {
             String find = request.getParameter(PN_FIND);
             if (MODE_REGEX.equals(request.getParameter(PN_MODE))) {
                 log.debug("Using regular expressions to search for {}", find);
+                
                 rfind = Pattern.compile(find);
             } else {
                 log.debug("Searching for {}", find);
diff --git a/core/src/main/java/org/apache/sling/cms/core/internal/operations/UpdateReferencesPostOperation.java b/core/src/main/java/org/apache/sling/cms/core/internal/operations/UpdateReferencesPostOperation.java
index 5684973..fd330a8 100644
--- a/core/src/main/java/org/apache/sling/cms/core/internal/operations/UpdateReferencesPostOperation.java
+++ b/core/src/main/java/org/apache/sling/cms/core/internal/operations/UpdateReferencesPostOperation.java
@@ -39,46 +39,49 @@ import org.slf4j.LoggerFactory;
 @Component(immediate = true, service = { SlingPostProcessor.class }, property = Constants.SERVICE_RANKING + "=-1")
 public class UpdateReferencesPostOperation implements SlingPostProcessor {
 
-	public static final String RP_UPDATE_REFERENCES = SlingPostConstants.RP_PREFIX + "updateReferences";
+    public static final String RP_UPDATE_REFERENCES = SlingPostConstants.RP_PREFIX + "updateReferences";
 
-	private static final Logger log = LoggerFactory.getLogger(UpdateReferencesPostOperation.class);
+    private static final Logger log = LoggerFactory.getLogger(UpdateReferencesPostOperation.class);
 
-	@Override
-	public void process(SlingHttpServletRequest request, final List<Modification> changes) throws Exception {
-		if ((SlingPostConstants.OPERATION_DELETE.equals(request.getParameter(SlingPostConstants.RP_OPERATION))
-				|| SlingPostConstants.OPERATION_MOVE.equals(request.getParameter(SlingPostConstants.RP_OPERATION)))
-				&& "true".equalsIgnoreCase(request.getParameter(RP_UPDATE_REFERENCES))) {
+    @Override
+    public void process(SlingHttpServletRequest request, final List<Modification> changes) throws Exception {
+        if ((SlingPostConstants.OPERATION_DELETE.equals(request.getParameter(SlingPostConstants.RP_OPERATION))
+                || SlingPostConstants.OPERATION_MOVE.equals(request.getParameter(SlingPostConstants.RP_OPERATION)))
+                && "true".equalsIgnoreCase(request.getParameter(RP_UPDATE_REFERENCES))) {
+            updateReferences(request, changes);
+        }
+    }
 
-			final String find = request.getResource().getPath();
-			final String destination = request.getParameter(SlingPostConstants.RP_DEST);
-			log.debug("Using destination: {}", destination);
-			ReferenceOperation ro = new ReferenceOperation(request.getResource()) {
-				@Override
-				public void doProcess(Resource resource, String matchingKey) {
-					ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
-					log.trace("Updating references in property {}@{}", resource.getPath(), matchingKey);
-					if (properties != null) {
-						if (properties.get(matchingKey) instanceof String) {
-							String value = properties.get(matchingKey, "").replace(find, destination);
-							properties.put(matchingKey, value);
-							log.trace("Updated value {}", value);
-						} else if (properties.get(matchingKey) instanceof String[]) {
-							String[] values = properties.get(matchingKey, new String[0]);
-							for (int i = 0; i < values.length; i++) {
-								values[i] = values[i].replace(find, destination);
-							}
-							properties.put(matchingKey, values);
-							if (log.isTraceEnabled()) {
-								log.trace("Updated values {}", Arrays.toString(values));
-							}
-						}
-					} else {
-						log.warn("Unable to update references in {}, unable to edit", resource);
-					}
-					changes.add(Modification.onModified(resource.getPath()));
-				}
-			};
-			ro.init();
-		}
-	}
+    private void updateReferences(SlingHttpServletRequest request, final List<Modification> changes) {
+        final String find = request.getResource().getPath();
+        final String destination = request.getParameter(SlingPostConstants.RP_DEST);
+        log.debug("Using destination: {}", destination);
+        ReferenceOperation ro = new ReferenceOperation(request.getResource()) {
+            @Override
+            public void doProcess(Resource resource, String matchingKey) {
+                ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);
+                log.trace("Updating references in property {}@{}", resource.getPath(), matchingKey);
+                if (properties != null) {
+                    if (properties.get(matchingKey) instanceof String) {
+                        String value = properties.get(matchingKey, "").replace(find, destination);
+                        properties.put(matchingKey, value);
+                        log.trace("Updated value {}", value);
+                    } else if (properties.get(matchingKey) instanceof String[]) {
+                        String[] values = properties.get(matchingKey, new String[0]);
+                        for (int i = 0; i < values.length; i++) {
+                            values[i] = values[i].replace(find, destination);
+                        }
+                        properties.put(matchingKey, values);
+                        if (log.isTraceEnabled()) {
+                            log.trace("Updated values {}", Arrays.toString(values));
+                        }
+                    }
+                } else {
+                    log.warn("Unable to update references in {}, unable to edit", resource);
+                }
+                changes.add(Modification.onModified(resource.getPath()));
+            }
+        };
+        ro.init();
+    }
 }
diff --git a/core/src/main/java/org/apache/sling/cms/core/internal/rewriter/HTML5Serializer.java b/core/src/main/java/org/apache/sling/cms/core/internal/rewriter/HTML5Serializer.java
index 0331542..35976a4 100644
--- a/core/src/main/java/org/apache/sling/cms/core/internal/rewriter/HTML5Serializer.java
+++ b/core/src/main/java/org/apache/sling/cms/core/internal/rewriter/HTML5Serializer.java
@@ -18,6 +18,7 @@ package org.apache.sling.cms.core.internal.rewriter;
 
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Set;
 
@@ -43,22 +44,11 @@ public class HTML5Serializer implements Serializer {
 
     private static final int CHAR_LT = 60;
 
-    private final Set<String> emptyTags = new HashSet<String>() {
-        private static final long serialVersionUID = 1L;
-        {
-            add("br");
-            add("area");
-            add("link");
-            add("img");
-            add("param");
-            add("hr");
-            add("input");
-            add("col");
-            add("base");
-            add("meta");
-        }
-    };
+    private static final Set<String> emptyTags = new HashSet<>();
+    static {
+        emptyTags.addAll(Arrays.asList("br", "area", "link", "img", "param", "hr", "input", "col", "base", "meta"));
 
+    };
     private PrintWriter writer;
 
     private ConfigurationResourceResolver resolver;
@@ -146,24 +136,14 @@ public class HTML5Serializer implements Serializer {
         for (int i = 0; i < atts.getLength(); i++) {
             if ("endSlash".equals(atts.getQName(i))) {
                 endSlash = true;
-                continue;
-            }
-            if ("a".equals(localName) && "shape".equals(atts.getLocalName(i))) {
-                continue;
-            }
-            if ("iframe".equals(localName)
-                    && ("frameborder".equals(atts.getLocalName(i)) || "scrolling".equals(atts.getLocalName(i)))) {
-                continue;
             }
-            if ("br".equals(localName) && ("clear".equals(atts.getLocalName(i)))) {
+            String value = atts.getValue(i);
+            if (shouldContinue(localName, atts, i)) {
                 continue;
             }
             writer.write(CHAR_SP);
             writer.write(atts.getLocalName(i));
-            String value = atts.getValue(i);
-            if (value == null) {
-                continue;
-            }
+
             writer.write(CHAR_EQ);
             writer.write('"');
             writer.write(value);
@@ -176,6 +156,26 @@ public class HTML5Serializer implements Serializer {
         writer.write(CHAR_GT);
     }
 
+    private boolean shouldContinue(String localName, Attributes atts, int i) {
+        if ("endSlash".equals(atts.getQName(i))) {
+            return true;
+        }
+        if ("a".equals(localName) && "shape".equals(atts.getLocalName(i))) {
+            return true;
+        }
+        if ("iframe".equals(localName)
+                && ("frameborder".equals(atts.getLocalName(i)) || "scrolling".equals(atts.getLocalName(i)))) {
+            return true;
+        }
+        if ("br".equals(localName) && ("clear".equals(atts.getLocalName(i)))) {
+            return true;
+        }
+        if (atts.getValue(i) == null) {
+            return true;
+        }
+        return false;
+    }
+
     @Override
     public void startPrefixMapping(String s, String s1) throws SAXException {
         // Nothing required


[sling-org-apache-sling-app-cms] 01/02: Adding a servlet to download files rather than just linking to them

Posted by dk...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

dklco pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-app-cms.git

commit 2167c18eb9b2f60c14d84679ee08e77237d04467
Author: Dan Klco <dk...@apache.org>
AuthorDate: Tue Jul 2 14:43:25 2019 -0400

    Adding a servlet to download files rather than just linking to them
---
 .../internal/servlets/DownloadFileServlet.java     | 28 +++++++++++++++++++++-
 .../libs/sling-cms/content/file/download.json      |  4 ++++
 .../libs/sling-cms/content/site/content.json       |  6 +++--
 .../libs/sling-cms/content/static/content.json     |  6 +++--
 4 files changed, 39 insertions(+), 5 deletions(-)

diff --git a/core/src/main/java/org/apache/sling/cms/core/internal/servlets/DownloadFileServlet.java b/core/src/main/java/org/apache/sling/cms/core/internal/servlets/DownloadFileServlet.java
index 124060c..c0ffb28 100644
--- a/core/src/main/java/org/apache/sling/cms/core/internal/servlets/DownloadFileServlet.java
+++ b/core/src/main/java/org/apache/sling/cms/core/internal/servlets/DownloadFileServlet.java
@@ -1,12 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.apache.sling.cms.core.internal.servlets;
 
 import java.io.IOException;
+import java.io.InputStream;
 
 import javax.servlet.Servlet;
 import javax.servlet.ServletException;
 
+import org.apache.poi.util.IOUtils;
 import org.apache.sling.api.SlingHttpServletRequest;
 import org.apache.sling.api.SlingHttpServletResponse;
+import org.apache.sling.api.resource.Resource;
 import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
 import org.osgi.service.component.annotations.Component;
 
@@ -16,9 +35,16 @@ public class DownloadFileServlet extends SlingSafeMethodsServlet {
 
     private static final long serialVersionUID = 6234007100684499058L;
 
+    @Override
     protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
             throws ServletException, IOException {
-        handleMethodNotImplemented(request, response);
+        Resource suffixResource = request.getRequestPathInfo().getSuffixResource();
+        if (suffixResource != null) {
+            response.setHeader("Content-Disposition", "attachment; " + suffixResource.getName());
+            IOUtils.copy(suffixResource.adaptTo(InputStream.class), response.getOutputStream());
+        } else {
+            response.sendError(404);
+        }
     }
 
 }
diff --git a/ui/src/main/resources/jcr_root/libs/sling-cms/content/file/download.json b/ui/src/main/resources/jcr_root/libs/sling-cms/content/file/download.json
new file mode 100644
index 0000000..26a2209
--- /dev/null
+++ b/ui/src/main/resources/jcr_root/libs/sling-cms/content/file/download.json
@@ -0,0 +1,4 @@
+{
+    "jcr:primaryType": "nt:unstructured",
+    "sling:resourceType": "sling-cms/file/download"
+}
diff --git a/ui/src/main/resources/jcr_root/libs/sling-cms/content/site/content.json b/ui/src/main/resources/jcr_root/libs/sling-cms/content/site/content.json
index 1241863..672c375 100644
--- a/ui/src/main/resources/jcr_root/libs/sling-cms/content/site/content.json
+++ b/ui/src/main/resources/jcr_root/libs/sling-cms/content/site/content.json
@@ -189,7 +189,8 @@
                                     "jcr:primaryType": "nt:unstructured",
                                     "modal": false,
                                     "title": "Download file",
-                                    "icon": "download"
+                                    "icon": "download",
+                                    "prefix": "/cms/file/download.html"
                                 },
                                 "references": {
                                     "jcr:primaryType": "nt:unstructured",
@@ -265,7 +266,8 @@
                                     "jcr:primaryType": "nt:unstructured",
                                     "modal": false,
                                     "title": "Download file",
-                                    "icon": "download"
+                                    "icon": "download",
+                                    "prefix": "/cms/file/download.html"
                                 },
                                 "references": {
                                     "jcr:primaryType": "nt:unstructured",
diff --git a/ui/src/main/resources/jcr_root/libs/sling-cms/content/static/content.json b/ui/src/main/resources/jcr_root/libs/sling-cms/content/static/content.json
index 77a36e4..034d36e 100644
--- a/ui/src/main/resources/jcr_root/libs/sling-cms/content/static/content.json
+++ b/ui/src/main/resources/jcr_root/libs/sling-cms/content/static/content.json
@@ -111,7 +111,8 @@
                                     "jcr:primaryType": "nt:unstructured",
                                     "modal": false,
                                     "title": "Download file",
-                                    "icon": "download"
+                                    "icon": "download",
+                                    "prefix": "/cms/file/download.html"
                                 },
                                 "movecopy": {
                                     "jcr:primaryType": "nt:unstructured",
@@ -182,7 +183,8 @@
                                     "jcr:primaryType": "nt:unstructured",
                                     "modal": false,
                                     "title": "Download file",
-                                    "icon": "download"
+                                    "icon": "download",
+                                    "prefix": "/cms/file/download.html"
                                 },
                                 "references": {
                                     "jcr:primaryType": "nt:unstructured",