1 /* 2 * Copyright (C) 2019 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 package com.android.tradefed.util; 17 18 import com.android.tradefed.host.HostOptions; 19 20 import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; 21 import com.google.api.client.http.HttpRequestInitializer; 22 import com.google.api.client.json.gson.GsonFactory; 23 import com.google.api.services.storage.Storage; 24 import com.google.auth.Credentials; 25 import com.google.auth.http.HttpCredentialsAdapter; 26 27 import java.io.File; 28 import java.io.IOException; 29 import java.security.GeneralSecurityException; 30 import java.util.Collection; 31 32 /** 33 * Base class for Gcs operation like download and upload. {@link GCSFileDownloader} and {@link 34 * GCSFileUploader}. 35 */ 36 public abstract class GCSCommon { 37 /** This is the key for {@link HostOptions}'s service-account-json-key-file option. */ 38 private static final String GCS_JSON_KEY = "gcs-json-key"; 39 40 protected static final int DEFAULT_TIMEOUT = 10 * 60 * 1000; // 10minutes 41 42 private File mJsonKeyFile = null; 43 private Storage mStorage; 44 GCSCommon(File jsonKeyFile)45 public GCSCommon(File jsonKeyFile) { 46 mJsonKeyFile = jsonKeyFile; 47 } 48 GCSCommon()49 public GCSCommon() {} 50 setJsonKeyFile(File jsonKeyFile)51 void setJsonKeyFile(File jsonKeyFile) { 52 mJsonKeyFile = jsonKeyFile; 53 } 54 getStorage(Collection<String> scopes)55 protected Storage getStorage(Collection<String> scopes) throws IOException { 56 Credentials credential = null; 57 try { 58 if (mStorage == null) { 59 credential = 60 GoogleApiClientUtil.createCredential( 61 scopes, true, mJsonKeyFile, GCS_JSON_KEY); 62 HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential); 63 mStorage = 64 new Storage.Builder( 65 GoogleNetHttpTransport.newTrustedTransport(), 66 GsonFactory.getDefaultInstance(), 67 GoogleApiClientUtil.configureRetryStrategy( 68 GoogleApiClientUtil.setHttpTimeout( 69 requestInitializer, 70 DEFAULT_TIMEOUT, 71 DEFAULT_TIMEOUT))) 72 .setApplicationName(GoogleApiClientUtil.APP_NAME) 73 .build(); 74 } 75 return mStorage; 76 } catch (GeneralSecurityException e) { 77 throw new IOException(e); 78 } 79 } 80 } 81