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

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