Skip to content

Commit dceeb5f

Browse files
BrandonYtswast
authored andcommitted
Switch to getApplicationDefault()-based auth. Modify docs+others accordingly.
1 parent bfab252 commit dceeb5f

File tree

5 files changed

+140
-145
lines changed

5 files changed

+140
-145
lines changed

storage/json-api/README.md

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,39 @@ Google Cloud Storage Service features a REST-based API that allows developers to
44

55
## Quickstart
66

7-
Install [Maven](http://maven.apache.org/).
7+
1. Install the [Google Cloud SDK](https://cloud.google.com/sdk/), including the [gcloud tool](https://cloud.google.com/sdk/gcloud/).
88

9-
Build your project with:
9+
1. Setup the gcloud tool.
10+
```
11+
gcloud init
12+
```
1013
11-
mvn package
14+
1. Clone this repo.
1215
13-
You can then run a given `ClassName` via:
16+
```
17+
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
18+
```
1419
15-
mvn exec:java -Dexec.mainClass=StorageSample \
20+
1. Install [Maven](http://maven.apache.org/).
21+
22+
1. Build this project from this directory:
23+
24+
```
25+
mvn package
26+
```
27+
28+
1. Run one of the sample apps by specifying its class name and a bucket name:
29+
30+
```
31+
mvn exec:java -Dexec.mainClass=StorageSample \
1632
-Dexec.args="ABucketName"
33+
```
34+
35+
Note that if it's been a while, you may need to login with gcloud.
36+
37+
```
38+
gcloud auth login
39+
```
1740
1841
## Products
1942
- [Google Cloud Storage][2]

storage/json-api/src/main/java/CustomerSuppliedEncryptionKeysSamples.java

Lines changed: 11 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,11 @@
1-
import com.google.api.client.auth.oauth2.Credential;
2-
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
3-
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
4-
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
5-
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
6-
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
71
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
82
import com.google.api.client.http.HttpHeaders;
9-
import com.google.api.client.http.HttpTransport;
103
import com.google.api.client.http.InputStreamContent;
11-
import com.google.api.client.json.JsonFactory;
12-
import com.google.api.client.json.jackson2.JacksonFactory;
13-
import com.google.api.client.util.store.DataStoreFactory;
14-
import com.google.api.client.util.store.FileDataStoreFactory;
154
import com.google.api.services.storage.Storage;
16-
import com.google.api.services.storage.StorageScopes;
175
import com.google.api.services.storage.model.RewriteResponse;
186

197
import java.io.IOException;
208
import java.io.InputStream;
21-
import java.io.InputStreamReader;
22-
import java.util.Collections;
239

2410
/**
2511
* Demonstrates the use of GCS's CSEK features via the Java API client library
@@ -35,9 +21,6 @@
3521
**/
3622
class CustomerSuppliedEncryptionKeysSamples {
3723

38-
private static final java.io.File DATA_STORE_DIR =
39-
new java.io.File(System.getProperty("user.home"), ".store/storage_sample");
40-
4124
// You can (and should) generate your own CSEK Key! Try running this from the command line:
4225
// python -c 'import base64; import os; print(base64.encodestring(os.urandom(32)))'
4326
// Also, these encryption keys are included here for simplicity, but please remember that
@@ -135,11 +118,11 @@ public static void uploadObject(
135118
httpHeaders.set("x-goog-encryption-algorithm", "AES256");
136119
httpHeaders.set("x-goog-encryption-key", base64CSEKey);
137120
httpHeaders.set("x-goog-encryption-key-sha256", base64CSEKeyHash);
138-
121+
139122
// Since our request includes our private key as a header, it is a good idea to instruct caches
140123
// and proxies not to store this request.
141124
httpHeaders.setCacheControl("no-store");
142-
125+
143126
insertObject.setRequestHeaders(httpHeaders);
144127

145128
try {
@@ -189,11 +172,11 @@ public static void rotateKey(
189172
httpHeaders.set("x-goog-encryption-algorithm", "AES256");
190173
httpHeaders.set("x-goog-encryption-key", newBase64Key);
191174
httpHeaders.set("x-goog-encryption-key-sha256", newBase64KeyHash);
192-
175+
193176
// Since our request includes our private key as a header, it is a good idea to instruct caches
194177
// and proxies not to store this request.
195178
httpHeaders.setCacheControl("no-store");
196-
179+
197180
rewriteObject.setRequestHeaders(httpHeaders);
198181

199182
try {
@@ -221,95 +204,23 @@ public static void main(String[] args) throws Exception {
221204
System.exit(1);
222205
}
223206
String bucketName = args[0];
224-
// CSEK, like the JSON API, may be used only via HTTPS.
225-
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
226-
DataStoreFactory dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
227-
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
228-
Credential credential = authorize(jsonFactory, httpTransport, dataStoreFactory);
229-
Storage storage =
230-
new Storage.Builder(httpTransport, jsonFactory, credential)
231-
.setApplicationName("JavaCSEKApiSample")
232-
.build();
233-
234-
InputStream dataToUpload = new ArbitrarilyLargeInputStream(10000000);
207+
208+
Storage storage = StorageFactory.getService();
209+
InputStream dataToUpload = new StorageUtils.ArbitrarilyLargeInputStream(10000000);
235210

236211
System.out.format("Uploading object gs://%s/%s using CSEK.\n", bucketName, OBJECT_NAME);
237212
uploadObject(storage, bucketName, OBJECT_NAME, dataToUpload, CSEK_KEY, CSEK_KEY_HASH);
213+
238214
System.out.format("Downloading object gs://%s/%s using CSEK.\n", bucketName, OBJECT_NAME);
239215
InputStream objectData =
240216
downloadObject(storage, bucketName, OBJECT_NAME, CSEK_KEY, CSEK_KEY_HASH);
241-
readStream(objectData);
217+
StorageUtils.readStream(objectData);
218+
242219
System.out.println("Rotating object to use a different CSEK.");
243220
rotateKey(storage, bucketName, OBJECT_NAME, CSEK_KEY, CSEK_KEY_HASH,
244221
ANOTHER_CESK_KEY, ANOTHER_CSEK_KEY_HASH);
245222

246-
System.out.println();
247-
}
248-
249-
private static Credential authorize(
250-
JsonFactory jsonFactory, HttpTransport httpTransport, DataStoreFactory dataStoreFactory)
251-
throws Exception {
252-
253-
InputStream clientSecretStream =
254-
CustomerSuppliedEncryptionKeysSamples.class
255-
.getResourceAsStream("client_secrets.json");
256-
if (clientSecretStream == null) {
257-
throw new RuntimeException("Could not load secrets");
258-
}
259-
260-
// Load client secrets
261-
GoogleClientSecrets clientSecrets =
262-
GoogleClientSecrets.load(jsonFactory, new InputStreamReader(clientSecretStream));
263-
264-
// Set up authorization code flow
265-
GoogleAuthorizationCodeFlow flow =
266-
new GoogleAuthorizationCodeFlow.Builder(
267-
httpTransport,
268-
jsonFactory,
269-
clientSecrets,
270-
Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL))
271-
.setDataStoreFactory(dataStoreFactory)
272-
.build();
273-
274-
// Authorize
275-
Credential credential =
276-
new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
277-
278-
return credential;
279-
}
280-
281-
/**
282-
* Reads the contents of an InputStream and does nothing with it.
283-
*/
284-
private static void readStream(InputStream is) throws IOException {
285-
byte inputBuffer[] = new byte[256];
286-
while (is.read(inputBuffer) != -1) {}
287-
// The caller is responsible for closing this InputStream.
288-
is.close();
289-
}
290-
291-
/**
292-
* A helper class to provide input streams of any size.
293-
* The input streams will be full of null bytes.
294-
*/
295-
static class ArbitrarilyLargeInputStream extends InputStream {
296-
297-
private long bytesRead;
298-
private final long streamSize;
299-
300-
public ArbitrarilyLargeInputStream(long streamSizeInBytes) {
301-
bytesRead = 0;
302-
this.streamSize = streamSizeInBytes;
303-
}
304-
305-
@Override
306-
public int read() throws IOException {
307-
if (bytesRead >= streamSize) {
308-
return -1;
309-
}
310-
bytesRead++;
311-
return 0;
312-
}
223+
System.out.println("Done");
313224
}
314225

315226
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
2+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
3+
import com.google.api.client.http.HttpTransport;
4+
import com.google.api.client.json.JsonFactory;
5+
import com.google.api.client.json.jackson2.JacksonFactory;
6+
import com.google.api.services.storage.Storage;
7+
import com.google.api.services.storage.StorageScopes;
8+
9+
import java.io.IOException;
10+
import java.security.GeneralSecurityException;
11+
import java.util.Collection;
12+
13+
/*
14+
* Copyright (c) 2016 Google Inc.
15+
*
16+
* Licensed under the Apache License, Version 2.0 (the "License"); you may
17+
* not use this file except in compliance with the License. You may obtain a
18+
* copy of the License at
19+
*
20+
* http://www.apache.org/licenses/LICENSE-2.0
21+
*
22+
* Unless required by applicable law or agreed to in writing, software
23+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
24+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
25+
* License for the specific language governing permissions and limitations under
26+
* the License.
27+
*/
28+
29+
/**
30+
* This class manages the details of creating a Storage service, including auth.
31+
*/
32+
public class StorageFactory {
33+
34+
private static Storage instance = null;
35+
36+
public static synchronized Storage getService() throws IOException, GeneralSecurityException {
37+
if (instance == null) {
38+
instance = buildService();
39+
}
40+
return instance;
41+
}
42+
43+
private static Storage buildService() throws IOException, GeneralSecurityException {
44+
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
45+
JsonFactory jsonFactory = new JacksonFactory();
46+
GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
47+
48+
if (credential.createScopedRequired()) {
49+
Collection<String> bigqueryScopes = StorageScopes.all();
50+
credential = credential.createScoped(bigqueryScopes);
51+
}
52+
53+
return new Storage.Builder(transport, jsonFactory, credential)
54+
.setApplicationName("GCS Samples")
55+
.build();
56+
}
57+
}

storage/json-api/src/main/java/StorageSample.java

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,8 @@
1313
* the License.
1414
*/
1515

16-
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
17-
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
18-
import com.google.api.client.http.HttpTransport;
1916
import com.google.api.client.http.InputStreamContent;
20-
import com.google.api.client.json.JsonFactory;
21-
import com.google.api.client.json.jackson2.JacksonFactory;
2217
import com.google.api.services.storage.Storage;
23-
import com.google.api.services.storage.StorageScopes;
2418
import com.google.api.services.storage.model.Bucket;
2519
import com.google.api.services.storage.model.ObjectAccessControl;
2620
import com.google.api.services.storage.model.Objects;
@@ -42,39 +36,9 @@
4236
*/
4337
public class StorageSample {
4438

45-
/**
46-
* Be sure to specify the name of your application. If the application name is {@code null} or
47-
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
48-
*/
49-
private static final String APPLICATION_NAME = "[[INSERT_YOUR_APP_NAME_HERE]]";
50-
5139
/** Global instance of the JSON factory. */
52-
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
5340
private static final String TEST_FILENAME = "json-test.txt";
5441

55-
// [START get_service]
56-
private static Storage storageService;
57-
58-
/**
59-
* Returns an authenticated Storage object used to make service calls to Cloud Storage.
60-
*/
61-
private static Storage getService() throws IOException, GeneralSecurityException {
62-
if (null == storageService) {
63-
GoogleCredential credential = GoogleCredential.getApplicationDefault();
64-
// Depending on the environment that provides the default credentials (e.g. Compute Engine,
65-
// App Engine), the credentials may require us to specify the scopes we need explicitly.
66-
// Check for this case, and inject the Cloud Storage scope if required.
67-
if (credential.createScopedRequired()) {
68-
credential = credential.createScoped(StorageScopes.all());
69-
}
70-
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
71-
storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
72-
.setApplicationName(APPLICATION_NAME).build();
73-
}
74-
return storageService;
75-
}
76-
// [END get_service]
77-
7842
// [START list_bucket]
7943
/**
8044
* Fetch a list of the objects within the given bucket.
@@ -84,7 +48,7 @@ private static Storage getService() throws IOException, GeneralSecurityException
8448
*/
8549
public static List<StorageObject> listBucket(String bucketName)
8650
throws IOException, GeneralSecurityException {
87-
Storage client = getService();
51+
Storage client = StorageFactory.getService();
8852
Storage.Objects.List listRequest = client.objects().list(bucketName);
8953

9054
List<StorageObject> results = new ArrayList<StorageObject>();
@@ -112,7 +76,7 @@ public static List<StorageObject> listBucket(String bucketName)
11276
* @return a Bucket containing the bucket's metadata.
11377
*/
11478
public static Bucket getBucket(String bucketName) throws IOException, GeneralSecurityException {
115-
Storage client = getService();
79+
Storage client = StorageFactory.getService();
11680

11781
Storage.Buckets.Get bucketRequest = client.buckets().get(bucketName);
11882
// Fetch the full set of the bucket's properties (e.g. include the ACLs in the response)
@@ -142,7 +106,7 @@ public static void uploadStream(
142106
new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
143107

144108
// Do the insert
145-
Storage client = getService();
109+
Storage client = StorageFactory.getService();
146110
Storage.Objects.Insert insertRequest = client.objects().insert(
147111
bucketName, objectMetadata, contentStream);
148112

@@ -159,7 +123,7 @@ public static void uploadStream(
159123
*/
160124
public static void deleteObject(String path, String bucketName)
161125
throws IOException, GeneralSecurityException {
162-
Storage client = getService();
126+
Storage client = StorageFactory.getService();
163127
client.objects().delete(bucketName, path).execute();
164128
}
165129
// [END delete_object]

0 commit comments

Comments
 (0)