Autopsy  4.14.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
BingTranslatorSettingsPanel.java
Go to the documentation of this file.
1 /*
2  * Autopsy
3  *
4  * Copyright 2019 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.texttranslation.translators;
20 
21 import com.google.gson.JsonArray;
22 import com.google.gson.JsonElement;
23 import com.google.gson.JsonParser;
24 import com.google.gson.JsonObject;
25 import com.squareup.okhttp.MediaType;
26 import com.squareup.okhttp.OkHttpClient;
27 import com.squareup.okhttp.Request;
28 import com.squareup.okhttp.RequestBody;
29 import com.squareup.okhttp.Response;
30 import java.io.IOException;
31 import java.util.logging.Level;
33 import javax.swing.event.DocumentEvent;
34 import javax.swing.event.DocumentListener;
35 import org.apache.commons.lang3.StringUtils;
36 import org.openide.util.NbBundle.Messages;
37 
41 public class BingTranslatorSettingsPanel extends javax.swing.JPanel {
42 
43  private static final Logger logger = Logger.getLogger(BingTranslatorSettingsPanel.class.getName());
44  private static final long serialVersionUID = 1L;
45  private static final String GET_TARGET_LANGUAGES_URL = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation";
46  private static final String DEFUALT_TEST_STRING = "traducción exitoso"; //spanish which should translate to something along the lines of "successful translation"
47  private String targetLanguageCode = "";
48 
52  public BingTranslatorSettingsPanel(String authenticationKey, String code) {
54  authenticationKeyField.setText(authenticationKey);
55  authenticationKeyField.getDocument().addDocumentListener(new DocumentListener() {
56  @Override
57  public void insertUpdate(DocumentEvent e) {
58  testResultValueLabel.setText("");
59  firePropertyChange("SettingChanged", true, false);
60  }
61 
62  @Override
63  public void removeUpdate(DocumentEvent e) {
64  testResultValueLabel.setText("");
65  firePropertyChange("SettingChanged", true, false);
66  }
67 
68  @Override
69  public void changedUpdate(DocumentEvent e) {
70  testResultValueLabel.setText("");
71  firePropertyChange("SettingChanged", true, false);
72  }
73 
74  });
77  targetLanguageCode = code;
78  }
79 
83  @Messages({"BingTranslatorSettingsPanel.warning.targetLanguageFailure=Unable to get list of target languages or parse the result that was received"})
84  private void populateComboBox() {
85  Request get_request = new Request.Builder()
86  .url(GET_TARGET_LANGUAGES_URL).build();
87  try {
88  Response response = new OkHttpClient().newCall(get_request).execute();
89  JsonParser parser = new JsonParser();
90  String responseBody = response.body().string();
91  JsonElement elementBody = parser.parse(responseBody);
92  JsonObject asObject = elementBody.getAsJsonObject();
93  JsonElement translationElement = asObject.get("translation");
94  JsonObject responses = translationElement.getAsJsonObject();
95  responses.entrySet().forEach((entry) -> {
96  targetLanguageComboBox.addItem(new LanguageWrapper(entry.getKey(), entry.getValue().getAsJsonObject().get("name").getAsString()));
97  });
98  targetLanguageComboBox.setEnabled(true);
99  } catch (IOException | IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException ex) {
100  logger.log(Level.SEVERE, Bundle.BingTranslatorSettingsPanel_warning_targetLanguageFailure(), ex);
101  warningLabel.setText(Bundle.BingTranslatorSettingsPanel_warning_targetLanguageFailure());
102  targetLanguageComboBox.setEnabled(false);
103  }
104 
105  }
106 
113  private void selectLanguageByCode(String code) {
114  for (int i = 0; i < targetLanguageComboBox.getModel().getSize(); i++) {
115  if (targetLanguageComboBox.getModel().getElementAt(i).getLanguageCode().equals(code)) {
116  targetLanguageComboBox.setSelectedIndex(i);
117  break;
118  }
119  }
120  }
121 
127  @SuppressWarnings("unchecked")
128  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
129  private void initComponents() {
130 
131  authenticationKeyField = new javax.swing.JTextField();
132  warningLabel = new javax.swing.JLabel();
133  testButton = new javax.swing.JButton();
134  targetLanguageLabel = new javax.swing.JLabel();
135  targetLanguageComboBox = new javax.swing.JComboBox<>();
136  testUntranslatedTextField = new javax.swing.JTextField();
137  untranslatedLabel = new javax.swing.JLabel();
138  resultLabel = new javax.swing.JLabel();
139  testResultValueLabel = new javax.swing.JLabel();
140  authenticationKeyLabel = new javax.swing.JLabel();
141  instructionsScrollPane = new javax.swing.JScrollPane();
142  instructionsTextArea = new javax.swing.JTextArea();
143 
144  authenticationKeyField.setToolTipText(org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.authenticationKeyField.toolTipText")); // NOI18N
145 
146  warningLabel.setForeground(new java.awt.Color(255, 0, 0));
147  org.openide.awt.Mnemonics.setLocalizedText(warningLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.warningLabel.text")); // NOI18N
148 
149  org.openide.awt.Mnemonics.setLocalizedText(testButton, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.testButton.text")); // NOI18N
150  testButton.addActionListener(new java.awt.event.ActionListener() {
151  public void actionPerformed(java.awt.event.ActionEvent evt) {
153  }
154  });
155 
156  org.openide.awt.Mnemonics.setLocalizedText(targetLanguageLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.targetLanguageLabel.text")); // NOI18N
157 
158  targetLanguageComboBox.setEnabled(false);
159  targetLanguageComboBox.addItemListener(new java.awt.event.ItemListener() {
160  public void itemStateChanged(java.awt.event.ItemEvent evt) {
162  }
163  });
164 
165  testUntranslatedTextField.setText(DEFUALT_TEST_STRING);
166 
167  org.openide.awt.Mnemonics.setLocalizedText(untranslatedLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.untranslatedLabel.text")); // NOI18N
168 
169  org.openide.awt.Mnemonics.setLocalizedText(resultLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.resultLabel.text")); // NOI18N
170 
171  org.openide.awt.Mnemonics.setLocalizedText(testResultValueLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.testResultValueLabel.text")); // NOI18N
172 
173  org.openide.awt.Mnemonics.setLocalizedText(authenticationKeyLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.authenticationKeyLabel.text")); // NOI18N
174 
175  instructionsScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder());
176  instructionsScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
177 
178  instructionsTextArea.setEditable(false);
179  instructionsTextArea.setBackground(new java.awt.Color(240, 240, 240));
180  instructionsTextArea.setColumns(20);
181  instructionsTextArea.setLineWrap(true);
182  instructionsTextArea.setRows(2);
183  instructionsTextArea.setText(org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.instructionsTextArea.text")); // NOI18N
184  instructionsTextArea.setWrapStyleWord(true);
186 
187  javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
188  this.setLayout(layout);
189  layout.setHorizontalGroup(
190  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
191  .addGroup(layout.createSequentialGroup()
192  .addContainerGap()
193  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
194  .addComponent(instructionsScrollPane)
195  .addGroup(layout.createSequentialGroup()
196  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
197  .addGroup(layout.createSequentialGroup()
198  .addComponent(authenticationKeyLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
199  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
200  .addComponent(authenticationKeyField, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
201  .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 551, javax.swing.GroupLayout.PREFERRED_SIZE)
202  .addGroup(layout.createSequentialGroup()
203  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
204  .addComponent(targetLanguageLabel)
205  .addComponent(testButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
206  .addGap(18, 18, 18)
207  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
208  .addGroup(layout.createSequentialGroup()
209  .addComponent(untranslatedLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
210  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
211  .addComponent(testUntranslatedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
212  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
213  .addComponent(resultLabel)
214  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
215  .addComponent(testResultValueLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
216  .addGroup(layout.createSequentialGroup()
217  .addComponent(targetLanguageComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
218  .addGap(276, 276, 276)))))
219  .addGap(0, 0, Short.MAX_VALUE)))
220  .addContainerGap())
221  );
222  layout.setVerticalGroup(
223  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
224  .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
225  .addContainerGap()
226  .addComponent(instructionsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
227  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
228  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
229  .addComponent(authenticationKeyField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
230  .addComponent(authenticationKeyLabel))
231  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
232  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
233  .addComponent(targetLanguageLabel)
234  .addComponent(targetLanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
235  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
236  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
237  .addComponent(testButton)
238  .addComponent(testUntranslatedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
239  .addComponent(untranslatedLabel)
240  .addComponent(resultLabel)
241  .addComponent(testResultValueLabel))
242  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
243  .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
244  .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
245  );
246  }// </editor-fold>//GEN-END:initComponents
247 
248  @Messages({"BingTranslatorSettingsPanel.warning.invalidKey=Invalid translation authentication key"})
249  private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed
250  if (testTranslationSetup()) {
251  warningLabel.setText("");
252  } else {
253  warningLabel.setText(Bundle.BingTranslatorSettingsPanel_warning_invalidKey());
254  }
255  }//GEN-LAST:event_testButtonActionPerformed
256 
257  private void targetLanguageComboBoxSelected(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_targetLanguageComboBoxSelected
258  String selectedCode = ((LanguageWrapper) targetLanguageComboBox.getSelectedItem()).getLanguageCode();
259  if (!StringUtils.isBlank(selectedCode) && !selectedCode.equals(targetLanguageCode)) {
260  targetLanguageCode = selectedCode;
261  testResultValueLabel.setText("");
262  firePropertyChange("SettingChanged", true, false);
263  }
264  }//GEN-LAST:event_targetLanguageComboBoxSelected
265 
266  // Variables declaration - do not modify//GEN-BEGIN:variables
267  private javax.swing.JTextField authenticationKeyField;
268  private javax.swing.JLabel authenticationKeyLabel;
269  private javax.swing.JScrollPane instructionsScrollPane;
270  private javax.swing.JTextArea instructionsTextArea;
271  private javax.swing.JLabel resultLabel;
272  private javax.swing.JComboBox<LanguageWrapper> targetLanguageComboBox;
273  private javax.swing.JLabel targetLanguageLabel;
274  private javax.swing.JButton testButton;
275  private javax.swing.JLabel testResultValueLabel;
276  private javax.swing.JTextField testUntranslatedTextField;
277  private javax.swing.JLabel untranslatedLabel;
278  private javax.swing.JLabel warningLabel;
279  // End of variables declaration//GEN-END:variables
280 
288  private boolean testTranslationSetup() {
289  testResultValueLabel.setText("");
290  MediaType mediaType = MediaType.parse("application/json");
291  JsonArray jsonArray = new JsonArray();
292  JsonObject jsonObject = new JsonObject();
293  jsonObject.addProperty("Text", testUntranslatedTextField.getText());
294  jsonArray.add(jsonObject);
295  String bodyString = jsonArray.toString();
296 
297  RequestBody body = RequestBody.create(mediaType,
298  bodyString);
299  Request request = new Request.Builder()
300  .url(BingTranslator.getTranlatorUrl(targetLanguageCode)).post(body)
301  .addHeader("Ocp-Apim-Subscription-Key", authenticationKeyField.getText())
302  .addHeader("Content-type", "application/json").build();
303  try {
304  Response response = new OkHttpClient().newCall(request).execute();
305  JsonParser parser = new JsonParser();
306  JsonArray responses = parser.parse(response.body().string()).getAsJsonArray();
307  //As far as I know, there's always exactly one item in the array.
308  JsonObject response0 = responses.get(0).getAsJsonObject();
309  JsonArray translations = response0.getAsJsonArray("translations");
310  JsonObject translation0 = translations.get(0).getAsJsonObject();
311  testResultValueLabel.setText(translation0.get("text").getAsString());
312  return true;
313  } catch (IOException | IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException e) {
314  logger.log(Level.WARNING, "Test of Bing Translator failed due to exception", e);
315  return false;
316  }
317  }
318 
325  String getAuthenticationKey() {
326  return authenticationKeyField.getText();
327  }
328 
334  String getTargetLanguageCode() {
335  return targetLanguageCode;
336  }
337 }
synchronized static Logger getLogger(String name)
Definition: Logger.java:124

Copyright © 2012-2020 Basis Technology. Generated on: Wed Apr 8 2020
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.