簡體   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