-
Notifications
You must be signed in to change notification settings - Fork 108
/
DatabaseManager.java
454 lines (374 loc) · 16.6 KB
/
DatabaseManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
* For questions related to commercial use licensing, please contact sales@telestax.com.
*
*/
package org.restcomm.android.olympus;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// Provides access to DB facilities
class DatabaseManager {
private static DatabaseManager instance = new DatabaseManager();
private static DatabaseHelper databaseHelper = null;
private static final String TAG = "DatabaseManager";
public static DatabaseManager getInstance()
{
return instance;
}
private DatabaseManager()
{
}
// Before we can use Database manager we need to first call open() and pass Android context
public void open(Context context)
{
if (databaseHelper == null) {
Log.i(TAG, "Database hasn't been opened; opening now");
// If this turns out to be slow, we might have to put it to background thread (AsyncTask, etc), but I think data are too little to cause us trouble
databaseHelper = new DatabaseHelper(context);
}
else {
Log.w(TAG, "Database is already open");
}
}
// ---- Contacts table
// Retrieve all contact entries from DB and return them
ArrayList<Map<String, String>> retrieveContacts()
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened yet, please call open()");
}
//SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
//qb.setTables(DatabaseContract.ContactEntry.TABLE_NAME);
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] columns = {
DatabaseContract.ContactEntry.COLUMN_NAME_NAME,
DatabaseContract.ContactEntry.COLUMN_NAME_URI,
};
// How you want the results sorted in the resulting Cursor
//String sortOrder = DatabaseContract.ContactEntry.COLUMN_NAME_NAME + " ASC";
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(
DatabaseContract.ContactEntry.TABLE_NAME, // The table to query
columns, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // don't sort the results
);
ArrayList<Map<String, String>> contactList = new ArrayList<Map<String, String>>();
// moveToFirst() fails if cursor is empty
if (cursor.moveToFirst()) {
// iterate the rows, read from db and populate contactList
do {
contactList.add(createContactEntry(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.ContactEntry.COLUMN_NAME_NAME)),
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.ContactEntry.COLUMN_NAME_URI))));
} while (cursor.moveToNext());
}
cursor.close();
return contactList;
}
public void addContact(String name, String uri) throws SQLException
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened.");
}
// Gets the data repository in write mode
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(DatabaseContract.ContactEntry.COLUMN_NAME_NAME, name);
values.put(DatabaseContract.ContactEntry.COLUMN_NAME_URI, uri);
db.insertOrThrow(DatabaseContract.ContactEntry.TABLE_NAME, null, values);
}
/*
* Add contact if it doesn't exist already.
* @return true if contact didn't exist (and hence was added), false if it existed
*/
public boolean addContactIfNeded(String uri)
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened.");
}
String contactName = uri.replaceAll("^sip:", "").replaceAll("@.*$", "");
Cursor cursor = getContactFromName(contactName);
if (!cursor.moveToFirst()) {
// doesn't exist, need to create it
// Gets the data repository in write mode
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(DatabaseContract.ContactEntry.COLUMN_NAME_NAME, contactName);
values.put(DatabaseContract.ContactEntry.COLUMN_NAME_URI, contactName);
db.insertOrThrow(DatabaseContract.ContactEntry.TABLE_NAME, null, values);
return true;
}
return false;
}
// Important: currently contactName passed by Application is in reality the user part of the sipuri, so to match a contact entry
// we try with COLUMN_NAME_URI, not COLUMN_NAME_NAME
private int getContactIdFromName(String contactName)
{
Cursor cursor = getContactFromName(contactName);
/*
// Only interested in the ID
String[] columns = {
DatabaseContract.ContactEntry._ID,
};
// Add the WHERE clause
String selection = DatabaseContract.ContactEntry.COLUMN_NAME_URI + " LIKE ?";
String[] selectionArgs = { "%" + contactName + "%"};
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(
DatabaseContract.ContactEntry.TABLE_NAME, // The table to query
columns, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null, // don't sort the results
"1" // only keep one entry
);
*/
// moveToFirst() fails if cursor is empty
if (cursor.moveToFirst()) {
int contactId = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.ContactEntry._ID));
return contactId;
}
else {
return -1;
}
}
// Important: currently contactName passed by Application is in reality the user part of the sipuri, so to match a contact entry
// we try with COLUMN_NAME_URI, not COLUMN_NAME_NAME
private Cursor getContactFromName(String contactName)
{
// Only interested in the ID
/*
String[] columns = {
DatabaseContract.ContactEntry._ID,
};
*/
// Add the WHERE clause
String selection = DatabaseContract.ContactEntry.COLUMN_NAME_URI + " LIKE ?";
String[] selectionArgs = { "%" + contactName + "%"};
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(
DatabaseContract.ContactEntry.TABLE_NAME, // The table to query
null, // The columns to return (all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null, // don't sort the results
"1" // only keep one entry
);
return cursor;
}
private Cursor getContactFromUri(String uri)
{
// Only interested in the ID
/*
String[] columns = {
DatabaseContract.ContactEntry._ID,
};
*/
// Add the WHERE clause
String selection = DatabaseContract.ContactEntry.COLUMN_NAME_URI + " LIKE ?";
String[] selectionArgs = { uri };
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor cursor = db.query(
DatabaseContract.ContactEntry.TABLE_NAME, // The table to query
null, // The columns to return (all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null, // don't sort the results
"1" // only keep one entry
);
return cursor;
}
// Updates contact in DB. Returns -1 if contact is not found
public int updateContact(String name, String uri)
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened.");
}
// Gets the data repository in write mode
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// Update name & uri columns
ContentValues values = new ContentValues();
// Don't allow contact name to be modified
//values.put(DatabaseContract.ContactEntry.COLUMN_NAME_NAME, name);
values.put(DatabaseContract.ContactEntry.COLUMN_NAME_URI, uri);
// Add the WHERE clause
String selection = DatabaseContract.ContactEntry.COLUMN_NAME_NAME + " LIKE ?";
String[] selectionArgs = { name };
int count = db.update(
DatabaseContract.ContactEntry.TABLE_NAME,
values,
selection,
selectionArgs);
if (count > 0) {
int i = 0;
ArrayList<Map<String, String>> allContacts = retrieveContacts();
for (Map<String, String> item: allContacts) {
if (item.get("username").equals(name)) {
return i;
}
i++;
}
}
return -1;
}
// Removes contact from DB. Returns -1 if contact is not found
public int removeContact(String name, String uri)
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened.");
}
boolean found = false;
int i = 0;
ArrayList<Map<String, String>> allContacts = retrieveContacts();
for (Map<String, String> item: allContacts) {
if (item.get("username").equals(name)) {
found = true;
break;
}
i++;
}
if (!found) {
return -1;
}
// Gets the data repository in write mode
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// Update name & uri columns
ContentValues values = new ContentValues();
// Add the WHERE clause
String selection = DatabaseContract.ContactEntry.COLUMN_NAME_NAME + " LIKE ?";
String[] selectionArgs = { name };
int count = db.delete(
DatabaseContract.ContactEntry.TABLE_NAME,
selection,
selectionArgs);
if (count > 0) {
return i;
}
return -1;
}
// ---- Message table
// Retrieve all messages for a contact ordered by timestamp
ArrayList<Map<String, String>> retrieveMessages(String contactName)
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened yet, please call open()");
}
SQLiteDatabase db = databaseHelper.getReadableDatabase();
// Add the WHERE clause
String[] selectionArgs = { contactName };
// Here's an example: SELECT * FROM message INNER JOIN contact ON message.contact_id = contact._id WHERE contact.name LIKE ? ORDER BY timestamp ASC
String sqlQuery = "SELECT * FROM " + DatabaseContract.MessageEntry.TABLE_NAME + " INNER JOIN " +
DatabaseContract.ContactEntry.TABLE_NAME + " ON message." + DatabaseContract.MessageEntry.COLUMN_NAME_CONTACT_ID + " = contact." +
DatabaseContract.ContactEntry._ID + " " +
"WHERE " + DatabaseContract.ContactEntry.TABLE_NAME + "." + DatabaseContract.ContactEntry.COLUMN_NAME_NAME + " LIKE ? " +
"ORDER BY " + DatabaseContract.MessageEntry.COLUMN_NAME_TIMESTAMP + " ASC";
Log.i(TAG, "Query String: " + sqlQuery);
Cursor cursor = db.rawQuery(sqlQuery, selectionArgs);
ArrayList<Map<String, String>> messageList = new ArrayList<Map<String, String>>();
// moveToFirst() fails if cursor is empty
if (cursor.moveToFirst()) {
// iterate the rows, read from db and populate contactList
do {
messageList.add(createMessageEntry(
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.MessageEntry.COLUMN_NAME_TYPE)),
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.ContactEntry.COLUMN_NAME_NAME)),
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.MessageEntry.COLUMN_NAME_TEXT))));
} while (cursor.moveToNext());
}
cursor.close();
return messageList;
}
public void addMessage(String contactName, String messageText, boolean isLocal) throws SQLException
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened.");
}
// Gets the data repository in write mode
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
String type = "local";
if (!isLocal) {
type = "remote";
}
int contactId = getContactIdFromName(contactName);
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_CONTACT_ID, contactId);
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TEXT, messageText);
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_TYPE, type);
db.insertOrThrow(DatabaseContract.MessageEntry.TABLE_NAME, null, values);
}
public void updateMessageStatus(String jobId, boolean isDelivered) throws SQLException
{
if (databaseHelper == null) {
throw new RuntimeException("Database hasn't been opened.");
}
// Gets the data repository in write mode
SQLiteDatabase db = databaseHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(DatabaseContract.MessageEntry.COLUMN_NAME_DELIVERY_STATUS, isDelivered);
// Add the WHERE clause
String selection = DatabaseContract.MessageEntry.COLUMN_NAME_JOB_ID + " LIKE ?";
String[] selectionArgs = { jobId };
int count = db.update(
DatabaseContract.MessageEntry.TABLE_NAME,
values,
selection,
selectionArgs);
}
// Helpers for adapters
private HashMap<String, String> createContactEntry(String name, String uri)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put("username", name);
item.put("sipuri", uri);
return item;
}
private HashMap<String, String> createMessageEntry(String type, String name, String message)
{
HashMap<String, String> item = new HashMap<String, String>();
if (type.equals("local")) {
item.put(MessageFragment.MESSAGE_CONTACT_KEY, "Me");
}
else {
item.put(MessageFragment.MESSAGE_CONTACT_KEY, name);
}
item.put(MessageFragment.MESSAGE_TEXT_KEY, message);
return item;
}
}