summaryrefslogtreecommitdiff
path: root/src/main/java/com/android/apkzlib/utils/CachedFileContents.java
blob: f2a333178dc9729f6d4d8fa59079cc18466f03b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.apkzlib.utils;

import com.google.common.base.Objects;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * A cache for file contents. The cache allows closing a file and saving in memory its contents (or
 * some related information). It can then be used to check if the contents are still valid at some
 * later time. Typical usage flow is:
 *
 * <p>
 *
 * <pre>{@code
 * Object fileRepresentation = // ...
 * File toWrite = // ...
 * // Write file contents and update in memory representation
 * CachedFileContents<Object> contents = new CachedFileContents<Object>(toWrite);
 * contents.closed(fileRepresentation);
 *
 * // Later, when data is needed:
 * if (contents.isValid()) {
 *     fileRepresentation = contents.getCache();
 * } else {
 *     // Re-read the file and recreate the file representation
 * }
 * }</pre>
 *
 * @param <T> the type of cached contents
 */
public class CachedFileContents<T> {

    /**
     * The file.
     */
    @Nonnull
    private File file;

    /**
     * Time when last closed (time when {@link #closed(Object)} was invoked).
     */
    private long lastClosed;

    /**
     * Size of the file when last closed.
     */
    private long size;

    /**
     * Hash of the file when closed. {@code null} if hashing failed for some reason.
     */
    @Nullable
    private HashCode hash;

    /**
     * Cached data associated with the file.
     */
    @Nullable
    private T cache;

    /**
     * Creates a new contents. When the file is written, {@link #closed(Object)} should be invoked
     * to set the cache.
     *
     * @param file the file
     */
    public CachedFileContents(@Nonnull File file) {
        this.file = file;
    }

    /**
     * Should be called when the file's contents are set and the file closed. This will save the
     * cache and register the file's timestamp to later detect if it has been modified.
     * <p>
     * This method can be called as many times as the file has been written.
     *
     * @param cache an optional cache to save
     */
    public void closed(@Nullable T cache) {
        this.cache = cache;
        lastClosed = file.lastModified();
        size = file.length();
        hash = hashFile();
    }

    /**
     * Are the cached contents still valid? If this method determines that the file has been
     * modified since the last time {@link #closed(Object)} was invoked.
     *
     * @return are the cached contents still valid? If this method returns {@code false}, the
     * cache is cleared
     */
    public boolean isValid() {
        boolean valid = true;

        if (!file.exists()) {
            valid = false;
        }

        if (valid && file.lastModified() != lastClosed) {
            valid = false;
        }

        if (valid && file.length() != size) {
            valid = false;
        }

        if (valid && !Objects.equal(hash, hashFile())) {
            valid = false;
        }

        if (!valid) {
            cache = null;
        }

        return valid;
    }

    /**
     * Obtains the cached data set with {@link #closed(Object)} if the file has not been modified
     * since {@link #closed(Object)} was invoked.
     *
     * @return the last cached data or {@code null} if the file has been modified since
     * {@link #closed(Object)} has been invoked
     */
    @Nullable
    public T getCache() {
        return cache;
    }

    /**
     * Computes the hashcode of the cached file.
     *
     * @return the hash code
     */
    @Nullable
    private HashCode hashFile() {
        try {
            return Files.hash(file, Hashing.crc32());
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * Obtains the file used for caching.
     *
     * @return the file; this file always exists and contains the old (cached) contents of the
     * file
     */
    @Nonnull
    public File getFile() {
        return file;
    }
}