1 /* 2 * Copyright (C) 2010 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 vogar.android; 18 19 import java.io.File; 20 import java.io.FileNotFoundException; 21 import java.util.HashSet; 22 import java.util.Set; 23 import vogar.FileCache; 24 import vogar.Log; 25 import vogar.commands.Command; 26 27 public class DeviceFileCache implements FileCache { 28 private final Log log; 29 private final File cacheRoot; 30 private DeviceFilesystem deviceFilesystem; 31 32 /** filled lazily */ 33 private Set<File> cachedFiles; 34 35 public DeviceFileCache(Log log, File deviceDir, DeviceFilesystem deviceFilesystem) { 36 this.log = log; 37 this.cacheRoot = new File(deviceDir, "md5-cache"); 38 this.deviceFilesystem = deviceFilesystem; 39 } 40 41 public boolean existsInCache(String key) { 42 if (cachedFiles == null) { 43 try { 44 cachedFiles = new HashSet<File>(); 45 cachedFiles.addAll(deviceFilesystem.ls(cacheRoot)); 46 log.verbose("indexed on-device cache: " + cachedFiles.size() + " entries."); 47 } catch (FileNotFoundException e) { 48 // cacheRoot probably just hasn't been created yet. 49 cachedFiles = new HashSet<File>(); 50 } 51 } 52 File cachedFile = new File(cacheRoot, key); 53 return cachedFiles.contains(cachedFile); 54 } 55 56 public void copyFromCache(String key, File destination) { 57 File cachedFile = new File(cacheRoot, key); 58 cp(cachedFile, destination); 59 } 60 61 public void copyToCache(File source, String key) { 62 File cachedFile = new File(cacheRoot, key); 63 deviceFilesystem.mkdirs(cacheRoot); 64 // Copy it onto the same file system first, then atomically move it into place. 65 // That way, if we fail, we don't leave anything dangerous lying around. 66 File temporary = new File(cachedFile + ".tmp"); 67 cp(source, temporary); 68 mv(cachedFile, temporary); 69 } 70 71 private void mv(File cachedFile, File temporary) { 72 new Command(log, "adb", "shell", "mv", temporary.getPath(), cachedFile.getPath()).execute(); 73 } 74 75 private void cp(File source, File temporary) { 76 // adb doesn't support "cp" command directly 77 new Command(log, "adb", "shell", "cat", source.getPath(), ">", temporary.getPath()) 78 .execute(); 79 } 80 } 81