Best Android App InstaSquare Lite for full-size publication of photos in Instagram, Facebook, Twitter. Run the android application on PC. You can through the android emulator Droid4X.

root/trunk/rapidandroid/org.rapidandroid/src/org/rapidandroid/activity/FormReviewer.java @ 134

Revision 134, 17.2 KB (checked in by dmyung, 10 months ago)

added some secret sections for FormReview? for debug data injection

but for real stuff, added a settings file that's generated on startup for the first time, and is persisted in the settings directory to set a preference for ACK replies for parse and no parse events.

Line 
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 */
22package org.rapidandroid.activity;
23
24import java.io.BufferedReader;
25import java.io.File;
26import java.io.IOException;
27import java.io.InputStream;
28import java.io.StringReader;
29import java.text.ParseException;
30import java.util.Calendar;
31import java.util.Date;
32import java.util.Random;
33import java.util.StringTokenizer;
34import java.util.Vector;
35
36import org.apache.http.HttpResponse;
37import org.apache.http.client.methods.HttpPost;
38import org.apache.http.entity.mime.MultipartEntity;
39import org.apache.http.entity.mime.content.FileBody;
40import org.apache.http.entity.mime.content.StringBody;
41import org.apache.http.impl.client.DefaultHttpClient;
42import org.rapidandroid.R;
43import org.rapidandroid.content.translation.MessageTranslator;
44import org.rapidandroid.content.translation.ModelTranslator;
45import org.rapidandroid.content.translation.ParsedDataTranslator;
46import org.rapidandroid.data.RapidSmsDBConstants;
47import org.rapidandroid.data.controller.ParsedDataReporter;
48import org.rapidandroid.view.adapter.FieldViewAdapter;
49import org.rapidsms.java.core.Constants;
50import org.rapidsms.java.core.model.Field;
51import org.rapidsms.java.core.model.Form;
52import org.rapidsms.java.core.model.Message;
53import org.rapidsms.java.core.model.Monitor;
54import org.rapidsms.java.core.parser.IParseResult;
55import org.rapidsms.java.core.parser.service.ParsingService;
56
57import android.app.Activity;
58import android.app.AlertDialog;
59import android.app.Dialog;
60import android.app.AlertDialog.Builder;
61import android.content.ContentValues;
62import android.content.Intent;
63import android.net.Uri;
64import android.os.Bundle;
65import android.os.Debug;
66import android.os.Handler;
67import android.util.Log;
68import android.view.Menu;
69import android.view.MenuItem;
70import android.widget.ListView;
71import android.widget.TextView;
72import android.widget.Toast;
73
74/**
75 * Activity for reviewing a form and doing form specific activities. Namely, CSV
76 * report output, HTTP upload, and a "hint" for how to compose the form in an
77 * SMS message using.
78 *
79 * @author Daniel Myung [email protected]
80 * @created Jan 12, 2009
81 *
82 */
83
84public class FormReviewer extends Activity {
85
86        public class CallParams {
87                public static final String REVIEW_FORM = "review_form";
88        }
89
90        private static final int MENU_DONE = Menu.FIRST;
91        private static final int MENU_FORMAT = Menu.FIRST + 1;
92        private static final int MENU_DUMP_CSV = Menu.FIRST + 2;
93        private static final int MENU_HTTP_UPLOAD = Menu.FIRST + 3;
94        private static final int MENU_INJECT_DEBUG = Menu.FIRST + 4;
95
96        public static final int ACTIVITY_FILE_BROWSE = 0;
97
98        boolean success = false;
99
100        private Form mForm;
101        final Handler mDebugHandler = new Handler();
102
103        final Runnable mCsvSaveCompleted = new Runnable() {
104                public void run() {
105                        alertCSVStatus();
106                }
107        };
108
109        final Runnable mUpdateResults = new Runnable() {
110                public void run() {
111                        updateResultsInUi();
112                }
113        };
114
115        final Runnable mFinishUpload = new Runnable() {
116                public void run() {
117                        alertUploadStatus();
118                }
119        };
120
121        @Override
122        protected void onCreate(Bundle savedInstanceState) {
123                // TODO Auto-generated method stub
124                super.onCreate(savedInstanceState);
125                setTitle("RapidAndroid :: Review Form");
126                setContentView(R.layout.form_edit);
127
128                Bundle extras = getIntent().getExtras();
129                if (extras != null) {
130
131                        if (!extras.containsKey(CallParams.REVIEW_FORM)) {
132                                throw new IllegalArgumentException("Error, activity was called without a Form ID to review.");
133                        }
134                        int formID = extras.getInt(CallParams.REVIEW_FORM);
135                        mForm = ModelTranslator.getFormById(formID);
136
137                        TextView txv_formname = (TextView) findViewById(R.id.txv_formname);
138                        TextView txv_prefix = (TextView) findViewById(R.id.txv_formprefix);
139                        TextView txv_description = (TextView) findViewById(R.id.txv_description);
140
141                        ListView lsv_fields = (ListView) findViewById(R.id.lsv_fields);
142
143                        txv_formname.setText(mForm.getFormName());
144                        txv_prefix.setText(mForm.getPrefix());
145                        txv_description.setText(mForm.getDescription());
146
147                        int len = mForm.getFields().length;
148
149                        // lsv_fields.setAdapter(new ArrayAdapter<String>(this,
150                        // android.R.layout.simple_list_item_1, fields));
151                        lsv_fields.setAdapter(new FieldViewAdapter(this, mForm.getFields()));
152
153                }
154        }
155
156        @Override
157        public boolean onCreateOptionsMenu(Menu menu) {
158                // TODO Auto-generated method stub
159                super.onCreateOptionsMenu(menu);
160                menu.add(0, MENU_DONE, 0, R.string.formreview_menu_done).setIcon(android.R.drawable.ic_menu_revert);
161
162                menu.add(0, MENU_FORMAT, 0, R.string.formreview_menu_format).setIcon(android.R.drawable.ic_menu_info_details);
163
164                menu.add(0, MENU_DUMP_CSV, 0, R.string.formreview_dump_csv).setIcon(android.R.drawable.ic_menu_save);
165
166//              menu.add(0, MENU_HTTP_UPLOAD, 0, R.string.formreview_upload_csv).setIcon(android.R.drawable.ic_menu_upload);
167
168                //menu.add(0, MENU_INJECT_DEBUG, 0, "Generate Data").setIcon(android.R.drawable.ic_menu_manage);
169                return true;
170        }
171
172        @Override
173        public boolean onOptionsItemSelected(MenuItem item) {
174                super.onOptionsItemSelected(item);
175                switch (item.getItemId()) {
176                        case MENU_DONE:
177                                finish();
178                                return true;
179                        case MENU_FORMAT:
180                                // Intent mIntent = new Intent();
181                                // mIntent.putExtras(bundle);
182                                // setResult(RESULT_OK, mIntent)
183
184                                try {
185                                        // this is because the randomization doesn't get
186                                        // instantiated
187                                        // for some weird reason
188                                        // unless we blow away the dialog
189                                        removeDialog(0);
190                                } catch (Exception ex) {
191                                }
192                                showDialog(0);
193                                return true;
194                        case MENU_DUMP_CSV:
195                                if (ParsedDataReporter.getOldestMessageDate(this, mForm).equals(Constants.NULLDATE)) {
196                                        Builder noDateDialog = new AlertDialog.Builder(this);
197                                        noDateDialog.setPositiveButton("Ok", null);
198                                        noDateDialog.setTitle("Alert");
199                                        noDateDialog.setMessage("This form has no messages or data to output");
200                                        noDateDialog.show();
201                                        return true;
202                                }
203
204                                outputCSV();
205                                break;
206                        case MENU_HTTP_UPLOAD:
207                                chooseFile();
208                                break;
209                        case MENU_INJECT_DEBUG:
210                                injectMessages();
211                                break;
212
213                }
214                return true;
215        }
216
217        @Override
218        protected Dialog onCreateDialog(int id) {
219                super.onCreateDialog(id);
220
221                String title = "Sample submission";
222
223                if (mForm == null) {
224                        return null;
225                }
226
227                StringBuilder sb = generateRandomMessage();
228
229                return new AlertDialog.Builder(FormReviewer.this).setTitle(title).setMessage(sb.toString().trim())
230                                                                                                                        .setPositiveButton("OK", null).create();
231
232        }
233
234        @Override
235        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
236                Bundle extras = null;
237                super.onActivityResult(requestCode, resultCode, intent);
238                if (intent != null) {
239                        extras = intent.getExtras();
240
241                        switch (requestCode) {
242                                case ACTIVITY_FILE_BROWSE:
243                                        // get the filename
244                                        String filename = extras.getString("filename");
245                                        uploadFile(filename);
246                                        break;
247                                default:
248                                        break;
249                        }
250                }
251
252        }
253
254        private void alertUploadStatus() {
255                if (success) {
256                        Toast.makeText(getApplicationContext(), "File upload successful", Toast.LENGTH_LONG).show();
257                } else {
258                        Toast.makeText(getApplicationContext(), "File upload failed", Toast.LENGTH_LONG).show();
259                }
260        }
261
262        private void alertCSVStatus() {
263
264                Toast.makeText(getApplicationContext(), "CSV Save Complete", Toast.LENGTH_LONG).show();
265
266        }
267
268        private void updateResultsInUi() {
269                Toast.makeText(getApplicationContext(), "Data injection completed", Toast.LENGTH_LONG).show();
270
271        }
272
273        private void chooseFile() {
274                // spawn the activity for file browsing
275                Intent i;
276                i = new Intent(this, FileBrowser.class);
277                startActivityForResult(i, ACTIVITY_FILE_BROWSE);
278                // on activity return do the upload
279        }
280
281        private void uploadFile(final String filename) {
282                Toast.makeText(getApplicationContext(), "File upload begun", Toast.LENGTH_LONG).show();
283                Thread t = new Thread() {
284                        @Override
285                        public void run() {
286                                try {
287                                        DefaultHttpClient httpclient = new DefaultHttpClient();
288
289                                        File f = new File(filename);
290
291                                        HttpPost httpost = new HttpPost("http://192.168.7.127:8160/upload/upload");
292                                        MultipartEntity entity = new MultipartEntity();
293                                        entity.addPart("myIdentifier", new StringBody("somevalue"));
294                                        entity.addPart("myFile", new FileBody(f));
295                                        httpost.setEntity(entity);
296
297                                        HttpResponse response;
298
299                                        // Post, check and show the result (not really spectacular,
300                                        // but works):
301                                        response = httpclient.execute(httpost);
302
303                                        Log.d("httpPost", "Login form get: " + response.getStatusLine());
304
305                                        if (entity != null) {
306                                                entity.consumeContent();
307                                        }
308
309                                        success = true;
310                                } catch (Exception ex) {
311                                        Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
312                                        success = false;
313                                } finally {
314                                        mDebugHandler.post(mFinishUpload);
315                                }
316                        }
317                };
318                t.start();
319        }
320
321        /**
322         *
323         */
324        private void outputCSV() {
325                Toast.makeText(getApplicationContext(), "CSV output job has begun", Toast.LENGTH_LONG).show();
326                // Fire off a thread to do some work that we shouldn't do directly in
327                // the UI thread
328                Thread t = new Thread() {
329                        @Override
330                        public void run() {
331                                Calendar now = Calendar.getInstance();
332                                Calendar then = Calendar.getInstance();
333                                then.set(Calendar.YEAR, 1990);
334                                ParsedDataReporter.exportFormDataToCSV(getBaseContext(), mForm, then, now);
335                                mDebugHandler.post(mCsvSaveCompleted);
336
337                        }
338                };
339                t.start();
340        }
341
342        /**
343         *
344         */
345        private void injectMessages() {
346                Toast.makeText(getApplicationContext(), "Debug data injection started", Toast.LENGTH_LONG).show();
347                // Fire off a thread to do some work that we shouldn't do directly in
348                // the UI thread
349                Thread t = new Thread() {
350                        @Override
351                        public void run() {
352                                if(mForm.getFormName().toLowerCase().equals("bednets")) {
353                                        doCsvDirectBednetsInjection();
354                                } else {
355                                        doRandomizedInjection();
356                                }
357                                mDebugHandler.post(mUpdateResults);
358                        }
359                };
360                t.start();
361        }
362
363       
364        private void doCsvDirectBednetsInjection() {
365                String rawMessageText = "";
366               
367                try {
368                        InputStream is = this.getAssets().open("testdata/rawdata.csv");
369
370                        int size = is.available();
371
372                        // Read the entire asset into a local byte buffer.
373                        byte[] buffer = new byte[size];
374                        is.read(buffer);
375                        is.close();
376
377                        // Convert the buffer into a Java string.
378                        String text = new String(buffer);
379
380                        rawMessageText = text;
381
382                } catch (IOException e) {
383                        // Should never happen!
384                        throw new RuntimeException(e);
385                }
386
387               
388                StringReader sr = new StringReader(rawMessageText);
389                BufferedReader bufRdr = new BufferedReader(sr);
390
391                String line = null;
392                int row = 0;
393                int col = 0;
394                Vector<String[]> lines = new Vector<String[]>();
395                // read each line of text file
396                try {
397                        while ((line = bufRdr.readLine()) != null) {
398                                StringTokenizer st = new StringTokenizer(line, ",");
399                                int tokCount = st.countTokens();
400
401                                String[] tokenizedLine = new String[tokCount];
402                                int toki = 0;
403                                while (st.hasMoreTokens()) {
404                                        tokenizedLine[toki] = st.nextToken();
405                                        toki++;
406                                }
407                                lines.add(tokenizedLine);
408                        }
409                } catch (IOException e) {
410                        // TODO Auto-generated catch block
411                        e.printStackTrace();
412                } finally {
413
414                        try {
415                                sr.close();
416                                bufRdr.close();
417                        } catch (IOException e) {
418                                // TODO Auto-generated catch block
419                                e.printStackTrace();
420                        }
421                }
422                int len = lines.size();
423
424                for (int i = 0; i < len; i++) {
425                        String[] csvline = lines.get(i);
426
427                        String datestr = csvline[0];
428
429                        Date dateval = new Date();
430                        try {
431                                dateval = Message.SQLDateFormatter.parse(datestr);
432                        } catch (ParseException e) {
433                                // TODO Auto-generated catch block
434                                e.printStackTrace();
435                               
436                        }
437                        String sender = csvline[1];
438                        String text = csvline[2];
439                       
440                        Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, sender);
441
442                        ContentValues messageValues = new ContentValues();
443                        messageValues.put(RapidSmsDBConstants.Message.MESSAGE, text);
444                        messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID());
445
446                        messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(getRandomDate()));
447                        messageValues.put(RapidSmsDBConstants.Message.RECEIVE_TIME, Message.SQLDateFormatter.format(dateval));
448                        messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false);
449
450                        Uri msgUri = null;
451                       
452                        msgUri = this.getContentResolver().insert(RapidSmsDBConstants.Message.CONTENT_URI, messageValues);
453                        Vector<IParseResult> results = ParsingService.ParseMessage(mForm, text);
454                        ParsedDataTranslator.InsertFormData(this, mForm, Integer.valueOf(msgUri.getPathSegments().get(1))
455                                                                                                                                                        .intValue(), results);
456                }
457
458
459
460        }
461       
462        private void doRandomizedInjection() {
463                Random r = new Random();
464
465                // Debug.startMethodTracing("injection");
466                for (int i = 0; i < 100; i++) {
467
468                        // first, let's get the
469                        String token = phones[r.nextInt(phones.length)];// Long.toString(Math.abs(r.nextLong()),
470                                                                                                                        // 36);
471                        Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(this, token);
472
473                        Uri writeMessageUri = RapidSmsDBConstants.Message.CONTENT_URI;
474
475                        StringBuilder sb = this.generateRandomMessage();
476                        ContentValues messageValues = new ContentValues();
477                        messageValues.put(RapidSmsDBConstants.Message.MESSAGE, sb.toString());
478                        messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID());
479
480                        Date now = getRandomDate();
481
482                        messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(now));
483                        messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false);
484
485                        Uri msgUri = null;
486
487                        msgUri = getContentResolver().insert(writeMessageUri, messageValues);
488
489                        Vector<IParseResult> results = ParsingService.ParseMessage(mForm, sb.toString());
490                        ParsedDataTranslator.InsertFormData(this, mForm, Integer.valueOf(msgUri.getPathSegments().get(1))
491                                                                                                                                        .intValue(), results);
492                }
493
494                Debug.stopMethodTracing();
495
496        }
497
498        private Date getRandomDate() {
499                Calendar cdr = Calendar.getInstance();
500                // cdr.set(1999, 1, 1);
501                cdr.set(Calendar.MONTH, cdr.get(Calendar.MONTH) - 3);
502                cdr.set(Calendar.HOUR_OF_DAY, 0);
503                cdr.set(Calendar.MINUTE, 0);
504                cdr.set(Calendar.SECOND, 0);
505                long val1 = cdr.getTimeInMillis();
506
507                cdr = Calendar.getInstance();
508                cdr.set(Calendar.HOUR_OF_DAY, 23);
509                cdr.set(Calendar.MINUTE, 59);
510                cdr.set(Calendar.SECOND, 0);
511                long val2 = cdr.getTimeInMillis();
512
513                Random r = new Random();
514                long randomTS = (long) (r.nextDouble() * (val2 - val1)) + val1;
515                Date d = new Date(randomTS);
516                return d;
517        }
518
519        private static String[] bools = new String[] { "t", "f", "true", "false", "yes", "no", "y", "n" };
520        private static String[] heights = new String[] { "cm", "m", "meters", "meter" };
521        private static String[] lengths = new String[] { "cm", "m" };
522        private static String[] weights = new String[] { "kg", "kilos", "kilo", "kg" };
523        private static String[] words = new String[] { "bos", "nyc", "jfk", "lax", "lun", "lhr", "asvasd", "alksjwlejrwer",
524                        "bshdkghk", "akhsdwer", "tiwowuy", "xvcxbxkhcvb" };
525        private static String[] phones = new String[] { "5558675309", "6175803100", "2128246918", "2123267768",
526                        "6175803103" };
527
528        private static String[] floats = new String[] { "0.24", "0.54", "1.5", "50%", "25 pct", "33 %", "15pct", "2/3",
529                        "3:2" };
530
531        Random r = new Random();
532
533        /**
534         * @return
535         */
536        private StringBuilder generateRandomMessage() {
537                StringBuilder sb = new StringBuilder();
538
539                sb.append(mForm.getPrefix() + " ");
540
541                Field[] fields = mForm.getFields();
542                int len = fields.length;
543
544                for (int i = 0; i < len; i++) {
545                        Field field = fields[i];
546
547                        String type = field.getFieldType().getReadableName();
548
549                        if (type.toLowerCase().equals("word")) {
550                                sb.append(words[r.nextInt(words.length)]);
551                        } else if (type.toLowerCase().equals("number")) {
552                                sb.append(r.nextInt(1000));
553                        } else if (type.equals("Height")) {
554                                sb.append(r.nextInt(200) + " " + heights[r.nextInt(heights.length)]);
555                        } else if (type.toLowerCase().equals("boolean") || type.toLowerCase().equals("yes/no")) {
556                                sb.append(bools[r.nextInt(bools.length)]);
557                        } else if (type.toLowerCase().equals("length")) {
558                                sb.append(r.nextInt(200) + " " + lengths[r.nextInt(lengths.length)]);
559                        } else if (type.toLowerCase().equals("ratio")) {
560
561                                sb.append(floats[r.nextInt(floats.length)]);
562                        } else if (type.toLowerCase().equals("weight")) {
563                                sb.append(r.nextInt(150) + " " + weights[r.nextInt(weights.length)]);
564                        }
565                        sb.append(" ");
566
567                }
568                return sb;
569        }
570}
Note: See TracBrowser for help on using the browser.