Google Cloud Endpoint Bucket Downloader

时间:2017-06-01 12:55:55

标签: java cloud google-cloud-storage bucket

我是非常 GC平台的新手,我正在尝试使用两种方法在Java中创建API:一种方法返回特定存储桶中所有文件的列表,另一种方法检索来自该存储桶的指定文件。目标是能够迭代文件列表以便从桶中下载每个文件。基本上,我想在Android设备上镜像存储桶的内容,因此将从Android应用程序中生成的客户端库调用API。 我的getFileList()方法返回ListResult个对象。如何从中提取文件列表?

@ApiMethod(name = "getFileList", path = "getFileList", httpMethod = ApiMethod.HttpMethod.GET)
public ListResult getFileList(@Named("bucketName") String bucketName) {
    GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
    ListResult result = null;
    try {
        result = gcsService.list(bucketName, ListOptions.DEFAULT);
        return result;
    } catch (IOException e) {
        return null; // Handle this properly.
    }
}

另外,我很难确定我的getFile() API方法的返回类型应该是什么。我不能使用字节数组,因为返回类型不能是我所理解的简单类型。这就是我的用武之地:

@ApiMethod(name = "getFile", path = "getFile", httpMethod = ApiMethod.HttpMethod.GET)
public byte[] getFile(@Named("bucketName") String bucketName, ListItem file) {
    GcsService gcsService = GcsServiceFactory.createGcsService();
    GcsFilename gcsFilename = new GcsFilename(bucketName, file.getName());
    ByteBuffer byteBuffer;
    try {
        int fileSize = (int) gcsService.getMetadata(gcsFilename).getLength();
        byteBuffer = ByteBuffer.allocate(fileSize);
        GcsInputChannel gcsInputChannel = gcsService.openReadChannel(gcsFilename, 0);
        gcsInputChannel.read(byteBuffer);
        return byteBuffer.array();
    } catch (IOException e) {
        return null; // Handle this properly.
    }
}

我在谷歌文档中迷失了这些东西,我担心我会从完全错误的方向前进,因为我所要做的就是安全下载一堆文件!

1 个答案:

答案 0 :(得分:1)

我无法为您提供完整的解决方案,因为这是我为公司编写的代码,但我可以向您展示一些基础知识。我使用google-cloud-java API。

首先,您需要创建一个API密钥并以JSON格式下载。更多详情can be found here

我 - 除其他外 - 我班上的这两个领域:

protected final Object storageInitLock = new Object();
protected Storage storage;

首先,您需要一个方法来初始化com.google.cloud.storage.Storage对象,例如(设置您的项目ID和路径到json api键):

protected final Storage getStorage() {
    synchronized (storageInitLock) {
        if (null == storage) {
            try {
                storage = StorageOptions.newBuilder()
                        .setProjectId(PROJECTID)
                        .setCredentials(ServiceAccountCredentials.fromStream(new FileInputStream(pathToJsonKey)))
                        .build()
                        .getService();
            } catch (IOException e) {
                throw new MyCustomException("Error reading auth file " + pathToJsonKey, e);
            } catch (StorageException e) {
                throw new MyCustomException("Error initializing storage", e);
            }
        }

        return storage;
    }
}

获取您可以使用的所有条目:

protected final Iterator<Blob> getAllEntries() {
    try {
        return getStorage().list(bucketName).iterateAll();
    } catch (StorageException e) {
        throw new MyCustomException("error retrieving entries", e);
    }
}

列出目录中的文件

public final Optional<Page<Blob>> listFilesInDirectory(@NotNull String directory) {
    try {
        return Optional.ofNullable(getStorage().list(getBucketName(), Storage.BlobListOption.currentDirectory(),
                Storage.BlobListOption.prefix(directory)));
    } catch (Exception e) {
        return Optional.empty();
    }
}

获取有关文件的信息:

public final Optional<Blob> getFileInfo(@NotNull String bucketFilename) {
    try {
        return Optional.ofNullable(getStorage().get(BlobId.of(getBucketName(), bucketFilename)));
    } catch (Exception e) {
        return Optional.empty();
    }
}

添加文件:

public final void addFile(@NotNull String localFilename, @NotNull String bucketFilename,
                               @Nullable ContentType contentType) {
    final BlobInfo.Builder builder = BlobInfo.newBuilder(BlobId.of(bucketName, bucketFilename));
    if (null != contentType) {
        builder.setContentType(contentType.getsValue());
    }
    final BlobInfo blobInfo = builder.build();

    try (final RandomAccessFile raf = new RandomAccessFile(localFilename, "r");
         final FileChannel channel = raf.getChannel();
         final WriteChannel writer = getStorage().writer(blobInfo)) {

        writer.write(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
    } catch (Exception e) {
        throw new MyCustomException(MessageFormat.format("Error storing {0} to {1}", localFilename,
                bucketFilename), e);
    }
}

我希望这些代码片段以及引用的文档能让您顺利进行,但这并不太难。