Browse Source

Improved SendConsentForm logic

Víctor Hernández 3 years ago
parent
commit
7da74adaec

+ 0
- 85
app/src/main/java/uprrp/tania/SendConsentForm.java View File

@@ -1,85 +0,0 @@
1
-/*************************************************************
2
- * By: Coralys Cubero Rivera
3
- * Date: 2019
4
- *************************************************************/
5
-
6
-package uprrp.tania;
7
-
8
-import android.os.AsyncTask;
9
-import android.util.Log;
10
-
11
-import java.io.BufferedReader;
12
-import java.io.BufferedWriter;
13
-import java.io.InputStream;
14
-import java.io.InputStreamReader;
15
-import java.io.OutputStreamWriter;
16
-import java.io.UnsupportedEncodingException;
17
-import java.io.Writer;
18
-import java.net.URL;
19
-import java.net.URLConnection;
20
-import java.net.URLEncoder;
21
-import java.nio.charset.StandardCharsets;
22
-
23
-public class SendConsentForm extends AsyncTask <String, String, String> {
24
-    @Override
25
-    protected String doInBackground(String... strings) {
26
-        String jsonConsentSignature  = "";
27
-
28
-        try {
29
-            jsonConsentSignature = URLEncoder.encode("data", "UTF-8") + "=" + URLEncoder.encode(strings[0], "UTF-8");
30
-        }
31
-
32
-        catch (UnsupportedEncodingException e) {
33
-            e.printStackTrace();
34
-        }
35
-
36
-        String serverReply = "";
37
-        BufferedReader serverReader;
38
-
39
-        //Send the signature to MARLE's server
40
-        try
41
-        {
42
-            //Defined URL  where to send data
43
-            URL url = new URL("https://tania.uprrp.edu/getSignatureIOS.php");
44
-
45
-            //Send POST data request
46
-            URLConnection conn = url.openConnection();
47
-            conn.setDoOutput(true);
48
-
49
-            Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
50
-            writer.write(jsonConsentSignature);
51
-            writer.close();
52
-
53
-            InputStream inputStream = conn.getInputStream();
54
-            if (inputStream == null) {
55
-                return null;
56
-            }
57
-
58
-            //Get the server response
59
-            serverReader = new BufferedReader(new InputStreamReader(inputStream));
60
-            StringBuilder serverResponse = new StringBuilder();
61
-            String serverResponseLine;
62
-
63
-            // Read Server Response
64
-            while((serverResponseLine = serverReader.readLine()) != null)
65
-            {
66
-                //Append server response in string
67
-                serverResponse.append(serverResponseLine);
68
-            }
69
-
70
-            serverReply = serverResponse.toString();
71
-        }
72
-        catch(Exception ex) {
73
-            Log.e("ERROR CONSENT SIGNATURE", ex.getMessage());
74
-        }
75
-
76
-        return serverReply;
77
-    }
78
-
79
-    @Override
80
-    protected void onPostExecute(String s) {
81
-        Log.d("CONSENT SERVER REPLY", s);
82
-
83
-    }
84
-
85
-}

+ 50
- 49
app/src/main/java/uprrp/tania/activities/GettingStartedActivity.java View File

@@ -26,8 +26,6 @@ import com.itextpdf.text.Image;
26 26
 import com.itextpdf.text.Paragraph;
27 27
 import com.itextpdf.text.pdf.PdfWriter;
28 28
 
29
-import org.json.JSONException;
30
-import org.json.JSONObject;
31 29
 import org.researchstack.backbone.StorageAccess;
32 30
 import org.researchstack.backbone.model.ConsentDocument;
33 31
 import org.researchstack.backbone.model.ConsentSection;
@@ -50,7 +48,8 @@ import java.io.IOException;
50 48
 
51 49
 import uprrp.tania.GlobalValues;
52 50
 import uprrp.tania.R;
53
-import uprrp.tania.SendConsentForm;
51
+import uprrp.tania.networking.SendConsentForm;
52
+import uprrp.tania.utils.URLEventListener;
54 53
 
