Skip to content

Commit fef30c3

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

File tree

3 files changed

+342
-0
lines changed

3 files changed

+342
-0
lines changed

cloud-storage/json-api/pom.xml

+49
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>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
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 JSON API sample.
39+
*
40+
* Demonstrates how to make an authenticated API call using the Google Cloud Storage API client
41+
* library for java, with Application Default Credentials.
42+
*/
43+
public class StorageSample {
44+
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+
51+
/** Global instance of the JSON factory. */
52+
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
53+
private static final String TEST_FILENAME = "json-test.txt";
54+
55+
private static Storage storageService;
56+
57+
/**
58+
* Returns an authenticated Storage object used to make service calls to Cloud Storage.
59+
*/
60+
private static Storage getService() throws IOException, GeneralSecurityException {
61+
if (null == storageService) {
62+
GoogleCredential credential = GoogleCredential.getApplicationDefault();
63+
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
64+
storageService = new Storage.Builder(httpTransport, JSON_FACTORY, credential)
65+
.setApplicationName(APPLICATION_NAME).build();
66+
}
67+
return storageService;
68+
}
69+
70+
// [START list_bucket]
71+
/**
72+
* Fetch a list of the objects within the given bucket.
73+
*
74+
* @param bucketName the name of the bucket to list.
75+
* @return a list of the contents of the specified bucket.
76+
*/
77+
public static List<StorageObject> listBucket(String bucketName)
78+
throws IOException, GeneralSecurityException {
79+
Storage client = getService();
80+
Storage.Objects.List listRequest = client.objects().list(bucketName);
81+
82+
List<StorageObject> results = new ArrayList<StorageObject>();
83+
Objects objects;
84+
85+
// Iterate through each page of results, and add them to our results list.
86+
do {
87+
objects = listRequest.execute();
88+
// Add the items in this page of results to the list we'll return.
89+
results.addAll(objects.getItems());
90+
91+
// Get the next page, in the next iteration of this loop.
92+
listRequest.setPageToken(objects.getNextPageToken());
93+
} while (null != objects.getNextPageToken());
94+
95+
return results;
96+
}
97+
// [END list_bucket]
98+
99+
// [START get_bucket]
100+
/**
101+
* Fetches the metadata for the given bucket.
102+
*
103+
* @param bucketName the name of the bucket to get metadata about.
104+
* @return a Bucket containing the bucket's metadata.
105+
*/
106+
public static Bucket getBucket(String bucketName) throws IOException, GeneralSecurityException {
107+
Storage client = getService();
108+
109+
Storage.Buckets.Get bucketRequest = client.buckets().get(bucketName);
110+
// Fetch the full set of the bucket's properties (eg include the ACLs in the response)
111+
bucketRequest.setProjection("full");
112+
return bucketRequest.execute();
113+
}
114+
// [END get_bucket]
115+
116+
// [START upload_stream]
117+
/**
118+
* Uploads data to an object in a bucket.
119+
*
120+
* @param name the name of the destination object.
121+
* @param contentType the MIME type of the data.
122+
* @param stream the data - for instance, you can use a FileInputStream to upload a file.
123+
* @param bucketName the name of the bucket to create the object in.
124+
*/
125+
public static void uploadStream(
126+
String name, String contentType, InputStream stream, String bucketName)
127+
throws IOException, GeneralSecurityException {
128+
InputStreamContent contentStream = new InputStreamContent(contentType, stream);
129+
StorageObject objectMetadata = new StorageObject()
130+
// Set the destination object name
131+
.setName(name)
132+
// Set the access control list to publicly read-only
133+
.setAcl(Arrays.asList(
134+
new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
135+
136+
// Do the insert
137+
Storage client = getService();
138+
Storage.Objects.Insert insertRequest = client.objects().insert(
139+
bucketName, objectMetadata, contentStream);
140+
141+
insertRequest.execute();
142+
}
143+
// [END upload_stream]
144+
145+
// [START delete_object]
146+
/**
147+
* Deletes an object in a bucket.
148+
*
149+
* @param path the path to the object to delete.
150+
* @param bucketName the bucket the object is contained in.
151+
*/
152+
public static void deleteObject(String path, String bucketName)
153+
throws IOException, GeneralSecurityException {
154+
Storage client = getService();
155+
client.objects().delete(bucketName, path).execute();
156+
}
157+
// [END delete_object]
158+
159+
/**
160+
* Exercises the class's functions - gets and lists a bucket, uploads and deletes an object.
161+
*
162+
* @param args the command-line arguments. The first argument should be the bucket name.
163+
*/
164+
public static void main(String[] args) {
165+
if (args.length < 1) {
166+
System.out.println("Usage: StorageSample <bucket-name>");
167+
System.exit(1);
168+
}
169+
170+
String bucketName = args[0];
171+
172+
try {
173+
// Get metadata about the specified bucket.
174+
Bucket bucket = getBucket(bucketName);
175+
System.out.println("name: " + bucketName);
176+
System.out.println("location: " + bucket.getLocation());
177+
System.out.println("timeCreated: " + bucket.getTimeCreated());
178+
System.out.println("owner: " + bucket.getOwner());
179+
180+
181+
// List the contents of the bucket.
182+
List<StorageObject> bucketContents = listBucket(bucketName);
183+
if (null == bucketContents) {
184+
System.out.println(
185+
"There were no objects in the given bucket; try adding some and re-running.");
186+
}
187+
for (StorageObject object : bucketContents) {
188+
System.out.println(object.getName() + " (" + object.getSize() + " bytes)");
189+
}
190+
191+
192+
// Upload a stream to the bucket. This could very well be a file.
193+
uploadStream(
194+
TEST_FILENAME, "text/plain",
195+
new ByteArrayInputStream("Test of json storage sample".getBytes()),
196+
bucketName);
197+
198+
// Now delete the file
199+
deleteObject(TEST_FILENAME, bucketName);
200+
201+
} catch (IOException e) {
202+
System.err.println(e.getMessage());
203+
System.exit(1);
204+
} catch (Throwable t) {
205+
t.printStackTrace();
206+
System.exit(1);
207+
}
208+
}
209+
}
210+
//[END all]
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)