1
2
3
4
5
6
7
8
9
10 package de.funfried.netbeans.plugins.external.formatter.java.spring;
11
12 import java.util.ArrayList;
13 import java.util.List;
14 import java.util.Objects;
15 import java.util.SortedSet;
16 import java.util.logging.Level;
17 import java.util.logging.Logger;
18
19 import org.apache.commons.collections4.CollectionUtils;
20 import org.apache.commons.lang3.tuple.Pair;
21 import org.eclipse.jdt.core.formatter.CodeFormatter;
22 import org.eclipse.jface.text.Document;
23 import org.eclipse.jface.text.IDocument;
24 import org.eclipse.jface.text.IRegion;
25 import org.eclipse.jface.text.Region;
26 import org.eclipse.text.edits.TextEdit;
27 import org.netbeans.api.annotations.common.CheckForNull;
28 import org.netbeans.api.annotations.common.NonNull;
29
30 import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
31 import io.spring.javaformat.formatter.Formatter;
32
33
34
35
36
37
38 public final class SpringJavaFormatterWrapper {
39
40 private static final int FORMATTER_OPTS = CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS ;
41
42
43 private final Formatter formatter = new Formatter();
44
45
46
47
48 SpringJavaFormatterWrapper() {
49 }
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 @CheckForNull
65 public String format(String code, String lineFeed, SortedSet<Pair<Integer, Integer>> changedElements) throws FormattingFailedException {
66 if (code == null) {
67 return null;
68 }
69
70 int codeLength = code.length();
71
72 List<IRegion> regions = new ArrayList<>();
73 if (changedElements == null) {
74 regions.add(new Region(0, codeLength));
75 } else if (!CollectionUtils.isEmpty(changedElements)) {
76 for (Pair<Integer, Integer> changedElement : changedElements) {
77 int length = (changedElement.getRight() - changedElement.getLeft()) + 1;
78 if (length > codeLength) {
79 length = codeLength;
80 }
81
82 regions.add(new Region(changedElement.getLeft(), length));
83 }
84 } else {
85
86 return code;
87 }
88
89 return format(code, regions.toArray(new IRegion[regions.size()]), lineFeed);
90 }
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105 @CheckForNull
106 private String format(@NonNull String code, @NonNull IRegion[] regions, String lineFeed) throws FormattingFailedException {
107 String formattedCode = null;
108
109 try {
110 TextEdit te = formatter.format(FORMATTER_OPTS, code, regions, 0, lineFeed);
111
112 if (te != null && te.getChildrenSize() > 0) {
113 IDocument dc = new Document(code);
114 te.apply(dc);
115
116 formattedCode = dc.get();
117
118 if (Objects.equals(code, formattedCode)) {
119 return null;
120 }
121 }
122 } catch (FormattingFailedException | IllegalArgumentException ex) {
123 throw ex;
124 } catch (Exception ex) {
125 Logger.getLogger(SpringJavaFormatterWrapper.class.getName()).log(Level.SEVERE, "Formatting ran into", ex);
126
127 throw new FormattingFailedException(ex);
128 }
129
130 return formattedCode;
131 }
132 }