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/unittests/org/rapidandroid/tests/MessageCorpusTests.java @ 133

Revision 133, 9.3 KB (checked in by dmyung, 10 months ago)

applying GPL license to source

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 */
19package org.rapidandroid.tests;
20
21import java.io.BufferedReader;
22import java.io.IOException;
23import java.io.InputStream;
24import java.io.StringReader;
25import java.text.ParseException;
26import java.util.Date;
27import java.util.StringTokenizer;
28import java.util.Vector;
29
30import org.rapidandroid.ModelBootstrap;
31import org.rapidandroid.content.translation.MessageTranslator;
32import org.rapidandroid.content.translation.ModelTranslator;
33import org.rapidandroid.content.translation.ParsedDataTranslator;
34import org.rapidandroid.data.RapidSmsDBConstants;
35import org.rapidandroid.data.SmsDbHelper;
36import org.rapidsms.java.core.model.Form;
37import org.rapidsms.java.core.model.Message;
38import org.rapidsms.java.core.model.Monitor;
39import org.rapidsms.java.core.parser.IParseResult;
40import org.rapidsms.java.core.parser.service.ParsingService;
41
42import android.content.ContentValues;
43import android.content.Context;
44import android.content.Intent;
45import android.database.Cursor;
46import android.net.Uri;
47import android.telephony.gsm.SmsManager;
48import android.test.AndroidTestCase;
49
50/**
51 * @author Daniel Myung [email protected]
52 * @created Feb 6, 2009 Summary:
53 */
54public class MessageCorpusTests extends AndroidTestCase {
55
56        private String[] prefixes = null;
57        private Form[] forms = null;
58        private Context mContext = null;
59
60        private SmsDbHelper mHelper;
61
62        private void initLists() {
63                forms = ModelTranslator.getAllForms();
64                prefixes = new String[forms.length];
65                for (int i = 0; i < forms.length; i++) {
66                        prefixes[i] = forms[i].getPrefix();
67                        getContext().getContentResolver().delete(
68                                                                                                                Uri.parse(RapidSmsDBConstants.FormData.CONTENT_URI_PREFIX
69                                                                                                                                + forms[i].getFormId()), null, null);
70
71                }
72        }
73
74        /*
75         * (non-Javadoc)
76         *
77         * @see android.test.AndroidTestCase#setUp()
78         */
79        @Override
80        protected void setUp() throws Exception {
81                // TODO Auto-generated method stub
82                super.setUp();
83                ModelBootstrap.InitApplicationDatabase(getContext());
84                mHelper = new SmsDbHelper(getContext());
85                ModelTranslator.setDbHelper(mHelper, getContext());
86
87                initLists();
88                getContext().getContentResolver().delete(RapidSmsDBConstants.Message.CONTENT_URI, null, null);
89        }
90
91        /*
92         * (non-Javadoc)
93         *
94         * @see android.test.AndroidTestCase#tearDown()
95         */
96        @Override
97        protected void tearDown() throws Exception {
98                // TODO Auto-generated method stub
99                super.tearDown();
100        }
101
102        @SuppressWarnings("finally")
103        private Vector<String[]> readRawMessages() {
104                String rawMessageText = loadAssetFile("testdata/rawdata.csv");
105                return readCsv(rawMessageText);
106        }
107
108        /**
109         * @param rawMessageText
110         * @return
111         */
112        private Vector<String[]> readCsv(String rawMessageText) {
113                StringReader sr = new StringReader(rawMessageText);
114                BufferedReader bufRdr = new BufferedReader(sr);
115
116                String line = null;
117                int row = 0;
118                int col = 0;
119                Vector<String[]> lines = new Vector<String[]>();
120                // read each line of text file
121                try {
122                        while ((line = bufRdr.readLine()) != null) {
123                                StringTokenizer st = new StringTokenizer(line, ",");
124                                int tokCount = st.countTokens();
125
126                                String[] tokenizedLine = new String[tokCount];
127                                int toki = 0;
128                                while (st.hasMoreTokens()) {
129                                        tokenizedLine[toki] = st.nextToken();
130                                        toki++;
131                                }
132                                lines.add(tokenizedLine);
133                        }
134                } catch (IOException e) {
135                        // TODO Auto-generated catch block
136                        e.printStackTrace();
137                } finally {
138
139                        try {
140                                sr.close();
141                                bufRdr.close();
142                        } catch (IOException e) {
143                                // TODO Auto-generated catch block
144                                e.printStackTrace();
145                        }
146                }
147                return lines;
148        }
149
150        private Vector<String[]> readRawAnswers() {
151                String rawMessageText = loadAssetFile("testdata/answers.csv");
152                return readCsv(rawMessageText);
153        }
154
155        private Form determineForm(String message) {
156                int len = prefixes.length;
157                for (int i = 0; i < len; i++) {
158                        String prefix = prefixes[i];
159                        if (message.toLowerCase().trim().startsWith(prefix + " ")) {
160                                return forms[i];
161                        }
162                }
163                return null;
164        }
165
166        /**
167         * Retains the dates in a given message
168         *
169         * @param phone
170         * @param date
171         * @param text
172         */
173        private void injectMessageDirect(String phone, Date date, String text) {
174                Uri writeMessageUri = RapidSmsDBConstants.Message.CONTENT_URI;
175                Monitor monitor = MessageTranslator.GetMonitorAndInsertIfNew(getContext(), phone);
176
177                ContentValues messageValues = new ContentValues();
178                messageValues.put(RapidSmsDBConstants.Message.MESSAGE, text);
179                messageValues.put(RapidSmsDBConstants.Message.MONITOR, monitor.getID());
180
181                messageValues.put(RapidSmsDBConstants.Message.TIME, Message.SQLDateFormatter.format(date));
182                messageValues.put(RapidSmsDBConstants.Message.RECEIVE_TIME, Message.SQLDateFormatter.format(date));
183                messageValues.put(RapidSmsDBConstants.Message.IS_OUTGOING, false);
184
185                Uri msgUri = null;
186                Form mForm = determineForm(text);
187                msgUri = getContext().getContentResolver().insert(writeMessageUri, messageValues);
188                Vector<IParseResult> results = ParsingService.ParseMessage(mForm, text);
189                ParsedDataTranslator.InsertFormData(getContext(), mForm, Integer.valueOf(msgUri.getPathSegments().get(1))
190                                                                                                                                                .intValue(), results);
191        }
192
193        private String loadAssetFile(String filename) {
194                try {
195                        InputStream is = getContext().getAssets().open(filename);
196
197                        int size = is.available();
198
199                        // Read the entire asset into a local byte buffer.
200                        byte[] buffer = new byte[size];
201                        is.read(buffer);
202                        is.close();
203
204                        // Convert the buffer into a Java string.
205                        String text = new String(buffer);
206
207                        return text;
208
209                } catch (IOException e) {
210                        // Should never happen!
211                        throw new RuntimeException(e);
212                }
213        }
214
215        private void sendMessageViaSMS(Context context, String mesg) {
216                SmsManager smgr = SmsManager.getDefault();
217                Intent intent = new Intent();
218                smgr.sendTextMessage("5554", null, mesg, null, null);
219        }
220
221        public void testInsertDirect() {
222                Vector<String[]> rawMessages = readRawMessages();
223                int len = rawMessages.size();
224
225                for (int i = 0; i < len; i++) {
226                        String[] line = rawMessages.get(i);
227                        assertEquals(3, line.length);
228
229                        String datestr = line[0];
230
231                        Date dateval = new Date();
232                        try {
233                                dateval = Message.SQLDateFormatter.parse(datestr);
234                        } catch (ParseException e) {
235                                // TODO Auto-generated catch block
236                                e.printStackTrace();
237                                assertTrue(false);
238                        }
239                        String sender = line[1];
240                        String text = line[2];
241
242                        injectMessageDirect(sender, dateval, text);
243                }
244
245                Cursor cr = getContext().getContentResolver().query(RapidSmsDBConstants.Message.CONTENT_URI, null, null, null,
246                                                                                                                        null);
247                assertEquals(cr.getCount(), rawMessages.size());
248        }
249
250        // public void testInsertViaSendSMS() {
251        // Vector<String[]> rawMessages = readRawMessages();
252        // int len = rawMessages.size();
253        //             
254        // for(int i = 0; i < len; i++) {
255        // String[] line = rawMessages.get(i);
256        // assertEquals(3,line.length);
257        // String text = line[2];
258        //                     
259        // sendMessageViaSMS(getContext(),text);
260        // }
261        //             
262        // Cursor cr =
263        // getContext().getContentResolver().query(RapidSmsDBConstants.Message.CONTENT_URI,
264        // null,null,null,null);
265        // assertEquals(cr.getCount(),rawMessages.size());
266        // }
267
268        public void testInsertVerifyCounts() {
269                testInsertDirect();
270                Vector<String[]> rawMessages = readRawMessages();
271                Vector<String[]> rawAnswers = readRawAnswers();
272                Form mForm = null;
273                assertEquals(rawMessages.size(), rawAnswers.size());
274                int len = rawMessages.size();
275                for (int i = 0; i < len; i++) {
276                        String[] line = rawMessages.get(i);
277                        // String[] answers = rawAnswers.get(i);
278                        String text = line[2];
279                        mForm = determineForm(text);
280                        if (i == 0) {
281                                Cursor cr = getContext().getContentResolver()
282                                                                                .query(
283                                                                                                Uri.parse(RapidSmsDBConstants.FormData.CONTENT_URI_PREFIX
284                                                                                                                + mForm.getFormId()), null, null, null, null);
285                                assertEquals(cr.getCount(), len);
286                                cr.close();
287                                // sorry, ridiculous, i know
288                                break;
289                        }
290                }
291
292                // now, let's parse the data itself
293                Cursor answercursor = getContext().getContentResolver()
294                                                                                        .query(
295                                                                                                        Uri.parse(RapidSmsDBConstants.FormData.CONTENT_URI_PREFIX
296                                                                                                                        + mForm.getFormId()), null, null, null, null);
297
298                answercursor.moveToFirst();
299
300                for (int i = 0; i < len; i++) {
301                        String[] answers = rawAnswers.get((len - 1) - i);
302                        // assertEquals(answercursor.getColumnCount(), 6);
303
304                        // this is cuz the answer data has a leading column
305                        for (int j = 1; j < answers.length; j++) {
306                                assertEquals(answers[j].trim().toLowerCase(), answercursor.getString(j + 1));
307                        }
308                        answercursor.moveToNext();
309                }
310        }
311
312}
Note: See TracBrowser for help on using the browser.