|
| 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] |
0 commit comments