Skip to content

Commit a27282e

Browse files
committed
Merge pull request #405 from ajkannan/add-storage-examples
Add step-by-step guide for storage README
2 parents a6da17e + 8ebfdf8 commit a27282e

1 file changed

Lines changed: 125 additions & 16 deletions

File tree

gcloud-java-storage/README.md

Lines changed: 125 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -56,29 +56,138 @@ Cloud Storage for your project.
5656
See the ``gcloud-java`` API [storage documentation][storage-api] to learn how to interact
5757
with the Cloud Storage using this Client Library.
5858

59-
Here is a code snippet showing a simple usage example from within Compute/App Engine. Note that you must [supply credentials](https://github.com/GoogleCloudPlatform/gcloud-java#authentication) and a project ID if running this snippet elsewhere.
59+
Getting Started
60+
---------------
61+
#### Prerequisites
62+
For this tutorial, you will need a [Google Developers Console](https://console.developers.google.com/) project with the Storage JSON API enabled. You will need to [enable billing](https://support.google.com/cloud/answer/6158867?hl=en) to use Google Cloud Storage. [Follow these instructions](https://cloud.google.com/docs/authentication#preparation) to get your project set up. You will also need to set up the local development environment by [installing the Google Cloud SDK](https://cloud.google.com/sdk/) and running the following commands in command line: `gcloud auth login` and `gcloud config set project [YOUR PROJECT ID]`.
63+
64+
#### Installation and setup
65+
You'll need to obtain the `gcloud-java-storage` library. See the [Quickstart](#quickstart) section to add `gcloud-java-storage` as a dependency in your code.
66+
67+
#### Creating an authorized service object
68+
To make authenticated requests to Google Cloud Storage, you must create a service object with credentials. You can then make API calls by calling methods on the Storage service object. The simplest way to authenticate is to use [Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials). These credentials are automatically inferred from your environment, so you only need the following code to create your service object:
69+
70+
```java
71+
import com.google.gcloud.storage.Storage;
72+
import com.google.gcloud.storage.StorageOptions;
73+
74+
Storage storage = StorageOptions.defaultInstance().service();
75+
```
76+
77+
For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/gcloud-java#authentication) page.
78+
79+
#### Storing data
80+
Stored objects are called "blobs" in `gcloud-java` and are organized into containers called "buckets". In this code snippet, we will create a new bucket and upload a blob to that bucket.
81+
82+
Add the following imports at the top of your file:
6083

6184
```java
6285
import static java.nio.charset.StandardCharsets.UTF_8;
6386

64-
import com.google.gcloud.storage.Blob;
87+
import com.google.gcloud.storage.BlobId;
88+
import com.google.gcloud.storage.BlobInfo;
89+
import com.google.gcloud.storage.BucketInfo;
90+
```
91+
92+
Then add the following code to create a bucket and upload a simple blob.
93+
94+
*Important: Bucket names have to be globally unique. If you choose a bucket name that already exists, you'll get a helpful error message telling you to choose another name. In the code below, replace "my_unique_bucket" with a unique bucket name. See more about naming rules [here](https://cloud.google.com/storage/docs/bucket-naming?hl=en#requirements).*
95+
96+
```java
97+
// Create a bucket
98+
String bucketName = "my_unique_bucket"; // Change this to something unique
99+
BucketInfo bucketInfo = storage.create(BucketInfo.of(bucketName));
100+
101+
// Upload a blob to the newly created bucket
102+
BlobId blobId = BlobId.of(bucketName, "my_blob_name");
103+
BlobInfo blobInfo = storage.create(
104+
BlobInfo.builder(blobId).contentType("text/plain").build(),
105+
"a simple blob".getBytes(UTF_8));
106+
```
107+
108+
At this point, you will be able to see your newly created bucket and blob on the Google Developers Console.
109+
110+
#### Retrieving data
111+
Now that we have content uploaded to the server, we can see how to read data from the server. Add the following line to your program to get back the blob we uploaded.
112+
113+
```java
114+
String blobContent = new String(storage.readAllBytes(blobId), UTF_8);
115+
```
116+
117+
#### Listing buckets and contents of buckets
118+
Suppose that you've added more buckets and blobs, and now you want to see the names of your buckets and the contents of each one. Add the following imports:
119+
120+
```java
121+
import java.util.Iterator;
122+
```
123+
124+
Then add the following code to list all your buckets and all the blobs inside your newly created bucket.
125+
126+
```java
127+
// List all your buckets
128+
Iterator<BucketInfo> bucketInfoIterator = storage.list().iterateAll();
129+
System.out.println("My buckets:");
130+
while (bucketInfoIterator.hasNext()) {
131+
System.out.println(bucketInfoIterator.next());
132+
}
133+
134+
// List the blobs in a particular bucket
135+
Iterator<BlobInfo> blobIterator = storage.list(bucketName).iterateAll();
136+
System.out.println("My blobs:");
137+
while (blobIterator.hasNext()) {
138+
System.out.println(blobIterator.next());
139+
}
140+
```
141+
142+
#### Complete source code
143+
144+
Here we put together all the code shown above into one program. This program assumes that you are running on Compute Engine or from your own desktop. To run this example on App Engine, simply move the code from the main method to your application's servlet class and change the print statements to display on your webpage.
145+
146+
```java
147+
import static java.nio.charset.StandardCharsets.UTF_8;
148+
149+
import com.google.gcloud.storage.BlobId;
150+
import com.google.gcloud.storage.BlobInfo;
151+
import com.google.gcloud.storage.BucketInfo;
65152
import com.google.gcloud.storage.Storage;
66153
import com.google.gcloud.storage.StorageOptions;
67154

68-
import java.nio.ByteBuffer;
69-
import java.nio.channels.WritableByteChannel;
70-
71-
Storage storage = StorageOptions.defaultInstance().service();
72-
Blob blob = new Blob(storage, "bucket", "blob_name");
73-
if (!blob.exists()) {
74-
storage2.create(blob.info(), "Hello, Cloud Storage!".getBytes(UTF_8));
75-
} else {
76-
System.out.println("Updating content for " + blob.info().name());
77-
byte[] prevContent = blob.content();
78-
System.out.println(new String(prevContent, UTF_8));
79-
WritableByteChannel channel = blob.writer();
80-
channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
81-
channel.close();
155+
import java.util.Iterator;
156+
157+
public class GcloudStorageExample {
158+
159+
public static void main(String[] args) {
160+
// Create a service object
161+
// Credentials are inferred from the environment.
162+
Storage storage = StorageOptions.defaultInstance().service();
163+
164+
// Create a bucket
165+
String bucketName = "my_unique_bucket"; // Change this to something unique
166+
BucketInfo bucketInfo = storage.create(BucketInfo.of(bucketName));
167+
168+
// Upload a blob to the newly created bucket
169+
BlobId blobId = BlobId.of(bucketName, "my_blob_name");
170+
BlobInfo blobInfo = storage.create(
171+
BlobInfo.builder(blobId).contentType("text/plain").build(),
172+
"a simple blob".getBytes(UTF_8));
173+
174+
// Retrieve a blob from the server
175+
String blobContent = new String(storage.readAllBytes(blobId), UTF_8);
176+
177+
// List all your buckets
178+
Iterator<BucketInfo> bucketInfoIterator = storage.list().iterateAll();
179+
System.out.println("My buckets:");
180+
while (bucketInfoIterator.hasNext()) {
181+
System.out.println(bucketInfoIterator.next());
182+
}
183+
184+
// List the blobs in a particular bucket
185+
Iterator<BlobInfo> blobIterator = storage.list(bucketName).iterateAll();
186+
System.out.println("My blobs:");
187+
while (blobIterator.hasNext()) {
188+
System.out.println(blobIterator.next());
189+
}
190+
}
82191
}
83192
```
84193

0 commit comments

Comments
 (0)