Autopsy  4.16.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
BingTranslator.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
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.JsonObject;
23 import com.google.gson.JsonParser;
24 import com.squareup.okhttp.MediaType;
25 import com.squareup.okhttp.OkHttpClient;
26 import com.squareup.okhttp.Request;
27 import com.squareup.okhttp.RequestBody;
28 import com.squareup.okhttp.Response;
29 import java.io.IOException;
30 import javax.swing.JPanel;
31 import org.openide.util.NbBundle.Messages;
32 import org.openide.util.lookup.ServiceProvider;
36 
41 @ServiceProvider(service = TextTranslator.class)
42 public class BingTranslator implements TextTranslator {
43 
44  //The target language follows the to= in the string below. You can include multiple target
45  //languages separated by commas. A full list of supported languages is here:
46  //https://docs.microsoft.com/en-us/azure/cognitive-services/translator/language-support
47  private static final String BASE_URL = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=";
48  private static final int MAX_STRING_LENGTH = 5000;
50  private final BingTranslatorSettings settings = new BingTranslatorSettings();
51  // This sends messages to Microsoft.
52  private final OkHttpClient CLIENT = new OkHttpClient();
53 
57  public BingTranslator() {
58  settingsPanel = new BingTranslatorSettingsPanel(settings.getAuthenticationKey(), settings.getTargetLanguageCode());
59  }
60 
70  static String getTranlatorUrl(String languageCode) {
71  return BASE_URL + languageCode;
72  }
73 
85  public String postTranslationRequest(String string) throws IOException {
86  MediaType mediaType = MediaType.parse("application/json");
87 
88  JsonArray jsonArray = new JsonArray();
89  JsonObject jsonObject = new JsonObject();
90  jsonObject.addProperty("Text", string);
91  jsonArray.add(jsonObject);
92  String bodyString = jsonArray.toString();
93 
94  RequestBody body = RequestBody.create(mediaType,
95  bodyString);
96  Request request = new Request.Builder()
97  .url(getTranlatorUrl(settings.getTargetLanguageCode())).post(body)
98  .addHeader("Ocp-Apim-Subscription-Key", settings.getAuthenticationKey())
99  .addHeader("Content-type", "application/json").build();
100  Response response = CLIENT.newCall(request).execute();
101  return response.body().string();
102  }
103 
104  @Override
105  public String translate(String string) throws TranslationException {
106  if (settings.getAuthenticationKey() == null || settings.getAuthenticationKey().isEmpty()) {
107  throw new TranslationException("Bing Translator has not been configured, authentication key needs to be specified");
108  }
109  String toTranslate = string.trim();
110  //Translates some text into English, without specifying the source langauge.
111 
112  //Google Translate required us to replace (\r\n|\n) with <br />
113  //but Bing Translator doesn not have that requirement.
114  //The free account has a maximum file size. If you have a paid account,
115  //you probably still want to limit file size to prevent accidentally
116  //translating very large documents.
117  if (toTranslate.length() > MAX_STRING_LENGTH) {
118  toTranslate = toTranslate.substring(0, MAX_STRING_LENGTH);
119  }
120 
121  try {
122  String response = postTranslationRequest(toTranslate);
123  return parseJSONResponse(response);
124  } catch (IOException | TranslationException ex) {
125  throw new TranslationException("Exception while attempting to translate using BingTranslator", ex);
126  }
127  }
128 
129  @Messages({"BingTranslator.name.text=Bing Translator"})
130  @Override
131  public String getName() {
132  return Bundle.BingTranslator_name_text();
133  }
134 
135  @Override
136  public JPanel getSettingsPanel() {
137  return settingsPanel;
138  }
139 
140  @Override
142  settings.setAuthenticationKey(settingsPanel.getAuthenticationKey());
143  settings.setTargetLanguageCode(settingsPanel.getTargetLanguageCode());
144  settings.saveSettings();
145  }
146 
157  private String parseJSONResponse(String json_text) throws TranslationException {
158  /*
159  * Here is an example of the text we get from Bing when input is "gato",
160  * the Spanish word for cat: [ { "detectedLanguage": { "language": "es",
161  * "score": 1.0 }, "translations": [ { "text": "cat", "to": "en" } ] } ]
162  */
163  JsonParser parser = new JsonParser();
164  try {
165  JsonArray responses = parser.parse(json_text).getAsJsonArray();
166  //As far as I know, there's always exactly one item in the array.
167  JsonObject response0 = responses.get(0).getAsJsonObject();
168  JsonArray translations = response0.getAsJsonArray("translations");
169  JsonObject translation0 = translations.get(0).getAsJsonObject();
170  return translation0.get("text").getAsString();
171  } catch (IllegalStateException | ClassCastException | NullPointerException | IndexOutOfBoundsException e) {
172  throw new TranslationException("JSON text does not match Bing Translator scheme: " + e);
173  }
174  }
175 
176  @Override
177  public int getMaxTextChars() {
178  return MAX_STRING_LENGTH;
179  }
180 }

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