-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathStorageExample.java
More file actions
397 lines (357 loc) · 11.6 KB
/
StorageExample.java
File metadata and controls
397 lines (357 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gcloud.examples;
import com.google.gcloud.spi.StorageRpc.Tuple;
import com.google.gcloud.storage.BatchRequest;
import com.google.gcloud.storage.BatchResponse;
import com.google.gcloud.storage.Blob;
import com.google.gcloud.storage.BlobReadChannel;
import com.google.gcloud.storage.BlobWriteChannel;
import com.google.gcloud.storage.Bucket;
import com.google.gcloud.storage.StorageService;
import com.google.gcloud.storage.StorageService.ComposeRequest;
import com.google.gcloud.storage.StorageService.CopyRequest;
import com.google.gcloud.storage.StorageServiceFactory;
import com.google.gcloud.storage.StorageServiceOptions;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* An example of using the Google Cloud Storage.
* <p>
* This example demonstrates a simple/typical usage.
* <p>
* Steps needed for running the example:
* <ol>
* <li>login using gcloud SDK - {@code gcloud auth login}.</li>
* <li>compile using maven - {@code mvn compile}</li>
* <li>run using maven -
* {@code mvn exec:java -Dexec.mainClass="com.google.gcloud.examples.StorageExample"
* -Dexec.args="[<project_id>] list [<bucket>]| info [<bucket> [<file>]]|
* download <bucket> <path> [local_file]| upload <local_file> <bucket> [<path>]|
* delete <bucket> <path>+| cp <from_bucket> <from_path> <to_bucket> <to_path>|
* compose <bucket> <from_path>+ <to_path>"}
* </li>
* </ol>
*/
public class StorageExample {
private static final Map<String, StorageAction> ACTIONS = new HashMap<>();
private static abstract class StorageAction<T> {
abstract void run(StorageService storage, T request) throws Exception;
abstract T parse(String... args) throws IllegalArgumentException;
protected String params() {
return "";
}
}
private static abstract class BlobAction extends StorageAction<Blob> {
@Override
Blob parse(String... args) {
if (args.length != 2) {
throw new IllegalArgumentException();
}
return Blob.of(args[0], args[1]);
}
@Override
public String params() {
return "<bucket> <path>";
}
}
private static abstract class BlobsAction extends StorageAction<Blob[]> {
@Override
Blob[] parse(String... args) {
if (args.length < 2) {
throw new IllegalArgumentException();
}
Blob[] blobs = new Blob[args.length - 1];
for (int i = 1; i < args.length; i++) {
blobs[i - 1] = Blob.of(args[0], args[i]);
}
return blobs;
}
@Override
public String params() {
return "<bucket> <path>+";
}
}
private static class InfoAction extends BlobsAction {
@Override
public void run(StorageService storage, Blob... blobs) {
if (blobs.length == 1) {
if (blobs[0].name().isEmpty()) {
System.out.println(storage.get(Bucket.of(blobs[0].bucket())));
} else {
System.out.println(storage.get(blobs[0]));
}
} else {
BatchRequest.Builder batch = BatchRequest.builder();
for (Blob blob : blobs) {
batch.get(blob);
}
BatchResponse response = storage.apply(batch.build());
System.out.println(response.gets());
}
}
@Override
Blob[] parse(String... args) {
if (args.length < 2) {
return new Blob[] {Blob.of(args[0], "")};
}
return super.parse(args);
}
@Override
public String params() {
return "<bucket> [<path>+]";
}
}
private static class DeleteAction extends BlobsAction {
@Override
public void run(StorageService storage, Blob... blobs) {
if (blobs.length == 1) {
System.out.println(storage.delete(blobs[0]));
} else {
BatchRequest.Builder batch = BatchRequest.builder();
for (Blob blob : blobs) {
batch.delete(blob);
}
BatchResponse response = storage.apply(batch.build());
System.out.println(response.deletes());
}
}
}
private static class ListAction extends StorageAction<String> {
@Override
String parse(String... args) {
if (args.length == 0) {
return null;
}
if (args.length == 1) {
return args[0];
}
throw new IllegalArgumentException();
}
@Override
public void run(StorageService storage, String bucket) {
if (bucket == null) {
for (Bucket b : storage.list()) {
System.out.println(b);
}
} else {
for (Blob b : storage.list(bucket)) {
System.out.println(b);
}
}
}
@Override
public String params() {
return "[<bucket>]";
}
}
private static class UploadAction extends StorageAction<Tuple<Path, Blob>> {
@Override
public void run(StorageService storage, Tuple<Path, Blob> tuple) throws Exception {
if (Files.size(tuple.x()) > 1024) {
try (BlobWriteChannel writer = storage.writer(tuple.y())) {
byte[] buffer = new byte[1024];
try (InputStream input = Files.newInputStream(tuple.x())) {
int limit;
while ((limit = input.read(buffer)) >= 0) {
try {
writer.write(ByteBuffer.wrap(buffer, 0, limit));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
} else {
byte[] bytes = Files.readAllBytes(tuple.x());
System.out.println(storage.create(tuple.y(), bytes));
}
}
@Override
Tuple<Path, Blob> parse(String... args) {
if (args.length < 2 || args.length > 3) {
throw new IllegalArgumentException();
}
Path path = Paths.get(args[0]);
String blob = args.length < 3 ? path.getFileName().toString() : args[2];
return Tuple.of(path, Blob.of(args[1], blob));
}
@Override
public String params() {
return "<local_file> <bucket> [<path>]";
}
}
private static class DownloadAction extends StorageAction<Tuple<Blob, Path>> {
@Override
public void run(StorageService storage, Tuple<Blob, Path> tuple) throws IOException {
Blob blob = storage.get(tuple.x());
if (blob == null) {
System.out.println("No such object");
return;
}
PrintStream writeTo = System.out;
if (tuple.y() != null) {
writeTo = new PrintStream(new FileOutputStream(tuple.y().toFile()));
}
if (blob.size() < 1024) {
writeTo.write(storage.load(blob));
} else {
try (BlobReadChannel reader = storage.reader(blob)) {
WritableByteChannel channel = Channels.newChannel(writeTo);
ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
while (reader.read(bytes) > 0) {
bytes.flip();
channel.write(bytes);
bytes.clear();
}
}
}
if (tuple.y() == null) {
writeTo.println();
} else {
writeTo.close();
}
}
@Override
Tuple<Blob, Path> parse(String... args) {
if (args.length < 2 || args.length > 3) {
throw new IllegalArgumentException();
}
Path path;
if (args.length > 2) {
path = Paths.get(args[2]);
if (Files.isDirectory(path)) {
path = path.resolve(Paths.get(args[1]).getFileName());
}
} else {
path = null;
}
return Tuple.of(Blob.of(args[0], args[1]), path);
}
@Override
public String params() {
return "<bucket> <path> [local_file]";
}
}
private static class CopyAction extends StorageAction<CopyRequest> {
@Override
public void run(StorageService storage, CopyRequest request) {
System.out.println(storage.copy(request));
}
@Override
CopyRequest parse(String... args) {
if (args.length != 4) {
throw new IllegalArgumentException();
}
return CopyRequest.of(Blob.of(args[0], args[1]), Blob.of(args[2], args[3]));
}
@Override
public String params() {
return "<from_bucket> <from_path> <to_bucket> <to_path>";
}
}
private static class ComposeAction extends StorageAction<ComposeRequest> {
@Override
public void run(StorageService storage, ComposeRequest request) {
System.out.println(storage.compose(request));
}
@Override
ComposeRequest parse(String... args) {
if (args.length < 3) {
throw new IllegalArgumentException();
}
ComposeRequest.Builder request = ComposeRequest.builder();
request.target(Blob.of(args[0], args[args.length - 1]));
for (int i = 1; i < args.length - 1; i++) {
request.addSource(args[i]);
}
return request.build();
}
@Override
public String params() {
return "<bucket> <from_path>+ <to_path>";
}
}
static {
ACTIONS.put("info", new InfoAction());
ACTIONS.put("delete", new DeleteAction());
ACTIONS.put("list", new ListAction());
ACTIONS.put("upload", new UploadAction());
ACTIONS.put("download", new DownloadAction());
ACTIONS.put("cp", new CopyAction());
ACTIONS.put("compose", new ComposeAction());
}
public static void printUsage() {
StringBuilder actionAndParams = new StringBuilder("");
for (Map.Entry<String, StorageAction> entry : ACTIONS.entrySet()) {
actionAndParams.append("\n\t").append(entry.getKey());
String param = entry.getValue().params();
if (param != null && !param.isEmpty()) {
actionAndParams.append(' ').append(param);
}
}
System.out.printf("Usage: %s [<project_id>] operation <args>*%s%n",
StorageExample.class.getSimpleName(), actionAndParams);
}
@SuppressWarnings("unchecked")
public static void main(String... args) throws Exception {
if (args.length < 1) {
System.out.println("Missing required project id and action");
printUsage();
return;
}
StorageServiceOptions.Builder optionsBuilder = StorageServiceOptions.builder();
StorageAction action;
if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
optionsBuilder.projectId(args[0]);
action = ACTIONS.get(args[1]);
args = Arrays.copyOfRange(args, 2, args.length);
} else {
action = ACTIONS.get(args[0]);
args = Arrays.copyOfRange(args, 1, args.length);
}
if (action == null) {
System.out.println("Unrecognized action '" + args[1] + "'");
printUsage();
return;
}
StorageService storage = StorageServiceFactory.instance().get(optionsBuilder.build());
Object request;
try {
request = action.parse(args);
} catch (IllegalArgumentException ex) {
System.out.println("Invalid input for action '" + args[1] + "'");
System.out.println("Expected: " + action.params());
return;
} catch (Exception ex) {
System.out.println("Failed to parse request.");
ex.printStackTrace();
return;
}
action.run(storage, request);
}
}