繁体   English   中英

Google Cloud Endpoint Bucket下载器

[英]Google Cloud Endpoint Bucket Downloader

新的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.
    }
}

我对这些东西迷失在Google文档中,并且担心我会从完全错误的方向进行操作,因为我要做的就是安全下载大量文件!

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

首先,您需要创建一个API密钥并以JSON格式下载。 可以在此处找到更多详细信息。

除其他外,我的课堂上有以下两个领域:

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

首先,您需要一种方法来初始化com.google.cloud.storage.Storage对象,类似于(将您的project-id和path设置为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);
    }
}

我希望这些代码片段和参考文档能帮助您入门,实际上并不太难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM