Autopsy  4.12.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  firePropertyChange("SettingChanged", true, false);
59  }
60 
61  @Override
62  public void removeUpdate(DocumentEvent e) {
63  firePropertyChange("SettingChanged", true, false);
64  }
65 
66  @Override
67  public void changedUpdate(DocumentEvent e) {
68  firePropertyChange("SettingChanged", true, false);
69  }
70 
71  });
74  targetLanguageCode = code;
75  }
76 
80  @Messages({"BingTranslatorSettingsPanel.warning.targetLanguageFailure=Unable to get list of target languages or parse the result that was received"})
81  private void populateComboBox() {
82  Request get_request = new Request.Builder()
83  .url(GET_TARGET_LANGUAGES_URL).build();
84  try {
85  Response response = new OkHttpClient().newCall(get_request).execute();
86  JsonParser parser = new JsonParser();
87  String responseBody = response.body().string();
88  JsonElement elementBody = parser.parse(responseBody);
89  JsonObject asObject = elementBody.getAsJsonObject();
90  JsonElement translationElement = asObject.get("translation");
91  JsonObject responses = translationElement.getAsJsonObject();
92  responses.entrySet().forEach((entry) -> {
93  targetLanguageComboBox.addItem(new LanguageWrapper(entry.getKey(), entry.getValue().getAsJsonObject().get("name").getAsString()));
94  });
95  targetLanguageComboBox.setEnabled(true);
96  } catch (IOException | IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException ex) {
97  logger.log(Level.SEVERE, Bundle.BingTranslatorSettingsPanel_warning_targetLanguageFailure(), ex);
98  warningLabel.setText(Bundle.BingTranslatorSettingsPanel_warning_targetLanguageFailure());
99  targetLanguageComboBox.setEnabled(false);
100  }
101 
102  }
103 
110  private void selectLanguageByCode(String code) {
111  for (int i = 0; i < targetLanguageComboBox.getModel().getSize(); i++) {
112  if (targetLanguageComboBox.getModel().getElementAt(i).getLanguageCode().equals(code)) {
113  targetLanguageComboBox.setSelectedIndex(i);
114  break;
115  }
116  }
117  }
118 
124  @SuppressWarnings("unchecked")
125  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
126  private void initComponents() {
127 
128  authenticationKeyField = new javax.swing.JTextField();
129  warningLabel = new javax.swing.JLabel();
130  testButton = new javax.swing.JButton();
131  targetLanguageLabel = new javax.swing.JLabel();
132  targetLanguageComboBox = new javax.swing.JComboBox<>();
133  testUntranslatedTextField = new javax.swing.JTextField();
134  untranslatedLabel = new javax.swing.JLabel();
135  resultLabel = new javax.swing.JLabel();
136  testResultValueLabel = new javax.swing.JLabel();
137  authenticationKeyLabel = new javax.swing.JLabel();
138  instructionsScrollPane = new javax.swing.JScrollPane();
139  instructionsTextArea = new javax.swing.JTextArea();
140 
141  authenticationKeyField.setToolTipText(org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.authenticationKeyField.toolTipText")); // NOI18N
142 
143  warningLabel.setForeground(new java.awt.Color(255, 0, 0));
144  org.openide.awt.Mnemonics.setLocalizedText(warningLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "GoogleTranslatorSettingsPanel.warningLabel.text")); // NOI18N
145 
146  org.openide.awt.Mnemonics.setLocalizedText(testButton, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.testButton.text")); // NOI18N
147  testButton.addActionListener(new java.awt.event.ActionListener() {
148  public void actionPerformed(java.awt.event.ActionEvent evt) {
150  }
151  });
152 
153  org.openide.awt.Mnemonics.setLocalizedText(targetLanguageLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.targetLanguageLabel.text")); // NOI18N
154 
155  targetLanguageComboBox.setEnabled(false);
156  targetLanguageComboBox.addItemListener(new java.awt.event.ItemListener() {
157  public void itemStateChanged(java.awt.event.ItemEvent evt) {
159  }
160  });
161 
162  testUntranslatedTextField.setText(DEFUALT_TEST_STRING);
163 
164  org.openide.awt.Mnemonics.setLocalizedText(untranslatedLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.untranslatedLabel.text")); // NOI18N
165 
166  org.openide.awt.Mnemonics.setLocalizedText(resultLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.resultLabel.text")); // NOI18N
167 
168  org.openide.awt.Mnemonics.setLocalizedText(testResultValueLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.testResultValueLabel.text")); // NOI18N
169 
170  org.openide.awt.Mnemonics.setLocalizedText(authenticationKeyLabel, org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.authenticationKeyLabel.text")); // NOI18N
171 
172  instructionsScrollPane.setBorder(javax.swing.BorderFactory.createEtchedBorder());
173  instructionsScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
174 
175  instructionsTextArea.setEditable(false);
176  instructionsTextArea.setBackground(new java.awt.Color(240, 240, 240));
177  instructionsTextArea.setColumns(20);
178  instructionsTextArea.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
179  instructionsTextArea.setLineWrap(true);
180  instructionsTextArea.setRows(2);
181  instructionsTextArea.setText(org.openide.util.NbBundle.getMessage(BingTranslatorSettingsPanel.class, "BingTranslatorSettingsPanel.instructionsTextArea.text")); // NOI18N
182  instructionsTextArea.setWrapStyleWord(true);
184 
185  javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
186  this.setLayout(layout);
187  layout.setHorizontalGroup(
188  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
189  .addGroup(layout.createSequentialGroup()
190  .addContainerGap()
191  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
192  .addComponent(instructionsScrollPane)
193  .addGroup(layout.createSequentialGroup()
194  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
195  .addGroup(layout.createSequentialGroup()
196  .addComponent(authenticationKeyLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
197  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
198  .addComponent(authenticationKeyField, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
199  .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 551, javax.swing.GroupLayout.PREFERRED_SIZE)
200  .addGroup(layout.createSequentialGroup()
201  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
202  .addComponent(targetLanguageLabel)
203  .addComponent(testButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
204  .addGap(18, 18, 18)
205  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
206  .addGroup(layout.createSequentialGroup()
207  .addComponent(untranslatedLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
208  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
209  .addComponent(testUntranslatedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
210  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
211  .addComponent(resultLabel)
212  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
213  .addComponent(testResultValueLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
214  .addGroup(layout.createSequentialGroup()
215  .addComponent(targetLanguageComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
216  .addGap(276, 276, 276)))))
217  .addGap(0, 0, Short.MAX_VALUE)))
218  .addContainerGap())
219  );
220  layout.setVerticalGroup(
221  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
222  .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
223  .addContainerGap()
224  .addComponent(instructionsScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
225  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
226  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
227  .addComponent(authenticationKeyField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
228  .addComponent(authenticationKeyLabel))
229  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
230  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
231  .addComponent(targetLanguageLabel)
232  .addComponent(targetLanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
233  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
234  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
235  .addComponent(testButton)
236  .addComponent(testUntranslatedTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
237  .addComponent(untranslatedLabel)
238  .addComponent(resultLabel)
239  .addComponent(testResultValueLabel))
240  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
241  .addComponent(warningLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
242  .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
243  );
244  }// </editor-fold>//GEN-END:initComponents
245 
246  @Messages({"BingTranslatorSettingsPanel.warning.invalidKey=Invalid translation authentication key"})
247  private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed
248  if (testTranslationSetup()) {
249  warningLabel.setText("");
250  } else {
251  warningLabel.setText(Bundle.BingTranslatorSettingsPanel_warning_invalidKey());
252  }
253  }//GEN-LAST:event_testButtonActionPerformed
254 
255  private void targetLanguageComboBoxSelected(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_targetLanguageComboBoxSelected
256  String selectedCode = ((LanguageWrapper) targetLanguageComboBox.getSelectedItem()).getLanguageCode();
257  if (!StringUtils.isBlank(selectedCode) && !selectedCode.equals(targetLanguageCode)) {
258  targetLanguageCode = selectedCode;
259  firePropertyChange("SettingChanged", true, false);
260  }
261  }//GEN-LAST:event_targetLanguageComboBoxSelected
262 
263  // Variables declaration - do not modify//GEN-BEGIN:variables
264  private javax.swing.JTextField authenticationKeyField;
265  private javax.swing.JLabel authenticationKeyLabel;
266  private javax.swing.JScrollPane instructionsScrollPane;
267  private javax.swing.JTextArea instructionsTextArea;
268  private javax.swing.JLabel resultLabel;
269  private javax.swing.JComboBox<LanguageWrapper> targetLanguageComboBox;
270  private javax.swing.JLabel targetLanguageLabel;
271  private javax.swing.JButton testButton;
272  private javax.swing.JLabel testResultValueLabel;
273  private javax.swing.JTextField testUntranslatedTextField;
274  private javax.swing.JLabel untranslatedLabel;
275  private javax.swing.JLabel warningLabel;
276  // End of variables declaration//GEN-END:variables
277 
285  private boolean testTranslationSetup() {
286  testResultValueLabel.setText("");
287  MediaType mediaType = MediaType.parse("application/json");
288  JsonArray jsonArray = new JsonArray();
289  JsonObject jsonObject = new JsonObject();
290  jsonObject.addProperty("Text", testUntranslatedTextField.getText());
291  jsonArray.add(jsonObject);
292  String bodyString = jsonArray.toString();
293 
294  RequestBody body = RequestBody.create(mediaType,
295  bodyString);
296  Request request = new Request.Builder()
297  .url(BingTranslator.getTranlatorUrl(targetLanguageCode)).post(body)
298  .addHeader("Ocp-Apim-Subscription-Key", authenticationKeyField.getText())
299  .addHeader("Content-type", "application/json").build();
300  try {
301  Response response = new OkHttpClient().newCall(request).execute();
302  JsonParser parser = new JsonParser();
303  JsonArray responses = parser.parse(response.body().string()).getAsJsonArray();
304  //As far as I know, there's always exactly one item in the array.
305  JsonObject response0 = responses.get(0).getAsJsonObject();
306  JsonArray translations = response0.getAsJsonArray("translations");
307  JsonObject translation0 = translations.get(0).getAsJsonObject();
308  testResultValueLabel.setText(translation0.get("text").getAsString());
309  return true;
310  } catch (IOException | IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException e) {
311  logger.log(Level.WARNING, "Test of Bing Translator failed due to exception", e);
312  return false;
313  }
314  }
315 
322  String getAuthenticationKey() {
323  return authenticationKeyField.getText();
324  }
325 
331  String getTargetLanguageCode() {
332  return targetLanguageCode;
333  }
334 }
synchronized static Logger getLogger(String name)
Definition: Logger.java:124

Copyright © 2012-2018 Basis Technology. Generated on: Wed Sep 18 2019
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.