Finished initial conversion of WebApiConnection to use Firebase. Need to update LogManager to use string IDs to make it compatible.

This commit is contained in:
Graham Jones
2022-03-18 21:01:59 +00:00
parent 542fc42e5d
commit f509e470d4
5 changed files with 201 additions and 386 deletions

View File

@@ -38,6 +38,7 @@ dependencies {
implementation 'androidx.constraintlayout:constraintlayout:2.1.3' implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'com.google.android.material:material:1.4.0' implementation 'com.google.android.material:material:1.4.0'
implementation 'com.google.firebase:firebase-auth:19.2.0' implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'androidx.test:core:1.4.0'
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
// Set this dependency if you want to use Mockito // Set this dependency if you want to use Mockito
testImplementation 'org.mockito:mockito-core:4.3.1' testImplementation 'org.mockito:mockito-core:4.3.1'

View File

@@ -35,7 +35,7 @@ public class EditEventActivity extends AppCompatActivity {
private HashMap<String, ArrayList<String>> mEventSubTypesHashMap = null; private HashMap<String, ArrayList<String>> mEventSubTypesHashMap = null;
private String mEventTypeStr = null; private String mEventTypeStr = null;
private String mEventSubTypeStr = null; private String mEventSubTypeStr = null;
private Long mEventId; private String mEventId;
private String mEventNotes = ""; private String mEventNotes = "";
//private Date mEventDateTime; //private Date mEventDateTime;
private RadioGroup mEventTypeRg; private RadioGroup mEventTypeRg;
@@ -59,7 +59,7 @@ public class EditEventActivity extends AppCompatActivity {
Bundle extras = getIntent().getExtras(); Bundle extras = getIntent().getExtras();
if (extras != null) { if (extras != null) {
Long eventId = extras.getLong("eventId"); String eventId = extras.getString("eventId");
mEventId = eventId; mEventId = eventId;
Log.v(TAG, "onCreate - mEventId=" + mEventId); Log.v(TAG, "onCreate - mEventId=" + mEventId);
} }

View File

@@ -14,11 +14,16 @@ import com.android.volley.VolleyError;
import com.android.volley.VolleyLog; import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley; import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@@ -65,28 +70,28 @@ public class WebApiConnection {
// Check if we are already logged in // Check if we are already logged in
FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth != null) { if (auth != null) {
Log.i(TAG,"Firebase Logged in OK"); Log.i(TAG, "Firebase Logged in OK");
mDb = FirebaseFirestore.getInstance(); mDb = FirebaseFirestore.getInstance();
} else { } else {
Log.e(TAG,"Firebase not logged in"); Log.e(TAG, "Firebase not logged in");
mDb = null; mDb = null;
} }
} }
public void close() { public void close() {
Log.i(TAG,"stop()"); Log.i(TAG, "stop()");
mQueue.stop(); mQueue.stop();
} }
public boolean isLoggedIn() { public boolean isLoggedIn() {
FirebaseAuth auth = FirebaseAuth.getInstance(); FirebaseAuth auth = FirebaseAuth.getInstance();
if (auth != null) { if (auth != null) {
Log.v(TAG,"isLoggedIn(): Firebase Logged in OK"); Log.v(TAG, "isLoggedIn(): Firebase Logged in OK");
return(false); return (false);
} else { } else {
Log.v(TAG,"isLoggedIn(): Firebase not logged in"); Log.v(TAG, "isLoggedIn(): Firebase not logged in");
return(true); return (true);
} }
} }
@@ -100,11 +105,12 @@ public class WebApiConnection {
// Create a new event in the remote database, based on the provided parameters. // Create a new event in the remote database, based on the provided parameters.
// passes the newly created documentId to function callback on successful completion, or null on error.
public boolean createEvent(final int osdAlarmState, final Date eventDate, final String eventDesc, StringCallback callback) { public boolean createEvent(final int osdAlarmState, final Date eventDate, final String eventDesc, StringCallback callback) {
Log.v(TAG, "createEvent()"); Log.v(TAG, "createEvent()");
String userId = null; String userId = null;
if (FirebaseAuth.getInstance().getCurrentUser() == null) { if (FirebaseAuth.getInstance().getCurrentUser() == null) {
Log.e(TAG,"ERROR: createEvent() - not logged in"); Log.e(TAG, "ERROR: createEvent() - not logged in");
return false; return false;
} else { } else {
userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
@@ -122,74 +128,52 @@ public class WebApiConnection {
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() { .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override @Override
public void onSuccess(DocumentReference documentReference) { public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); Log.d(TAG, "createEvent.onSuccess() - DocumentSnapshot added with ID: " + documentReference.getId());
mServerConnectionOk = true; mServerConnectionOk = true;
callback.accept("OK"); callback.accept(documentReference.getId());
} }
}) })
.addOnFailureListener(new OnFailureListener() { .addOnFailureListener(new OnFailureListener() {
@Override @Override
public void onFailure(@NonNull Exception e) { public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e); Log.w(TAG, "createEvent.onFailure() - Error adding document", e);
callback.accept(null); callback.accept(null);
} }
}); });
return(true);
}
public boolean getEvent(Long eventId, JSONObjectCallback callback) {
//Long eventId=Long.valueOf(285);
Log.v(TAG, "getEvent()");
String urlStr = mUrlBase + "/api/events/" + eventId;
Log.v(TAG, "getEvent(): urlStr=" + urlStr);
final String authtoken = getStoredToken();
if (!isLoggedIn()) {
Log.v(TAG, "not logged in - doing nothing");
return (false);
}
StringRequest req = new StringRequest(Request.Method.GET, urlStr,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v(TAG, "Response is: " + response);
try {
JSONObject retObj = new JSONObject(response);
retObj.put("alarmStateStr", mUtil.alarmStatusToString(retObj.getInt("osdAlarmState")));
callback.accept(retObj);
} catch (JSONException e) {
Log.e(TAG, "getEventTypes.onRespons(): Error: " + e.getMessage() + "," + e.toString());
callback.accept(null);
}
mServerConnectionOk = true;
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error != null) {
Log.e(TAG, "Create Event Error: " + error.toString() + ", message:" + error.getMessage());
} else {
Log.e(TAG, "Create Event Error: returned null response");
}
mServerConnectionOk = false;
callback.accept(null);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token " + getStoredToken());
return params;
}
};
mQueue.add(req);
return (true); return (true);
} }
// calls function callback with a JSONObject representation of the event with id 'eventId'
public boolean getEvent(String eventId, JSONObjectCallback callback) {
Log.v(TAG, "getEvent()");
DocumentReference docRef = mDb.collection("Events").document(eventId);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "getEvent.onComplete(): DocumentSnapshot data: " + document.getData());
if (document.getData() == null) {
callback.accept(null);
} else
callback.accept(new JSONObject(document.getData()));
} else {
Log.d(TAG, "No such document");
callback.accept(null);
}
} else {
Log.d(TAG, "get failed with ", task.getException());
callback.accept(null);
}
}
});
return true;
}
/** /**
* Retrieve all events accessible to the logged in user, and pass them to the callback function as a JSONObject * Retrieve all events accessible to the logged in user, and pass them to the callback function as a JSONObject
* *
@@ -199,303 +183,117 @@ public class WebApiConnection {
public boolean getEvents(JSONObjectCallback callback) { public boolean getEvents(JSONObjectCallback callback) {
//Long eventId=Long.valueOf(285); //Long eventId=Long.valueOf(285);
Log.v(TAG, "getEvents()"); Log.v(TAG, "getEvents()");
String urlStr = mUrlBase + "/api/events/"; mDb.collection("Events")
Log.v(TAG, "getEvents(): urlStr=" + urlStr); .get()
final String authtoken = getStoredToken(); .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
if (!isLoggedIn()) {
Log.v(TAG, "not logged in - doing nothing");
return (false);
}
StringRequest req = new StringRequest(Request.Method.GET, urlStr,
new Response.Listener<String>() {
@Override @Override
public void onResponse(String response) { public void onComplete(@NonNull Task<QuerySnapshot> task) {
Log.v(TAG, "Response is: " + response); if (task.isSuccessful()) {
mServerConnectionOk = true;
try { try {
JSONObject retObj = new JSONObject(); JSONObject retObj = new JSONObject();
JSONArray eventArray = new JSONArray(response); JSONArray eventArray = new JSONArray();
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
eventArray.put(new JSONObject(document.getData()));
}
retObj.put("events", eventArray); retObj.put("events", eventArray);
callback.accept(retObj); callback.accept(retObj);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "getEventTypes.onRespons(): Error: " + e.getMessage() + "," + e.toString()); Log.e(TAG, "getEventTypes.onResponse(): Error: " + e.getMessage() + "," + e.toString());
callback.accept(null); callback.accept(null);
} }
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//if ((error != null) && (error.networkResponse != null) && (error.networkResponse.data != null)) {#
mServerConnectionOk = false;
if (error != null) {
if (error.networkResponse != null) {
Log.e(TAG, "getEvents(): Error: " + error.toString() + ", message:" + error.getMessage());
} else {
Log.e(TAG, "getEvents(): Error: - request returned null networkResponse");
}
} else{
Log.e(TAG, "getEvents(): Error: - request returned null response");
}
callback.accept(null);
}
}) {
@Override } else {
public Map<String, String> getHeaders() throws AuthFailureError { Log.d(TAG, "Error getting documents: ", task.getException());
Map<String, String> params = new HashMap<String, String>(); callback.accept(null);
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token " + getStoredToken());
return params;
} }
}; }
mQueue.add(req); });
return (true); return (true);
} }
public boolean updateEvent(final JSONObject eventObj, JSONObjectCallback callback) { public boolean updateEvent(final JSONObject eventObj, JSONObjectCallback callback) {
Long eventId; String eventId;
Log.v(TAG, "updateEvent()"); Log.v(TAG, "updateEvent()");
final String authtoken = getStoredToken();
if (!isLoggedIn()) {
Log.v(TAG, "not logged in - doing nothing");
return (false);
}
try { try {
eventId = eventObj.getLong("id"); eventId = eventObj.getString("id");
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "updateEvent(): Error reading id from eventObj"); Log.e(TAG, "updateEvent(): Error reading id from eventObj");
eventId = Long.valueOf(-1); eventId = null;
return false;
} }
final String dataStr = eventObj.toString(); final String dataStr = eventObj.toString();
Log.v(TAG, "createEvent - data=" + dataStr); Log.v(TAG, "updateEvent - data=" + dataStr);
DocumentReference docRef = mDb.collection("Events").document(eventId);
int reqMethod; docRef.update((Map<String, Object>) eventObj)
String urlStr; .addOnSuccessListener(new OnSuccessListener<Void>() {
if (eventId != -1) {
Log.v(TAG, "updateEvent() - found eventId " + eventId + ", Updating event record");
urlStr = mUrlBase + "/api/events/" + eventId + "/";
Log.v(TAG, "urlStr=" + urlStr);
reqMethod = Request.Method.PUT;
} else {
Log.v(TAG, "updateEvent() - eventId not found - creating new event record");
urlStr = mUrlBase + "/api/events/";
Log.v(TAG, "urlStr=" + urlStr);
reqMethod = Request.Method.POST;
}
StringRequest req = new StringRequest(reqMethod, urlStr,
new Response.Listener<String>() {
@Override @Override
public void onResponse(String response) { public void onSuccess(Void aVoid) {
Log.v(TAG, "Response is: " + response); JSONObject retObj;
mServerConnectionOk = true;
try { try {
JSONObject retObj = new JSONObject(response); retObj = new JSONObject("{\"status\":\"OK\"}");
} catch (Exception e) {
retObj = null;
}
callback.accept(retObj); callback.accept(retObj);
} catch (JSONException e) { }
Log.e(TAG, "getEventTypes.onRespons(): Error: " + e.getMessage() + "," + e.toString()); })
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error updating document", e);
callback.accept(null); callback.accept(null);
} }
} });
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mServerConnectionOk = false;
if (error != null) {
Log.e(TAG, "Create Event Error: " + error.toString() + ", message:" + error.getMessage());
} else {
Log.e(TAG, "Create Event Error - returned null response");
}
callback.accept(null);
}
}) {
// Note, this is overriding part of StringRequest, not one of the sub-classes above!
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// params.put("name",sname); // passing parameters to server
String authToken = getStoredToken();
params.put("Authorization: Token " + authToken, authToken);
Log.v(TAG, "getParams: params=" + params.toString());
//params.put("eventType", String.valueOf(eventType));
//params.put("dataTime", dateFormat.format(eventDate));
//params.put("desc", eventDesc);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token " + getStoredToken());
return params;
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return dataStr == null ? null : dataStr.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", dataStr, "utf-8");
return null;
}
}
};
mQueue.add(req);
return (true); return (true);
} }
public boolean createDatapoint(JSONObject dataObj, int eventId, StringCallback callback) { public boolean createDatapoint(JSONObject dataObj, int eventId, StringCallback callback) {
Log.v(TAG, "createDatapoint()"); Log.v(TAG, "createDatapoint()");
// Create a new event in the remote database, based on the provided parameters. // Create a new event in the remote database, based on the provided parameters.
String urlStr = mUrlBase + "/api/datapoints/"; String userId = null;
Log.v(TAG, "urlStr=" + urlStr); if (FirebaseAuth.getInstance().getCurrentUser() == null) {
final String authtoken = getStoredToken(); Log.e(TAG, "ERROR: createDatapoint() - not logged in");
return false;
if (!isLoggedIn()) {
Log.v(TAG, "not logged in - doing nothing");
return (false);
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
JSONObject jsonObject = new JSONObject();
try {
//jsonObject.put("userId", -1);
jsonObject.put("eventId", String.valueOf(eventId));
jsonObject.put("dataTime", dataObj.getString("dataTime"));
jsonObject.put("dataJSON", dataObj.toString());
} catch (JSONException e) {
Log.e(TAG, "Error generating event JSON string");
}
final String dataStr = jsonObject.toString();
Log.v(TAG, "createDatapoint - dataStr=" + dataStr);
StringRequest req = new StringRequest(Request.Method.POST, urlStr,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v(TAG, "Response is: " + response);
mServerConnectionOk = true;
callback.accept(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mServerConnectionOk = false;
if (error != null) {
Log.e(TAG, "Create Datapoint Error: " + error.toString() + ", message:" + error.getMessage());
callback.accept(null);
} else { } else {
Log.e(TAG, "Create Datapoint Error - returned null respones"); userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
callback.accept(null);
} }
} String dataTime;
}) {
// Note, this is overriding part of StringRequest, not one of the sub-classes above!
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// params.put("name",sname); // passing parameters to server
String authToken = getStoredToken();
params.put("Authorization: Token " + authToken, authToken);
Log.v(TAG, "getParams: params=" + params.toString());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token " + getStoredToken());
return params;
}
@Override
public byte[] getBody() throws AuthFailureError {
try { try {
return dataStr == null ? null : dataStr.getBytes("utf-8"); dataTime = dataObj.getString("dataTime");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", dataStr, "utf-8");
return null;
}
}
};
mQueue.add(req);
return (true);
}
/**
* Retieve the user profile of the authenticated user from the server, and return it to the callback function.
* @param callback - function to be called with a JSONObject as a parameter that contains the user profile data.
* @return true if request sent successfully, or else false.
*/
public boolean getUserProfile(JSONObjectCallback callback) {
Log.v(TAG, "getUserProfile()");
String urlStr = mUrlBase + "/api/accounts/profile/";
Log.v(TAG, "getUserProfile(): urlStr=" + urlStr);
final String authtoken = getStoredToken();
if (!isLoggedIn()) {
Log.v(TAG, "not logged in - doing nothing");
return (false);
}
StringRequest req = new StringRequest(Request.Method.GET, urlStr,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v(TAG, "Response is: " + response);
try {
JSONObject retObj = new JSONObject(response);
callback.accept(retObj);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "getUserProfile.onRespons(): Error: " + e.getMessage() + "," + e.toString()); dataTime = "";
callback.accept(null);
} }
mServerConnectionOk = true; Map<String, Object> datapoint = new HashMap<>();
} datapoint.put("dataTime", dataTime);
}, datapoint.put("dataJSON",dataObj.toString());
new Response.ErrorListener() { datapoint.put("userId", userId);
@Override datapoint.put("eventId", userId);
public void onErrorResponse(VolleyError error) {
if (error != null) {
Log.e(TAG, "Create Event Error: " + error.toString() + ", message:" + error.getMessage());
} else {
Log.e(TAG, "Create Event Error: returned null response");
}
mServerConnectionOk = false;
callback.accept(null);
}
}) {
mDb.collection("Datapoints")
.add(datapoint)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override @Override
public Map<String, String> getHeaders() throws AuthFailureError { public void onSuccess(DocumentReference documentReference) {
Map<String, String> params = new HashMap<String, String>(); Log.d(TAG, "createDatapoint.onSuccess() - DocumentSnapshot added with ID: " + documentReference.getId());
params.put("Content-Type", "application/json; charset=UTF-8"); mServerConnectionOk = true;
params.put("Authorization", "Token " + getStoredToken()); callback.accept(documentReference.getId());
return params;
} }
}; })
mQueue.add(req); .addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "createDatapoint.onFailure() - Error adding document", e);
callback.accept(null);
}
});
return (true); return (true);
} }
/** /**
* Retrieve the file containing the standard event types from the server. * Retrieve the file containing the standard event types from the server.
* Calls the specified callback function, passing a JSONObject as a parameter when the data has been received and parsed. * Calls the specified callback function, passing a JSONObject as a parameter when the data has been received and parsed.
@@ -504,53 +302,32 @@ public class WebApiConnection {
*/ */
public boolean getEventTypes(JSONObjectCallback callback) { public boolean getEventTypes(JSONObjectCallback callback) {
Log.v(TAG, "getEventTypes()"); Log.v(TAG, "getEventTypes()");
String urlStr = mUrlBase + "/static/eventTypes.json";
Log.v(TAG, "urlStr=" + urlStr);
final String authtoken = getStoredToken();
if (!isLoggedIn()) { mDb.collection("EventTypes")
Log.v(TAG, "not logged in - doing nothing"); .get()
return (false); .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
}
StringRequest req = new StringRequest(Request.Method.GET, urlStr,
new Response.Listener<String>() {
@Override @Override
public void onResponse(String response) { public void onComplete(@NonNull Task<QuerySnapshot> task) {
Log.v(TAG, "getEventTypes.onResponse(): Response is: " + response); if (task.isSuccessful()) {
mServerConnectionOk = true;
try { try {
JSONObject retObj = new JSONObject(response); JSONObject retObj = new JSONObject();
JSONArray eventArray = new JSONArray();
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
eventArray.put(new JSONObject(document.getData()));
}
retObj.put("eventTypes", eventArray);
callback.accept(retObj); callback.accept(retObj);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "getEventTypes.onRespons(): Error: " + e.getMessage() + "," + e.toString()); Log.e(TAG, "getEventTypes.onResponse(): Error: " + e.getMessage() + "," + e.toString());
callback.accept(null); callback.accept(null);
} }
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mServerConnectionOk = false;
if (error != null) {
Log.e(TAG, "getEventTypes.onErrorResponse(): " + error.toString() + ", message:" + error.getMessage());
} else { } else {
Log.e(TAG, "getEventTypes.onErrorResponse() - returned null response"); Log.d(TAG, "Error getting documents: ", task.getException());
}
callback.accept(null); callback.accept(null);
} }
}) {
// Note, this is overriding part of StringRequest, not one of the sub-classes above!
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Token " + getStoredToken());
return params;
} }
}; });
mQueue.add(req);
return (true); return (true);
} }
@@ -558,32 +335,13 @@ public class WebApiConnection {
/** /**
* Retrieve a trivial file from the server to check we have a good server connection. * Retrieve a trivial file from the server to check we have a good server connection.
* sets mServerConnectionOk. * sets mServerConnectionOk.
*
* @return true if request sent successfully or else false. * @return true if request sent successfully or else false.
*/ */
public boolean checkServerConnection() { public boolean checkServerConnection() {
Log.v(TAG, "checkServerConnection()"); //FIXME There must be a Firebase function for this?
String urlStr = mUrlBase + "/static/test.txt";
Log.v(TAG, "urlStr=" + urlStr);
StringRequest req = new StringRequest(Request.Method.GET, urlStr,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v(TAG, "checkServerConnection.onResponse(): Response is: " + response);
mServerConnectionOk = true; mServerConnectionOk = true;
} return true;
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "checkServerConnection.onErrorResponse");
mServerConnectionOk = false;
}
});
mQueue.add(req);
return (true);
} }
} }

