working on local vocabulary management when offline

parent f386fccf
...@@ -122,7 +122,6 @@ public class RestapiWrapper { ...@@ -122,7 +122,6 @@ public class RestapiWrapper {
public static String GET(String surl, Hashtable<String, String> params, iRestapiListener listener) { public static String GET(String surl, Hashtable<String, String> params, iRestapiListener listener) {
String result=null; String result=null;
InputStream inputStream = null; InputStream inputStream = null;
URL url = null; URL url = null;
try { try {
...@@ -179,7 +178,6 @@ public class RestapiWrapper { ...@@ -179,7 +178,6 @@ public class RestapiWrapper {
sparams=""; sparams="";
for (String param : params.keySet()) { for (String param : params.keySet()) {
String value = params.get(param); String value = params.get(param);
Log.e(this.getClass().getCanonicalName(),param+"="+value+" total:"+sparams+" json?"+json_params);
if (param.equals("token")) if (param.equals("token"))
urlConnection.setRequestProperty("Authorization", "Bearer " + value); urlConnection.setRequestProperty("Authorization", "Bearer " + value);
else { else {
...@@ -253,7 +251,7 @@ public class RestapiWrapper { ...@@ -253,7 +251,7 @@ public class RestapiWrapper {
try { try {
//if (params.e) //if (params.e)
if(params.result!=null) { if(params.result!=null) {
Log.d(LOG_TAG, "JSON: " + params.result); Log.i(LOG_TAG, "Picto JSON Result: " + params.result);
Object jsonResult = new JSONTokener(params.result).nextValue(); Object jsonResult = new JSONTokener(params.result).nextValue();
if (jsonResult instanceof JSONObject) { if (jsonResult instanceof JSONObject) {
......
...@@ -306,7 +306,7 @@ public class Device extends SQLiteOpenHelper { ...@@ -306,7 +306,7 @@ public class Device extends SQLiteOpenHelper {
for (User user : prev_users) for (User user : prev_users)
db.delete("users_detail","id_stu=? AND id_sup=?",new String[]{Integer.toString(user.get_id_stu()),Integer.toString(user.get_id_sup())}); db.delete("users_detail","id_stu=? AND id_sup=?",new String[]{Integer.toString(user.get_id_stu()),Integer.toString(user.get_id_sup())});
ImgDownloader downloader = new ImgDownloader(this.context, imgListener, ImgDownloader.source.remote ); ImgDownloader downloader = new ImgDownloader(this.context, imgListener, ImgDownloader.tsource.remote );
downloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,imgs); downloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,imgs);
......
...@@ -266,7 +266,7 @@ public class PCBDBHelper extends SQLiteOpenHelper { ...@@ -266,7 +266,7 @@ public class PCBDBHelper extends SQLiteOpenHelper {
ContentValues values = new ContentValues(1); ContentValues values = new ContentValues(1);
values.put("attributes",attrs); values.put("attributes",attrs);
int updates=db.update("collection",values, "id_stu=? AND id_picto=?", new String[] {Integer.toString(id_stu), Integer.toString(picto_id)}); int updates=db.update("collection",values, "id_stu=? AND id_picto=?", new String[] {Integer.toString(id_stu), Integer.toString(picto_id)});
Log.i(this.getClass().getCanonicalName(),"Modify "+updates+" picto, id. "+picto_id+" attributes="+attrs); Log.i(this.getClass().getCanonicalName(),"Modify "+updates+" Picto, id. "+picto_id+" attributes="+attrs);
db.close(); db.close();
} }
......
...@@ -47,11 +47,11 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -47,11 +47,11 @@ public class Vocabulary implements Iterable<Picto> {
this.pictos = new Hashtable<>(Vocabulary.DEFAULT_VOCABULARY_SIZE); this.pictos = new Hashtable<>(Vocabulary.DEFAULT_VOCABULARY_SIZE);
this.imgListener=listener; this.imgListener=listener;
if (PCBcontext.getNetService().online()) { if (PCBcontext.getNetService().online()) {
Log.i(this.getClass().getName(), "downloading vocabulary"); Log.i(this.getClass().getName(), "FERNANDO Downloading vocabulary");
synchronize(); synchronize();
}else }else
try { try {
Log.i(this.getClass().getName(), "local vocabulary"); Log.i(this.getClass().getName(), "FERNANDO Local vocabulary");
PCBcontext.getPcbdb().getStudentVocabulary(this); PCBcontext.getPcbdb().getStudentVocabulary(this);
listener.loadComplete(); listener.loadComplete();
} catch (JSONException e) { } catch (JSONException e) {
...@@ -69,6 +69,7 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -69,6 +69,7 @@ public class Vocabulary implements Iterable<Picto> {
break; break;
} }
case update:{ case update:{
Log.i(this.getClass().getCanonicalName(), "Picto update "+args.toString());
modifyAttsPicto(picto_cat, picto_id, args); modifyAttsPicto(picto_cat, picto_id, args);
break; break;
} }
...@@ -79,7 +80,7 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -79,7 +80,7 @@ public class Vocabulary implements Iterable<Picto> {
String uri=args.getJSONObject("picto").getString("uri"); String uri=args.getJSONObject("picto").getString("uri");
JSONObject attrs_picto = args.getJSONObject("attributes"); JSONObject attrs_picto = args.getJSONObject("attributes");
addPicto(new Picto(picto_id, uri, text, attrs_picto),ImgDownloader.source.remote); addPicto(new Picto(picto_id, uri, text, attrs_picto),ImgDownloader.tsource.remote);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(this.getClass().getCanonicalName(), e.getClass().getCanonicalName() + "--" + e); Log.e(this.getClass().getCanonicalName(), e.getClass().getCanonicalName() + "--" + e);
...@@ -94,29 +95,44 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -94,29 +95,44 @@ public class Vocabulary implements Iterable<Picto> {
},listener}; },listener};
talk = new VocabularyTalk(room, listeners); talk = new VocabularyTalk(room, listeners);
} }
/** /**
* the vocabulary is (i) updated to and (ii) downloaded from the server. * UPload local status modifications and new pictos. Note that when
* a picto is uploaded is not required to delete from the local PCB
* because the PCB will get the remote vocabulary at the end of the process
* The only issue is: what happens whether the upload fails? --> The image will be lost.
* TODO: keep record of failed uploaded images to re-include as local pictos
*/ */
public void synchronize() { private void synchronize_upload() {
try { try {
PCBcontext.getPcbdb().getStudentVocabulary(this); PCBcontext.getPcbdb().getStudentVocabulary(this);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(this.getClass().getName(), " Picto json error from local storage: " + e.getMessage()); Log.e(this.getClass().getName(), " Picto json error from local storage: " + e.getMessage());
} }
for (Picto picto: this) { for (Picto picto: this) {
if (picto.status_modified()) { if (picto.status_modified()) {
new PictoUploader(picto).uploadState(); new PictoUploader(picto).uploadState();
Log.i(this.getClass().getCanonicalName(), "Picto status modified while offline. Picto label: " + Log.i(this.getClass().getCanonicalName(), "Picto status modified while offline. Picto translation: '" +
picto.get_translation() + ", id:" + picto.get_id() + " Current status:" + picto.status_modified()); picto.get_translation() + "', id:" + picto.get_id() + " Current status:" + picto.status_modified());
} }
if (picto.get_id() < 0) if (picto.get_id() < 0) //id<0 iif it is a local id
try { try {
new PictoUploader(picto).upload(); //id<0 iif it is a local id new PictoUploader(picto).upload();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Log.e(this.getClass().getName(), " Picto json error from server: " + picto.toString()); Log.e(this.getClass().getName(), " Picto json error from server: " + picto.toString());
} }
} }
}
/**
* the vocabulary is (i) updated to and (ii) downloaded from the server.
*/
public void synchronize() {
synchronize_upload();
//download
final String picto_str="/pictos"; final String picto_str="/pictos";
String operation=PCBcontext.getPcbdb().getCurrentUser().get_restapi_operation_stu()+picto_str; String operation=PCBcontext.getPcbdb().getCurrentUser().get_restapi_operation_stu()+picto_str;
PCBcontext.getRestapiWrapper().ask(operation, new iRestapiListener() { PCBcontext.getRestapiWrapper().ask(operation, new iRestapiListener() {
...@@ -199,7 +215,7 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -199,7 +215,7 @@ public class Vocabulary implements Iterable<Picto> {
imgs.add(new Img(picto.get_id(), picto.get_url(), Img.VOCABULARY)); imgs.add(new Img(picto.get_id(), picto.get_url(), Img.VOCABULARY));
} }
Log.d(this.getClass().getName(), "Vocabulary size: " + updated_collection.length); Log.d(this.getClass().getName(), "Vocabulary size: " + updated_collection.length);
ImgDownloader downloader = new ImgDownloader(PCBcontext.getContext(), imgListener,ImgDownloader.source.remote); ImgDownloader downloader = new ImgDownloader(PCBcontext.getContext(), imgListener,ImgDownloader.tsource.remote);
downloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imgs); downloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imgs);
PCBcontext.getPcbdb().setStudentVocabulary(this); PCBcontext.getPcbdb().setStudentVocabulary(this);
...@@ -211,7 +227,7 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -211,7 +227,7 @@ public class Vocabulary implements Iterable<Picto> {
* It includes/updates a new picto to the user collection: download the image from remote or local storage, add the picto to the current vocabulary and update the database * It includes/updates a new picto to the user collection: download the image from remote or local storage, add the picto to the current vocabulary and update the database
* @param pic * @param pic
*/ */
public void addPicto(Picto pic, ImgDownloader.source source){ public void addPicto(Picto pic, ImgDownloader.tsource source){
Vector<Img> imgs=new Vector<Img>(1); Vector<Img> imgs=new Vector<Img>(1);
imgs.add(new Img(pic.get_id(), pic.get_url(), Img.VOCABULARY)); imgs.add(new Img(pic.get_id(), pic.get_url(), Img.VOCABULARY));
...@@ -330,7 +346,7 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -330,7 +346,7 @@ public class Vocabulary implements Iterable<Picto> {
try { try {
picto = new Picto(id, url, exp, cat, coord_x, coord_y); picto = new Picto(id, url, exp, cat, coord_x, coord_y);
addPicto(picto, ImgDownloader.source.local); addPicto(picto, ImgDownloader.tsource.local);
new PictoUploader(picto).upload(); //id<0 iif it is a local id new PictoUploader(picto).upload(); //id<0 iif it is a local id
} catch (Exception e) { } catch (Exception e) {
picto=null; picto=null;
......
...@@ -29,16 +29,16 @@ public class ImgDownloader extends AsyncTask<Vector<Img>, Void, Img> { ...@@ -29,16 +29,16 @@ public class ImgDownloader extends AsyncTask<Vector<Img>, Void, Img> {
iImgDownloaderListener imgListener; iImgDownloaderListener imgListener;
public static enum status {downloading, downloaded_ok, downloaded_failed} public static enum status {downloading, downloaded_ok, downloaded_failed}
public static enum source{remote,local} public static enum tsource{remote,local}
public status current; public status current;
private boolean force_download; private boolean force_download;
Context context; Context context;
ActivityManager.MemoryInfo mi; ActivityManager.MemoryInfo mi;
ActivityManager activityManager; ActivityManager activityManager;
source source; tsource source;
public ImgDownloader(Context context, iImgDownloaderListener listener, source source) { public ImgDownloader(Context context, iImgDownloaderListener listener, tsource source) {
this.imgListener = listener; this.imgListener = listener;
this.context=context; this.context=context;
this.mi = new ActivityManager.MemoryInfo(); this.mi = new ActivityManager.MemoryInfo();
......
...@@ -60,9 +60,6 @@ public class NetService implements Runnable { ...@@ -60,9 +60,6 @@ public class NetService implements Runnable {
exec.scheduleWithFixedDelay(this, 0, delay, TimeUnit.SECONDS); exec.scheduleWithFixedDelay(this, 0, delay, TimeUnit.SECONDS);
} }
public NetService(){
}
public boolean online() {return updated;} public boolean online() {return updated;}
...@@ -93,7 +90,7 @@ public class NetService implements Runnable { ...@@ -93,7 +90,7 @@ public class NetService implements Runnable {
PCBcontext.getActionLog().batch(); PCBcontext.getActionLog().batch();
updated = true; updated = true;
} }
Log.i(this.getClass().getName(), "PCB status checked. Updated? " + updated+ " in Room? "+PCBcontext.getRoom().inRoom()); Log.i(this.getClass().getName(), "PCB status checked. Updated? " + updated);
} }
@Override @Override
......
...@@ -11,6 +11,7 @@ import com.yottacode.pictogram.R; ...@@ -11,6 +11,7 @@ import com.yottacode.pictogram.R;
import com.yottacode.pictogram.action.PictoAction; import com.yottacode.pictogram.action.PictoAction;
import com.yottacode.pictogram.action.VocabularyAction; import com.yottacode.pictogram.action.VocabularyAction;
import com.yottacode.pictogram.dao.Picto; import com.yottacode.pictogram.dao.Picto;
import com.yottacode.pictogram.grammar.Vocabulary;
import com.yottacode.pictogram.tools.Img; import com.yottacode.pictogram.tools.Img;
import com.yottacode.pictogram.tools.PCBcontext; import com.yottacode.pictogram.tools.PCBcontext;
...@@ -85,8 +86,7 @@ public class PictoUploader { ...@@ -85,8 +86,7 @@ public class PictoUploader {
/** /**
* if the a picto was included from the PCB, the translation is uploaded to the server * if the a picto was included from the PCB, the translation is uploaded to the server
*/ */
private int uploadAttributes(int id_picto) { private void uploadAttributes(int id_picto) {
final int id_stupicto[]=new int[1];
Hashtable<String, String> params = new Hashtable<String, String>(4); Hashtable<String, String> params = new Hashtable<String, String>(4);
try { try {
params.put("json", new JSONObject().put("attributes", params.put("json", new JSONObject().put("attributes",
...@@ -111,22 +111,14 @@ public class PictoUploader { ...@@ -111,22 +111,14 @@ public class PictoUploader {
@Override @Override
public void result(JSONObject result) { public void result(JSONObject result) {
Log.i(this.getClass().getCanonicalName(), " Attributes uploaded: " + result.toString()); Log.i(this.getClass().getCanonicalName(), " Attributes uploaded: " + result.toString());
/* try {
id_stupicto[0]=result.getJSONObject("picto").getInt("id");
} catch (JSONException e) {
e.printStackTrace();
Log.e(this.getClass().getCanonicalName(), "Error: " + e.getLocalizedMessage());
}*/
} }
@Override @Override
public void error(Exception e) { public void error(Exception e) {
Log.e(this.getClass().getCanonicalName(), " Error uploading attributes: " + e.getLocalizedMessage()); Log.e(this.getClass().getCanonicalName(), " Error uploading attributes: " + e.getLocalizedMessage());
id_stupicto[0]=-1; PCBcontext.getVocabulary().addPicto(picto, ImgDownloader.tsource.local);
} }
}); });
return id_stupicto[0];
} }
/** /**
...@@ -155,22 +147,22 @@ public class PictoUploader { ...@@ -155,22 +147,22 @@ public class PictoUploader {
@Override @Override
public void error(Exception e) { public void error(Exception e) {
Log.e(this.getClass().getCanonicalName(), "Error: " + e.getLocalizedMessage()); Log.e(this.getClass().getCanonicalName(), "Error: " + e.getLocalizedMessage());
PCBcontext.getVocabulary().addPicto(picto, ImgDownloader.tsource.local);
} }
}); });
} }
/** /**
*Upload local picto. It requires: i) to upload the image, ii) to upload the attributes and iii) to upload the expression *Try to Upload local picto. It requires: i) to upload the image, ii) to upload the attributes and iii) to upload the expression
**/ **/
public void upload() throws IOException { public void upload() throws IOException {
if (PCBcontext.getNetService().online()) {
int img_id = uploadImg(this.picto);
if (img_id > 0) { int img_id = uploadImg(this.picto);
uploadAttributes(img_id); if (img_id > 0) {
uploadTranslation(img_id); uploadAttributes(img_id);
} uploadTranslation(img_id);
} }
else PCBcontext.getVocabulary().addPicto(picto, ImgDownloader.tsource.local);
} }
/** /**
...@@ -184,12 +176,10 @@ public class PictoUploader { ...@@ -184,12 +176,10 @@ public class PictoUploader {
params.put("id_stu", Integer.toString(PCBcontext.getPcbdb().getCurrentUser().get_id_stu())); params.put("id_stu", Integer.toString(PCBcontext.getPcbdb().getCurrentUser().get_id_stu()));
params.put("id_pic", Integer.toString(this.picto.get_id())); params.put("id_pic", Integer.toString(this.picto.get_id()));
Log.i(this.getClass().getCanonicalName(), "Picto Uploading " + params.toString());
if (PCBcontext.getNetService().online()) { PCBcontext.getRestapiWrapper().ask(
Log.i(this.getClass().getCanonicalName(), "Uploading " + params.toString()); PCBcontext.getPcbdb().getCurrentUser().get_restapi_operation_stu() + "/picto",
PCBcontext.getRestapiWrapper().ask(PCBcontext.getPcbdb().getCurrentUser().get_restapi_operation_stu() params, "put", new iRestapiListener() {
+ "/picto"
, params, "put", new iRestapiListener() {
@Override @Override
public void preExecute() { public void preExecute() {
} }
...@@ -214,7 +204,6 @@ public class PictoUploader { ...@@ -214,7 +204,6 @@ public class PictoUploader {
} }
} }
); );
}
} }
......
...@@ -28,7 +28,7 @@ public final class PCBcontext { ...@@ -28,7 +28,7 @@ public final class PCBcontext {
private static RestapiWrapper wrapper; private static RestapiWrapper wrapper;
private static Vocabulary vocabulary; private static Vocabulary vocabulary;
private static ActionLog actionLog; private static ActionLog actionLog;
private static boolean init=false;
protected PCBcontext() { protected PCBcontext() {
// Initialize internal objects. This initialization is run only the first time // Initialize internal objects. This initialization is run only the first time
...@@ -50,10 +50,15 @@ public final class PCBcontext { ...@@ -50,10 +50,15 @@ public final class PCBcontext {
// Init method for passing params to the singleton // Init method for passing params to the singleton
public static void init(Context c){ public static void init(Context c){
context=c; if (!init) {
device = new Device(c, null, 1); init=true;
wrapper = new RestapiWrapper(context.getResources().getString(R.string.server),null); context = c;
Log.i(PCBcontext.class.getCanonicalName(), "PCB context started, waiting. It's required set user "); device = new Device(c, null, 1);
wrapper = new RestapiWrapper(context.getResources().getString(R.string.server), null);
service = new NetService(context.getResources().getInteger(R.integer.netservice_timing));
Log.i(PCBcontext.class.getCanonicalName(), "PCB context started. It's required to be invoked set_user method");
}
else Log.e(PCBcontext.class.getClass().getCanonicalName(), "Init method was previously invoked! Please, revise your code");
} }
/** /**
...@@ -64,13 +69,14 @@ public final class PCBcontext { ...@@ -64,13 +69,14 @@ public final class PCBcontext {
* @param listener * @param listener
*/ */
public static void set_user(User student, String token, iImgDownloaderListener listener) { public static void set_user(User student, String token, iImgDownloaderListener listener) {
Log.i(PCBcontext.class.getCanonicalName(), "User set at student "+student.get_name_stu()); if (!init) throw new java.lang.AssertionError("init must be called once previously ");
Log.i(PCBcontext.class.getCanonicalName(), "User set at student " + student.get_name_stu());
wrapper.setToken(token); wrapper.setToken(token);
pcbdb = new PCBDBHelper(null, 1, student); pcbdb = new PCBDBHelper(null, 1, student);
service = new NetService(context.getResources().getInteger(R.integer.netservice_timing));
vocabulary= new Vocabulary(listener);
room = new Room(); room = new Room();
actionLog = new ActionLog(); actionLog = new ActionLog();
vocabulary = new Vocabulary(listener);
} }
// Return the context // Return the context
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment