1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.ui.contentapp.configuration.column.renderer;
35
36 import info.magnolia.context.WebContext;
37
38 import java.util.Optional;
39
40 import javax.inject.Inject;
41
42 import org.apache.commons.lang3.StringUtils;
43 import org.jsoup.Jsoup;
44 import org.jsoup.nodes.Document;
45 import org.jsoup.nodes.Element;
46 import org.jsoup.safety.Cleaner;
47 import org.jsoup.safety.Whitelist;
48
49 import com.vaadin.ui.renderers.HtmlRenderer;
50
51 import elemental.json.JsonValue;
52
53
54
55
56 public class HtmlCleaningRenderer extends HtmlRenderer {
57
58 private static final Cleaner CLEANER = new Cleaner(Whitelist.relaxed()
59 .addAttributes("a", "target")
60 .addAttributes(":all", "class", "title", "style")
61 .preserveRelativeLinks(true)
62 );
63
64 private final String baseUri;
65
66 @Inject
67 public HtmlCleaningRenderer(WebContext context) {
68 baseUri = StringUtils.substringBefore(context.getRequest().getRequestURL().toString(), context.getContextPath());
69 }
70
71 @Override
72 public JsonValue encode(String value) {
73 return Optional.ofNullable(value)
74 .map(bodyHtml -> Jsoup.parseBodyFragment(bodyHtml, baseUri))
75 .filter(document -> !CLEANER.isValid(document))
76 .map(CLEANER::clean)
77 .map(Document::body)
78 .map(Element::html)
79 .map(super::encode)
80 .orElseGet(() -> super.encode(value));
81 }
82 }