1 /*
2  * Copyright (C) 2018 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 android.app.backup;
18 
19 import android.app.backup.FullBackup.BackupScheme.PathWithRequiredFlags;
20 
21 import java.io.File;
22 import java.io.IOException;
23 import java.util.Collection;
24 
25 /** @hide */
26 public class BackupUtils {
27 
BackupUtils()28     private BackupUtils() {}
29 
30     /**
31      * Returns {@code true} if {@code file} is either directly in {@code canonicalPathList} or is a
32      * file contained in a directory in the list.
33      */
isFileSpecifiedInPathList( File file, Collection<PathWithRequiredFlags> canonicalPathList)34     public static boolean isFileSpecifiedInPathList(
35             File file, Collection<PathWithRequiredFlags> canonicalPathList) throws IOException {
36         for (PathWithRequiredFlags canonical : canonicalPathList) {
37             String canonicalPath = canonical.getPath();
38             File fileFromList = new File(canonicalPath);
39             if (fileFromList.isDirectory()) {
40                 if (file.isDirectory()) {
41                     // If they are both directories check exact equals.
42                     if (file.equals(fileFromList)) {
43                         return true;
44                     }
45                 } else {
46                     // O/w we have to check if the file is within the directory from the list.
47                     if (file.toPath().startsWith(canonicalPath)) {
48                         return true;
49                     }
50                 }
51             } else if (file.equals(fileFromList)) {
52                 // Need to check the explicit "equals" so we don't end up with substrings.
53                 return true;
54             }
55         }
56         return false;
57     }
58 }
59