View File

@@ -15,20 +15,14 @@ import java.util.TimeZone;
@RunWith(RobolectricTestRunner.class) @RunWith(RobolectricTestRunner.class)
@Config(sdk = {Build.VERSION_CODES.O_MR1}, packageName = "uk.org.openseizuredetector") @Config(sdk = {Build.VERSION_CODES.O_MR1}, packageName = "uk.org.openseizuredetector")
public class LogManagerTest extends TestCase { public class LogManagerTest extends TestCase {
LogManager mLm;
public void setUp() throws Exception {
super.setUp();
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
mLm = new LogManager(RuntimeEnvironment.systemContext);
}
public void tearDown() throws Exception { public void tearDown() throws Exception {
mLm.close();
} }
SdData getFakeSdData() { SdData getFakeSdData() {
SdData sdData = new SdData(); return null;
return sdData;
} }

View File

@@ -0,0 +1,62 @@
package uk.org.openseizuredetector;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.platform.app.InstrumentationRegistry;
import com.google.firebase.FirebaseApp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class WebApiConnectionTest {
WebApiConnection mWac;
@Before
public void setUp() throws Exception {
Context context = ApplicationProvider.getApplicationContext();
FirebaseApp.initializeApp(context);
mWac = new WebApiConnection(context);
}
@After
public void tearDown() throws Exception {
}
@Test
public void isLoggedIn() {
assertTrue(mWac.isLoggedIn());
assertFalse(mWac.isLoggedIn());
}
@Test
public void createEvent() {
}
@Test
public void getEvent() {
}
@Test
public void getEvents() {
}
@Test
public void updateEvent() {
}
@Test
public void createDatapoint() {
}
@Test
public void getUserProfile() {
}
}