Modificaciones para el modo OFFLINE

parent ad83e21c
package com.yottacode.net;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.concurrent.Executor;
import java.net.UnknownHostException;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;
import com.google.gson.JsonParser;
import com.koushikdutta.async.parser.JSONObjectParser;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.HttpsURLConnection;
/**
......@@ -119,10 +116,14 @@ public class RestapiWrapper {
boolean pingResult = false;
try {
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) {
e.printStackTrace();
Log.e(com.yottacode.net.RestapiWrapper.class.getName(), "ping failed at"+ping_op);
error_listener.error(e);
//error_listener.error(e);
}
return pingResult;
}
......
......@@ -51,6 +51,7 @@ public class Vocabulary implements Iterable<Picto> {
}else
try {
PCBcontext.getPcbdb().getStudentVocabulary(this);
if (listener!=null)
listener.loadComplete();
} catch (JSONException e) {
Log.e(this.getClass().getName(),"Local vocabulary recover failed: "+e.getMessage());
......
......@@ -2,11 +2,7 @@ package com.yottacode.pictogram.gui;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
......@@ -14,16 +10,14 @@ import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.yottacode.pictogram.dao.LoginException;
import com.yottacode.pictogram.dao.User;
import com.yottacode.pictogram.R;
import com.yottacode.net.iRestapiListener;
import com.yottacode.net.SSLDummyContext;
import com.yottacode.net.RestapiWrapper;
import com.yottacode.pictogram.net.NetService;
import com.yottacode.pictogram.tools.Img;
import com.yottacode.pictogram.tools.PCBcontext;
import com.yottacode.pictogram.net.iImgDownloaderListener;
......@@ -32,7 +26,6 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
......@@ -64,6 +57,8 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
private ProgressDialog progressDialog;
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
......@@ -76,6 +71,13 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
super.onCreate(savedInstanceState);
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
//startLockTask();
//DevicePolicyManager myDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
......@@ -108,22 +110,74 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
SSLDummyContext.init(getResources().getBoolean(R.bool.ssl_connect));
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)) {
// No puedo comprobar si el serial es válido. Muestro un alertdialog de error, y cierro la aplicación
AlertDialog alertDialog = new AlertDialog.Builder(
LoginActivity.this).create();
alertDialog.setTitle(getResources().getString(R.string.systemMessage));
alertDialog.setMessage(getResources().getString(R.string.noInternetConnection));
//alertDialog.setIcon(R.drawable.tick);
alertDialog.setButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.exitingApp), Toast.LENGTH_SHORT).show();
// MODO OFFLINE
try {
Log.d(LOG_TAG, "username guardado:" + username);
Log.d(LOG_TAG, "password guardado:" + password);
Vector<User> localUsers = PCBcontext.getDevice().findUser(username, password);
// Si sólo hay 1 estudiante, cargo el st_id
if (localUsers.size() == 1){
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{
// NUEVO
// Modo ONLINE
sup_id = getIntent().getExtras().getInt("sup_id");
token = getIntent().getExtras().getString("token");
......@@ -153,10 +207,9 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
}
@Override
public void result(JSONArray students_supervisors) { //FERNANDO
public void result(JSONArray students_supervisors) {
try {
// Saco los pares estudiante-supervisor
// looping through All Students
Vector<User> users = new Vector<User>(students_supervisors.length());
if (students_supervisors.length() == 0){
......@@ -166,10 +219,6 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
.setCancelable(false)
.setPositiveButton("Entendido y salir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Salgo de la aplicación
// ????
//System.exit(0);
//finish();
}
});
AlertDialog alert = builder.create();
......@@ -200,7 +249,7 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
int st_supervision_int = st_supervision.intValue();
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,
sup_id, "nickname_sup","pwd_sup","", "", "", "M", "es-es", "");
sup_id, username, password,"", "", "", "M", "es-es", "");
users.add(student);
}
}
......@@ -214,7 +263,7 @@ public class LoginActivity extends FragmentActivity implements iRestapiListener{
} else{
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() {
@Override
public void loadComplete() {
......
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 com.yottacode.net.RestapiWrapper;
import com.yottacode.net.iRestapiListener;
import com.yottacode.pictogram.R;
import com.yottacode.pictogram.gui.PictogramActivity;
import com.yottacode.pictogram.tools.PCBcontext;
import org.json.JSONArray;
......@@ -34,16 +28,12 @@ import java.util.concurrent.TimeUnit;
public class NetService implements Runnable {
public static final String PREFS_NAME = "MyPrefsFile";
static final String ping_session="server/ping";
private boolean updated;
private NotificationCompat.Builder builder;
public NetService(int delay) {
this.updated=RestapiWrapper.ping(PCBcontext.getContext().getResources().getString(R.string.server), ping_session, new iRestapiListener() {
@Override
public void preExecute() {
......@@ -57,13 +47,11 @@ public class NetService implements Runnable {
@Override
public void result(JSONObject result) {
updated=true;
notifyStatus();
}
@Override
public void error(Exception e) {
updated=false;
notifyStatus();
}
});
Log.i(this.getClass().getName(), "Checking Pictogram server access...");
......@@ -96,51 +84,32 @@ public class NetService implements Runnable {
if (result == null) {
updated = false;
} 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");
PCBcontext.getRoom().reconnect();
PCBcontext.getVocabulary().synchronize();
PCBcontext.getActionLog().batch();
updated = true;
}
}
Log.i(this.getClass().getName(), "PCB status checked. Updated? " + updated);
notifyStatus();
}
@Override
public void error(Exception e) {
updated = false;
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