1
2
3
4
5
6
7
8
9
10 package de.funfried.netbeans.plugins.external.formatter.java.palantir;
11
12 import java.util.ArrayList;
13 import java.util.Collection;
14 import java.util.SortedSet;
15
16 import org.apache.commons.collections4.CollectionUtils;
17 import org.apache.commons.lang3.tuple.Pair;
18 import org.netbeans.api.annotations.common.CheckForNull;
19
20 import com.google.common.collect.Range;
21 import com.palantir.javaformat.java.Formatter;
22 import com.palantir.javaformat.java.FormatterException;
23 import com.palantir.javaformat.java.ImportOrderer;
24 import com.palantir.javaformat.java.JavaFormatterOptions;
25 import com.palantir.javaformat.java.RemoveUnusedImports;
26
27 import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
28
29
30
31
32
33
34 public final class PalantirJavaFormatterWrapper {
35
36
37
38 PalantirJavaFormatterWrapper() {
39 }
40
41
42
43
44
45
46
47
48
49
50
51
52
53 @CheckForNull
54 public String format(String code, SortedSet<Pair<Integer, Integer>> changedElements) throws FormattingFailedException {
55 if (code == null) {
56 return null;
57 }
58
59 Collection<Range<Integer>> characterRanges = new ArrayList<>();
60 if (changedElements == null) {
61 characterRanges.add(Range.closedOpen(0, code.length()));
62 } else if (!CollectionUtils.isEmpty(changedElements)) {
63 for (Pair<Integer, Integer> changedElement : changedElements) {
64 int start = changedElement.getLeft();
65 int end = changedElement.getRight();
66
67 if (start == end) {
68 end++;
69 }
70
71 characterRanges.add(Range.open(start, end));
72 }
73 }
74
75 if (changedElements == null || !CollectionUtils.isEmpty(changedElements)) {
76 try {
77 Formatter formatter = Formatter.createFormatter(JavaFormatterOptions.builder().style(JavaFormatterOptions.Style.PALANTIR).build());
78 code = formatter.formatSource(code, characterRanges);
79 } catch (FormatterException ex) {
80 throw new FormattingFailedException(ex);
81 }
82 }
83
84 return code;
85 }
86
87 @CheckForNull
88 public String organizeImports(String code) throws FormattingFailedException {
89 if (code == null) {
90 return null;
91 }
92
93 try {
94 code = RemoveUnusedImports.removeUnusedImports(code);
95 } catch (FormatterException ex) {
96 throw new FormattingFailedException(ex);
97 }
98
99 try {
100 code = ImportOrderer.reorderImports(code, JavaFormatterOptions.Style.PALANTIR);
101 } catch (FormatterException ex) {
102 throw new FormattingFailedException(ex);
103 }
104
105 return code;
106 }
107 }