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