Skip to content

Commit dcf91cc

Browse files
author
Jerjou Cheng
committed
Update to use App Default Creds.
+ some other cleanup.
1 parent 9ebe7fa commit dcf91cc

File tree

5 files changed

+65
-83
lines changed

5 files changed

+65
-83
lines changed

cloud-storage/xml-api/serviceaccount-cmdline-sample/README.md

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,23 @@ for setting up a service account.
1515
Checkout Instructions
1616
---------------------
1717

18-
**Prerequisites:** install the latest version of [Java](http//java.com) and [Maven](http://maven.apache.org/download.html). You must also be able to work with qcGitHub repository (see e.g.,
19-
https://help.github.com/articles/set-up-git).
20-
21-
You may need to set your `JAVA_HOME`.
18+
1. **Prerequisites:**
19+
1. install the latest version of [Java](http//java.com) and [Maven](http://maven.apache.org/download.html).
20+
1. [Create](https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets) a Google Cloud Storage bucket
21+
1. You must also be able to work with [GitHub](https://help.github.com/articles/set-up-git) repositories.
22+
1. You may need to set your `JAVA_HOME`.
2223

2324
1. Clone repository.
2425

25-
cd [someDirectory]
2626
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
2727
cd java-docs-samples/cloud-storage/xml-api/serviceaccount-cmdline-sample
2828

29-
2. Update key.p12 file.
30-
3. Edit `StorageServiceAccountSample.java` to add your bucket and service account email.
31-
4. Compile and run
29+
1. Update key.json file.
30+
1. Compile and run
3231

3332
mvn compile install
34-
mvn -q exec:java
33+
export GOOGLE_APPLICATION_CREDENTIALS=key.json
34+
mvn -q exec:java -Dexec.args="your-bucket-name"
3535

3636

3737
To enable logging of HTTP requests and responses (highly recommended when
@@ -40,8 +40,9 @@ developing), please take a look at logging.properties.
4040
Set Up a Project in Eclipse
4141
---------------------------
4242

43-
**Prerequisites:** install [Eclipse](http://www.eclipse.org/downloads/), the [Maven plugin](http://m2eclipse.sonatype.org/installing-m2eclipse.html), and optionally the
44-
[GitHub plugin](http://eclipse.github.com/).
43+
* **Prerequisites:**
44+
* Install [Eclipse](http://www.eclipse.org/downloads/), the [Maven plugin](http://eclipse.org/m2e/), and optionally the [GitHub plugin](http://eclipse.github.com/).
45+
* [Create](https://cloud.google.com/storage/docs/cloud-console#_creatingbuckets) a Google Cloud Storage bucket
4546

4647
* Set up Eclipse Preferences
4748

@@ -63,9 +64,11 @@ to work with GitHub repositories.
6364
* Make sure the Eclipse package name matches the package name used in the
6465
code file `com.google.api.services.samples.storage.serviceaccount.cmdline`.
6566
* Select the project and **Convert to Maven Project** to add Maven Dependencies.
66-
* Edit `StorageServiceAccountSample.java` and specify your SERVICE_ACCOUNT_EMAIL and
67-
BUCKET_NAME.
68-
* Update the key.p12 file.
67+
* Update the key.json file.
68+
* Click on Run > Run configurations
69+
* Navigate to your **Java Application**'s configuration section
70+
* In the **Arguments** tab, add your bucket name as a **Program argument**
71+
* In the **Environment** tab, create a variable `GOOGLE_APPLICATION_CREDENTIALS` and set it to `key.json`
6972

7073
* Run
7174

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Please download key.json file from the Google APIs Console at https://console.developers.google.com.
2+
3+
For more information, see https://developers.google.com/storage/docs/xml-api-java-samples.

cloud-storage/xml-api/serviceaccount-cmdline-sample/key.p12

Lines changed: 0 additions & 3 deletions
This file was deleted.

cloud-storage/xml-api/serviceaccount-cmdline-sample/pom.xml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,21 @@
2929
<dependency>
3030
<groupId>com.google.apis</groupId>
3131
<artifactId>google-api-services-storage</artifactId>
32-
<version>v1beta2-rev43-1.18.0-rc</version>
32+
<version>v1-rev35-1.20.0</version>
3333
</dependency>
3434
<dependency>
3535
<groupId>com.google.http-client</groupId>
3636
<artifactId>google-http-client-jackson2</artifactId>
3737
<version>${project.http.version}</version>
3838
</dependency>
3939
<dependency>
40-
<groupId>com.google.guava</groupId>
41-
<artifactId>guava</artifactId>
42-
<version>16.0.1</version>
40+
<groupId>com.google.guava</groupId>
41+
<artifactId>guava</artifactId>
42+
<version>18.0</version>
4343
</dependency>
4444
</dependencies>
4545
<properties>
46-
<project.http.version>1.17.0-rc</project.http.version>
46+
<project.http.version>1.20.0</project.http.version>
4747
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
4848
</properties>
4949
</project>

cloud-storage/xml-api/serviceaccount-cmdline-sample/src/main/java/StorageServiceAccountSample.java

Lines changed: 40 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@
2727
import com.google.api.client.util.Preconditions;
2828
import com.google.common.io.Files;
2929

30-
import java.io.File;
3130
import java.io.IOException;
3231
import java.io.StringReader;
3332
import java.io.StringWriter;
3433
import java.nio.charset.Charset;
3534
import java.util.Collections;
35+
import java.net.URLEncoder;
3636

3737
import javax.xml.transform.OutputKeys;
3838
import javax.xml.transform.Source;
@@ -43,76 +43,55 @@
4343

4444
public class StorageServiceAccountSample {
4545

46-
/** E-mail address of the service account. */
47-
private static final String SERVICE_ACCOUNT_EMAIL = "[[INSERT_SERVICE_ACCOUNT_EMAIL_HERE]]";
48-
49-
/** Bucket to list. */
50-
private static final String BUCKET_NAME = "[[INSERT_YOUR_BUCKET_NAME_HERE]]";
51-
5246
/** Global configuration of Google Cloud Storage OAuth 2.0 scope. */
5347
private static final String STORAGE_SCOPE =
5448
"https://www.googleapis.com/auth/devstorage.read_write";
5549

5650
/** Global instance of the HTTP transport. */
5751
private static HttpTransport httpTransport;
5852

59-
/** Global instance of the JSON factory. */
60-
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
61-
6253
public static void main(String[] args) {
6354
try {
64-
try {
65-
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
66-
// Check for valid setup.
67-
Preconditions.checkArgument(!SERVICE_ACCOUNT_EMAIL.startsWith("[["),
68-
"Please enter your service account e-mail from the Google APIs "
69-
+ "Console to the SERVICE_ACCOUNT_EMAIL constant in %s",
70-
StorageServiceAccountSample.class.getName());
71-
Preconditions.checkArgument(!BUCKET_NAME.startsWith("[["),
72-
"Please enter your desired Google Cloud Storage bucket name "
73-
+ "to the BUCKET_NAME constant in %s", StorageServiceAccountSample.class.getName());
74-
String p12Content = Files.readFirstLine(new File("key.p12"), Charset.defaultCharset());
75-
Preconditions.checkArgument(!p12Content.startsWith("Please"), p12Content);
76-
77-
//[START snippet]
78-
// Build a service account credential.
79-
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
80-
.setJsonFactory(JSON_FACTORY)
81-
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
82-
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
83-
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
84-
.build();
85-
86-
// Set up and execute a Google Cloud Storage request.
87-
String URI = "https://storage.googleapis.com/" + BUCKET_NAME;
88-
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
89-
GenericUrl url = new GenericUrl(URI);
90-
HttpRequest request = requestFactory.buildGetRequest(url);
91-
HttpResponse response = request.execute();
92-
String content = response.parseAsString();
93-
//[END snippet]
94-
95-
// Instantiate transformer input.
96-
Source xmlInput = new StreamSource(new StringReader(content));
97-
StreamResult xmlOutput = new StreamResult(new StringWriter());
98-
99-
// Configure transformer.
100-
Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An identity
101-
// transformer
102-
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
103-
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
104-
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
105-
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
106-
transformer.transform(xmlInput, xmlOutput);
107-
108-
// Pretty print the output XML.
109-
System.out.println("\nBucket listing for " + BUCKET_NAME + ":\n");
110-
System.out.println(xmlOutput.getWriter().toString());
111-
System.exit(0);
112-
113-
} catch (IOException e) {
55+
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
56+
// Check for valid setup.
57+
Preconditions.checkArgument(args.length == 1,
58+
"Please pass in the Google Cloud Storage bucket name to display");
59+
String bucketName = args[0];
60+
61+
//[START snippet]
62+
// Build a service account credential.
63+
GoogleCredential credential = GoogleCredential.getApplicationDefault()
64+
.createScoped(Collections.singleton(STORAGE_SCOPE));
65+
66+
// Set up and execute a Google Cloud Storage request.
67+
String URI = "https://storage.googleapis.com/" + URLEncoder.encode(bucketName, "UTF-8");
68+
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
69+
GenericUrl url = new GenericUrl(URI);
70+
HttpRequest request = requestFactory.buildGetRequest(url);
71+
HttpResponse response = request.execute();
72+
String content = response.parseAsString();
73+
//[END snippet]
74+
75+
// Instantiate transformer input.
76+
Source xmlInput = new StreamSource(new StringReader(content));
77+
StreamResult xmlOutput = new StreamResult(new StringWriter());
78+
79+
// Configure transformer.
80+
Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An identity
81+
// transformer
82+
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
83+
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
84+
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
85+
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
86+
transformer.transform(xmlInput, xmlOutput);
87+
88+
// Pretty print the output XML.
89+
System.out.println("\nBucket listing for " + bucketName + ":\n");
90+
System.out.println(xmlOutput.getWriter().toString());
91+
System.exit(0);
92+
93+
} catch (IOException e) {
11494
System.err.println(e.getMessage());
115-
}
11695
} catch (Throwable t) {
11796
t.printStackTrace();
11897
}

0 commit comments

Comments
 (0)