Skip to content

Commit

Permalink
Discourage use of API key in translation
Browse files Browse the repository at this point in the history
Addresses googleapis#1594.
  • Loading branch information
tcoffee-google committed Jun 14, 2017
1 parent d43a540 commit 780042d
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 25 deletions.
15 changes: 7 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ Google Cloud Language (Beta)
### Preview
Here is a code snippet showing a simple usage example of LanguageServiceClient. The example assumes that either default application
credentials or a valid api key are available. (See [Authentication section](#authentication) for more information)
credentials or a valid API key are available. (See [Authentication section](#authentication) for more information)
```java
try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
Document document = Document.newBuilder().build();
Expand All @@ -476,7 +476,7 @@ Google Cloud Vision (Beta)
### Preview
Here is a code snippet showing a simple usage example of ImageAnnotatorClient.
The example assumes that either default application credentials or a valid api key
The example assumes that either default application credentials or a valid API key
are available. (See [Authentication section](#authentication) for more information)
```java
try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) {
Expand Down Expand Up @@ -732,9 +732,8 @@ Google Translation (Beta)
Here's a snippet showing a simple usage example. The example shows how to detect the language of
some text and how to translate some text. The example assumes that either default application
credentials or a valid api key are available. An api key stored in the `GOOGLE_API_KEY` environment
variable will be automatically detected. Alternatively, you can use the `apiKey(String)` setter in
`TranslateOptions.Builder`. Complete source code can be found at
credentials or a valid API key are available. An API key stored in the `GOOGLE_API_KEY` environment
variable will be automatically detected. Complete source code can be found at
[DetectLanguageAndTranslate.java](./google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java).
```java
Expand Down Expand Up @@ -766,7 +765,7 @@ Google Cloud Speech (Alpha)
### Preview
Here is a code snippet showing a simple usage example of SpeechClient. The example assumes that either default application
credentials or a valid api key are available. (See [Authentication section](#authentication) for more information)
credentials or a valid API key are available. (See [Authentication section](#authentication) for more information)
Note that you must provide a uri to a FLAC audio file to run this.
```java
Expand Down Expand Up @@ -796,7 +795,7 @@ Google Cloud Trace (Alpha)
### Preview
Here is a code snippet showing a simple usage example of TraceServiceClient. The example assumes that either default application
credentials or a valid api key are available.
credentials or a valid API key are available.
Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
```java
try (TraceServiceClient traceServiceClient = TraceServiceClient.create()) {
Expand All @@ -814,7 +813,7 @@ Google Cloud Video Intelligence (Alpha)
### Preview
Here is a code snippet showing a simple usage example of TraceServiceClient. The example assumes that either default application
credentials or a valid api key are available.
credentials or a valid API key are available.
Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere.
```java
try (VideoIntelligenceServiceClient videoIntelligenceServiceClient =
Expand Down
8 changes: 5 additions & 3 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,14 @@ Google Translation service.

1. Create a test Google Cloud project.

2. Follow [Translate Quickstart](https://cloud.google.com/translate/v2/quickstart) to get an API
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]
key.

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

1. Create a test Google Cloud project.

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].
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].

3. Create or use an existing Cloud Spanner Instance.

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

[cloud-platform-authentication]:https://cloud.google.com/docs/authentication/getting-started
[cloud-platform-storage-authentication]:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts
[create-service-account]:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount
[cloud-nio]:https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-contrib/google-cloud-nio
10 changes: 5 additions & 5 deletions google-cloud-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,12 @@ To run examples from your command line:
* Here's an example run of `TranslateExample`.
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.
Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translation API" is enabled.
```
target/appassembler/bin/TranslateExample <apiKey> languages
target/appassembler/bin/TranslateExample <apiKey> detect Hello,\ World!
target/appassembler/bin/TranslateExample <apiKey> translate ¡Hola\ Mundo!
target/appassembler/bin/TranslateExample <apiKey> es translate Hello,\ World!
target/appassembler/bin/TranslateExample languages
target/appassembler/bin/TranslateExample detect Hello,\ World!
target/appassembler/bin/TranslateExample translate ¡Hola\ Mundo!
target/appassembler/bin/TranslateExample es translate Hello,\ World!
```
Troubleshooting
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
* <a href="https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-examples/README.md">
* README</a> for compilation instructions. Run this code with
* <pre>{@code target/appassembler/bin/TranslateExample
* -Dexec.args="<apiKey> [<targetLanguage>]
* -Dexec.args="[[<apiKey>] <targetLanguage>]
* list languages <languageCode>?
* detect <text>+
* translate <text>+"}</pre>
Expand Down Expand Up @@ -169,7 +169,7 @@ private static void printUsage() {
actionAndParams.append(' ').append(param);
}
}
System.out.printf("Usage: %s [<apiKey>] [<targetLanguage>] operation <args>*%s%n",
System.out.printf("Usage: %s [[<apiKey>] <targetLanguage>] operation <args>*%s%n",
TranslateExample.class.getSimpleName(), actionAndParams);
}

Expand All @@ -189,7 +189,7 @@ public static void main(String... args) throws Exception {
optionsBuilder.setTargetLanguage(args[1]);
args = Arrays.copyOfRange(args, 3, args.length);
} else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
optionsBuilder.setApiKey(args[0]);
optionsBuilder.setTargetLanguage(args[0]);
actionName = args[1];
args = Arrays.copyOfRange(args, 2, args.length);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ public class DetectLanguageAndTranslate {

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

// Detect the language of some text
Expand Down
7 changes: 4 additions & 3 deletions google-cloud-translate/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ Example Application
Authentication
--------------

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

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

See the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart) for more details
on how to activate Google Translation for your project.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public Builder setProjectId(String projectId) {
* {@code GOOGLE_API_KEY} environment variable. For instructions on how to get an API key see
* <a href="https://cloud.google.com/translate/v2/quickstart">Translate quickstart</a>.
*/
@Deprecated
public Builder setApiKey(String apiKey) {
this.apiKey = apiKey;
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,43 @@ public TranslateOptions getOptions() {
return options;
}

/**
* Creates a {@code RemoteTranslateHelper} object for the given project id and JSON key input
* stream.
*
* @param projectId id of the project to be used for running the tests
* @param keyStream input stream for a JSON key
* @return A {@code RemoteTranslateHelper} object for the provided options
* @throws com.google.cloud.translate.testing.RemoteTranslateHelper.TranslateHelperException if
* {@code keyStream} is not a valid JSON key stream
*/
public static RemoteTranslateHelper create(String projectId, InputStream keyStream)
throws TranslateHelperException {
try {
HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions();
transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000)
.build();
TranslateOptions translateOptions = TranslateOptions.newBuilder()
.setCredentials(GoogleCredentials.fromStream(keyStream))
.setProjectId(projectId)
.setRetrySettings(retrySettings())
.setTransportOptions(transportOptions)
.build();
return new RemoteTranslateHelper(translateOptions);
} catch (IOException ex) {
if (log.isLoggable(Level.WARNING)) {
log.log(Level.WARNING, ex.getMessage());
}
throw TranslateHelperException.translate(ex);
}
}

/**
* Creates a {@code RemoteTranslateHelper} object for the given API key.
*
* @param apiKey API key used to issue requests to Google Translation.
*/
@Deprecated
public static RemoteTranslateHelper create(String apiKey) {
HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions();
transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000)
Expand All @@ -67,7 +99,8 @@ public static RemoteTranslateHelper create(String apiKey) {
}

/**
* Creates a {@code RemoteStorageHelper} object.
* Creates a {@code RemoteTranslateHelper} object using default project id and authentication
* credentials.
*/
public static RemoteTranslateHelper create() {
HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions();
Expand All @@ -91,4 +124,21 @@ private static RetrySettings retryParams() {
.setMaxRpcTimeout(Duration.ofMillis(120000L))
.build();
}

public static class TranslateHelperException extends RuntimeException {

private static final long serialVersionUID = -1356870058436149798L;

public TranslateHelperException(String message) {
super(message);
}

public TranslateHelperException(String message, Throwable cause) {
super(message, cause);
}

public static TranslateHelperException translate(Exception ex) {
return new TranslateHelperException(ex.getMessage(), ex);
}
}
}

0 comments on commit 780042d

Please sign in to comment.