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

Copyright © 2012-2024 Sleuth Kit Labs. Generated on: Mon Mar 17 2025
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.