1 /*
2 * Copyright (c) 2020 bahlef.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v2.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v20.html
7 * Contributors:
8 * bahlef - initial API and implementation and/or initial documentation
9 */
10 package de.funfried.netbeans.plugins.external.formatter.xml.revelc;
11
12 import java.util.Objects;
13
14 import org.netbeans.api.annotations.common.CheckForNull;
15 import org.netbeans.api.annotations.common.NonNull;
16
17 import net.revelc.code.formatter.xml.lib.FormattingPreferences;
18 import net.revelc.code.formatter.xml.lib.XmlDocumentFormatter;
19
20 /**
21 * Wrapper class to the revelc.net formatter implementation.
22 *
23 * @author bahlef
24 */
25 public final class RevelcXmlFormatterWrapper {
26 /**
27 * Package private Constructor for creating a new instance of {@link RevelcXmlFormatterWrapper}.
28 */
29 RevelcXmlFormatterWrapper() {
30 }
31
32 /**
33 * Formats the given {@code code} with the given configurations and returns
34 * the formatted code.
35 *
36 * @param code the unformatted code
37 * @param lineFeed the line feed to use for formatting
38 * @param prefs the {@link FormattingPreferences}
39 *
40 * @return the formatted code
41 */
42 @CheckForNull
43 public String format(String code, String lineFeed, FormattingPreferences prefs) {
44 if (code == null) {
45 return null;
46 }
47
48 if (lineFeed == null) {
49 lineFeed = System.getProperty("line.separator");
50 }
51
52 if (prefs == null) {
53 prefs = new FormattingPreferences();
54 }
55
56 XmlDocumentFormatter xmlFormatter = new XmlDocumentFormatter(lineFeed, prefs);
57
58 return format(xmlFormatter, code);
59 }
60
61 /**
62 * Formats the given {@code code} with the given configurations and returns
63 * the formatted code.
64 *
65 * @param xmlFormatter the {@link XmlDocumentFormatter}
66 * @param code the unformatted code
67 *
68 * @return the formatted code
69 */
70 @CheckForNull
71 private String format(XmlDocumentFormatter xmlFormatter, @NonNull String code) {
72 String formattedCode = xmlFormatter.format(code);
73 if (Objects.equals(code, formattedCode)) {
74 return null;
75 }
76
77 return formattedCode;
78 }
79 }