1
2
3
4
5
6
7
8
9
10 package de.funfried.netbeans.plugins.external.formatter.java.google;
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.google.googlejavaformat.java.Formatter;
22 import com.google.googlejavaformat.java.FormatterException;
23 import com.google.googlejavaformat.java.ImportOrderer;
24 import com.google.googlejavaformat.java.JavaFormatterOptions;
25 import com.google.googlejavaformat.java.RemoveUnusedImports;
26
27 import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
28
29
30
31
32
33
34 public final class GoogleJavaFormatterWrapper {
35
36
37
38 GoogleJavaFormatterWrapper() {
39 }
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56 @CheckForNull
57 public String format(String code, JavaFormatterOptions.Style codeStyle, SortedSet<Pair<Integer, Integer>> changedElements)
58 throws FormattingFailedException {
59 if (code == null) {
60 return null;
61 }
62
63 if (codeStyle == null) {
64 codeStyle = JavaFormatterOptions.Style.GOOGLE;
65 }
66
67 Collection<Range<Integer>> characterRanges = new ArrayList<>();
68 if (changedElements == null) {
69 characterRanges.add(Range.closedOpen(0, code.length()));
70 } else if (!CollectionUtils.isEmpty(changedElements)) {
71 for (Pair<Integer, Integer> changedElement : changedElements) {
72 int start = changedElement.getLeft();
73 int end = changedElement.getRight();
74
75 if (start == end) {
76 end++;
77 }
78
79 characterRanges.add(Range.open(start, end));
80 }
81 }
82
83 if (changedElements == null || !CollectionUtils.isEmpty(changedElements)) {
84 try {
85 Formatter formatter = new Formatter(JavaFormatterOptions.builder().style(codeStyle).build());
86 code = formatter.formatSource(code, characterRanges);
87 } catch (FormatterException ex) {
88 throw new FormattingFailedException(ex);
89 }
90 }
91
92 return code;
93 }
94
95 @CheckForNull
96 public String organizeImports(String code, JavaFormatterOptions.Style codeStyle) throws FormattingFailedException {
97 if (code == null) {
98 return null;
99 }
100
101 if (codeStyle == null) {
102 codeStyle = JavaFormatterOptions.Style.GOOGLE;
103 }
104
105 try {
106 code = RemoveUnusedImports.removeUnusedImports(code);
107 } catch (FormatterException ex) {
108 throw new FormattingFailedException(ex);
109 }
110
111 try {
112 code = ImportOrderer.reorderImports(code, codeStyle);
113 } catch (FormatterException ex) {
114 throw new FormattingFailedException(ex);
115 }
116
117 return code;
118 }
119 }