Added README file
[metux-java.git] / util / URLDownloader.java
blobb23374ca68037a86f8a2105713056ac8c42448a7
2 package org.de.metux.util;
4 import java.io.BufferedReader;
5 import java.io.IOException;
6 import java.util.Properties;
7 import java.io.InputStreamReader;
8 import java.io.File;
10 // FIXME: should introduce a callback interface for UIs
12 public class URLDownloader
14 static final String path_curl = "curl";
16 public interface Notify
18 public void progress(int percent, int size_got, int size_total);
19 public void msg(String msg);
20 public void debug(String msg);
23 Notify notify;
25 public URLDownloader()
29 public URLDownloader(Notify n)
31 notify = n;
34 private void _file_err(String local, String msg)
36 if (notify!=null)
37 notify.msg("ERROR: "+msg);
40 public boolean download(String url,String local, boolean verbose)
42 String[] argv =
44 path_curl,
45 url,
46 "-o", local,
47 "-L",
48 "--show-error",
49 "--stderr", "-",
50 "--verbose"
53 Process p;
54 try
56 p = Runtime.getRuntime().exec(argv);
57 if (notify!=null)
58 notify.debug("executed command");
60 catch (IOException e)
62 if (notify!=null)
63 notify.msg("Error calling curl: "+e);
64 rm.remove_recursive(local);
65 return false;
68 if (notify!=null)
69 notify.debug("now reading from subprocess ...\n");
71 BufferedReader br = new BufferedReader(
72 new InputStreamReader(p.getInputStream()));
74 try
76 for (String line=""; (line=br.readLine())!=null;)
78 if (notify!=null)
79 notify.debug("GOT: "+line);
81 if ((line.indexOf("< 550") > -1)||
82 (line.indexOf("No such file or directory") > -1))
84 rm.remove_recursive(local);
85 return false;
88 if (line.indexOf("< HTTP/1.1 40") > -1)
90 rm.remove_recursive(local);
91 _file_err(local,"object not found: "+url);
92 return false;
96 catch (IOException e)
98 System.err.println("Error while reading from socket: "+e);
101 if (!((new File(local)).exists()))
103 _file_err(local,"could not download from: "+url);
104 rm.remove_recursive(local);
105 return false;
108 // FIXME: should check error code!
109 return true;
112 public boolean download(String url, String local)
114 return download(url,local,false);