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.config.remote; 17 18 import com.android.annotations.VisibleForTesting; 19 import com.android.tradefed.build.BuildRetrievalError; 20 import com.android.tradefed.config.DynamicRemoteFileResolver; 21 import com.android.tradefed.util.FileUtil; 22 import com.android.tradefed.util.net.HttpHelper; 23 import com.android.tradefed.util.net.IHttpHelper; 24 25 import java.io.File; 26 import java.io.FileOutputStream; 27 import java.io.IOException; 28 import java.util.Map; 29 30 import javax.annotation.Nonnull; 31 32 /** Implementation of {@link IRemoteFileResolver} that allows downloading remote file via http */ 33 public class HttpRemoteFileResolver implements IRemoteFileResolver { 34 35 public static final String PROTOCOL_HTTP = "http"; 36 37 @Override resolveRemoteFiles(File consideredFile, Map<String, String> queryArgs)38 public File resolveRemoteFiles(File consideredFile, Map<String, String> queryArgs) 39 throws BuildRetrievalError { 40 // Don't use absolute path as it would not start with gs: 41 String path = consideredFile.getPath(); 42 // Replace the very first / by // to be http:// again. 43 path = path.replaceFirst(":/", "://"); 44 45 IHttpHelper downloader = getDownloader(); 46 File downloadedFile = null; 47 try { 48 downloadedFile = 49 FileUtil.createTempFile( 50 FileUtil.getBaseName(consideredFile.getName()), 51 FileUtil.getExtension(consideredFile.getName())); 52 downloader.doGet(path, new FileOutputStream(downloadedFile)); 53 return DynamicRemoteFileResolver.unzipIfRequired(downloadedFile, queryArgs); 54 } catch (IOException | RuntimeException e) { 55 FileUtil.deleteFile(downloadedFile); 56 throw new BuildRetrievalError( 57 String.format("Failed to download %s due to: %s", path, e.getMessage()), e); 58 } 59 } 60 61 @Override getSupportedProtocol()62 public @Nonnull String getSupportedProtocol() { 63 return PROTOCOL_HTTP; 64 } 65 66 @VisibleForTesting getDownloader()67 protected IHttpHelper getDownloader() { 68 return new HttpHelper(); 69 } 70 } 71