1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tradefed.util; 18 19 import com.android.tradefed.host.HostOptions; 20 import com.android.tradefed.util.gcs.GCSCommon; 21 22 import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 23 import com.google.api.client.http.HttpRequestInitializer; 24 import com.google.api.client.json.gson.GsonFactory; 25 import com.google.api.services.storage.Storage; 26 import com.google.auth.Credentials; 27 import com.google.auth.http.HttpCredentialsAdapter; 28 29 import java.io.File; 30 import java.io.IOException; 31 import java.security.GeneralSecurityException; 32 import java.util.Collection; 33 34 public class GCSHelper { 35 36 /** This is the key for {@link HostOptions}'s service-account-json-key-file option. */ 37 private static final String GCS_JSON_KEY = "gcs-json-key"; 38 39 /** 40 * Get {@link Storage} object for the remote GCS bucket with credential based on TF options. 41 * 42 * @param scopes specific scopes to request credential for. 43 * @return {@link Storage} object of the GCS bucket 44 * @throws IOException 45 */ getStorage(Collection<String> scopes, File keyFile)46 public static Storage getStorage(Collection<String> scopes, File keyFile) throws IOException { 47 Credentials credential = null; 48 try { 49 credential = GoogleApiClientUtil.createCredential(scopes, true, keyFile, GCS_JSON_KEY); 50 HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential); 51 return new Storage.Builder( 52 GoogleNetHttpTransport.newTrustedTransport(), 53 GsonFactory.getDefaultInstance(), 54 GoogleApiClientUtil.configureRetryStrategy( 55 GoogleApiClientUtil.setHttpTimeout( 56 requestInitializer, 57 GCSCommon.DEFAULT_TIMEOUT, 58 GCSCommon.DEFAULT_TIMEOUT))) 59 .setApplicationName(GoogleApiClientUtil.APP_NAME) 60 .build(); 61 62 } catch (GeneralSecurityException e) { 63 throw new IOException(e); 64 } 65 } 66 } 67