issues #459,#460, #461 closed

parent fab68c4d
......@@ -13,7 +13,7 @@
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="jdk" jdkName="1.7" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
......@@ -8,11 +8,13 @@ import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InterfaceAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Hashtable;
import org.apache.http.client.HttpResponseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -23,6 +25,9 @@ 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;
......@@ -42,6 +47,9 @@ public class RestapiWrapper {
String server;
String token;
public static final int TIME_OUT=10000;
private static final String SERVER_RESULT="result";
private static final String SERVER_ERROR="error";
// String constant for logs
private final String LOG_TAG = this.getClass().getSimpleName(); // Or .getCanonicalName()
......@@ -130,10 +138,32 @@ public class RestapiWrapper {
return pingResult;
}
public static String GET(String surl, Hashtable<String, String> params) throws IOException {
String result=null;
InputStream inputStream = null;
URL url = null;
private static JSONObject resultToJSON(HttpURLConnection urlConnection) throws IOException {
int responseCode=urlConnection.getResponseCode();
String response="'";
String line;
JSONObject JSONresponse;
BufferedReader br = new BufferedReader(new InputStreamReader(responseCode == HttpsURLConnection.HTTP_OK
? urlConnection.getInputStream()
: urlConnection.getErrorStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
response+="'";
try {
JSONresponse = new JSONObject("{ "+SERVER_RESULT+": " + response + (responseCode == HttpsURLConnection.HTTP_OK
? "}"
: ", "+SERVER_ERROR+": " + responseCode +"}"));
} catch (JSONException e) {
JSONresponse = null;
Log.e(RestapiWrapper.class.getCanonicalName(),e.getMessage());
}
return JSONresponse;
}
public static JSONObject GET(String surl, Hashtable<String, String> params) throws IOException {
URL url;
if (params!=null) {
surl += '?';
......@@ -151,25 +181,12 @@ public class RestapiWrapper {
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
// convert inputstream to string
if (inputStream!=null) result = convertInputStreamToString(inputStream);
if (result.equals("") && urlConnection.getResponseCode() == 200) {
result = "{ result: \"OK\" }";
} else if (result.equals("")) {
result = "{ error: " + urlConnection.getResponseCode() + " }";
}
return result;
return RestapiWrapper.resultToJSON(urlConnection);
}
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);
public JSONObject POST(String surl, String request_method, Hashtable<String, String> params, boolean json_params) throws IOException {
URL url = new URL(surl);
HttpURLConnection urlConnection = null;
urlConnection = (HttpsURLConnection) url.openConnection();
......@@ -206,35 +223,9 @@ public class RestapiWrapper {
wr.flush();
wr.close();
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;
}
if (response.equals("") && responseCode != HttpsURLConnection.HTTP_OK) {
response = "{ error: " + responseCode + " }";
}
return response;
return RestapiWrapper.resultToJSON(urlConnection);
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
private class HttpAsyncTaskParams {
protected String request_method;
......@@ -252,10 +243,13 @@ public class RestapiWrapper {
@Override
protected HttpAsyncTaskParams doInBackground(HttpAsyncTaskParams... params) {
try {
params[0].result = params[0].request_method.equalsIgnoreCase("GET")
JSONObject jresult = 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);
} catch (IOException e) {
params[0].result=jresult.getString(SERVER_RESULT);
if (jresult.has(SERVER_ERROR))
params[0].error= new HttpResponseException(Integer.parseInt(jresult.getString(SERVER_ERROR)),params[0].result);
} catch (Exception e) {
Log.e(com.yottacode.net.RestapiWrapper.class.getName(), "Error: '" + e.getLocalizedMessage() + "' when asking for " + params[0].url);
params[0].result=null;
params[0].error=e;
......@@ -269,8 +263,9 @@ public class RestapiWrapper {
try {
if (params.error!=null) params.listener.error(params.error);
else
if(params.result!=null) {
if(params.result.length()>0) {
Log.i(LOG_TAG, "Picto JSON Result: " + params.result);
JSONTokener tokener=new JSONTokener(params.result);
Object jsonResult = new JSONTokener(params.result).nextValue();
if (jsonResult instanceof JSONObject) {
......
......@@ -249,7 +249,7 @@ public class Device extends SQLiteOpenHelper {
if (users.size() == 0)
throw new LoginException("Supervisor hasn't got students", LoginException.NO_STUDENTS);
}
else throw new LoginException("Supervisor password incorrect", LoginException.BAD_PASSWORD);
else throw new LoginException("Supervisor password incorrect", LoginException.BAD_LOGIN);
}
cursor.close();
if (!user_found) {
......@@ -262,12 +262,12 @@ public class Device extends SQLiteOpenHelper {
users.add(new User(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8),
User.NO_SUPERVISOR, "", "", "", "", "", "", "", ""));
}
else throw new LoginException("Student password incorrect", LoginException.BAD_PASSWORD);
else throw new LoginException("Student password incorrect", LoginException.BAD_LOGIN);
}
cursor.close();
}
if (!user_found) throw new LoginException("User not found", LoginException.UNKNOWN_USERNAME);
if (!user_found) throw new LoginException("User not found", LoginException.BAD_LOGIN);
db.close();
return users;
......
......@@ -4,9 +4,7 @@ package com.yottacode.pictogram.dao;
* Created by Fernando on 15/03/2016.
*/
public class LoginException extends Exception{
public static final int UNKNOWN_USERNAME=0;
public static final int BAD_PASSWORD=1;
public static final int BAD_LOGIN=1;
public static final int NO_STUDENTS=2;
int code;
public LoginException(String msg, int code) {
......@@ -15,11 +13,10 @@ public class LoginException extends Exception{
}
public boolean no_username_found() {return this.code==LoginException.UNKNOWN_USERNAME;}
public boolean no_pwd_found() {return this.code==LoginException.BAD_PASSWORD;}
public boolean login_failed() {return this.code==LoginException.BAD_LOGIN;}
public boolean no_supervisor_students() {return this.code==LoginException.NO_STUDENTS;}
public String getLocalizedMessage() {
return super.getLocalizedMessage()+" Username found:"+!no_username_found()+" Password found"+!no_pwd_found()+"Supervisor without students:"+no_supervisor_students();
return super.getLocalizedMessage()+" Login ok:"+!login_failed()+" Supervisor without students:"+no_supervisor_students();
}
}
......@@ -51,6 +51,12 @@ public class MainActivity extends Activity {
}
@Override
protected void onDestroy() {
super.onDestroy();
PCBcontext.getNetService().closeNotifyStatus();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
......
......@@ -160,6 +160,7 @@ public class PictogramActivity extends Activity implements iVocabularyListener,
} else {
this.showPictoMainGridView();
}
}
@Override
......@@ -175,7 +176,7 @@ public class PictogramActivity extends Activity implements iVocabularyListener,
if (tts != null){
tts.shutdown();
}
PCBcontext.getNetService().closeNotifyStatus();
// PCBcontext.getNetService().closeNotifyStatus();
}
/**
......
......@@ -113,12 +113,11 @@ public class SerialActivity extends Activity {
}
@Override
public void error(Exception e) {
Log.i(this.getClass().getCanonicalName(),"Login fail:"+e.getMessage()+" ("+e.getClass().getCanonicalName()+")");
progressDialog.dismiss();
if (e instanceof LoginException)
if (((LoginException)e).no_pwd_found())
GUITools.show_alert(SerialActivity.this, R.string.passErrorMsg);
else if (((LoginException)e).no_username_found())
GUITools.show_alert(SerialActivity.this, R.string.userErrorMsg);
if (((LoginException)e).login_failed())
GUITools.show_alert(SerialActivity.this, R.string.loginErrorMsg);
else if (((LoginException)e).no_supervisor_students())
GUITools.show_alert(SerialActivity.this, R.string.noStudentsError);
else
......@@ -149,9 +148,7 @@ public class SerialActivity extends Activity {
} catch (JSONException e) {
e.printStackTrace();
} catch (LoginException e) {
if (e.no_pwd_found())
GUITools.show_alert(this, R.string.passErrorMsg);
else if (e.no_username_found())
if (e.login_failed())
GUITools.show_alert(this, R.string.userInetErrorMsg);
else if (e.no_supervisor_students())
GUITools.show_alert(this, R.string.noStudentsError);
......@@ -210,12 +207,11 @@ public class SerialActivity extends Activity {
}
@Override
public void error(Exception e) {
Log.d("login_student LISTENER ",e.getMessage());
progressDialog.dismiss();
if (e instanceof LoginException)
if (((LoginException)e).no_pwd_found())
GUITools.show_alert(SerialActivity.this, R.string.passErrorMsg);
else if (((LoginException)e).no_username_found())
GUITools.show_alert(SerialActivity.this, R.string.userErrorMsg);
if (((LoginException)e).login_failed())
GUITools.show_alert(SerialActivity.this, R.string.loginErrorMsg);
else
GUITools.show_alert(SerialActivity.this, R.string.serverError, e.getMessage());
Log.e(this.getClass().getCanonicalName(), "Server error:"+ e.getLocalizedMessage());
......@@ -232,9 +228,7 @@ public class SerialActivity extends Activity {
} catch (JSONException e) {
e.printStackTrace();
} catch (LoginException e) {
GUITools.show_alert(this, e.no_username_found()
? R.string.userInetErrorMsg
: R.string.passErrorMsg);
GUITools.show_alert(this, R.string.userInetErrorMsg);
}
} //offline student login
}
......
......@@ -131,7 +131,8 @@ public class StudentFragmentGrid extends Fragment{
}
public void error(Exception e) {
GUITools.show_alert(PCBcontext.getContext(), R.string.serverError, e.getMessage());
progressDialog.dismiss();
GUITools.show_alert(StudentFragmentGrid.this.getActivity(), R.string.serverError, e.getMessage());
Log.e(this.getClass().getCanonicalName(), "Server error:"+ e.getLocalizedMessage());
}
});
......@@ -232,7 +233,7 @@ public class StudentFragmentGrid extends Fragment{
}
switch (students.length()) {
case 0:
GUITools.show_alert(getActivity(), R.string.LoginError,getString(R.string.noStudentsError), new GUITools.iOKListener() {
GUITools.show_alert(getActivity(), R.string.loginErrorTxt,getString(R.string.noStudentsError), new GUITools.iOKListener() {
@Override
public void ok() {
PCBcontext.restart_app();
......
......@@ -128,9 +128,7 @@ public class NetService implements Runnable {
@Override
public void result(JSONObject result) {
if (result == null) {
updated = false;
} else if (!updated) {
if (!updated) {
// Comprobar si hay usuario offline, para hacer login transparente
if (PCBcontext.is_user_offline()){
login();
......
package com.yottacode.pictogram.net;
import android.util.Log;
import com.yottacode.net.RestapiWrapper;
import com.yottacode.net.iRestapiListener;
import com.yottacode.pictogram.dao.LoginException;
import com.yottacode.pictogram.tools.PCBcontext;
......@@ -15,23 +18,6 @@ import java.util.Hashtable;
*/
public class ServerLogin {
private static void checkLogin(JSONObject result) throws LoginException {
String error;
try {
error=result.has("error")
? result.getString("error")
: null;
} catch (JSONException e) {
e.printStackTrace();
error=null;
}
if (error!=null){
if (error.toLowerCase().contains("password") || error.contains("No credentials sent"))
throw new LoginException(error, LoginException.BAD_PASSWORD);
else if (error.toLowerCase().contains("user"))
throw new LoginException(error, LoginException.UNKNOWN_USERNAME);
}
}
public static void login_student(String username, String password, iRestapiListener listener) {
login("stu/login", null, username, password, listener);
}
......@@ -60,7 +46,6 @@ public class ServerLogin {
public void result(JSONObject result) {
try {
checkLogin(result);
if (PCBcontext.is_user_offline()) {
final String TAG_TOKEN="token";
PCBcontext.getPcbdb().user_online(true);
......@@ -68,8 +53,6 @@ public class ServerLogin {
PCBcontext.getVocabulary().synchronize();
}
listener.result(result);
} catch (LoginException e) {
listener.error(e);
} catch (JSONException e) {
listener.error(e);
}
......@@ -77,7 +60,7 @@ public class ServerLogin {
@Override
public void error(Exception e) {
listener.error(e);
listener.error(new LoginException(e.getMessage(),LoginException.BAD_LOGIN));
}
});
}
......
......@@ -98,6 +98,7 @@ public final class PCBcontext {
PCBcontext.getContext().startActivity(serialActivity);
}
/**
* @return true if the user is logged offline and it has not been online previously. False in
* other case (user not logged, user logged online, user offline but it was previously online
......
......@@ -17,10 +17,8 @@
<string name="title_activity_splash_screen">SplashScreenActivity</string>
<string name="logout">Logout</string>
<string name="loginTitle">Who are you?</string>
<string name="LoginError">Login</string>
<string name="passErrorMsg">This password is not correct. Try again.</string>
<string name="userErrorTxt">User not found</string>
<string name="userErrorMsg">Unknown user name</string>
<string name="loginErrorTxt">Login</string>
<string name="loginErrorMsg">El usuario no existe o la contraseña indicada no es correcta. Inténtelo de nuevo.</string>
<string name="userInetErrorMsg">Unknown new user name because Internet conection is not available</string>
<string name="userLoadingTxt">Loading</string>
<string name="userLoadingMsg">Loading students. Please wait.</string>
......
......@@ -18,12 +18,8 @@
<string name="action_entrar">Entrar</string>
<string name="logout">Cerrar sesión</string>
<string name="loginTitle">¿Quién eres?</string>
<string name="LoginError">Login</string>
<string name="passErrorMsg">La contraseña indicada no es correcta. Inténtelo de nuevo.</string>
<string name="userErrorTxt">User not found</string>
<string name="userErrorMsg">Nombre de usuario desconocido</string>
<string name="userLoadingTxt">Cargando</string>
<string name="userLoadingMsg">Cargando alumnos. Por favor espere.</string>
<string name="loginErrorTxt">Login</string>
<string name="loginErrorMsg">El usuario no existe o la contraseña indicada no es correcta. Inténtelo de nuevo.</string>
<string name="imguserLoadingMsg">Cargando imágenes de los alumnos. Por favor espere.</string>
<string name="noStudentsError">El usuario indicado no tiene alumnos asignados. Asigne estudiantes desde el panel de control</string>
......
......@@ -18,11 +18,9 @@
<string name="action_entrar">Entrar</string>
<string name="logout">Cerrar sesión</string>
<string name="loginTitle">¿Quién eres?</string>
<string name="LoginError">Login</string>
<string name="passErrorMsg">La contraseña indicada no es correcta. Inténtelo de nuevo.</string>
<string name="userErrorTxt">Usuario no encontrado</string>
<string name="userErrorMsg">Nombre de usuario desconocido</string>
<string name="userInetErrorMsg">Nombre de usuario nuevo no se pudo comprobar porque no hay conexión a internet</string>
<string name="loginErrorTxt">Login</string>
<string name="loginErrorMsg">El usuario no existe o la contraseña indicada no es correcta. Inténtelo de nuevo.</string>
<string name="userInetErrorMsg">Este usuario requiere conexión a internet para ser validado</string>
<string name="userLoadingTxt">Cargando</string>
<string name="userLoadingMsg">Cargando alumnos. Por favor espere.</string>
<string name="imguserLoadingMsg">Cargando imágenes de los alumnos. Por favor espere.</string>
......
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