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;
/**
......@@ -85,7 +82,7 @@ public class RestapiWrapper {
}
public void ask(String operation, iRestapiListener listener) {
this.ask(operation, null, "get", listener);
this.ask(operation, null, "get", listener);
}
/**
......@@ -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;
}
......@@ -133,12 +134,12 @@ public class RestapiWrapper {
URL url = null;
if (params!=null) {
surl += '?';
for (String param : params.keySet()) {
String value = params.get(param);
surl += param + '=' + value + '&';
}
surl=surl.substring(0,surl.length()-1);
surl += '?';
for (String param : params.keySet()) {
String value = params.get(param);
surl += param + '=' + value + '&';
}
surl=surl.substring(0,surl.length()-1);
}
url = new URL(surl);
HttpURLConnection urlConnection = null;
......@@ -154,60 +155,60 @@ public class RestapiWrapper {
if (inputStream!=null) result = convertInputStreamToString(inputStream);
return result;
}
public String POST(String surl, String request_method, Hashtable<String, String> params, boolean json_params) throws IOException {
URL url = null;
String response = "";
url = new URL(surl);
HttpURLConnection urlConnection = null;
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(60000);
urlConnection.setConnectTimeout(60000);
urlConnection.setRequestMethod(request_method);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
if (json_params) {
urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
urlConnection.setRequestProperty("Accept", "application/json, text/plain, */*");
}
String sparams;
if (json_params) {
sparams = params.get("json");
params.remove("json");
} else
sparams="";
for (String param : params.keySet()) {
String value = params.get(param);
if (param.equals("token"))
urlConnection.setRequestProperty("Authorization", "Bearer " + value);
else {
if (sparams.length() > 0) sparams += '&';
sparams += param + '=' + value;
}
url = new URL(surl);
HttpURLConnection urlConnection = null;
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(60000);
urlConnection.setConnectTimeout(60000);
urlConnection.setRequestMethod(request_method);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
if (json_params) {
urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
urlConnection.setRequestProperty("Accept", "application/json, text/plain, */*");
}
String sparams;
if (json_params) {
sparams = params.get("json");
params.remove("json");
} else
sparams="";
for (String param : params.keySet()) {
String value = params.get(param);
if (param.equals("token"))
urlConnection.setRequestProperty("Authorization", "Bearer " + value);
else {
if (sparams.length() > 0) sparams += '&';
sparams += param + '=' + value;
}
}
//Send request
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes(sparams);
wr.flush();
wr.close();
//Send request
DataOutputStream wr = new DataOutputStream (
urlConnection.getOutputStream ());
wr.writeBytes(sparams);
wr.flush();
wr.close();
OutputStream os = urlConnection.getOutputStream();
os.close();
int responseCode=urlConnection.getResponseCode();
OutputStream os = urlConnection.getOutputStream();
os.close();
int responseCode=urlConnection.getResponseCode();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(responseCode == HttpsURLConnection.HTTP_OK
? urlConnection.getInputStream()
: urlConnection.getErrorStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(responseCode == HttpsURLConnection.HTTP_OK
? urlConnection.getInputStream()
: urlConnection.getErrorStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
return response;
}
......@@ -241,8 +242,8 @@ public class RestapiWrapper {
protected HttpAsyncTaskParams doInBackground(HttpAsyncTaskParams... params) {
try {
params[0].result = params[0].request_method.equalsIgnoreCase("GET")
? GET(params[0].url, params[0].url_params)
: POST(params[0].url, params[0].request_method, params[0].url_params, params[0].json_params);
? GET(params[0].url, params[0].url_params)
: POST(params[0].url, params[0].request_method, params[0].url_params, params[0].json_params);
} catch (IOException e) {
Log.e(com.yottacode.net.RestapiWrapper.class.getName(), "Error:" + e.getLocalizedMessage() + " when asking for " + params[0].url);
params[0].result=null;
......
......@@ -235,14 +235,14 @@ public class Device extends SQLiteOpenHelper {
Vector<User> users=null;
Cursor cursor = db.query("supervisor", null, null, null, null, null, null, null);
while (cursor.moveToNext() && users == null && !user_found) {
user_found = cursor.getString(1).equalsIgnoreCase(auser);
if (user_found)
if (cursor.getString(2).equals(apwd)) {
users = recoverStudents(cursor.getInt(0));
if (users.size() == 0)
throw new LoginException("Supervisor hasn't got students", false, true, true);
}
else throw new LoginException("Supervisor password incorrect", false, true,false);
user_found = cursor.getString(1).equalsIgnoreCase(auser);
if (user_found)
if (cursor.getString(2).equals(apwd)) {
users = recoverStudents(cursor.getInt(0));
if (users.size() == 0)
throw new LoginException("Supervisor hasn't got students", false, true, true);
}
else throw new LoginException("Supervisor password incorrect", false, true,false);
}
cursor.close();
if (!user_found) {
......
......@@ -51,7 +51,8 @@ public class Vocabulary implements Iterable<Picto> {
}else
try {
PCBcontext.getPcbdb().getStudentVocabulary(this);
listener.loadComplete();
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);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
});
alertDialog.show();
} 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,38 +28,32 @@ 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() {
@Override
public void preExecute() {
}
}
@Override
public void result(JSONArray result) {
@Override
public void result(JSONArray result) {
}
}
@Override
public void result(JSONObject result) {
updated=true;
notifyStatus();
}
@Override
public void result(JSONObject result) {
updated=true;
}
@Override
public void error(Exception e) {
updated=false;
notifyStatus();
}
});
@Override
public void error(Exception e) {
updated=false;
}
});
Log.i(this.getClass().getName(), "Checking Pictogram server access...");
Log.i(this.getClass().getName(), this.updated ? "Pictogram server access ok" : "Pictogram server access failed, Internet connection available?");
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
......@@ -96,51 +84,32 @@ public class NetService implements Runnable {
if (result == null) {
updated = false;
} else if (!updated) {
Log.i(this.getClass().getName(), "PCB reconnect");
PCBcontext.getRoom().reconnect();
PCBcontext.getVocabulary().synchronize();
PCBcontext.getActionLog().batch();
updated = true;
// 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