Trabajando en operaciones batch y tarea asíncrona

parent 8daa337e
......@@ -54,13 +54,19 @@ public class RestapiWrapper {
public void ask(String operation, Hashtable<String, String> params, String postOrGet, iRestapiListener listener) {
// call AsynTask to perform network operation on separate thread
String url = this.server + '/' + operation;
if (this.token != null) {
if (params == null)
params = new Hashtable<>(1);
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) {
......@@ -137,15 +143,13 @@ public class RestapiWrapper {
String response = "";
try {
url = new URL(surl);
Log.d(LOG_TAG, "POST url:" + surl);
String sparams="";
for (String param : params.keySet()) {
String value = params.get(param);
sparams += param + '=' + value + '&';
}
if (sparams.length()>0) sparams=sparams.substring(0,sparams.length()-1);
Log.d(LOG_TAG, "POST url:" + surl+" params:"+sparams);
HttpURLConnection urlConnection = null;
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(60000);
......@@ -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
protected String doInBackground(String... params) {
String postOrGet = params[0];
String url = params[1];
//Hashtable<String, String> postDataParams = params[2];
return postOrGet.equals("post") ? POST(url, postDataParams, listener)
: GET(url, postDataParams, listener);
protected HttpAsyncTaskParams doInBackground(HttpAsyncTaskParams... params) {
Log.d(LOG_TAG, "POST params doIn:" + params[0].url_params.toString());
params[0].result = params[0].get ? POST(params[0].url, params[0].url_params,params[0].listener)
: GET(params[0].url, params[0].url_params,params[0].listener);
return params[0];
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
protected void onPostExecute(HttpAsyncTaskParams params) {
try {
if(result!=null) {
Log.d(LOG_TAG, "JSON: " + result);
if(params.result!=null) {
Log.d(LOG_TAG, "JSON: " + params.result);
Object jsonResult = new JSONTokener(result).nextValue();
Object jsonResult = new JSONTokener(params.result).nextValue();
if (jsonResult instanceof JSONObject) {
// The result is an object
this.listener.result((JSONObject) jsonResult);
params.listener.result((JSONObject) jsonResult);
} else if (jsonResult instanceof JSONArray) {
// The result is an array
this.listener.result((JSONArray) jsonResult);
params.listener.result((JSONArray) jsonResult);
}
}else{
this.listener.result((JSONObject) null);
params.listener.result((JSONObject) null);
}
} catch (JSONException e) {
listener.error(e);
params.listener.error(e);
}
}
}
......
......@@ -39,7 +39,7 @@ public class Action {
protected JSONObject get_json() {
final String param_id_stu="id_stu";
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 Date currentTime = new Date();
SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
......@@ -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() {
final String param_type = "type";
public JSONObject getDescription() {
final String param_action= "action";
final String param_attributes= "attributes";
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) {
Log.e(this.getClass().getCanonicalName(),e.getMessage());
}
......
......@@ -20,10 +20,11 @@ import java.util.Vector;
*/
public class ActionLog implements iRestapiListener {
Vector<String> actions_buffer;
Vector<JSONObject> actions_buffer;
public ActionLog() {
actions_buffer=PCBcontext.getPcbdb().loadActions();
actions_buffer=new Vector<>();//TODO BORRAR
if (PCBcontext.getNetService().online()) batch();
}
// String constant for logs
......@@ -37,6 +38,7 @@ public class ActionLog implements iRestapiListener {
// If there is no available connection, the action is stored in local DB
PCBcontext.getPcbdb().insertAction(action);
actions_buffer.add(action.getDescription());
Log.i(this.getClass().getCanonicalName(), " Batch action included: " + action.getDescription());
}
}
......@@ -44,13 +46,14 @@ public class ActionLog implements iRestapiListener {
public void batch() {
if (!actions_buffer.isEmpty()) {
Hashtable<String, String> params= new Hashtable<>(1);
String url="stu/actions_batch";
String actions="";
for (String action: actions_buffer)
actions+=","+action;
actions= "{ actions:[" + actions.substring(1) + "] }";
for (JSONObject action: actions_buffer)
actions+=","+action.toString();
actions= "[" + actions.substring(1) + "]";
params.put("actions",actions);
Log.i(this.getClass().getCanonicalName()," Sending batch actions: "+actions);
PCBcontext.getRestapiWrapper().ask("/stu/" + PCBcontext.getPcbdb().getCurrentUser().get_id_stu() + "/actions_batch", params, "post", this);
Log.i(this.getClass().getCanonicalName()," Sending batch actions: "+url+": "+actions);
PCBcontext.getRestapiWrapper().ask(url, params, "post", this);
params.clear();
}
}
......
......@@ -22,6 +22,7 @@ import com.yottacode.pictogram.tools.PCBcontext;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Platform abstraction (Android)
......@@ -131,7 +132,7 @@ public class PCBDBHelper extends SQLiteOpenHelper {
public void insertAction(Action action) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values=new ContentValues(1);
values.put("json_action",action.getDescription());
values.put("json_action",action.getDescription().toString());
db.insert("action", null, values);
db.close();
}
......@@ -140,15 +141,19 @@ public class PCBDBHelper extends SQLiteOpenHelper {
* @see Action
*/
public Vector<String> loadActions() {
public Vector<JSONObject> loadActions() {
SQLiteDatabase db = this.getReadableDatabase();
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");
cursor.moveToFirst();
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();
db.close();
return actions;
......
......@@ -29,19 +29,18 @@ import java.util.concurrent.TimeUnit;
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) {
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.online() ? "Pictogram server access ok" : "Pictogram server access failed, Internet connection available?");
this.updated=this.online();
Log.i(this.getClass().getName(), "Checking Pictogram server access...");
Log.d(this.getClass().getName(), this.updated ? "Pictogram server access ok" : "Pictogram server access failed, Internet connection available?");
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
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
......@@ -57,21 +56,21 @@ public class NetService implements Runnable, iRestapiListener {
@Override
public void result(JSONObject result) {
String msg="PCB status checked. From "+(this.online ? "online" : "offline");
if (result==null ) {
this.online=false;
} else if (!this.online) {
this.online=true;
this.updated=false;
} else if (!this.updated) {
PCBcontext.getRoom().reconnect();
PCBcontext.getVocabulary().download();
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
public void error(Exception e) {
this.online=false;
this.updated=false;
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