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

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