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.gallery3d.data;
18
19import com.android.gallery3d.common.Utils;
20import com.android.gallery3d.util.ThreadPool.CancelListener;
21import com.android.gallery3d.util.ThreadPool.JobContext;
22
23import java.io.File;
24import java.io.FileOutputStream;
25import java.io.IOException;
26import java.io.InputStream;
27import java.io.InterruptedIOException;
28import java.io.OutputStream;
29import java.net.URL;
30
31public class DownloadUtils {
32    private static final String TAG = "DownloadService";
33
34    public static boolean requestDownload(JobContext jc, URL url, File file) {
35        FileOutputStream fos = null;
36        try {
37            fos = new FileOutputStream(file);
38            return download(jc, url, fos);
39        } catch (Throwable t) {
40            return false;
41        } finally {
42            Utils.closeSilently(fos);
43        }
44    }
45
46    public static void dump(JobContext jc, InputStream is, OutputStream os)
47            throws IOException {
48        byte buffer[] = new byte[4096];
49        int rc = is.read(buffer, 0, buffer.length);
50        final Thread thread = Thread.currentThread();
51        jc.setCancelListener(new CancelListener() {
52            @Override
53            public void onCancel() {
54                thread.interrupt();
55            }
56        });
57        while (rc > 0) {
58            if (jc.isCancelled()) throw new InterruptedIOException();
59            os.write(buffer, 0, rc);
60            rc = is.read(buffer, 0, buffer.length);
61        }
62        jc.setCancelListener(null);
63        Thread.interrupted(); // consume the interrupt signal
64    }
65
66    public static boolean download(JobContext jc, URL url, OutputStream output) {
67        InputStream input = null;
68        try {
69            input = url.openStream();
70            dump(jc, input, output);
71            return true;
72        } catch (Throwable t) {
73            Log.w(TAG, "fail to download", t);
74            return false;
75        } finally {
76            Utils.closeSilently(input);
77        }
78    }
79}