1 | /* |
---|
2 | * rapidandroid - SMS gateway for the android platform |
---|
3 | * Copyright (C) 2009 Dimagi Inc., UNICEF |
---|
4 | * |
---|
5 | * This program is free software: you can redistribute it and/or modify |
---|
6 | * it under the terms of the GNU General Public License as published by |
---|
7 | * the Free Software Foundation, either version 3 of the License, or |
---|
8 | * (at your option) any later version. |
---|
9 | * |
---|
10 | * This program is distributed in the hope that it will be useful, |
---|
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
---|
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
---|
13 | * GNU General Public License for more details. |
---|
14 | * |
---|
15 | * You should have received a copy of the GNU General Public License |
---|
16 | * along with this program. If not, see <http://www.gnu.org/licenses/>. |
---|
17 | * |
---|
18 | */ |
---|
19 | /** |
---|
20 | * |
---|
21 | */ |
---|
22 | package org.rapidandroid.activity; |
---|
23 | |
---|
24 | import java.io.File; |
---|
25 | import java.util.Calendar; |
---|
26 | import java.util.Date; |
---|
27 | import java.util.Random; |
---|
28 | import java.util.Vector; |
---|
29 | |
---|
30 | import org.apache.http.HttpResponse; |
---|
31 | import org.apache.http.client.methods.HttpPost; |
---|
32 | import org.apache.http.entity.mime.MultipartEntity; |
---|
33 | import org.apache.http.entity.mime.content.FileBody; |
---|
34 | import org.apache.http.entity.mime.content.StringBody; |
---|
35 | import org.apache.http.impl.client.DefaultHttpClient; |
---|
36 | import org.rapidandroid.R; |
---|
37 | import org.rapidandroid.content.translation.MessageTranslator; |
---|
38 | import org.rapidandroid.content.translation.ModelTranslator; |
---|
39 | import org.rapidandroid.content.translation.ParsedDataTranslator; |
---|
40 | import org.rapidandroid.data.RapidSmsDBConstants; |
---|
41 | import org.rapidandroid.data.controller.ParsedDataReporter; |
---|
42 | import org.rapidandroid.view.adapter.FieldViewAdapter; |
---|
43 | import org.rapidsms.java.core.Constants; |
---|
44 | import org.rapidsms.java.core.model.Field; |
---|
45 | import org.rapidsms.java.core.model.Form; |
---|
46 | import org.rapidsms.java.core.model.Message; |
---|
47 | import org.rapidsms.java.core.model.Monitor; |
---|
48 | import org.rapidsms.java.core.parser.IParseResult; |
---|
49 | import org.rapidsms.java.core.parser.service.ParsingService; |
---|
50 | |
---|
51 | import android.app.Activity; |
---|
52 | import android.app.AlertDialog; |
---|
53 | import android.app.Dialog; |
---|
54 | import android.app.AlertDialog.Builder; |
---|
55 | import android.content.ContentValues; |
---|
56 | import android.content.Intent; |
---|
57 | import android.net.Uri; |
---|
58 | import android.os.Bundle; |
---|
59 | import android.os.Debug; |
---|
60 | import android.os.Handler; |
---|
61 | import android.util.Log; |
---|
62 | import android.view.Menu; |
---|
63 | import android.view.MenuItem; |
---|
64 | import android.widget.ListView; |
---|
65 | import android.widget.TextView; |
---|
66 | import android.widget.Toast; |
---|
67 | |
---|
68 | /** |
---|
69 | * Activity for reviewing a form and doing form specific activities. Namely, CSV |
---|
70 | * report output, HTTP upload, and a "hint" for how to compose the form in an |
---|
71 | * SMS message using. |
---|
72 | * |
---|
73 | * @author Daniel Myung [email protected] |
---|
74 | * @created Jan 12, 2009 |
---|
75 | * |
---|
76 | */ |
---|
77 | |
---|
78 | public class FormReviewer extends Activity { |
---|
79 | |
---|
80 | public class CallParams { |
---|
81 | public static final String REVIEW_FORM = "review_form"; |
---|
82 | } |
---|
83 | |
---|
84 | private static final int MENU_DONE = Menu.FIRST; |
---|
85 | private static final int MENU_FORMAT = Menu.FIRST + 1; |
---|
86 | private static final int MENU_DUMP_CSV = Menu.FIRST + 2; |
---|
87 | private static final int MENU_HTTP_UPLOAD = Menu.FIRST + 3; |
---|
88 | private static final int MENU_INJECT_DEBUG = Menu.FIRST + 4; |
---|
89 | |
---|
90 | public static final int ACTIVITY_FILE_BROWSE = 0; |
---|
91 | |
---|
92 | boolean success = false; |
---|
93 | |
---|
94 | private Form mForm; |
---|
95 | final Handler mDebugHandler = new Handler(); |
---|
96 | |
---|
97 | final Runnable mCsvSaveCompleted = new Runnable() { |
---|
98 | public void run() { |
---|
99 | alertCSVStatus(); |
---|
100 | } |
---|
101 | }; |
---|
102 | |
---|
103 | final Runnable mUpdateResults = new Runnable() { |
---|
104 | public void run() { |
---|
105 | updateResultsInUi(); |
---|
106 | } |
---|
107 | }; |
---|
108 | |
---|
109 | final Runnable mFinishUpload = new Runnable() { |
---|
110 | public void run() { |
---|
111 | alertUploadStatus(); |
---|
112 | } |
---|
113 | }; |
---|
114 | |
---|
115 | @Override |
---|
116 | protected void onCreate(Bundle savedInstanceState) { |
---|
117 | // TODO Auto-generated method stub |
---|
118 | super.onCreate(savedInstanceState); |
---|
119 | setTitle("RapidAndroid :: Review Form"); |
---|
120 | setContentView(R.layout.form_edit); |
---|
121 | |
---|
122 | Bundle extras = getIntent().getExtras(); |
---|
123 | if (extras != null) { |
---|
124 | |
---|
125 | if (!extras.containsKey(CallParams.REVIEW_FORM)) { |
---|
126 | throw new IllegalArgumentException("Error, activity was called without a Form ID to review."); |
---|
127 | } |
---|
128 | int formID = extras.getInt(CallParams.REVIEW_FORM); |
---|
129 | mForm = ModelTranslator.getFormById(formID); |
---|
130 | |
---|
131 | TextView txv_formname = (TextView) findViewById(R.id.txv_formname); |
---|
132 | TextView txv_prefix = (TextView) findViewById(R.id.txv_formprefix); |
---|
133 | TextView txv_description = (TextView) findViewById(R.id.txv_description); |
---|
134 | |
---|
135 | ListView lsv_fields = (ListView) findViewById(R.id.lsv_fields); |
---|
136 | |
---|
137 | txv_formname.setText(mForm.getFormName()); |
---|
138 | txv_prefix.setText(mForm.getPrefix()); |
---|
139 | txv_description.setText(mForm.getDescription()); |
---|
140 | |
---|
141 | int len = mForm.getFields().length; |
---|
142 | |
---|
143 | // lsv_fields.setAdapter(new ArrayAdapter<String>(this, |
---|
144 | // android.R.layout.simple_list_item_1, fields)); |
---|
145 | lsv_fields.setAdapter(new FieldViewAdapter(this, mForm.getFields())); |
---|
146 | |
---|
147 | } |
---|
148 | } |
---|
149 | |
---|
150 | @Override |
---|
151 | public boolean onCreateOptionsMenu(Menu menu) { |
---|
152 | // TODO Auto-generated method stub |
---|
153 | super.onCreateOptionsMenu(menu); |
---|
154 | menu.add(0, MENU_DONE, 0, R.string.formreview_menu_done).setIcon(android.R.drawable.ic_menu_revert); |
---|
155 | |
---|
156 | menu.add(0, MENU_FORMAT, 0, R.string.formreview_menu_format).setIcon(android.R.drawable.ic_menu_info_details); |
---|
157 | |
---|
158 | menu.add(0, MENU_DUMP_CSV, 0, R.string.formreview_dump_csv).setIcon(android.R.drawable.ic_menu_save); |
---|
159 | |
---|
160 | menu.add(0, MENU_HTTP_UPLOAD, 0, R.string.formreview_upload_csv).setIcon(android.R.drawable.ic_menu_upload); |
---|
161 | |
---|
162 | menu.add(0, MENU_INJECT_DEBUG, 0, "Generate Data").setIcon(android.R.drawable.ic_menu_manage); |
---|
163 | return true; |
---|
164 | } |
---|
165 | |
---|
166 | @Override |
---|
167 | public boolean onOptionsItemSelected(MenuItem item) { |
---|
168 | super.onOptionsItemSelected(item); |
---|
169 | switch (item.getItemId()) { |
---|
170 | case MENU_DONE: |
---|
171 | finish(); |
---|
172 | return true; |
---|
173 | case MENU_FORMAT: |
---|
174 | // Intent mIntent = new Intent(); |
---|
175 | // mIntent.putExtras(bundle); |
---|
176 | // setResult(RESULT_OK, mIntent) |
---|
177 | |
---|
178 | try { |
---|
179 | // this is because the randomization doesn't get |
---|
180 | // instantiated |
---|
181 | // for some weird reason |
---|
182 | // unless we blow away the dialog |
---|
183 | removeDialog(0); |
---|
184 | } catch (Exception ex) { |
---|
185 | } |
---|
186 | showDialog(0); |
---|
187 | return true; |
---|
188 | case MENU_DUMP_CSV: |
---|
189 | if (ParsedDataReporter.getOldestMessageDate(this, mForm).equals(Constants.NULLDATE)) { |
---|
190 | Builder noDateDialog = new AlertDialog.Builder(this); |
---|
191 | noDateDialog.setPositiveButton("Ok", null); |
---|
192 | noDateDialog.setTitle("Alert"); |
---|
193 | noDateDialog.setMessage("This form has no messages or data to output"); |
---|
194 | noDateDialog.show(); |
---|
195 | return true; |
---|
196 | } |
---|
197 | |
---|
198 | outputCSV(); |
---|
199 | break; |
---|
200 | case MENU_HTTP_UPLOAD: |
---|
201 | chooseFile(); |
---|
202 | break; |
---|
203 | case MENU_INJECT_DEBUG: |
---|
204 | injectMessages(); |
---|
205 | break; |
---|
206 | |
---|
207 | } |
---|
208 | return true; |
---|
209 | } |
---|
210 | |
---|
211 | @Override |
---|
212 | protected Dialog onCreateDialog(int id) { |
---|
213 | super.onCreateDialog(id); |
---|
214 | |
---|
215 | String title = "Sample submission"; |
---|
216 | |
---|
217 | if (mForm == null) { |
---|
218 | return null; |
---|
219 | } |
---|
220 | |
---|
221 | StringBuilder sb = generateRandomMessage(); |
---|
222 | |
---|
223 | return new AlertDialog.Builder(FormReviewer.this).setTitle(title).setMessage(sb.toString().trim()) |
---|
224 | .setPositiveButton("OK", null).create(); |
---|
225 | |
---|
226 | } |
---|
227 | |
---|
228 | @Override |
---|
229 | protected void onActivityResult(int requestCode, int resultCode, Intent intent) { |
---|
230 | Bundle extras = null; |
---|
231 | super.onActivityResult(requestCode, resultCode, intent); |
---|
232 | if (intent != null) { |
---|
233 | extras = intent.getExtras(); |
---|
234 | |
---|
235 | switch (requestCode) { |
---|
236 | case ACTIVITY_FILE_BROWSE: |
---|
237 | // get the filename |
---|
238 | String filename = extras.getString("filename"); |
---|
239 | uploadFile(filename); |
---|
240 | break; |
---|
241 | default: |
---|
242 | break; |
---|
243 | } |
---|
244 | } |
---|
245 | |
---|
246 | } |
---|
247 | |
---|
248 | private void alertUploadStatus() { |
---|
249 | if (success) { |
---|
250 | Toast.makeText(getApplicationContext(), "File upload successful", Toast.LENGTH_LONG).show(); |
---|
251 | } else { |
---|
252 | Toast.makeText(getApplicationContext(), "File upload failed", Toast.LENGTH_LONG).show(); |
---|
253 | } |
---|
254 | } |
---|
255 | |
---|
256 | private void alertCSVStatus() { |
---|
257 | |
---|
258 | Toast.makeText(getApplicationContext(), "CSV Save Complete", Toast.LENGTH_LONG).show(); |
---|
259 | |
---|
260 | } |
---|
261 | |
---|
262 | private void updateResultsInUi() { |
---|
263 | Toast.makeText(getApplicationContext(), "Data injection completed", Toast.LENGTH_LONG).show(); |
---|
264 | |
---|
265 | } |
---|
266 | |
---|
267 | private void chooseFile() { |
---|
268 | // spawn the activity for file browsing |
---|
269 | Intent i; |
---|
270 | i = new Intent(this, FileBrowser.class); |
---|
271 | startActivityForResult(i, ACTIVITY_FILE_BROWSE); |
---|
272 | // on activity return do the upload |
---|
273 | } |
---|
274 | |
---|
275 | private void uploadFile(final String filename) { |
---|
276 | Toast.makeText(getApplicationContext(), "File upload begun", Toast.LENGTH_LONG).show(); |
---|
277 | Thread t = new Thread() { |
---|
278 | @Override |
---|
279 | public void run() { |
---|
280 | try { |
---|
281 | DefaultHttpClient httpclient = new DefaultHttpClient(); |
---|
282 | |
---|
283 | File f = new File(filename); |
---|
284 | |
---|
285 | HttpPost httpost = new HttpPost("http://192.168.7.127:8160/upload/upload"); |
---|
286 | MultipartEntity entity = new MultipartEntity(); |
---|
287 | entity.addPart("myIdentifier", new StringBody("somevalue")); |
---|
288 | entity.addPart("myFile", new FileBody(f)); |
---|
289 | httpost.setEntity(entity); |
---|
290 | |
---|
291 | HttpResponse response; |
---|
292 | |
---|
293 | // Post, check and show the result (not really spectacular, |
---|
294 | // but works): |
---|
295 | response = httpclient.execute(httpost); |
---|
296 | |
---|
297 | Log.d("httpPost", "Login form get: " + response.getStatusLine()); |
---|
298 | |
---|
299 | if (entity != null) { |
---|
300 | entity.consumeContent(); |
---|
301 | } |
---|
302 | |
---|
303 | success = true; |
---|
304 | } catch (Exception ex) { |
---|
305 | Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); |
---|
306 | success = false; |
---|
307 | } finally { |
---|
308 | mDebugHandler.post(mFinishUpload); |
---|
309 | } |
---|
310 | } |
---|
311 | }; |
---|
312 | t.start(); |
---|
313 | } |
---|
314 | |
---|
315 | /** |
---|
316 | * |
---|
317 | */ |
---|
318 | private void outputCSV() { |
---|
319 | Toast.makeText(getApplicationContext(), "CSV output job has begun", Toast.LENGTH_LONG).show(); |
---|
320 | // Fire off a thread to do some work that we shouldn't do directly in |
---|
321 | // the UI thread |
---|
322 | Thread t = new Thread() { |
---|
323 | @Override |
---|
324 | public void run() { |
---|
325 | Calendar now = Calendar.getInstance(); |
---|
326 | Calendar then = Calendar.getInstance(); |
---|
327 | then.set(Calendar.YEAR, 1990); |
---|
328 | ParsedDataReporter.exportFormDataToCSV(getBaseContext(), mForm, then, now); |
---|
329 | mDebugHandler.post(mCsvSaveCompleted); |
---|
330 | |
---|
331 | } |
---|
332 | }; |
---|
333 | t.start(); |
---|
334 | } |
---|
335 | |
---|
336 | /** |
---|
337 | * |
---|
338 | */ |
---|
339 | private void injectMessages() { |
---|
340 | Toast.makeText(getApplicationContext(), "Debug data injection started", Toast.LENGTH_LONG).show(); |
---|
341 | // Fire off a thread to do some work that we shouldn't do directly in |
---|
342 | // the UI thread |
---|
343 | Thread t = new Thread() { |
---|
344 | @Override |
---|
345 | public void run() { |
---|
346 | doInjection(); |
---|
347 | mDebugHandler.post(mUpdateResults); |
---|
348 | } |
---|
349 | }; |
---|
350 | t.start(); |
---|
351 | } |
---|
352 | |
---|
353 | private void doInjection() { |
---|
354 | Random r = new Random(); |
---|
355 | |
---|
356 | // Debug.startMethodTracing("injection"); |
---|
357 | for (int i = 0; i < 100; i++) { |
---|
358 | |
---|
359 | // first, let's get the |
---|
360 | String token = phones[r.nextInt(phones.length)];// Long.toString(Math.abs(r.nextLong()), |
---|
361 | // 36); |
---|
362 | Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, token); |
---|
363 | |
---|
364 | Uri writeMessageUri = RapidSmsDBConstants.Message.CONTENT_URI; |
---|
365 | |
---|
366 | StringBuilder sb = this.generateRandomMessage(); |
---|
367 | ContentValues messageValues = new ContentValues(); |
---|
368 | messageValues.put(RapidSmsDBConstants.Message.MESSAGE, sb.toString()); |
---|
369 | messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID()); |
---|
370 | |
---|
371 | Date now = getRandomDate(); |
---|
372 | |
---|
373 | messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(now)); |
---|
374 | messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false); |
---|
375 | |
---|
376 | Uri msgUri = null; |
---|
377 | |
---|
378 | msgUri = getContentResolver().insert(writeMessageUri, messageValues); |
---|
379 | |
---|
380 | Vector<IParseResult> results = ParsingService.ParseMessage(mForm, sb.toString()); |
---|
381 | ParsedDataTranslator.InsertFormData(this, mForm, Integer.valueOf(msgUri.getPathSegments().get(1)) |
---|
382 | .intValue(), results); |
---|
383 | } |
---|
384 | |
---|
385 | Debug.stopMethodTracing(); |
---|
386 | |
---|
387 | } |
---|
388 | |
---|
389 | private Date getRandomDate() { |
---|
390 | Calendar cdr = Calendar.getInstance(); |
---|
391 | // cdr.set(1999, 1, 1); |
---|
392 | cdr.set(Calendar.MONTH, cdr.get(Calendar.MONTH) - 3); |
---|
393 | cdr.set(Calendar.HOUR_OF_DAY, 0); |
---|
394 | cdr.set(Calendar.MINUTE, 0); |
---|
395 | cdr.set(Calendar.SECOND, 0); |
---|
396 | long val1 = cdr.getTimeInMillis(); |
---|
397 | |
---|
398 | cdr = Calendar.getInstance(); |
---|
399 | cdr.set(Calendar.HOUR_OF_DAY, 23); |
---|
400 | cdr.set(Calendar.MINUTE, 59); |
---|
401 | cdr.set(Calendar.SECOND, 0); |
---|
402 | long val2 = cdr.getTimeInMillis(); |
---|
403 | |
---|
404 | Random r = new Random(); |
---|
405 | long randomTS = (long) (r.nextDouble() * (val2 - val1)) + val1; |
---|
406 | Date d = new Date(randomTS); |
---|
407 | return d; |
---|
408 | } |
---|
409 | |
---|
410 | private static String[] bools = new String[] { "t", "f", "true", "false", "yes", "no", "y", "n" }; |
---|
411 | private static String[] heights = new String[] { "cm", "m", "meters", "meter" }; |
---|
412 | private static String[] lengths = new String[] { "cm", "m" }; |
---|
413 | private static String[] weights = new String[] { "kg", "kilos", "kilo", "kg" }; |
---|
414 | private static String[] words = new String[] { "bos", "nyc", "jfk", "lax", "lun", "lhr", "asvasd", "alksjwlejrwer", |
---|
415 | "bshdkghk", "akhsdwer", "tiwowuy", "xvcxbxkhcvb" }; |
---|
416 | private static String[] phones = new String[] { "5558675309", "6175803100", "2128246918", "2123267768", |
---|
417 | "6175803103" }; |
---|
418 | |
---|
419 | private static String[] floats = new String[] { "0.24", "0.54", "1.5", "50%", "25 pct", "33 %", "15pct", "2/3", |
---|
420 | "3:2" }; |
---|
421 | |
---|
422 | Random r = new Random(); |
---|
423 | |
---|
424 | /** |
---|
425 | * @return |
---|
426 | */ |
---|
427 | private StringBuilder generateRandomMessage() { |
---|
428 | StringBuilder sb = new StringBuilder(); |
---|
429 | |
---|
430 | sb.append(mForm.getPrefix() + " "); |
---|
431 | |
---|
432 | Field[] fields = mForm.getFields(); |
---|
433 | int len = fields.length; |
---|
434 | |
---|
435 | for (int i = 0; i < len; i++) { |
---|
436 | Field field = fields[i]; |
---|
437 | |
---|
438 | String type = field.getFieldType().getReadableName(); |
---|
439 | |
---|
440 | if (type.toLowerCase().equals("word")) { |
---|
441 | sb.append(words[r.nextInt(words.length)]); |
---|
442 | } else if (type.toLowerCase().equals("number")) { |
---|
443 | sb.append(r.nextInt(1000)); |
---|
444 | } else if (type.equals("Height")) { |
---|
445 | sb.append(r.nextInt(200) + " " + heights[r.nextInt(heights.length)]); |
---|
446 | } else if (type.toLowerCase().equals("boolean") || type.toLowerCase().equals("yes/no")) { |
---|
447 | sb.append(bools[r.nextInt(bools.length)]); |
---|
448 | } else if (type.toLowerCase().equals("length")) { |
---|
449 | sb.append(r.nextInt(200) + " " + lengths[r.nextInt(lengths.length)]); |
---|
450 | } else if (type.toLowerCase().equals("ratio")) { |
---|
451 | |
---|
452 | sb.append(floats[r.nextInt(floats.length)]); |
---|
453 | } else if (type.toLowerCase().equals("weight")) { |
---|
454 | sb.append(r.nextInt(150) + " " + weights[r.nextInt(weights.length)]); |
---|
455 | } |
---|
456 | sb.append(" "); |
---|
457 | |
---|
458 | } |
---|
459 | return sb; |
---|
460 | } |
---|
461 | } |
---|