Autopsy  4.11.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
GoogleTranslator.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.auth.Credentials;
22 import com.google.auth.oauth2.ServiceAccountCredentials;
23 import com.google.cloud.translate.Translate;
24 import com.google.cloud.translate.TranslateOptions;
25 import com.google.cloud.translate.Translation;
26 import java.awt.Component;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.net.InetAddress;
32 import java.net.UnknownHostException;
33 import java.util.logging.Level;
34 import java.util.logging.Logger;
35 import org.apache.commons.lang3.StringUtils;
36 import org.openide.util.NbBundle.Messages;
37 import org.openide.util.lookup.ServiceProvider;
41 
46 @ServiceProvider(service = TextTranslator.class)
47 public final class GoogleTranslator implements TextTranslator {
48 
49  private static final Logger logger = Logger.getLogger(GoogleTranslator.class.getName());
50  //See translate method for justification of this limit.
51  private static final int MAX_PAYLOAD_SIZE = 5000;
53  private final GoogleTranslatorSettings settings = new GoogleTranslatorSettings();
54  private Translate googleTranslate;
55 
59  public GoogleTranslator() {
60  // Instantiates a client
61  settingsPanel = new GoogleTranslatorSettingsPanel(settings.getCredentialPath(), settings.getTargetLanguageCode());
62  loadTranslator();
63  }
64 
70  private static boolean googleIsReachable() {
71  String host = "www.google.com";
72  InetAddress address;
73  try {
74  address = InetAddress.getByName(host);
75  return address.isReachable(1500);
76  } catch (UnknownHostException ex) {
77  logger.log(Level.WARNING, "Unable to reach google.com due to unknown host", ex);
78  return false;
79  } catch (IOException ex) {
80  logger.log(Level.WARNING, "Unable to reach google.com due IOException", ex);
81  return false;
82  }
83  }
84 
85  @Override
86  public String translate(String string) throws TranslationException {
87  if (!googleIsReachable()) {
88  throw new TranslationException("Failure translating using GoogleTranslator: Cannot connect to Google");
89  }
90 
91  if (googleTranslate != null) {
92  try {
93  // Translates some text into English, without specifying the source language.
94  String substring = string.trim();
95 
96  // We can't currently set parameters, so we are using the default behavior of
97  // assuming the input is HTML. We need to replace newlines with <br> for Google to preserve them
98  substring = substring.replaceAll("(\r\n|\n)", "<br />");
99 
100  // The API complains if the "Payload" is over 204800 bytes. Google references that
101  //their service is optimized for 2K code points and recommends keeping the requests that size.
102  //There is a hard limit of 30K code points per request. There is also a time-based quota that
103  //we are not enforcing, which may lead to 403 errors. We are currently configured for a max of 5K
104  //in each request, for two reasons. 1) To be more in line with Google's recommendation. 2) To
105  //minimize accidental exceedence of time based quotas.
106  if (substring.length() > MAX_PAYLOAD_SIZE) {
107  substring = substring.substring(0, MAX_PAYLOAD_SIZE);
108  }
109  Translation translation
110  = googleTranslate.translate(substring);
111  String translatedString = translation.getTranslatedText();
112 
113  // put back the newlines
114  translatedString = translatedString.replaceAll("<br />", "\n");
115 
116  // With our current settings, Google Translate outputs HTML
117  // so we need to undo the escape characters.
118  translatedString = EscapeUtil.unEscapeHtml(translatedString);
119  return translatedString;
120  } catch (Throwable ex) {
121  //Catching throwables because some of this Google Translate code throws throwables
122  throw new TranslationException("Failure translating using GoogleTranslator", ex);
123  }
124  } else {
125  throw new TranslationException("Google Translator has not been configured, credentials need to be specified");
126  }
127  }
128 
129  @Messages({"GoogleTranslator.name.text=Google Translate"})
130  @Override
131  public String getName() {
132  return Bundle.GoogleTranslator_name_text();
133  }
134 
135  @Override
136  public Component getComponent() {
137  return settingsPanel;
138  }
139 
144  private void loadTranslator() {
145  InputStream credentialStream = null;
146  Credentials creds = null;
147  if (StringUtils.isBlank(settings.getCredentialPath())) {
148  logger.log(Level.INFO, "No credentials file has been provided for Google Translator");
149  } else {
150  try {
151  credentialStream = new FileInputStream(settings.getCredentialPath());
152  } catch (FileNotFoundException ex) {
153  logger.log(Level.WARNING, "JSON file for GoogleTranslator credentials not found", ex);
154  }
155  }
156  if (credentialStream != null) {
157  try {
158  creds = ServiceAccountCredentials.fromStream(credentialStream);
159  } catch (IOException ex) {
160  logger.log(Level.WARNING, "Error converting JSON file to Credentials object for GoogleTranslator", ex);
161  }
162  }
163  if (creds == null) {
164  logger.log(Level.WARNING, "Credentials were not successfully made, no translations will be available from the GoogleTranslator");
165  googleTranslate = null;
166  } else {
167  TranslateOptions.Builder builder = TranslateOptions.newBuilder();
168  builder.setCredentials(creds);
169  builder.setTargetLanguage(settings.getTargetLanguageCode());
170  googleTranslate = builder.build().getService();
171  }
172  }
173 
174  @Override
175  public void saveSettings() {
176  settings.setTargetLanguageCode(settingsPanel.getTargetLanguageCode());
177  settings.setCredentialPath(settingsPanel.getCredentialsPath());
178  settings.saveSettings();
179  loadTranslator();
180  }
181 
182  @Override
183  public int getMaxPayloadSize() {
184  return MAX_PAYLOAD_SIZE;
185  }
186 }
static String unEscapeHtml(String toUnescape)
Definition: EscapeUtil.java:86

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.