• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package com.android.vts.util;
2 
3 import com.google.auth.oauth2.ServiceAccountCredentials;
4 import com.google.cloud.storage.Storage;
5 import com.google.cloud.storage.StorageOptions;
6 
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.util.Optional;
10 import java.util.logging.Level;
11 import java.util.logging.Logger;
12 
13 /** GcsHelper, a helper class for interacting with Google Cloud Storage. */
14 public class GcsHelper {
15     private static final Logger logger = Logger.getLogger(GcsHelper.class.getName());
16 
17     /** Google Cloud Storage project ID */
18     private static String GCS_PROJECT_ID;
19 
setGcsProjectId(String gcsProjectId)20     public static void setGcsProjectId(String gcsProjectId) {
21         GCS_PROJECT_ID = gcsProjectId;
22     }
23 
24     /**
25      * Get GCS storage from Key file input stream parameter.
26      */
getStorage(InputStream keyFileInputStream)27     public static Optional<Storage> getStorage(InputStream keyFileInputStream) {
28 
29         if (keyFileInputStream == null) {
30             logger.log(Level.SEVERE, "Error GCS key file is not exiting. Check key file!");
31             return Optional.empty();
32         } else {
33             try {
34                 Storage storage =
35                         StorageOptions.newBuilder()
36                                 .setProjectId(GCS_PROJECT_ID)
37                                 .setCredentials(
38                                         ServiceAccountCredentials.fromStream(keyFileInputStream))
39                                 .build()
40                                 .getService();
41                 return Optional.of(storage);
42             } catch (IOException e) {
43                 logger.log(Level.SEVERE, "Error on creating storage instance!");
44                 return Optional.empty();
45             }
46         }
47     }
48 }
49