1
2
3
4
5
6
7
8
9
10 package de.funfried.netbeans.plugins.external.formatter.json.jackson;
11
12 import java.util.prefs.Preferences;
13
14 import javax.swing.SwingUtilities;
15 import javax.swing.text.BadLocationException;
16 import javax.swing.text.StyledDocument;
17
18 import org.netbeans.editor.BaseDocument;
19 import org.openide.awt.NotificationDisplayer;
20 import org.openide.awt.StatusDisplayer;
21
22 import de.funfried.netbeans.plugins.external.formatter.AbstractFormatJob;
23 import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
24 import de.funfried.netbeans.plugins.external.formatter.ui.Icons;
25 import de.funfried.netbeans.plugins.external.formatter.ui.options.Settings;
26
27
28
29
30
31
32
33 class JacksonFormatJob extends AbstractFormatJob {
34
35 private final JacksonJsonFormatterWrapper formatter;
36
37
38
39
40
41
42
43 JacksonFormatJob(StyledDocument document, JacksonJsonFormatterWrapper formatter) {
44 super(document, null);
45
46 this.formatter = formatter;
47 }
48
49
50
51
52 @Override
53 public void format() throws BadLocationException {
54 Preferences pref = Settings.getActivePreferences(document);
55
56 int indentSize = pref.getInt(JacksonJsonFormatterSettings.INDENT_SIZE, 2);
57 int spacesPerTab = pref.getInt(JacksonJsonFormatterSettings.SPACES_PER_TAB, 2);
58 boolean expandTabToSpaces = pref.getBoolean(JacksonJsonFormatterSettings.EXPAND_TABS_TO_SPACES, true);
59 boolean spacesBeforeSeparator = pref.getBoolean(JacksonJsonFormatterSettings.SPACE_BEFORE_SEPARATOR, false);
60 String lineFeedSetting = pref.get(JacksonJsonFormatterSettings.LINEFEED, "");
61
62 JacksonJsonFormatterWrapper.Options options = new JacksonJsonFormatterWrapper.Options();
63 options.setIndentSize(indentSize);
64 options.setSpacesPerTab(spacesPerTab);
65 options.setExpandTabsToSpaces(expandTabToSpaces);
66 options.setSpaceBeforeSeparator(spacesBeforeSeparator);
67
68
69 String lineFeed = Settings.getLineFeed(lineFeedSetting, System.getProperty("line.separator"));
70 if (null != lineFeed) {
71 document.putProperty(BaseDocument.READ_LINE_SEPARATOR_PROP, lineFeed);
72 document.putProperty(BaseDocument.WRITE_LINE_SEPARATOR_PROP, lineFeed);
73 }
74
75 String code = getCode();
76
77 try {
78 String formattedContent = formatter.format(code, lineFeed, options);
79 if (setFormattedCode(code, formattedContent)) {
80 SwingUtilities.invokeLater(() -> {
81 if (pref.getBoolean(Settings.SHOW_NOTIFICATIONS, false)) {
82 NotificationDisplayer.getDefault().notify("Format using Jackson Json formatter", Icons.ICON_JACKSON, "", null);
83 }
84
85 StatusDisplayer.getDefault().setStatusText("Format using Jackson Json formatter");
86 });
87 }
88 } catch (FormattingFailedException ex) {
89 SwingUtilities.invokeLater(() -> {
90 StatusDisplayer.getDefault().setStatusText("Failed to format using Jackson Json formatter: " + ex.getMessage());
91 });
92
93 throw ex;
94 }
95 }
96 }