@@ -26,56 +26,76 @@
import de .greenrobot .event .EventBus ;
/**
* Static class used to communicate with the webserver
* class used to communicate with the webserver
* Created by Brandon on 4/29/2015.
* @author Brandon Bell
* @author Josh Rueschenberg
* @author Alexander Cherry
*/
public class WebServiceHelper {
/** Base url for all the queries*/
private static final String BASE_URL = "http://450.atwebpages.com/" ;
/**Tag used to get the result status from the JSON object*/
private static final String RESULT_TAG = "result" ;
/**Tag used to obtain the error message from the JSON object*/
private static final String ERROR_TAG = "error" ;
/**tag use to get the userid from the ?*/
private static final String ID_TAG = "userid" ;
private JSONArray mArray ;
/**Tag used to get whether or not a query was successful*/
private static final String SUCCESS_TAG = "success" ;
/**Tag used with JSON object to get the message*/
private static final String MESSAGE_TAG = "message" ;
/**Used to retrieve failure message*/
private static final String FAIL_TAG = "fail" ;
// private JSONArray mArray;
protected JSONObject mJSONObject ;
private ProgressDialog mProgressDialog ;
private Context mContext ;
private String mCallingMethod ;
private DownloadWebPageTask mDownloadTask ;
/**
* Constructs a new instance of WebserviceHelper
* @param context for the asnyctask to affect.
*/
public WebServiceHelper (Context context ) {
mContext = context ;
mDownloadTask = new DownloadWebPageTask ();
mArray = null ;
mJSONObject = null ;
mCallingMethod = null ;
}
//******************************************************
//Query executors below here
//******************************************************
/**
* Adds a new user to the webservice
* @param email of the user
* @param password hashed password of the user
* @param question security question
* @param answer security answer
*/
public void addUser (final String email , final String password ,
final String question , final String answer ) {
//TODO check for and remove illegal characters using authenticator
String query = BASE_URL + "adduser.php?" + "email=" + email + "&password=" + password
+ "&question=" + question .replace (" " , "%20" ).replace ("?" , "%3F" )
+ "&answer=" + answer .replace (" " , "%20" );
// String result ="debug string";
Log .d ("WEBQUERY" , query );
mCallingMethod = "addUser" ;
mDownloadTask .execute (new String [] {query });
//problem is here, this code needs to wait for the task to complete before executing
}
/**
* Logs in a user
* @param email to log in with
* @param password to log in with
*/
public void loginUser (final String email , final String password ) {
mCallingMethod = "loginUser" ;
@@ -84,29 +104,42 @@ public void loginUser(final String email, final String password) {
mDownloadTask .execute (new String [] {query });
}
/**
* Resets the user's password
* @param email of the account to reset the password of.
*/
public void resetPassword (final String email ) {
mCallingMethod = "resetPassword" ;
String query = BASE_URL + "reset.php?email=" + email ;
mDownloadTask .execute (new String [] {query });
}
/**
* Queries the server for the TOS
*/
public void getAgreement () {
mCallingMethod = "getAgreement" ;
String query = BASE_URL + "agreement.php" ;
mDownloadTask .execute (new String [] {query });
}
/**
* Used by the Location database to log points to the webservice.
* @param cursor containing a reference to all rows of the database.
*/
public void logPoint (Cursor cursor ) {
SharedPreferences prefs = mContext .getSharedPreferences (mContext .getString (R .string .shared_pref_key ),
Context .MODE_PRIVATE );
Log .d ("CURSOR RECEIVED" , "" + cursor .getDouble (0 )
+ "Timestamp: " + cursor .getInt (5 ) + " UserID: " + cursor .getString (4 ));
//Obtain user id from shared preferences
String uid = prefs .getString (mContext .getString (R .string .saved_user_id_key ),
mContext .getString (R .string .default_restore_key ));
//TODO open up the database, select all rows, iterate through and log every point
mCallingMethod = "logPoint" ;
//build query
String query = BASE_URL
+ "logAdd.php?lat=" + cursor .getDouble (0 )
+ "&lon=" + cursor .getDouble (1 )
@@ -120,26 +153,28 @@ public void logPoint(Cursor cursor) {
}
/**
* Gets a range of points between from two specified dates.
* @param startDate
* @param endDate
*/
public void getRange (Date startDate , Date endDate ) {
SharedPreferences prefs = mContext .getSharedPreferences (mContext .getString (R .string .shared_pref_key ),
Context .MODE_PRIVATE );
String uid = prefs .getString (mContext .getString (R .string .saved_user_id_key ),
mContext .getString (R .string .default_restore_key ));
mCallingMethod = "getRange" ;
Log .d ("GETTINGRANGE" , "Initiated range query" );
/* Log.d("GETTINGRANGE", "Initiated range query");
Log.d("QTIME", "START DATE: " + startDate.toString());
Log.d("QTIME", "\nSTART TIME: " + (startDate.getTime() / 1000L));
Log.d("QTIME", "\nEND DATE: " + endDate.toString());
Log .d ("QTIME" , "\nEND TIME: " + (endDate .getTime () / 1000L ));
Log.d("QTIME", "\nEND TIME: " + (endDate.getTime() / 1000L));*/
String query = BASE_URL + "view.php?uid=" + uid
+ "&start=" + startDate .getTime () / 1000L
@@ -148,9 +183,9 @@ public void getRange(Date startDate, Date endDate) {
mDownloadTask .execute (query );
}
//**********************************************************
//Post execute methods below here
//**********************************************************
//****************************************************************
//Post execute methods below here; These contain most of the logic
//****************************************************************
/**
* Method to be called after thread has finished creating the user.
@@ -163,12 +198,12 @@ private void addUserPostExecute() {
if (mJSONObject != null ) {
try {
// JSONObject object = mArray.getJSONObject(0);
Log .d ("RAWJSONSTRING" , mJSONObject .toString ());
if (mJSONObject .getString (RESULT_TAG ).equals ("success" )) {
if (mJSONObject .getString (RESULT_TAG ).equals (SUCCESS_TAG )) {
Log .d ("WEBSERVICE" , "User successfully created" );
success = true ;
result = mJSONObject .getString ("message" );
result = mJSONObject .getString (MESSAGE_TAG );
} else {
Log .d ("ERRORSTRING" , mJSONObject .getString (ERROR_TAG ));
@@ -186,18 +221,21 @@ private void addUserPostExecute() {
}
mArray = null ;
// mArray = null;
}
}
/**
* Method to be called after the login query has been processed and returned from the server.
*/
private void loginUserPostExecute () {
String result = "debug string" ;
boolean success = false ;
if (mJSONObject != null ) {
try {
Log .d ("RAWJSONSTRING" , mJSONObject .toString ());
if (mJSONObject .getString (RESULT_TAG ).equals ("success" )) {
if (mJSONObject .getString (RESULT_TAG ).equals (SUCCESS_TAG )) {
mContext .getSharedPreferences (mContext .getString (R .string .shared_pref_key ),
Context .MODE_PRIVATE )
@@ -210,23 +248,23 @@ private void loginUserPostExecute() {
success = true ;
Log .d ("LOGINSUCCESS" , "login successful" );
}
else if (mJSONObject .getString (RESULT_TAG ).equals ("fail" )) {
result = mJSONObject .getString ("error" ); //TODO create constant
else if (mJSONObject .getString (RESULT_TAG ).equals (FAIL_TAG )) {
result = mJSONObject .getString (ERROR_TAG );
}
} catch (JSONException e ) {
Log .e ("LOGINFAILED" , "Login failed" );
e .printStackTrace ();
}
}
//Poptart.display(mContext, result, 2);
//Send off event to listeners.
EventBus .getDefault ().postSticky (new WebServiceEvent (result , success ));
Log .d ("LOGINEVENT" , "Event posted." );
//test change
}
/**Handles the post execute behavior of resetting the password.*/
private void resetPasswordPostExecute () {
String result = "debug string" ;
boolean success = false ;
@@ -238,14 +276,16 @@ private void resetPasswordPostExecute() {
String jsonResult = mJSONObject .getString (RESULT_TAG );
if (jsonResult .equals ("success" )) {
result = mJSONObject .getString ("message" );
if (jsonResult .equals (SUCCESS_TAG )) {
result = mJSONObject .getString (MESSAGE_TAG );
success = true ;
} else {
result = mJSONObject .getString ("error" );
result = mJSONObject .getString (ERROR_TAG );
}
Log .d ("RESETRESULT" , "reset success" );
//Send off event
EventBus .getDefault ().postSticky (new WebServiceEvent (result , success ));
} catch (JSONException e ) {
@@ -256,8 +296,12 @@ private void resetPasswordPostExecute() {
Log .d ("RESETPOSTED" , "Posted reset result." );
}
}
/**
* Handles the post execute behavior for getting the agreement from the webservice.
* Sends off the result to register activity via EventBus
*/
private void getAgreementPostExecute () {
// boolean success = true;
if (mJSONObject != null ) {
try {
@@ -270,13 +314,16 @@ private void getAgreementPostExecute() {
}
}
/**
* Handles post execute behavior for logging points.
*/
private void logPointPostExecute () {
//nothing to display to the user directly. All return data is for debugging.
if (mJSONObject != null ) {
try {
String jsonResult = mJSONObject .getString (RESULT_TAG );
if (jsonResult .equals ("success" )) {
if (jsonResult .equals (SUCCESS_TAG )) {
Log .d ("PLOGSUCCESS" , "Logged point successfully" );
} else {
Log .e ("PLOGFAIL" , mJSONObject .getString ("error" ));
@@ -289,6 +336,9 @@ private void logPointPostExecute() {
}
/**
* Handles the post execute bhavior for getting a range of locations.
*/
private void getRangePostExecute () {
boolean success = false ;
String eventMessage = "move along, nothing to see here." ;
@@ -297,13 +347,14 @@ private void getRangePostExecute() {
String result = mJSONObject .getString (RESULT_TAG );
ArrayList <Location > locArr = new ArrayList <>();
if (result .equals ("success" )) {
if (result .equals (SUCCESS_TAG )) {
JSONArray jsonArray = mJSONObject .getJSONArray ("points" ); // actually gets locations
Log .d ("RETRIEVED" , "Points retrieved from webservice" );
for (int i = 0 ; i < jsonArray .length (); i ++) {
JSONObject currObject = jsonArray .getJSONObject (i );
//Create temporary location
Location loc = new Location ("temploc" );
//add current location to array
loc .setLatitude (currObject .getDouble ("lat" ));
@@ -314,67 +365,89 @@ private void getRangePostExecute() {
locArr .add (loc );
}//endfor
eventMessage = "Retrieved Locations successfully." ;
success = true ;
} else {
Log .d ("NOPOINTS" , "No points to retrieve" );
eventMessage = mJSONObject .getString ("error" );
eventMessage = mJSONObject .getString (ERROR_TAG );
}
//Send off locations to the activity
EventBus .getDefault ().postSticky (new LocationEvent (eventMessage , locArr , success ));
} catch (JSONException e ) {
e .printStackTrace ();
eventMessage = "Yo code broke son." ;
}
}
}
/**
* Event class used to send locations to the tracking fragment.
*/
public class LocationEvent {
/**Message for this event*/
public final String mEventMessage ;
/**Collection of Locations queried from the getRange method*/
public final ArrayList <Location > mLocations ;
/**Whether or not this event was successful*/
public final boolean mSuccess ;
/**
* Public constructor
* @param mEventMessage
* @param theArr of Locations
* @param theSucc whether or not the query was successful
*/
public LocationEvent (String mEventMessage , ArrayList <Location > theArr , boolean theSucc ) {
this .mEventMessage = mEventMessage ;
this .mLocations = theArr ;
this .mSuccess = theSucc ;
}
}
/**
* Event used to send the agreement obtained through the getAgreement method.
*/
public class AgreementEvent {
/**Html formatted string containing our agreement string*/
public final String theAgreement ;
/**
* Public constructor
* @param theString containing the agreement
*/
public AgreementEvent (final String theString ) {
theAgreement = theString ;
}
}
/**
* Event used to notify activities that the webservice completed.
* Sends the message returned by the query who sends the event.
*/
public class WebServiceEvent {
/** Message to be displayed on the receiver's end.*/
public final String message ;
/** Whether or not the query reached success*/
public final boolean success ;
/**
* Public constructor
* @param message
* @param success
*/
public WebServiceEvent (String message , boolean success ) {
this .message = message ;
this .success = success ;
}
}
//not sure if making it static is kosher, we'll see.
/**
* Private Asynctask used to process all queries to the webservice.
* Mostly boilerplate code for retrieving a JSON string from the webservice.
*/
private class DownloadWebPageTask extends AsyncTask <String , Void , String > {
@ Override
@@ -421,28 +494,24 @@ protected void onPostExecute(String result) {
if (!mCallingMethod .equals ("logPoint" ) && !mCallingMethod .equals ("getRange" )) {
mProgressDialog .dismiss ();//push
}
String queryResult = result ; //redundant, can probably remove
if (queryResult != null ) {
if (result != null ) {
try {
// mArray = new JSONArray(result);
mJSONObject = new JSONObject (result );
Log .d ("JSONOBJECT" , "JSON object created." );
// JSONObject object = arr.getJSONObject()
//Where the magic happens
postExecuteHandler ();
} catch (Exception e ) {
Log .e ("JSON-E" , "JSONEXCEPTION thrown" );
e .printStackTrace ();
}
}
}
/**
* Tests for which method created a query and calls the post execute method accordingly.
*/
private void postExecuteHandler () {
switch (mCallingMethod ) {
case "addUser" :
addUserPostExecute ();
break ;
@@ -462,12 +531,9 @@ private void postExecuteHandler() {
getRangePostExecute ();
break ;
default :
break ;
}
mCallingMethod = null ;
}
}
}