Skip to content

Commit 1d687bd

Browse files
author
Jerjou Cheng
committed
Add samples for cloud storage json api.
1 parent e7c7050 commit 1d687bd

File tree

3 files changed

+340
-0
lines changed

3 files changed

+340
-0
lines changed

cloud-storage/json-api/pom.xml

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project>
3+
<parent>
4+
<artifactId>doc-samples</artifactId>
5+
<groupId>com.google.cloud</groupId>
6+
<version>1.0.0</version>
7+
<relativePath>../..</relativePath>
8+
</parent>
9+
10+
<modelVersion>4.0.0</modelVersion>
11+
<groupId>com.google.apis-samples</groupId>
12+
<artifactId>storage-json-sample</artifactId>
13+
<version>1</version>
14+
<name>Sample accessing the Google Cloud Storage JSON API using OAuth 2.0.</name>
15+
<build>
16+
<plugins>
17+
<plugin>
18+
<groupId>org.codehaus.mojo</groupId>
19+
<artifactId>exec-maven-plugin</artifactId>
20+
<version>1.1</version>
21+
<executions>
22+
<execution>
23+
<goals>
24+
<goal>java</goal>
25+
</goals>
26+
</execution>
27+
</executions>
28+
<configuration>
29+
<mainClass>StorageSample</mainClass>
30+
</configuration>
31+
</plugin>
32+
</plugins>
33+
<finalName>${project.artifactId}-${project.version}</finalName>
34+
</build>
35+
<dependencies>
36+
<dependency>
37+
<groupId>com.google.apis</groupId>
38+
<artifactId>google-api-services-storage</artifactId>
39+
<version>v1-rev18-1.19.0</version>
40+
</dependency>
41+
<!-- Test Dependencies -->
42+
<dependency>
43+
<groupId>junit</groupId>
44+
<artifactId>junit</artifactId>
45+
<version>4.10</version>
46+
<scope>test</scope>
47+
</dependency>
48+
</dependencies>
49+
</project>
Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
//[START all]
2+
/*
3+
* Copyright (c) 2014 Google Inc.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6+
* in compliance with the License. You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software distributed under the License
11+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12+
* or implied. See the License for the specific language governing permissions and limitations under
13+
* the License.
14+
*/
15+
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;
19+
import com.google.api.client.http.InputStreamContent;
20+
import com.google.api.client.json.JsonFactory;
21+
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.services.storage.Storage;
23+
import com.google.api.services.storage.model.Bucket;
24+
import com.google.api.services.storage.model.ObjectAccessControl;
25+
import com.google.api.services.storage.model.Objects;
26+
import com.google.api.services.storage.model.StorageObject;
27+
28+
import java.io.ByteArrayInputStream;
29+
import java.io.File;
30+
import java.io.IOException;
31+
import java.io.InputStream;
32+
import java.security.GeneralSecurityException;
33+
import java.util.ArrayList;
34+
import java.util.Arrays;
35+
import java.util.List;
36+
37+
/**
38+
* Main class for the Cloud Storage API command line sample.
39+
* Demonstrates how to make an authenticated API call using Application Default
40+
* Credentials.
41+
*/
42+
public class StorageSample {
43+
44+
/**
45+
* Be sure to specify the name of your application. If the application name is {@code null} or
46+
* blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
47+
*/
48+
private static final String APPLICATION_NAME = "[[INSERT_YOUR_APP_NAME_HERE]]";
49+
50+
/** Global instance of the JSON factory. */
51+
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
52+
private static final String TEST_FILENAME = "json-test.txt";
53+
54+
private static Storage storageService;
55+
56+
/**
57+
* Returns an authenticated Storage object used to make service calls to Cloud Storage.
58+
*/
59+
private static Storage getService() throws IOException, GeneralSecurityException {
60+
if (null == storageService) {
61+
GoogleCredential credential = GoogleCredential.getApplicationDefault();
62+
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
63+
storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
64+
.setApplicationName(APPLICATION_NAME).build();
65+
}
66+
return storageService;
67+
}
68+
69+
// [START list_bucket]
70+
/**
71+
* Fetch a list of the objects within the given bucket.
72+
*
73+
* @param bucketName the name of the bucket to list.
74+
* @return a list of the contents of the specified bucket.
75+
*/
76+
public static List<StorageObject> listBucket(String bucketName)
77+
throws IOException, GeneralSecurityException {
78+
Storage client = getService();
79+
Storage.Objects.List listRequest = client.objects().list(bucketName);
80+
81+
List<StorageObject> results = new ArrayList<StorageObject>();
82+
Objects objects;
83+
84+
// Iterate through each page of results, and add them to our results list.
85+
do {
86+
objects = listRequest.execute();
87+
// Add the items in this page of results to the list we'll return.
88+
results.addAll(objects.getItems());
89+
90+
// Get the next page, in the next iteration of this loop.
91+
listRequest.setPageToken(objects.getNextPageToken());
92+
} while (null != objects.getNextPageToken());
93+
94+
return results;
95+
}
96+
// [END list_bucket]
97+
98+
// [START get_bucket]
99+
/**
100+
* Fetches the metadata for the given bucket.
101+
*
102+
* @param bucketName the name of the bucket to get metadata about.
103+
* @return a Bucket containing the bucket's metadata.
104+
*/
105+
public static Bucket getBucket(String bucketName) throws IOException, GeneralSecurityException {
106+
Storage client = getService();
107+
108+
Storage.Buckets.Get bucketRequest = client.buckets().get(bucketName);
109+
bucketRequest.setProjection("full");
110+
return bucketRequest.execute();
111+
}
112+
// [END get_bucket]
113+
114+
// [START upload_stream]
115+
/**
116+
* Uploads data to an object in a bucket.
117+
*
118+
* @param name the name of the destination object.
119+
* @param contentType the MIME type of the data.
120+
* @param stream the data - for instance, you can use a FileInputStream to upload a file.
121+
* @param bucketName the name of the bucket to create the object in.
122+
*/
123+
public static void uploadStream(
124+
String name, String contentType, InputStream stream, String bucketName)
125+
throws IOException, GeneralSecurityException {
126+
InputStreamContent contentStream = new InputStreamContent(contentType, stream);
127+
StorageObject objectMetadata = new StorageObject()
128+
// Set the destination object name
129+
.setName(name)
130+
// Set the access control list to publicly read-only
131+
.setAcl(Arrays.asList(
132+
new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
133+
134+
// Do the insert
135+
Storage client = getService();
136+
Storage.Objects.Insert insertRequest = client.objects().insert(
137+
bucketName, objectMetadata, contentStream);
138+
139+
insertRequest.execute();
140+
}
141+
// [END upload_stream]
142+
143+
// [START delete_object]
144+
/**
145+
* Deletes an object in a bucket.
146+
*
147+
* @param path the path to the object to delete.
148+
* @param bucketName the bucket the object is contained in.
149+
*/
150+
public static void deleteObject(String path, String bucketName)
151+
throws IOException, GeneralSecurityException {
152+
Storage client = getService();
153+
client.objects().delete(bucketName, path).execute();
154+
}
155+
// [END delete_object]
156+
157+
/**
158+
* Exercises the class's functions - gets and lists a bucket, uploads and deletes an object.
159+
*
160+
* @param args the command-line arguments. The first argument should be the bucket name.
161+
*/
162+
public static void main(String[] args) {
163+
if (args.length < 1) {
164+
System.out.println("Usage: StorageSample <bucket-name>");
165+
System.exit(1);
166+
}
167+
168+
String bucketName = args[0];
169+
170+
try {
171+
// Get metadata about the specified bucket.
172+
Bucket bucket = getBucket(bucketName);
173+
System.out.println("name: " + bucketName);
174+
System.out.println("location: " + bucket.getLocation());
175+
System.out.println("timeCreated: " + bucket.getTimeCreated());
176+
System.out.println("owner: " + bucket.getOwner());
177+
178+
179+
// List the contents of the bucket.
180+
List<StorageObject> bucketContents = listBucket(bucketName);
181+
if (null == bucketContents) {
182+
System.out.println(
183+
"There were no objects in the given bucket; try adding some and re-running.");
184+
}
185+
for (StorageObject object : bucketContents) {
186+
System.out.println(object.getName() + " (" + object.getSize() + " bytes)");
187+
}
188+
189+
190+
// Upload a stream to the bucket. This could very well be a file.
191+
uploadStream(
192+
TEST_FILENAME, "text/plain",
193+
new ByteArrayInputStream("Test of json storage sample".getBytes()),
194+
bucketName);
195+
196+
// Now delete the file
197+
deleteObject(TEST_FILENAME, bucketName);
198+
199+
} catch (IOException e) {
200+
System.err.println(e.getMessage());
201+
System.exit(1);
202+
} catch (Throwable t) {
203+
t.printStackTrace();
204+
System.exit(1);
205+
}
206+
}
207+
}
208+
//[END all]
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/**
2+
* Copyright 2015 Google Inc. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
// [START all]
18+
19+
import static org.junit.Assert.*;
20+
21+
import com.google.api.services.storage.model.Bucket;
22+
import com.google.api.services.storage.model.StorageObject;
23+
24+
import org.junit.Test;
25+
26+
import java.util.List;
27+
import java.util.regex.Pattern;
28+
import java.io.ByteArrayInputStream;
29+
30+
public class StorageSampleTest {
31+
private static final String BUCKET = "cloud-samples-tests";
32+
private static final String TEST_OBJECT = "storage-sample-test-upload.txt";
33+
34+
@Test
35+
public void testListBucket() throws Exception {
36+
List<StorageObject> listing = StorageSample.listBucket(BUCKET);
37+
assertTrue(listing.size() > 0);
38+
}
39+
40+
@Test
41+
public void testGetBucket() throws Exception {
42+
Bucket bucket = StorageSample.getBucket(BUCKET);
43+
assertEquals(bucket.getName(), BUCKET);
44+
assertEquals(bucket.getLocation(), "US-CENTRAL1");
45+
}
46+
47+
@Test
48+
public void testUploadDelete() throws Exception {
49+
StorageSample.uploadStream(
50+
TEST_OBJECT, "text/plain",
51+
new ByteArrayInputStream(("This object is uploaded and deleted as part of the "
52+
+ "StorageSampleTest integration test.").getBytes()),
53+
BUCKET);
54+
55+
try {
56+
// Verify that the object was created
57+
List<StorageObject> listing = StorageSample.listBucket(BUCKET);
58+
boolean found = false;
59+
for (StorageObject so : listing) {
60+
if (TEST_OBJECT.equals(so.getName())) {
61+
found = true;
62+
break;
63+
}
64+
}
65+
assertTrue("Should have uploaded successfully", found);
66+
67+
} finally {
68+
StorageSample.deleteObject(TEST_OBJECT, BUCKET);
69+
70+
// Verify that the object no longer exists
71+
List<StorageObject> listing = StorageSample.listBucket(BUCKET);
72+
boolean found = false;
73+
for (StorageObject so : listing) {
74+
if (TEST_OBJECT.equals(so.getName())) {
75+
found = true;
76+
break;
77+
}
78+
}
79+
assertFalse("Object (" + TEST_OBJECT + ") should have been deleted", found);
80+
}
81+
}
82+
}
83+
// [END all]

0 commit comments

Comments
 (0)