View Javadoc
1   package com.jsql.view.swing.panel.consoles;
2   
3   import com.jsql.model.bean.util.HttpHeader;
4   import com.jsql.model.injection.vendor.model.VendorYaml;
5   import com.jsql.util.I18nUtil;
6   import com.jsql.util.LogLevelUtil;
7   import com.jsql.util.StringUtil;
8   import com.jsql.view.swing.panel.util.HTMLEditorKitTextPaneWrap;
9   import com.jsql.view.swing.tab.TabbedPaneWheeled;
10  import com.jsql.view.swing.text.JPopupTextComponent;
11  import com.jsql.view.swing.text.JTextPanePlaceholder;
12  import com.jsql.view.swing.text.SyntaxTextArea;
13  import com.jsql.view.swing.util.I18nViewUtil;
14  import com.jsql.view.swing.util.MediatorHelper;
15  import com.jsql.view.swing.util.UiUtil;
16  import org.apache.commons.lang3.StringUtils;
17  import org.apache.logging.log4j.LogManager;
18  import org.apache.logging.log4j.Logger;
19  import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
20  import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
21  import org.fife.ui.rtextarea.RTextScrollPane;
22  import org.jsoup.Jsoup;
23  import org.jsoup.safety.Safelist;
24  
25  import javax.swing.*;
26  import javax.swing.text.DefaultCaret;
27  import java.awt.*;
28  import java.awt.event.FocusAdapter;
29  import java.awt.event.FocusEvent;
30  import java.util.AbstractMap.SimpleEntry;
31  import java.util.Arrays;
32  import java.util.Map;
33  import java.util.stream.Stream;
34  
35  public class TabbedPaneNetworkTab extends TabbedPaneWheeled {
36      
37      /**
38       * Log4j logger sent to view.
39       */
40      private static final Logger LOGGER = LogManager.getRootLogger();
41  
42      private final RSyntaxTextArea textAreaUrl = new SyntaxTextArea(I18nUtil.valueByKey("NETWORK_LINE_PLACEHOLDER_URL"));
43      private final RSyntaxTextArea textAreaResponse = new SyntaxTextArea(I18nUtil.valueByKey("NETWORK_LINE_PLACEHOLDER_RESPONSE"));
44      private final RSyntaxTextArea textAreaSource = new SyntaxTextArea(I18nUtil.valueByKey("NETWORK_LINE_PLACEHOLDER_SOURCE"));
45      private final JTextPane textPanePreview = new JPopupTextComponent<>(new JTextPanePlaceholder(I18nUtil.valueByKey("NETWORK_LINE_PLACEHOLDER_PREVIEW")){
46          @Override
47          public boolean isEditable() {
48              return false;
49          }
50      }).getProxy();
51      private final RSyntaxTextArea textAreaHeader = new SyntaxTextArea(I18nUtil.valueByKey("NETWORK_LINE_PLACEHOLDER_HEADERS"));
52      private final RSyntaxTextArea textAreaRequest = new SyntaxTextArea(I18nUtil.valueByKey("NETWORK_LINE_PLACEHOLDER_REQUEST"));
53      private final JCheckBox checkBoxDecode = new JCheckBox("Decode", MediatorHelper.model().getMediatorUtils().getPreferencesUtil().isUrlDecodeNetworkTab());
54  
55      public TabbedPaneNetworkTab() {
56          this.setName("tabNetwork");
57          var panelDecode = new JPanel(new BorderLayout());
58          panelDecode.add(this.checkBoxDecode, BorderLayout.EAST);  // reduce to minimum size as checkbox expands by the label
59          this.putClientProperty("JTabbedPane.trailingComponent", panelDecode);
60          this.checkBoxDecode.setHorizontalTextPosition(SwingConstants.TRAILING);
61  
62          I18nViewUtil.addComponentForKey("NETWORK_LINE_PLACEHOLDER_URL", this.textAreaUrl);
63          I18nViewUtil.addComponentForKey("NETWORK_LINE_PLACEHOLDER_RESPONSE", this.textAreaResponse);
64          I18nViewUtil.addComponentForKey("NETWORK_LINE_PLACEHOLDER_SOURCE", this.textAreaSource);
65          I18nViewUtil.addComponentForKey("NETWORK_LINE_PLACEHOLDER_PREVIEW", this.textPanePreview);
66          I18nViewUtil.addComponentForKey("NETWORK_LINE_PLACEHOLDER_HEADERS", this.textAreaHeader);
67          I18nViewUtil.addComponentForKey("NETWORK_LINE_PLACEHOLDER_REQUEST", this.textAreaRequest);
68          Stream.of(
69              new SimpleEntry<>("NETWORK_TAB_URL_LABEL", this.textAreaUrl),
70              new SimpleEntry<>("NETWORK_TAB_HEADERS_LABEL", this.textAreaHeader),
71              new SimpleEntry<>("NETWORK_TAB_PARAMS_LABEL", this.textAreaRequest),
72              new SimpleEntry<>("NETWORK_TAB_RESPONSE_LABEL", this.textAreaResponse),
73              new SimpleEntry<>("NETWORK_TAB_SOURCE_LABEL", this.textAreaSource),
74              new SimpleEntry<>("NETWORK_TAB_PREVIEW_LABEL", this.textPanePreview)
75          )
76          .forEach(entry -> {
77              this.addTab(
78                  I18nUtil.valueByKey(entry.getKey()),
79                  entry.getValue() == this.textAreaSource
80                  ? new RTextScrollPane(entry.getValue(), false)
81                  : new JScrollPane(entry.getValue())
82              );
83              var label = new JLabel(I18nUtil.valueByKey(entry.getKey()));
84              label.setName("label"+ entry.getKey());
85              this.setTabComponentAt(
86                  this.indexOfTab(I18nUtil.valueByKey(entry.getKey())),
87                  label
88              );
89              I18nViewUtil.addComponentForKey(entry.getKey(), label);
90  
91              entry.getValue().setName("text"+ entry.getKey());
92  
93              DefaultCaret caret = (DefaultCaret) entry.getValue().getCaret();
94              caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
95          });
96  
97          Arrays.asList(this.textAreaUrl, this.textAreaHeader, this.textAreaRequest, this.textAreaResponse, this.textAreaSource).forEach(entry -> {
98              entry.setEditable(false);
99              entry.setLineWrap(true);
100         });
101         this.textAreaResponse.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_HTML);
102         this.textAreaSource.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_HTML);
103         this.textAreaSource.setHighlightSecondaryLanguages(true);
104         this.applyTheme();
105         
106         this.textPanePreview.setEditorKit(new HTMLEditorKitTextPaneWrap());
107         this.textPanePreview.setContentType("text/html");
108         this.textPanePreview.setEditable(false);
109         this.textPanePreview.getCaret().setBlinkRate(0);
110         this.textPanePreview.addFocusListener(new FocusAdapter() {
111             @Override
112             public void focusGained(FocusEvent focusEvent) {
113                 TabbedPaneNetworkTab.this.textPanePreview.getCaret().setVisible(true);
114                 TabbedPaneNetworkTab.this.textPanePreview.getCaret().setSelectionVisible(true);
115             }
116         });
117     }
118     
119     public void changeTextNetwork(HttpHeader networkData) {
120         this.textAreaRequest.setText(this.getDecodedValue(this.checkBoxDecode.isSelected(), networkData.getPost()));
121         this.textAreaUrl.setText(this.getDecodedValue(this.checkBoxDecode.isSelected(), networkData.getUrl()));
122         this.updateTextArea(this.textAreaHeader, networkData.getHeader());
123         this.updateTextArea(this.textAreaResponse, networkData.getResponse());
124 
125         // Fix #53736: ArrayIndexOutOfBoundsException on setText()
126         // Fix #54573: NullPointerException on setText()
127         try {
128             this.textAreaSource.setText(
129                 StringUtil.detectUtf8(networkData.getSource())
130                 .replaceAll(VendorYaml.CALIBRATOR_SQL +"{5,}", VendorYaml.CALIBRATOR_SQL +"*")
131                 .trim()
132             );
133         } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
134             LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
135         }
136         
137         this.textPanePreview.getEditorKit().createDefaultDocument();  // Reset EditorKit to disable previous document effect
138         // Proxy is used by jsoup to display <img> tags
139         // Previous test for 2xx Success and 3xx Redirection was Header only, now get the HTML content
140         // Fix #35352: EmptyStackException on setText()
141         // Fix #39841: RuntimeException on setText()
142         // Fix #42523: ExceptionInInitializerError on clean()
143         try {
144             this.textPanePreview.setText(
145                 Jsoup.clean(
146                     String.format(
147                         "<html>%s</html>",
148                         StringUtil.detectUtf8(networkData.getSource())
149                     )
150                     .replaceAll("<img[^>]*>",StringUtils.EMPTY)  // avoid loading external resources
151                     .replaceAll("<input[^>]*type=\"?hidden\"?.*>", StringUtils.EMPTY)
152                     .replaceAll(
153                         "<input[^>]*type=\"?(submit|button)\"?.*>",
154                         "<div style=\"background-color:#eeeeee;text-align:center;border:1px solid black;width:100px;\">button</div>"
155                     )
156                     .replaceAll(
157                         "<input[^>]*>",
158                         "<div style=\"text-align:center;border:1px solid black;width:100px;\">input</div>"
159                     ),
160                     Safelist.relaxed().addTags("center", "div", "span").addAttributes(":all", "style")
161                 )
162             );
163         } catch (Exception | ExceptionInInitializerError e) {
164             LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
165         }
166     }
167 
168     private void updateTextArea(JTextArea textArea, Map<String, String> httpData) {
169         textArea.setText(StringUtils.EMPTY);
170         if (httpData != null) {
171             httpData.forEach((key, value) -> {
172                 String decodedValue = this.getDecodedValue(this.checkBoxDecode.isSelected(), value);
173                 textArea.append(key + ": " + decodedValue + "\n");
174             });
175         }
176     }
177 
178     private String getDecodedValue(boolean isSelected, String value) {
179         return isSelected ? StringUtil.fromUrl(value) : value;
180     }
181 
182     public void reset() {
183         this.textAreaUrl.setText(StringUtils.EMPTY);
184         this.textAreaHeader.setText(StringUtils.EMPTY);
185         this.textAreaRequest.setText(StringUtils.EMPTY);
186         this.textAreaResponse.setText(StringUtils.EMPTY);
187         
188         // Fix #54572: NullPointerException on setText()
189         try {
190             this.textAreaSource.setText(StringUtils.EMPTY);
191         } catch (NullPointerException e) {
192             LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
193         }
194         
195         // Fix #41879: ArrayIndexOutOfBoundsException on setText()
196         try {
197             this.textPanePreview.setText(StringUtils.EMPTY);
198         } catch (ArrayIndexOutOfBoundsException e) {
199             LOGGER.log(LogLevelUtil.CONSOLE_JAVA, e, e);
200         }
201     }
202 
203     public void applyTheme() {
204         Arrays.asList(
205             this.textAreaUrl, this.textAreaHeader, this.textAreaRequest, this.textAreaResponse, this.textAreaSource
206         ).forEach(UiUtil::applySyntaxTheme);
207     }
208 
209     public JCheckBox getCheckBoxDecode() {
210         return this.checkBoxDecode;
211     }
212 }