pretty much working version
[wl-mobile.git] / src / pl / org / nowoczesnapolska / wlmobi / Downloader.java
1 package pl.org.nowoczesnapolska.wlmobi;
2  
3 /*
4  @author Mauro Rocco http://www.toforge.com
5  
6  Radek Czajka: don't prepend /sdcard/
7 */
8  
9 import org.json.JSONArray;
10 import org.json.JSONException;
11  
12 import android.util.Log;
13  
14 import com.phonegap.DroidGap;
15 import com.phonegap.api.Plugin;
16 import com.phonegap.api.PluginResult;
17  
18 import java.io.File;
19 import java.io.FileOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.HttpURLConnection;
23 import java.net.URL;
24  
25 public class Downloader extends Plugin{
26  
27  @Override
28  public PluginResult execute(String action, JSONArray args, String callbackId) {
29  if (action.equals("downloadFile")) {
30  try {
31  return this.downloadUrl(args.getString(0),args.getString(1),args.getString(2),args.getString(3));
32  } catch (JSONException e) {
33  return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
34  }
35  }
36  else {
37  return new PluginResult(PluginResult.Status.INVALID_ACTION);
38  }
39  
40  }
41  
42  PluginResult downloadUrl(String fileUrl, String dirName, String fileName, String overwrite){
43  try{
44  Log.d("DownloaderPlugin", "DIRECTORY CALLED "+dirName+" created");
45  File dir =     new File(dirName);
46  if(!dir.exists()){
47  Log.d("DownloaderPlugin", "directory "+dirName+" created");
48  dir.mkdirs();
49  }
50  
51  File file = new File(dirName+fileName);
52  
53  if(overwrite.equals("false") && file.exists()){
54  Log.d("DownloaderPlugin", "File already exist");
55  return new PluginResult(PluginResult.Status.OK, "exist");
56  }
57  
58  URL url = new URL(fileUrl);
59  Log.d("DownloaderPlugin", "connecting to server for downloading " + url);
60  HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
61  ucon.setRequestMethod("GET");
62  ucon.setDoOutput(true);
63  ucon.connect();
64  
65  Log.d("DownloaderPlugin", "download begining");
66  
67  Log.d("DownloaderPlugin", "download url:" + url);
68  
69  InputStream is = ucon.getInputStream();
70  
71  byte[] buffer = new byte[1024];
72  
73  int len1 = 0;
74  
75  FileOutputStream fos = new FileOutputStream(file);
76  
77  while ( (len1 = is.read(buffer)) > 0 ) {
78  fos.write(buffer, 0, len1);
79                  //new String(buffer, "ISO8859_1").getBytes("UTF-8"), 0, len1);
80  }
81  
82  fos.close();
83  
84  Log.d("DownloaderPlugin", "Download complete in" + fileName);
85  
86  } catch (IOException e) {
87  
88  Log.d("DownloaderPlugin", "Error: " + e);
89  return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
90  
91  }
92  
93  return new PluginResult(PluginResult.Status.OK, fileName);
94  
95  }
96  
97 }