2017-06-01 238 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;我在我的代碼中有這個,並首先將其剝離; –

相關問題