Trabajando en operaciones batch y tarea asíncrona

parent 8daa337e
...@@ -54,13 +54,19 @@ public class RestapiWrapper { ...@@ -54,13 +54,19 @@ public class RestapiWrapper {
public void ask(String operation, Hashtable<String, String> params, String postOrGet, iRestapiListener listener) { public void ask(String operation, Hashtable<String, String> params, String postOrGet, iRestapiListener listener) {
// call AsynTask to perform network operation on separate thread // call AsynTask to perform network operation on separate thread
String url = this.server + '/' + operation;
if (this.token != null) { if (this.token != null) {
if (params == null) if (params == null)
params = new Hashtable<>(1); params = new Hashtable<>(1);
params.put("token", this.token); params.put("token", this.token);
} }
new HttpAsyncTask(listener, params).execute(postOrGet, url); Log.d(LOG_TAG, "POST params:" + params.toString());
HttpAsyncTaskParams httpAsyncTaskParams=new HttpAsyncTaskParams();
httpAsyncTaskParams.get=postOrGet.equals("get");
httpAsyncTaskParams.listener=listener;
httpAsyncTaskParams.url_params=params;
httpAsyncTaskParams.url=this.server + '/' + operation;;
new HttpAsyncTask().execute(httpAsyncTaskParams);
} }
public void ask(String operation, iRestapiListener listener) { public void ask(String operation, iRestapiListener listener) {
...@@ -137,15 +143,13 @@ public class RestapiWrapper { ...@@ -137,15 +143,13 @@ public class RestapiWrapper {
String response = ""; String response = "";
try { try {
url = new URL(surl); url = new URL(surl);
Log.d(LOG_TAG, "POST url:" + surl);
String sparams=""; String sparams="";
for (String param : params.keySet()) { for (String param : params.keySet()) {
String value = params.get(param); String value = params.get(param);
sparams += param + '=' + value + '&'; sparams += param + '=' + value + '&';
} }
if (sparams.length()>0) sparams=sparams.substring(0,sparams.length()-1); if (sparams.length()>0) sparams=sparams.substring(0,sparams.length()-1);
Log.d(LOG_TAG, "POST url:" + surl+" params:"+sparams);
HttpURLConnection urlConnection = null; HttpURLConnection urlConnection = null;
urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(60000); urlConnection.setReadTimeout(60000);
...@@ -194,49 +198,45 @@ public class RestapiWrapper { ...@@ -194,49 +198,45 @@ public class RestapiWrapper {
} }
private class HttpAsyncTaskParams {
protected boolean get;
protected String url;
protected Hashtable<String, String> url_params;
protected iRestapiListener listener;
protected String result;
}
private class HttpAsyncTask extends AsyncTask<HttpAsyncTaskParams, Void, HttpAsyncTaskParams> {
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
iRestapiListener listener;
Hashtable<String, String> postDataParams;
public HttpAsyncTask(iRestapiListener listener, Hashtable<String, String> postDataParams) {
super();
this.listener=listener;
this.postDataParams = postDataParams;
}
@Override @Override
protected String doInBackground(String... params) { protected HttpAsyncTaskParams doInBackground(HttpAsyncTaskParams... params) {
String postOrGet = params[0]; Log.d(LOG_TAG, "POST params doIn:" + params[0].url_params.toString());
String url = params[1]; params[0].result = params[0].get ? POST(params[0].url, params[0].url_params,params[0].listener)
//Hashtable<String, String> postDataParams = params[2]; : GET(params[0].url, params[0].url_params,params[0].listener);
return params[0];
return postOrGet.equals("post") ? POST(url, postDataParams, listener)
: GET(url, postDataParams, listener);
} }
// onPostExecute displays the results of the AsyncTask. // onPostExecute displays the results of the AsyncTask.
@Override @Override
protected void onPostExecute(String result) { protected void onPostExecute(HttpAsyncTaskParams params) {
try { try {
if(result!=null) { if(params.result!=null) {
Log.d(LOG_TAG, "JSON: " + result); Log.d(LOG_TAG, "JSON: " + params.result);
Object jsonResult = new JSONTokener(result).nextValue(); Object jsonResult = new JSONTokener(params.result).nextValue();
if (jsonResult instanceof JSONObject) { if (jsonResult instanceof JSONObject) {
// The result is an object // The result is an object
this.listener.result((JSONObject) jsonResult); params.listener.result((JSONObject) jsonResult);
} else if (jsonResult instanceof JSONArray) { } else if (jsonResult instanceof JSONArray) {
// The result is an array // The result is an array
this.listener.result((JSONArray) jsonResult); params.listener.result((JSONArray) jsonResult);
} }
}else{ }else{
this.listener.result((JSONObject) null); params.listener.result((JSONObject) null);
} }
} catch (JSONException e) { } catch (JSONException e) {
listener.error(e); params.listener.error(e);
} }
} }
} }
......
...@@ -39,7 +39,7 @@ public class Action { ...@@ -39,7 +39,7 @@ public class Action {
protected JSONObject get_json() { protected JSONObject get_json() {
final String param_id_stu="id_stu"; final String param_id_stu="id_stu";
final String param_id_sup="id_sup"; final String param_id_sup="id_sup";
final String param_id_dev="device"; final String param_id_dev="id_dev";
final String param_timestamp="timestamp"; final String param_timestamp="timestamp";
final Date currentTime = new Date(); final Date currentTime = new Date();
SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
...@@ -62,12 +62,15 @@ public class Action { ...@@ -62,12 +62,15 @@ public class Action {
/** /**
* *
* @return the whole description of the action, including the action type (required for sending batch actions) * @return the whole description of the action, including the action type (required for sending batch actions,
* more info at http://scm.ujaen.es/softuno/pictogram/wikis/RestapivalidActionsBatch)
*/ */
public String getDescription() { public JSONObject getDescription() {
final String param_type = "type"; final String param_action= "action";
final String param_attributes= "attributes";
try { try {
return get_json().put(param_type, this.type).toString(); return (new JSONObject().put(param_action, this.type)
.put(param_attributes, this.get_json()));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(this.getClass().getCanonicalName(),e.getMessage()); Log.e(this.getClass().getCanonicalName(),e.getMessage());
} }
......
...@@ -20,10 +20,11 @@ import java.util.Vector; ...@@ -20,10 +20,11 @@ import java.util.Vector;
*/ */
public class ActionLog implements iRestapiListener { public class ActionLog implements iRestapiListener {
Vector<String> actions_buffer; Vector<JSONObject> actions_buffer;
public ActionLog() { public ActionLog() {
actions_buffer=PCBcontext.getPcbdb().loadActions(); actions_buffer=PCBcontext.getPcbdb().loadActions();
actions_buffer=new Vector<>();//TODO BORRAR
if (PCBcontext.getNetService().online()) batch(); if (PCBcontext.getNetService().online()) batch();
} }
// String constant for logs // String constant for logs
...@@ -37,6 +38,7 @@ public class ActionLog implements iRestapiListener { ...@@ -37,6 +38,7 @@ public class ActionLog implements iRestapiListener {
// If there is no available connection, the action is stored in local DB // If there is no available connection, the action is stored in local DB
PCBcontext.getPcbdb().insertAction(action); PCBcontext.getPcbdb().insertAction(action);
actions_buffer.add(action.getDescription()); actions_buffer.add(action.getDescription());
Log.i(this.getClass().getCanonicalName(), " Batch action included: " + action.getDescription());
} }
} }
...@@ -44,13 +46,14 @@ public class ActionLog implements iRestapiListener { ...@@ -44,13 +46,14 @@ public class ActionLog implements iRestapiListener {
public void batch() { public void batch() {
if (!actions_buffer.isEmpty()) { if (!actions_buffer.isEmpty()) {
Hashtable<String, String> params= new Hashtable<>(1); Hashtable<String, String> params= new Hashtable<>(1);
String url="stu/actions_batch";
String actions=""; String actions="";
for (String action: actions_buffer) for (JSONObject action: actions_buffer)
actions+=","+action; actions+=","+action.toString();
actions= "{ actions:[" + actions.substring(1) + "] }"; actions= "[" + actions.substring(1) + "]";
params.put("actions",actions); params.put("actions",actions);
Log.i(this.getClass().getCanonicalName()," Sending batch actions: "+actions); Log.i(this.getClass().getCanonicalName()," Sending batch actions: "+url+": "+actions);
PCBcontext.getRestapiWrapper().ask("/stu/" + PCBcontext.getPcbdb().getCurrentUser().get_id_stu() + "/actions_batch", params, "post", this); PCBcontext.getRestapiWrapper().ask(url, params, "post", this);
params.clear(); params.clear();
} }
} }
......
...@@ -22,6 +22,7 @@ import com.yottacode.pictogram.tools.PCBcontext; ...@@ -22,6 +22,7 @@ import com.yottacode.pictogram.tools.PCBcontext;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject;
/** /**
* Platform abstraction (Android) * Platform abstraction (Android)
...@@ -131,7 +132,7 @@ public class PCBDBHelper extends SQLiteOpenHelper { ...@@ -131,7 +132,7 @@ public class PCBDBHelper extends SQLiteOpenHelper {
public void insertAction(Action action) { public void insertAction(Action action) {
SQLiteDatabase db = this.getWritableDatabase(); SQLiteDatabase db = this.getWritableDatabase();
ContentValues values=new ContentValues(1); ContentValues values=new ContentValues(1);
values.put("json_action",action.getDescription()); values.put("json_action",action.getDescription().toString());
db.insert("action", null, values); db.insert("action", null, values);
db.close(); db.close();
} }
...@@ -140,15 +141,19 @@ public class PCBDBHelper extends SQLiteOpenHelper { ...@@ -140,15 +141,19 @@ public class PCBDBHelper extends SQLiteOpenHelper {
* @see Action * @see Action
*/ */
public Vector<String> loadActions() { public Vector<JSONObject> loadActions() {
SQLiteDatabase db = this.getReadableDatabase(); SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query("action", null, null, null, null, null, null, null); Cursor cursor = db.query("action", null, null, null, null, null, null, null);
Vector<String> actions= new Vector(cursor.getCount()); Vector<JSONObject> actions= new Vector(cursor.getCount());
Log.i(this.getClass().getName(), "Local action recovering " + cursor.getCount() + " actions from local DB"); Log.i(this.getClass().getName(), "Local action recovering " + cursor.getCount() + " actions from local DB");
cursor.moveToFirst(); cursor.moveToFirst();
while (cursor.moveToNext()) while (cursor.moveToNext())
actions.add(cursor.getString(0)); try {
actions.add(new JSONObject(cursor.getString(0)));
} catch (JSONException e) {
Log.e(this.getClass().getName(), "Recovering batch actions:"+e.getMessage());
}
cursor.close(); cursor.close();
db.close(); db.close();
return actions; return actions;
......
...@@ -29,19 +29,18 @@ import java.util.concurrent.TimeUnit; ...@@ -29,19 +29,18 @@ import java.util.concurrent.TimeUnit;
public class NetService implements Runnable, iRestapiListener { public class NetService implements Runnable, iRestapiListener {
boolean online;
static final String ping_session="server/ping";
static final String ping_session="server/ping";
private boolean updated;
public NetService(int delay) { public NetService(int delay) {
this.updated=this.online();
Log.i(this.getClass().getName(),"Checking Pictogram server access..."); Log.i(this.getClass().getName(), "Checking Pictogram server access...");
this.online = RestapiWrapper.ping(PCBcontext.getContext().getResources().getString(R.string.server), ping_session, this); Log.d(this.getClass().getName(), this.updated ? "Pictogram server access ok" : "Pictogram server access failed, Internet connection available?");
Log.d(this.getClass().getName(),this.online() ? "Pictogram server access ok" : "Pictogram server access failed, Internet connection available?");
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleWithFixedDelay(this, 0, delay, TimeUnit.SECONDS); exec.scheduleWithFixedDelay(this, 0, delay, TimeUnit.SECONDS);
} }
public boolean online() {return this.online;} public boolean online() {return RestapiWrapper.ping(PCBcontext.getContext().getResources().getString(R.string.server), ping_session, this);}
/** /**
* ping to the server by using a restapi call. If ok, the call will return the empty set * ping to the server by using a restapi call. If ok, the call will return the empty set
...@@ -57,21 +56,21 @@ public class NetService implements Runnable, iRestapiListener { ...@@ -57,21 +56,21 @@ public class NetService implements Runnable, iRestapiListener {
@Override @Override
public void result(JSONObject result) { public void result(JSONObject result) {
String msg="PCB status checked. From "+(this.online ? "online" : "offline");
if (result==null ) { if (result==null ) {
this.online=false; this.updated=false;
} else if (!this.online) { } else if (!this.updated) {
this.online=true;
PCBcontext.getRoom().reconnect(); PCBcontext.getRoom().reconnect();
PCBcontext.getVocabulary().download(); PCBcontext.getVocabulary().download();
PCBcontext.getActionLog().batch(); PCBcontext.getActionLog().batch();
this.updated=true;
} }
Log.i(this.getClass().getName(), msg+" to "+ (this.online ? "online" : "offline")); Log.i(this.getClass().getName(),"PCB status checked. Updated? "+this.updated);
} }
@Override @Override
public void error(Exception e) { public void error(Exception e) {
this.online=false; this.updated=false;
Log.i(this.getClass().getName(), "PCB offline because exception happens: "+e.getMessage()); Log.i(this.getClass().getName(), "PCB offline because exception happens: "+e.getMessage());
} }
} }
\ No newline at end of file
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