1
2
3
4
5
6
7
8
9
10 package de.funfried.netbeans.plugins.external.formatter.xml.jsoup;
11
12 import java.util.Objects;
13
14 import org.apache.commons.lang3.StringUtils;
15 import org.jsoup.Jsoup;
16 import org.jsoup.nodes.Document;
17 import org.jsoup.nodes.Entities;
18 import org.jsoup.parser.Parser;
19 import org.netbeans.api.annotations.common.CheckForNull;
20 import org.netbeans.api.annotations.common.NonNull;
21
22
23
24
25
26
27 public final class JsoupXmlFormatterWrapper {
28
29 private static final String DEFAULT_LINE_SEPARATOR = "\n";
30
31
32
33
34 JsoupXmlFormatterWrapper() {
35 }
36
37
38
39
40
41
42
43
44
45
46
47 @CheckForNull
48 public String format(String code, String lineFeed, Document.OutputSettings options) {
49 if (code == null) {
50 return null;
51 }
52
53 if (lineFeed == null) {
54 lineFeed = System.getProperty("line.separator");
55 }
56
57 if (options == null) {
58 options = new Document.OutputSettings();
59 }
60
61 options.escapeMode(Entities.EscapeMode.xhtml);
62 options.syntax(Document.OutputSettings.Syntax.xml);
63
64 return format(options, code, lineFeed);
65 }
66
67
68
69
70
71
72
73
74
75
76
77 @CheckForNull
78 private String format(Document.OutputSettings options, @NonNull String code, String lineFeed) {
79 Document document = Jsoup.parse(code, "", Parser.xmlParser());
80 document.outputSettings(options);
81
82 String formattedCode = document.outerHtml();
83 if (Objects.equals(code, formattedCode)) {
84 return null;
85 } else if (!DEFAULT_LINE_SEPARATOR.equals(lineFeed)) {
86 formattedCode = StringUtils.replace(formattedCode, DEFAULT_LINE_SEPARATOR, lineFeed);
87 }
88
89 return formattedCode;
90 }
91 }