Modificaciones para el modo OFFLINE

parent ad83e21c
package com.yottacode.net; package com.yottacode.net;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Hashtable; import java.net.UnknownHostException;
import java.util.concurrent.Executor; import java.util.Hashtable;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.json.JSONTokener; import org.json.JSONTokener;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.StrictMode; import android.os.StrictMode;
import android.util.Log; import android.util.Log;
import com.google.gson.JsonParser; import javax.net.ssl.HttpsURLConnection;
import com.koushikdutta.async.parser.JSONObjectParser;
import javax.net.ssl.HttpsURLConnection;
/** /**
...@@ -119,10 +116,14 @@ public class RestapiWrapper { ...@@ -119,10 +116,14 @@ public class RestapiWrapper {
boolean pingResult = false; boolean pingResult = false;
try { try {
pingResult = GET(server + "/" + ping_op, null)!=null; pingResult = GET(server + "/" + ping_op, null)!=null;
} catch (UnknownHostException e){
//e.printStackTrace();
Log.e(RestapiWrapper.class.getName(), "ping failed at"+ping_op);
return false;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Log.e(com.yottacode.net.RestapiWrapper.class.getName(), "ping failed at"+ping_op); Log.e(com.yottacode.net.RestapiWrapper.class.getName(), "ping failed at"+ping_op);
error_listener.error(e); //error_listener.error(e);
} }
return pingResult; return pingResult;
} }
......
...@@ -51,6 +51,7 @@ public class Vocabulary implements Iterable<Picto> { ...@@ -51,6 +51,7 @@ public class Vocabulary implements Iterable<Picto> {
}else }else
try { try {
PCBcontext.getPcbdb().getStudentVocabulary(this); PCBcontext.getPcbdb().getStudentVocabulary(this);
if (listener!=null)
listener.loadComplete(); listener.loadComplete();
} catch (JSONException e) { } catch (JSONException e) {
Log.e(this.getClass().getName(),"Local vocabulary recover failed: "+e.getMessage()); Log.e(this.getClass().getName(),"Local vocabulary recover failed: "+e.getMessage());
......
...@@ -2,11 +2,7 @@ package com.yottacode.pictogram.gui; ...@@ -2,11 +2,7 @@ package com.yottacode.pictogram.gui;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ProgressDialog; import android.app.ProgressDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.Build; import android.os.Build;
...@@ -14,16 +10,14 @@ import android.os.Bundle; ...@@ -14,16 +10,14 @@ import android.os.Bundle;
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentActivity;
import android.util.Log; import android.util.Log;
import android.view.Window; import android.view.Window;
import android.widget.CompoundButton;
import android.widget.Toast; import android.widget.Toast;
import android.widget.ToggleButton;
import com.yottacode.pictogram.dao.LoginException;
import com.yottacode.pictogram.dao.User; import com.yottacode.pictogram.dao.User;
import com.yottacode.pictogram.R; import com.yottacode.pictogram.R;
import com.yottacode.net.iRestapiListener; import com.yottacode.net.iRestapiListener;
import com.yottacode.net.SSLDummyContext; import com.yottacode.net.SSLDummyContext;
import com.yottacode.net.RestapiWrapper; import com.yottacode.net.RestapiWrapper;
import com.yottacode.pictogram.net.NetService;
import com.yottacode.pictogram.tools.Img; import com.yottacode.pictogram.tools.Img;
import com.yottacode.pictogram.tools.PCBcontext; import com.yottacode.pictogram.tools.PCBcontext;
import com.yottacode.pictogram.net.iImgDownloaderListener; import com.yottacode.pictogram.net.iImgDownloaderListener;
...@@ -32,7 +26,6 @@ import org.json.JSONArray; ...@@ -32,7 +26,6 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Vector; import java.util.Vector;
...@@ -64,6 +57,8 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -64,6 +57,8 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
private ProgressDialog progressDialog; private ProgressDialog progressDialog;
private String token=null; private String token=null;
private String username = null;
private String password = null;
/** /**
* If there is Internet connection it calls the WS to recover the pairs student-supervisor * If there is Internet connection it calls the WS to recover the pairs student-supervisor
...@@ -76,6 +71,13 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -76,6 +71,13 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
Intent intent=getIntent();
Boolean offline=intent.getBooleanExtra("offline", false);
if (offline){
username=intent.getStringExtra("username");
password=intent.getStringExtra("password");
}
// Activo el modo KIOSKO // Activo el modo KIOSKO
//startLockTask(); //startLockTask();
//DevicePolicyManager myDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); //DevicePolicyManager myDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
...@@ -108,22 +110,74 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -108,22 +110,74 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
SSLDummyContext.init(getResources().getBoolean(R.bool.ssl_connect)); SSLDummyContext.init(getResources().getBoolean(R.bool.ssl_connect));
PCBcontext.init(this); PCBcontext.init(this);
// Compruebo si tengo acceso a internet // Compruebo si tengo acceso a internet y al servicio web
if (!RestapiWrapper.ping(getResources().getString(R.string.server),"server/ping",this)) { if (!RestapiWrapper.ping(getResources().getString(R.string.server),"server/ping",this)) {
// No puedo comprobar si el serial es válido. Muestro un alertdialog de error, y cierro la aplicación // MODO OFFLINE
AlertDialog alertDialog = new AlertDialog.Builder( try {
LoginActivity.this).create(); Log.d(LOG_TAG, "username guardado:" + username);
alertDialog.setTitle(getResources().getString(R.string.systemMessage)); Log.d(LOG_TAG, "password guardado:" + password);
alertDialog.setMessage(getResources().getString(R.string.noInternetConnection));
//alertDialog.setIcon(R.drawable.tick); Vector<User> localUsers = PCBcontext.getDevice().findUser(username, password);
alertDialog.setButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { // Si sólo hay 1 estudiante, cargo el st_id
public void onClick(DialogInterface dialog, int which) { if (localUsers.size() == 1){
Toast.makeText(getApplicationContext(), getResources().getString(R.string.exitingApp), Toast.LENGTH_SHORT).show(); PCBcontext.set_user(localUsers.elementAt(0), null, null);
} else{
User student = null;
try {
student = new User(-1, "nickname_stu","pwd_stu","", "", "", "M", "es-es", "",
sup_id, "nickname_sup", "pwd_sup","", "", "", "M", "es-es", "");
PCBcontext.set_user(student, token, new iImgDownloaderListener() {
@Override
public void loadComplete() {
//close the progress dialog
//progressDialog.dismiss();
//setContentView(R.layout.activity_login);
}
@Override
public void loadImg(Img image) {
//close the progress dialog
//progressDialog.dismiss();
//setContentView(R.layout.activity_login);
} }
}); });
alertDialog.show(); } catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (LoginException e) {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
if (e.known_supervisor()){
// El password del supervisor no es correcto
builder.setMessage("La contraseña indicada no es correcta. Inténtelo de nuevo.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
} else if (e.no_students()){
// Este supervisor existe pero no tiene estudiantes
builder.setMessage("El usuario indicado no tiene alumnos asignados. Asigne estudiantes desde el panel de control.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
} else{
// El supervisor indicado no existe
builder.setMessage("El usuario indicado no es correcto. Inténtelo de nuevo.")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
e.printStackTrace();
}
} else{ } else{
// NUEVO // Modo ONLINE
sup_id = getIntent().getExtras().getInt("sup_id"); sup_id = getIntent().getExtras().getInt("sup_id");
token = getIntent().getExtras().getString("token"); token = getIntent().getExtras().getString("token");
...@@ -153,10 +207,9 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -153,10 +207,9 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
} }
@Override @Override
public void result(JSONArray students_supervisors) { //FERNANDO public void result(JSONArray students_supervisors) {
try { try {
// Saco los pares estudiante-supervisor // Saco los pares estudiante-supervisor
// looping through All Students
Vector<User> users = new Vector<User>(students_supervisors.length()); Vector<User> users = new Vector<User>(students_supervisors.length());
if (students_supervisors.length() == 0){ if (students_supervisors.length() == 0){
...@@ -166,10 +219,6 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -166,10 +219,6 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
.setCancelable(false) .setCancelable(false)
.setPositiveButton("Entendido y salir", new DialogInterface.OnClickListener() { .setPositiveButton("Entendido y salir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
// Salgo de la aplicación
// ????
//System.exit(0);
//finish();
} }
}); });
AlertDialog alert = builder.create(); AlertDialog alert = builder.create();
...@@ -200,7 +249,7 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -200,7 +249,7 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
int st_supervision_int = st_supervision.intValue(); int st_supervision_int = st_supervision.intValue();
if (st_supervision_int==2){ if (st_supervision_int==2){
student = new User(st_id_int,"nickname_stu","pwd_stu", st_name, st_surname, st_pic, st_gender, st_lang, st_attributes, student = new User(st_id_int,"nickname_stu","pwd_stu", st_name, st_surname, st_pic, st_gender, st_lang, st_attributes,
sup_id, "nickname_sup","pwd_sup","", "", "", "M", "es-es", ""); sup_id, username, password,"", "", "", "M", "es-es", "");
users.add(student); users.add(student);
} }
} }
...@@ -214,7 +263,7 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{ ...@@ -214,7 +263,7 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
} else{ } else{
student = new User(-1, "nickname_stu","pwd_stu","", "", "", "M", "es-es", "", student = new User(-1, "nickname_stu","pwd_stu","", "", "", "M", "es-es", "",
sup_id, "nickname_stu","pwd_stu","", "", "", "M", "es-es", ""); sup_id, username, password,"", "", "", "M", "es-es", "");
PCBcontext.set_user(student, token, new iImgDownloaderListener() { PCBcontext.set_user(student, token, new iImgDownloaderListener() {
@Override @Override
public void loadComplete() { public void loadComplete() {
......
package com.yottacode.pictogram.net; package com.yottacode.pictogram.net;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log; import android.util.Log;
import com.yottacode.net.RestapiWrapper; import com.yottacode.net.RestapiWrapper;
import com.yottacode.net.iRestapiListener; import com.yottacode.net.iRestapiListener;
import com.yottacode.pictogram.R; import com.yottacode.pictogram.R;
import com.yottacode.pictogram.gui.PictogramActivity;
import com.yottacode.pictogram.tools.PCBcontext; import com.yottacode.pictogram.tools.PCBcontext;
import org.json.JSONArray; import org.json.JSONArray;
...@@ -34,16 +28,12 @@ import java.util.concurrent.TimeUnit; ...@@ -34,16 +28,12 @@ import java.util.concurrent.TimeUnit;
public class NetService implements Runnable { public class NetService implements Runnable {
public static final String PREFS_NAME = "MyPrefsFile";
static final String ping_session="server/ping"; static final String ping_session="server/ping";
private boolean updated; private boolean updated;
private NotificationCompat.Builder builder;
public NetService(int delay) { public NetService(int delay) {
this.updated=RestapiWrapper.ping(PCBcontext.getContext().getResources().getString(R.string.server), ping_session, new iRestapiListener() { this.updated=RestapiWrapper.ping(PCBcontext.getContext().getResources().getString(R.string.server), ping_session, new iRestapiListener() {
@Override @Override
public void preExecute() { public void preExecute() {
...@@ -57,13 +47,11 @@ public class NetService implements Runnable { ...@@ -57,13 +47,11 @@ public class NetService implements Runnable {
@Override @Override
public void result(JSONObject result) { public void result(JSONObject result) {
updated=true; updated=true;
notifyStatus();
} }
@Override @Override
public void error(Exception e) { public void error(Exception e) {
updated=false; updated=false;
notifyStatus();
} }
}); });
Log.i(this.getClass().getName(), "Checking Pictogram server access..."); Log.i(this.getClass().getName(), "Checking Pictogram server access...");
...@@ -96,51 +84,32 @@ public class NetService implements Runnable { ...@@ -96,51 +84,32 @@ public class NetService implements Runnable {
if (result == null) { if (result == null) {
updated = false; updated = false;
} else if (!updated) { } else if (!updated) {
// Comprobar si no tiene token, para hacer login transparente
if (PCBcontext.getRestapiWrapper().getToken() == null){
// Login transparente para el token
// Saco username y pass
//SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//String username = settings.getString("username", "");
// ....
} else{
// MOVER ESTO AL LISTENER DE RESULT
Log.i(this.getClass().getName(), "PCB reconnect"); Log.i(this.getClass().getName(), "PCB reconnect");
PCBcontext.getRoom().reconnect(); PCBcontext.getRoom().reconnect();
PCBcontext.getVocabulary().synchronize(); PCBcontext.getVocabulary().synchronize();
PCBcontext.getActionLog().batch(); PCBcontext.getActionLog().batch();
updated = true; updated = true;
} }
}
Log.i(this.getClass().getName(), "PCB status checked. Updated? " + updated); Log.i(this.getClass().getName(), "PCB status checked. Updated? " + updated);
notifyStatus();
} }
@Override @Override
public void error(Exception e) { public void error(Exception e) {
updated = false; 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());
notifyStatus();
} }
}); });
} }
private void notifyStatus() {
int notifyID=1;
this.builder = new NotificationCompat.Builder(PCBcontext.getContext());
Intent resultIntent = new Intent(PCBcontext.getContext(), PictogramActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(PCBcontext.getContext());
stackBuilder.addParentStack(PictogramActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
this.builder.setContentIntent(resultPendingIntent);
if (updated)
this.builder.setSmallIcon(R.drawable.picton)
.setContentTitle("Pictogram online")
.setContentText(PCBcontext.getContext().getResources().getString(R.string.pictogram_online));
else
this.builder.setSmallIcon(R.drawable.pictoff)
.setContentTitle("Pictogram offline")
.setContentText(PCBcontext.getContext().getResources().getString(R.string.pictogram_offline));
NotificationManager mNotificationManager =
(NotificationManager)PCBcontext.getContext().getSystemService(PCBcontext.getContext().NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(notifyID, this.builder.build());
}
} }
\ 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