2017-06-01 162 views
0

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

@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. 
    } 
} 

另外,我正在努力确定我的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

我不能给你一个完整的解决方案,因为这是我为我的公司写的代码,但我可以告诉你一些基本知识。我使用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); 
    } 
} 

我希望这些代码片断和引用文档将在目录

列表文件让你走,真的不难。

+0

太好了。非常感谢!我会让你知道我是怎么得到的...... – user3352488

+0

只是对'getStorage()'方法做了一个小改动,用于lazy init;我在我的代码中有这个,并首先将其剥离; –

相关问题