55 54
 public class GettingStartedActivity extends AppCompatActivity {
56 55
 
@@ -123,62 +122,64 @@ public class GettingStartedActivity extends AppCompatActivity {
123 122
     }
124 123
 
125 124
 
126
-    // TODO: decide which parts in this function to move to a background task
127
-    // TODO: define a model for the JSON and use Gson to encode it
128 125
     private void processConsentResult(TaskResult result) {
129 126
 
130 127
         boolean consented = (boolean) result.getStepResult(CONSENT_DOC).getResult();
131 128
         StorageAccess.getInstance().getAppDatabase().saveTaskResult(result);
132 129
 
133 130
         if(consented) {
134
-            try {
135
-
136
-                // Get signature in base64
137
-                TaskResult taskResult = StorageAccess.getInstance()
138
-                        .getAppDatabase()
139
-                        .loadLatestTaskResult(CONSENT);
140
-                String signatureBase64 = (String) taskResult.getStepResult(SIGNATURE)
141
-                        .getResultForIdentifier(ConsentSignatureStepLayout.KEY_SIGNATURE);
142
-
143
-                // Get signature date
144
-                String signatureDate = (String) result.getStepResult(SIGNATURE)
145
-                        .getResultForIdentifier(ConsentSignatureStepLayout.KEY_SIGNATURE_DATE);
146
-
147
-                // Use signature to get encoded consent form
148
-                byte[] signatureBytes = Base64.decode(signatureBase64, Base64.DEFAULT);
149
-                String consentFormBase64 = createPdf(signatureBytes, signatureDate);
150
-
151
-                // Send JSON with consent form, signature date, and token
152
-                JSONObject signatureJSON = new JSONObject();
153
-                signatureJSON.put("signaturePDFBase64", consentFormBase64);
154
-                signatureJSON.put("signatureDate", signatureDate);
155
-                signatureJSON.put("token", GlobalValues.getInstance().getDeviceToken()); // FirebaseInstanceId.getInstance().getToken()
156
-                Log.d("CONSENT JSON", signatureJSON.toString()); // log
157
-                SendConsentForm sendConsentForm = new SendConsentForm();
158
-                sendConsentForm.execute(signatureJSON.toString());
159
-
160
-                // Save consent signature and date separately on preferences
161
-                SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
162
-                SharedPreferences.Editor editor = prefs.edit();
163
-                editor.putString("consentSignature", signatureBase64);
164
-                editor.putString("consentDate", signatureDate);
165
-                editor.apply();
166
-
167
-                // Prompt user to register as student
168
-                Intent registration = new Intent(this, RegisterActivity.class);
169
-                startActivity(registration);
170
-
171
-            } catch (JSONException e) {
172
-                Log.e(TAG, "Couldn't prepare consent form JSON!");
173
-                e.printStackTrace();
174
-            } catch (Exception e) {
175
-                Log.e(TAG, "Error on processConsentResult(): " + e.getMessage());
176
-                e.printStackTrace();
177
-            }
131
+
132
+            // Get signature in base64
133
+            TaskResult taskResult = StorageAccess.getInstance()
134
+                    .getAppDatabase()
135
+                    .loadLatestTaskResult(CONSENT);
136
+            String signatureBase64 = (String) taskResult.getStepResult(SIGNATURE)
137
+                    .getResultForIdentifier(ConsentSignatureStepLayout.KEY_SIGNATURE);
138
+
139
+            // Get signature date
140
+            String signatureDate = (String) result.getStepResult(SIGNATURE)
141
+                    .getResultForIdentifier(ConsentSignatureStepLayout.KEY_SIGNATURE_DATE);
142
+
143
+            // Use signature to get encoded consent form
144
+            byte[] signatureBytes = Base64.decode(signatureBase64, Base64.DEFAULT);
145
+            String consentFormBase64 = createPdf(signatureBytes, signatureDate);
146
+
147
+            // Send JSON with consent form, signature date, and token
148
+            String deviceToken = GlobalValues.getInstance().getDeviceToken();
149
+            this.sendConsentForm(deviceToken, consentFormBase64, signatureDate);
150
+
151
+            // Save consent signature and date separately on preferences
152
+            SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
153
+            SharedPreferences.Editor editor = prefs.edit();
154
+            editor.putString("consentSignature", signatureBase64);
155
+            editor.putString("consentDate", signatureDate);
156
+            editor.apply();
157
+
158
+            // Prompt user to register as student
159
+            Intent registration = new Intent(this, RegisterActivity.class);
160
+            startActivity(registration);
161
+
178 162
         }
179 163
 
180 164
     }
181 165
 
166
+    private void sendConsentForm(String deviceToken, String consentFormBase64, String signatureDate) {
167
+        SendConsentForm sendConsentFormTask = new SendConsentForm(new URLEventListener() {
168
+            @Override
169
+            public void onSuccess() {
170
+                Toast.makeText(getApplicationContext(), "Sent consent form to server!", Toast.LENGTH_LONG).show();
171
+            }
172
+
173
+            @Override
174
+            public void onFailure(Exception e) {
175
+                Toast.makeText(getApplicationContext(), "Couldn't send consent form to server!", Toast.LENGTH_LONG).show();
176
+                Log.e(TAG, "Couldn't send consent form to server!");
177
+                e.printStackTrace();
178
+            }
179
+        });
180
+
181
+        sendConsentFormTask.execute(deviceToken, consentFormBase64, signatureDate);
182
+    }
182 183
 
183 184
     private void launchConsent() {
184 185
 

+ 1
- 1
app/src/main/java/uprrp/tania/networking/SendAccountRecovery.java View File

@@ -16,7 +16,7 @@ import java.net.URLEncoder;
16 16
 
17 17
 import uprrp.tania.utils.URLEventListener;
18 18
 
19
-public class SendAccountRecovery extends AsyncTask<String, String, String> {
19
+public class SendAccountRecovery extends AsyncTask<String, Void, String> {
20 20
 
21 21
     private static final String TAG = "SendAccountRecovery";
22 22
     private static final String loginBaseURL = "https://tania.uprrp.edu/recoverAccount.php";

+ 154
- 0
app/src/main/java/uprrp/tania/networking/SendConsentForm.java View File

@@ -0,0 +1,154 @@
1
+package uprrp.tania.networking;
2
+
3
+import android.os.AsyncTask;
4
+import android.util.Log;
5
+
6
+import org.json.JSONException;
7
+import org.json.JSONObject;
8
+
9
+import java.io.BufferedReader;
10
+import java.io.BufferedWriter;
11
+import java.io.InputStreamReader;
12
+import java.io.OutputStreamWriter;
13
+import java.io.UnsupportedEncodingException;
14
+import java.io.Writer;
15
+import java.net.URL;
16
+import java.net.URLConnection;
17
+import java.net.URLEncoder;
18
+import java.nio.charset.StandardCharsets;
19
+
20
+import uprrp.tania.utils.URLEventListener;
21
+
22
+public class SendConsentForm extends AsyncTask <String, Void, String> {
23
+
24
+    private static final String TAG = "SendConsentForm";
25
+    private static final String consentFormBaseURL = "https://tania.uprrp.edu/getSignatureIOS.php";
26
+    private final URLEventListener myCallback;
27
+
28
+    public SendConsentForm(URLEventListener callback) {
29
+        this.myCallback = callback;
30
+    }
31
+
32
+    private boolean validInputs(String... strings) {
33
+
34
+        if(strings.length != 3) {
35
+            Log.e(TAG, "Invalid string array length!");
36
+            return false;
37
+        }
38
+
39
+        String deviceToken = strings[0];
40
+        String consentFormBase64 = strings[1];
41
+        String signatureDate = strings[2];
42
+
43
+        if(consentFormBase64 == null) {
44
+            Log.e(TAG, "Encountered null consent form!");
45
+            return false;
46
+        } else if (deviceToken == null) {
47
+            Log.e(TAG, "Encountered null device token!");
48
+            return false;
49
+        } else if (signatureDate == null) {
50
+            Log.e(TAG, "Encountered null signature date!");
51
+            return false;
52
+        }
53
+
54
+        return true;
55
+
56
+    }
57
+
58
+    // TODO: instead of making a normal POST request with
59
+    //  the body data=<JSON>, we should just send the JSON itself
60
+    //  This is adding unnecessary layers of complexity when decoding AND encoding
61
+    /*
62
+        JSON format:
63
+        {
64
+            "signatureDate": String,
65
+            "signaturePDFBase64": String,
66
+            "token": String,
67
+        }
68
+    */
69
+    @Override
70
+    protected String doInBackground(String... strings) {
71
+
72
+        // Validation
73
+        if(!validInputs(strings)) {
74
+            Log.e(TAG, "Invalid inputs given!");
75
+            return null;
76
+        }
77
+
78
+        // Extract variables
79
+        String deviceToken = strings[0];
80
+        String consentFormBase64 = strings[1];
81
+        String signatureDate = strings[2];
82
+
83
+        try {
84
+
85
+            // Create JSON
86
+            JSONObject consentFormJSON = new JSONObject();
87
+            consentFormJSON.put("token", deviceToken);
88
+            consentFormJSON.put("signaturePDFBase64", consentFormBase64);
89
+            consentFormJSON.put("signatureDate", signatureDate);
90
+            Log.d(TAG, "ConsentFormJSON is " + consentFormJSON.toString()); // log
91
+
92
+            // Encode data
93
+            String jsonConsentSignature = URLEncoder.encode("data", "UTF-8") + "=" + URLEncoder.encode(strings[0], "UTF-8");
94
+
95
+            // Send POST data request
96
+            URL url = new URL(consentFormBaseURL);
97
+            URLConnection conn = url.openConnection();
98
+            conn.setDoOutput(true);
99
+            Writer writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
100
+            writer.write(jsonConsentSignature);
101
+            writer.close();
102
+
103
+            // Get the server response
104
+            BufferedReader serverReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
105
+            StringBuilder serverResponse = new StringBuilder();
106
+
107
+            String line = "";
108
+            while(line != null) {
109
+                serverResponse.append(line);
110
+                line = serverReader.readLine();
111
+            }
112
+
113
+            String response = serverResponse.toString();
114
+            Log.d(TAG, "The server's response is " + response);
115
+            if(response.toLowerCase().contains("error")) {
116
+                return null;
117
+            } else {
118
+                return response;
119
+            }
120
+
121
+        } catch (JSONException e) {
122
+            Log.e(TAG, "Couldn't prepare consentFormJSON!");
123
+            e.printStackTrace();
124
+            return null;
125
+        } catch (UnsupportedEncodingException e) {
126
+            Log.e(TAG, "Couldn't encode consentFormJSON");
127
+            e.printStackTrace();
128
+            return null;
129
+        } catch(Exception e) {
130
+            Log.e(TAG, "Couldn't communicate with server while recovering account!");
131
+            e.printStackTrace();
132
+            return null;
133
+        }
134
+
135
+    }
136
+
137
+    @Override
138
+    protected void onPostExecute(String response) {
139
+
140
+        if(this.myCallback == null) {
141
+            Log.e(TAG, "Callback wasn't initialized first!");
142
+            return;
143
+        }
144
+
145
+        if(response == null) {
146
+            this.myCallback.onFailure(new Exception("Error occurred during transaction!"));
147
+            return;
148
+        }
149
+
150
+        this.myCallback.onSuccess();
151
+
152
+    }
153
+
154
+}

+ 1
- 1
app/src/main/java/uprrp/tania/networking/SendExperienceRegistration.java View File

@@ -17,7 +17,7 @@ import javax.net.ssl.HttpsURLConnection;
17 17
 
18 18
 import uprrp.tania.utils.URLEventListener;
19 19
 
20
-public class SendExperienceRegistration extends AsyncTask<String, String, String> {
20
+public class SendExperienceRegistration extends AsyncTask<String, Void, String> {
21 21
 
22 22
     private static final String TAG = "SendActivateExperience";
23 23
     private static final String activateExperienceURL = "https://tania.uprrp.edu/inscripcionExperiencia.php";

+ 1
- 1
app/src/main/java/uprrp/tania/networking/SendWithdrawal.java View File

@@ -20,7 +20,7 @@ import javax.net.ssl.HttpsURLConnection;
20 20
 
21 21
 import uprrp.tania.utils.URLEventListener;
22 22
 
23
-public class SendWithdrawal extends AsyncTask<String, String, String> {
23
+public class SendWithdrawal extends AsyncTask<String, Void, String> {
24 24
 
25 25
     private static final String TAG = "SendWithdrawal";
26 26
     private static final String withdrawalURL = "https://tania.uprrp.edu/withdrawal.php";