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 17 package com.android.gallery3d.data; 18 19 import com.android.gallery3d.common.Utils; 20 import com.android.gallery3d.util.ThreadPool.CancelListener; 21 import com.android.gallery3d.util.ThreadPool.JobContext; 22 23 import java.io.File; 24 import java.io.FileOutputStream; 25 import java.io.IOException; 26 import java.io.InputStream; 27 import java.io.InterruptedIOException; 28 import java.io.OutputStream; 29 import java.net.URL; 30 31 public 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 public void onCancel() { 53 thread.interrupt(); 54 } 55 }); 56 while (rc > 0) { 57 if (jc.isCancelled()) throw new InterruptedIOException(); 58 os.write(buffer, 0, rc); 59 rc = is.read(buffer, 0, buffer.length); 60 } 61 jc.setCancelListener(null); 62 Thread.interrupted(); // consume the interrupt signal 63 } 64 65 public static boolean download(JobContext jc, URL url, OutputStream output) { 66 InputStream input = null; 67 try { 68 input = url.openStream(); 69 dump(jc, input, output); 70 return true; 71 } catch (Throwable t) { 72 Log.w(TAG, "fail to download", t); 73 return false; 74 } finally { 75 Utils.closeSilently(input); 76 } 77 } 78 }