1 /* 2 * Copyright (C) 2012 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.result; 17 18 import com.android.tradefed.log.LogUtil.CLog; 19 import com.android.tradefed.util.FileUtil; 20 21 import java.io.File; 22 import java.io.IOException; 23 import java.text.ParseException; 24 import java.text.SimpleDateFormat; 25 import java.util.Date; 26 27 /** 28 * Helper class for creating a .retention file in a directory. 29 * Intended to be used by external tools to determine when a directory can be deleted. 30 */ 31 public class RetentionFileSaver { 32 33 public static final String RETENTION_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss zzz"; 34 public static final String RETENTION_FILE_NAME = ".retention"; 35 36 /** 37 * Creates a .retention file in given dir with timestamp == current + logRetentionDays 38 */ writeRetentionFile(File dir, int logRetentionDays)39 public void writeRetentionFile(File dir, int logRetentionDays) { 40 try { 41 long deleteTimeEpoch = System.currentTimeMillis() + (long)logRetentionDays * 24 * 60 * 42 60 * 1000; 43 Date date = new Date(deleteTimeEpoch); 44 File retentionFile = new File(dir, RETENTION_FILE_NAME); 45 FileUtil.writeToFile(new SimpleDateFormat(RETENTION_DATE_FORMAT).format(date), 46 retentionFile); 47 } catch (IOException e) { 48 CLog.e("Unable to create retention file in directory in %s", dir.getAbsolutePath()); 49 CLog.e(e); 50 } 51 } 52 shouldDelete(File retentionFile)53 public boolean shouldDelete(File retentionFile) { 54 if (!retentionFile.isFile() || !retentionFile.getName().equals(RETENTION_FILE_NAME)) { 55 CLog.w("%s is not a retention file", retentionFile.getAbsolutePath()); 56 return false; 57 } 58 String timestamp; 59 try { 60 timestamp = FileUtil.readStringFromFile(retentionFile); 61 Date retentionDate = new SimpleDateFormat(RETENTION_DATE_FORMAT).parse(timestamp); 62 return new Date().after(retentionDate); 63 } catch (IOException e) { 64 CLog.e("Unable to read retention file %s", retentionFile.getAbsolutePath()); 65 CLog.e(e); 66 } catch (ParseException e) { 67 CLog.e("Unable to read timestamp in retention file %s", retentionFile.getAbsolutePath()); 68 CLog.e(e); 69 } 70 return false; 71 } 72 } 73