Skip to content

Commit 42afcd1

Browse files
Discourage use of API key in translation
Addresses #1594.
1 parent d43a540 commit 42afcd1

File tree

8 files changed

+87
-26
lines changed

8 files changed

+87
-26
lines changed

README.md

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ Google Cloud Language (Beta)
459459
### Preview
460460
461461
Here is a code snippet showing a simple usage example of LanguageServiceClient. The example assumes that either default application
462-
credentials or a valid api key are available. (See [Authentication section](#authentication) for more information)
462+
credentials or a valid API key are available. (See [Authentication section](#authentication) for more information)
463463
```java
464464
try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
465465
Document document = Document.newBuilder().build();
@@ -476,7 +476,7 @@ Google Cloud Vision (Beta)
476476
### Preview
477477
478478
Here is a code snippet showing a simple usage example of ImageAnnotatorClient.
479-
The example assumes that either default application credentials or a valid api key
479+
The example assumes that either default application credentials or a valid API key
480480
are available. (See [Authentication section](#authentication) for more information)
481481
```java
482482
try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
@@ -732,9 +732,8 @@ Google Translation (Beta)
732732
733733
Here's a snippet showing a simple usage example. The example shows how to detect the language of
734734
some text and how to translate some text. The example assumes that either default application
735-
credentials or a valid api key are available. An api key stored in the `GOOGLE_API_KEY` environment
736-
variable will be automatically detected. Alternatively, you can use the `apiKey(String)` setter in
737-
`TranslateOptions.Builder`. Complete source code can be found at
735+
credentials or a valid API key are available. An API key stored in the `GOOGLE_API_KEY` environment
736+
variable will be automatically detected. Complete source code can be found at
738737
[DetectLanguageAndTranslate.java](./google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java).
739738
740739
```java
@@ -766,7 +765,7 @@ Google Cloud Speech (Alpha)
766765
### Preview
767766
768767
Here is a code snippet showing a simple usage example of SpeechClient. The example assumes that either default application
769-
credentials or a valid api key are available. (See [Authentication section](#authentication) for more information)
768+
credentials or a valid API key are available. (See [Authentication section](#authentication) for more information)
770769
Note that you must provide a uri to a FLAC audio file to run this.
771770
772771
```java
@@ -796,7 +795,7 @@ Google Cloud Trace (Alpha)
796795
### Preview
797796
798797
Here is a code snippet showing a simple usage example of TraceServiceClient. The example assumes that either default application
799-
credentials or a valid api key are available.
798+
credentials or a valid API key are available.
800799
Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
801800
```java
802801
try (TraceServiceClient traceServiceClient = TraceServiceClient.create()) {
@@ -814,7 +813,7 @@ Google Cloud Video Intelligence (Alpha)
814813
### Preview
815814
816815
Here is a code snippet showing a simple usage example of TraceServiceClient. The example assumes that either default application
817-
credentials or a valid api key are available.
816+
credentials or a valid API key are available.
818817
Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
819818
```java
820819
try (VideoIntelligenceServiceClient videoIntelligenceServiceClient =

TESTING.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -239,13 +239,14 @@ Google Translation service.
239239

240240
1. Create a test Google Cloud project.
241241

242-
2. Follow [Translate Quickstart](https://cloud.google.com/translate/v2/quickstart) to get an API
242+
2. Download a JSON service account credentials file from the Google Developer's Console. See more about this on the [Google Cloud Platform Authentication page][cloud-platform-authentication]
243243
key.
244244

245245
3. Create a `RemoteTranslateHelper` object using your project ID and API key. Here is an example
246246
that uses the `RemoteTranslateHelper` to list supported languages.
247247
```java
248-
RemoteTranslateHelper translateHelper = RemoteTranslateHelper.create(PROJECT_ID, API_KEY);
248+
RemoteTranslateHelper translateHelper =
249+
RemoteTranslateHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json"));
249250
Translate translate = translateHelper.getOptions().getService();
250251
List<Language> languages = translate.listSupportedLanguages();
251252
```
@@ -258,7 +259,7 @@ Currently, there isn't an emulator for Cloud Spanner, so an alternative is to cr
258259

259260
1. Create a test Google Cloud project.
260261

261-
2. Download a JSON service account credentials file from the Google Developer's Console. See more about this on the [Google Cloud Platform Storage Authentication page][cloud-platform-storage-authentication].
262+
2. Download a JSON service account credentials file from the Google Developer's Console. See more about this on the [Google Cloud Platform Authentication page][cloud-platform-authentication].
262263

263264
3. Create or use an existing Cloud Spanner Instance.
264265

@@ -283,6 +284,7 @@ Here is an example that uses the `RemoteSpannerHelper` to create a database.
283284
RemoteSpannerHelper.cleanUp();
284285
```
285286

287+
[cloud-platform-authentication]:https://cloud.google.com/docs/authentication/getting-started
286288
[cloud-platform-storage-authentication]:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts
287289
[create-service-account]:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
288290
[cloud-nio]:https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-contrib/google-cloud-nio

google-cloud-examples/README.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -160,12 +160,12 @@ To run examples from your command line:
160160
161161
* Here's an example run of `TranslateExample`.
162162
163-
Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translation API" is enabled and that you have a valid API key.
163+
Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translation API" is enabled.
164164
```
165-
target/appassembler/bin/TranslateExample <apiKey> languages
166-
target/appassembler/bin/TranslateExample <apiKey> detect Hello,\ World!
167-
target/appassembler/bin/TranslateExample <apiKey> translate ¡Hola\ Mundo!
168-
target/appassembler/bin/TranslateExample <apiKey> es translate Hello,\ World!
165+
target/appassembler/bin/TranslateExample languages
166+
target/appassembler/bin/TranslateExample detect Hello,\ World!
167+
target/appassembler/bin/TranslateExample translate ¡Hola\ Mundo!
168+
target/appassembler/bin/TranslateExample es translate Hello,\ World!
169169
```
170170
171171
Troubleshooting

google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
* <a href="https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-examples/README.md">
3737
* README</a> for compilation instructions. Run this code with
3838
* <pre>{@code target/appassembler/bin/TranslateExample
39-
* -Dexec.args="<apiKey> [<targetLanguage>]
39+
* -Dexec.args="[[<apiKey>] <targetLanguage>]
4040
* list languages <languageCode>?
4141
* detect <text>+
4242
* translate <text>+"}</pre>
@@ -169,7 +169,7 @@ private static void printUsage() {
169169
actionAndParams.append(' ').append(param);
170170
}
171171
}
172-
System.out.printf("Usage: %s [<apiKey>] [<targetLanguage>] operation <args>*%s%n",
172+
System.out.printf("Usage: %s [[<apiKey>] <targetLanguage>] operation <args>*%s%n",
173173
TranslateExample.class.getSimpleName(), actionAndParams);
174174
}
175175

@@ -189,7 +189,7 @@ public static void main(String... args) throws Exception {
189189
optionsBuilder.setTargetLanguage(args[1]);
190190
args = Arrays.copyOfRange(args, 3, args.length);
191191
} else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
192-
optionsBuilder.setApiKey(args[0]);
192+
optionsBuilder.setTargetLanguage(args[0]);
193193
actionName = args[1];
194194
args = Arrays.copyOfRange(args, 2, args.length);
195195
} else {

google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ public class DetectLanguageAndTranslate {
3636

3737
public static void main(String... args) {
3838
// Create a service object
39-
// Default application credentials or an API key from the GOOGLE_API_KEY environment variable
40-
// are used to authenticate requests
39+
//
40+
// Requests are authenticated using default application credentials if available; otherwise,
41+
// using an API key from the GOOGLE_API_KEY environment variable
4142
Translate translate = TranslateOptions.getDefaultInstance().getService();
4243

4344
// Detect the language of some text

google-cloud-translate/README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,9 @@ Example Application
4242
Authentication
4343
--------------
4444

45-
Google Translation requires an API key to be passed with every request. For instructions on how to
46-
get an API key follow the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart).
45+
For instructions on how to set up authentication and make authenticated calls,
46+
follow
47+
the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart).
4748

4849
About Google Translation
4950
--------------------
@@ -52,7 +53,7 @@ About Google Translation
5253
arbitrary string into any supported language. Translation is highly responsive, so websites and
5354
applications can integrate with Translation API for fast, dynamic translation of source text from the
5455
source language to a target language (e.g., French to English). Language detection is also
55-
available In cases where the source language is unknown.
56+
available in cases where the source language is unknown.
5657

5758
See the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart) for more details
5859
on how to activate Google Translation for your project.

google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ public Builder setProjectId(String projectId) {
107107
* {@code GOOGLE_API_KEY} environment variable. For instructions on how to get an API key see
108108
* <a href="https://cloud.google.com/translate/v2/quickstart">Translate quickstart</a>.
109109
*/
110+
@Deprecated
110111
public Builder setApiKey(String apiKey) {
111112
this.apiKey = apiKey;
112113
return this;

google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,17 @@
1616

1717
package com.google.cloud.translate.testing;
1818

19-
import com.google.cloud.http.HttpTransportOptions;
2019
import com.google.api.gax.retrying.RetrySettings;
20+
import com.google.auth.oauth2.GoogleCredentials;
21+
import com.google.cloud.http.HttpTransportOptions;
2122
import com.google.cloud.translate.TranslateOptions;
2223
import org.threeten.bp.Duration;
2324

25+
import java.io.IOException;
26+
import java.io.InputStream;
27+
import java.util.logging.Level;
28+
import java.util.logging.Logger;
29+
2430
/**
2531
* Utility to create a remote translate configuration for testing. Translate options can be obtained
2632
* via the {@link #getOptions()} ()} method. Returned options have custom
@@ -34,6 +40,7 @@
3440
* both set to {@code 60000}.
3541
*/
3642
public class RemoteTranslateHelper {
43+
private static final Logger logger = Logger.getLogger(RemoteTranslateHelper.class.getName());
3744

3845
private final TranslateOptions options;
3946

@@ -49,11 +56,43 @@ public TranslateOptions getOptions() {
4956
return options;
5057
}
5158

59+
/**
60+
* Creates a {@code RemoteTranslateHelper} object for the given project id and JSON key input
61+
* stream.
62+
*
63+
* @param projectId id of the project to be used for running the tests
64+
* @param keyStream input stream for a JSON key
65+
* @return A {@code RemoteTranslateHelper} object for the provided options
66+
* @throws com.google.cloud.translate.testing.RemoteTranslateHelper.TranslateHelperException if
67+
* {@code keyStream} is not a valid JSON key stream
68+
*/
69+
public static RemoteTranslateHelper create(String projectId, InputStream keyStream)
70+
throws TranslateHelperException {
71+
try {
72+
HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions();
73+
transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000)
74+
.build();
75+
TranslateOptions translateOptions = TranslateOptions.newBuilder()
76+
.setCredentials(GoogleCredentials.fromStream(keyStream))
77+
.setProjectId(projectId)
78+
.setRetrySettings(retryParams())
79+
.setTransportOptions(transportOptions)
80+
.build();
81+
return new RemoteTranslateHelper(translateOptions);
82+
} catch (IOException ex) {
83+
if (logger.isLoggable(Level.WARNING)) {
84+
logger.log(Level.WARNING, ex.getMessage());
85+
}
86+
throw TranslateHelperException.translate(ex);
87+
}
88+
}
89+
5290
/**
5391
* Creates a {@code RemoteTranslateHelper} object for the given API key.
5492
*
5593
* @param apiKey API key used to issue requests to Google Translation.
5694
*/
95+
@Deprecated
5796
public static RemoteTranslateHelper create(String apiKey) {
5897
HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions();
5998
transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000)
@@ -67,7 +106,8 @@ public static RemoteTranslateHelper create(String apiKey) {
67106
}
68107

69108
/**
70-
* Creates a {@code RemoteStorageHelper} object.
109+
* Creates a {@code RemoteTranslateHelper} object using default project id and authentication
110+
* credentials.
71111
*/
72112
public static RemoteTranslateHelper create() {
73113
HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions();
@@ -91,4 +131,21 @@ private static RetrySettings retryParams() {
91131
.setMaxRpcTimeout(Duration.ofMillis(120000L))
92132
.build();
93133
}
134+
135+
public static class TranslateHelperException extends RuntimeException {
136+
137+
private static final long serialVersionUID = -1356870058436149798L;
138+
139+
public TranslateHelperException(String message) {
140+
super(message);
141+
}
142+
143+
public TranslateHelperException(String message, Throwable cause) {
144+
super(message, cause);
145+
}
146+
147+
public static TranslateHelperException translate(Exception ex) {
148+
return new TranslateHelperException(ex.getMessage(), ex);
149+
}
150+
}
94151
}

0 commit comments

Comments
 (0)