ImapTempFileLiteral.java revision 0fd444b0b4c07ac1545e0edc64b54fd738edfc94
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
17package com.android.email.mail.store.imap;
18
19import com.android.email.Email;
20import com.android.email.FixedLengthInputStream;
21import com.android.email.Utility;
22
23import org.apache.commons.io.IOUtils;
24
25import android.util.Log;
26
27import java.io.ByteArrayInputStream;
28import java.io.File;
29import java.io.FileInputStream;
30import java.io.FileNotFoundException;
31import java.io.FileOutputStream;
32import java.io.IOException;
33import java.io.InputStream;
34import java.io.OutputStream;
35
36/**
37 * Subclass of {@link ImapString} used for literals backed by a temp file.
38 */
39public class ImapTempFileLiteral extends ImapString {
40    /* package for test */ final File mFile;
41
42    /** Size is purely for toString() */
43    private final int mSize;
44
45    /* package */  ImapTempFileLiteral(FixedLengthInputStream stream) throws IOException {
46        mSize = stream.getLength();
47        mFile = File.createTempFile("imap", ".tmp", Email.getTempDirectory());
48
49        // Unfortunately, we can't really use deleteOnExit(), because temp filenames are random
50        // so it'd simply cause a memory leak.
51        // deleteOnExit() simply adds filenames to a static list and the list will never shrink.
52        // mFile.deleteOnExit();
53        OutputStream out = new FileOutputStream(mFile);
54        IOUtils.copy(stream, out);
55        out.close();
56    }
57
58    /**
59     * Make sure we delete the temp file.
60     *
61     * We should always be calling {@link ImapResponse#destroy()}, but it's here as a last resort.
62     */
63    @Override
64    protected void finalize() throws Throwable {
65        try {
66            destroy();
67        } finally {
68            super.finalize();
69        }
70    }
71
72    @Override
73    public InputStream getAsStream() {
74        checkNotDestroyed();
75        try {
76            return new FileInputStream(mFile);
77        } catch (FileNotFoundException e) {
78            // It's probably possible if we're low on storage and the system clears the cache dir.
79            Log.w(Email.LOG_TAG, "ImapTempFileLiteral: Temp file not found");
80
81            // Return 0 byte stream as a dummy...
82            return new ByteArrayInputStream(new byte[0]);
83        }
84    }
85
86    @Override
87    public String getString() {
88        checkNotDestroyed();
89        try {
90            return Utility.fromAscii(IOUtils.toByteArray(getAsStream()));
91        } catch (IOException e) {
92            Log.w(Email.LOG_TAG, "ImapTempFileLiteral: Error while reading temp file");
93            return "";
94        }
95    }
96
97    @Override
98    public void destroy() {
99        try {
100            if (!isDestroyed() && mFile.exists()) {
101                mFile.delete();
102            }
103        } catch (RuntimeException re) {
104            // Just log and ignore.
105            Log.w(Email.LOG_TAG, "Failed to remove temp file: " + re.getMessage());
106        }
107        super.destroy();
108    }
109
110    @Override
111    public String toString() {
112        return String.format("{%d byte literal(file)}", mSize);
113    }
114
115    public boolean tempFileExistsForTest() {
116        return mFile.exists();
117    }
118}
119