1 package pl.org.nowoczesnapolska.wlmobi;
7 import org.json.JSONArray;
8 import org.json.JSONException;
10 import android.util.Log;
11 import android.content.res.AssetManager;
13 import com.phonegap.api.Plugin;
14 import com.phonegap.api.PluginResult;
17 import java.io.FileOutputStream;
18 import java.io.InputStream;
19 import java.io.IOException;
20 import pl.org.nowoczesnapolska.wlmobi.Downloader;
22 public class DBPut extends Plugin{
25 public PluginResult execute(String action, JSONArray args, String callbackId) {
26 if (action.equals("put")) {
28 return this.put(args.getString(0), args.getString(1), args.getString(2));
29 } catch (JSONException e) {
30 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
33 else if (action.equals("fetch")) {
35 return this.fetch(args.getString(0));
36 } catch (JSONException e) {
37 return new PluginResult(PluginResult.Status.ERROR, "Param errrors");
41 return new PluginResult(PluginResult.Status.INVALID_ACTION);
45 private PluginResult fetch(String url) {
46 String fileName = "0000000000000001.db";
47 String targetPath = "/data/data/" + this.ctx.getPackageName() + "/app_database/file__0/";
49 Log.d("DBPut", "database path: " + targetPath + " / " + fileName);
51 Downloader d = new Downloader();
52 return d.downloadUrl(url, targetPath, fileName, "true");
56 private PluginResult put(String assetPath, String targetPath, String overwrite) {
57 // this hard-coding is kinda creepy, should probably create the db and use getDatabasePath instead
58 String absoluteTargetPath = "/data/data/" + this.ctx.getPackageName() + "/app_database/" + targetPath;
59 int index = absoluteTargetPath.lastIndexOf('/');
60 String targetDir = absoluteTargetPath.substring(0, index);
63 File dir = new File(targetDir);
65 Log.d("DBPut", "directory " + targetDir + " created");
69 File fout = new File(absoluteTargetPath);
71 if(overwrite.equals("false") && fout.exists()) {
72 Log.d("DBPut", "File already exists");
73 return new PluginResult(PluginResult.Status.OK, "exist");
76 FileOutputStream fos = new FileOutputStream(fout);
78 AssetManager assetManager = this.ctx.getResources().getAssets();
79 InputStream is = assetManager.open(assetPath);
81 byte[] buffer = new byte[1024];
84 while ( (len1 = is.read(buffer)) > 0 ) {
85 fos.write(buffer,0, len1);
90 Log.d("DBPut", "Copied to " + absoluteTargetPath);
91 } catch (IOException e) {
92 Log.d("DBPut", "Error: " + e);
93 return new PluginResult(PluginResult.Status.ERROR, "Error: " + e);
95 return new PluginResult(PluginResult.Status.OK, absoluteTargetPath);