1 /* 2 * Copyright (C) 2023 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 org.apache.test.android; 18 19 import org.junit.Assert; 20 21 import java.io.File; 22 import java.io.IOException; 23 import java.io.UncheckedIOException; 24 import java.net.URL; 25 import java.nio.file.Files; 26 import java.nio.file.Path; 27 28 public class AndroidFileUtils { 29 30 private static final Path TEMP_DIR; 31 32 static { 33 try { 34 TEMP_DIR = Files.createTempDirectory(AndroidFileUtils.class.getName()); 35 } catch (IOException e) { 36 throw new UncheckedIOException(e); 37 } 38 } 39 40 /** 41 * Returns the URL string to the jar resource for a given input file path. 42 * @return null if the input file is not found. 43 */ getInputFileUrl(String path)44 public static URL getInputFileUrl(String path) { 45 Path p = Path.of(path); 46 // Ignore the parts for the current directory. 47 while (true) { 48 if (p.getNameCount() == 0) { 49 return null; 50 } 51 String first = p.getName(0).toString(); 52 if (!first.isEmpty() && !first.equals(".")) { 53 break; 54 } 55 p = p.subpath(1, p.getNameCount()); 56 } 57 String first = p.getName(0).toString(); 58 if (!first.equals("inputs")) { 59 return null; 60 } 61 p = p.subpath(1, p.getNameCount()); 62 p = Path.of("api", p.toString()); 63 return AndroidFileUtils.class.getClassLoader().getResource(p.toString()); 64 } 65 66 /** 67 * Returns the URL string to the jar resource for a given input file path. 68 * @return null if the input file is not found. 69 */ getInputFileUrlString(String path)70 public static String getInputFileUrlString(String path) { 71 URL url = getInputFileUrl(path); 72 return url != null ? url.toExternalForm() : null; 73 } 74 /** 75 * Return a File object to the path, and created all directories along the path. 76 * @throws AssertionError if the directories can't be created. 77 */ getOutputFile(String relativePath)78 public static File getOutputFile(String relativePath) { 79 File target = TEMP_DIR.resolve(relativePath).toAbsolutePath().toFile(); 80 File parent = target.getParentFile(); 81 if (!parent.exists()) { 82 Assert.assertTrue(parent.mkdirs()); 83 } 84 return target; 85 } 86 } 87