Home | History | Annotate | Download | only in pdu
      1 /*
      2  * Copyright (C) 2007-2008 Esmertec AG.
      3  * Copyright (C) 2007-2008 The Android Open Source Project
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *      http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  */
     17 
     18 package com.google.android.mms.pdu;
     19 
     20 import com.google.android.mms.ContentType;
     21 import com.google.android.mms.InvalidHeaderValueException;
     22 import com.google.android.mms.MmsException;
     23 import com.google.android.mms.util.PduCache;
     24 import com.google.android.mms.util.PduCacheEntry;
     25 import com.google.android.mms.util.SqliteWrapper;
     26 
     27 import android.content.ContentResolver;
     28 import android.content.ContentUris;
     29 import android.content.ContentValues;
     30 import android.content.Context;
     31 import android.database.Cursor;
     32 import android.database.DatabaseUtils;
     33 import android.net.Uri;
     34 import android.provider.Telephony;
     35 import android.provider.Telephony.Mms;
     36 import android.provider.Telephony.MmsSms;
     37 import android.provider.Telephony.Threads;
     38 import android.provider.Telephony.Mms.Addr;
     39 import android.provider.Telephony.Mms.Part;
     40 import android.provider.Telephony.MmsSms.PendingMessages;
     41 import android.text.TextUtils;
     42 import android.util.Config;
     43 import android.util.Log;
     44 
     45 import java.io.ByteArrayOutputStream;
     46 import java.io.FileNotFoundException;
     47 import java.io.IOException;
     48 import java.io.InputStream;
     49 import java.io.OutputStream;
     50 import java.io.UnsupportedEncodingException;
     51 import java.util.ArrayList;
     52 import java.util.HashMap;
     53 import java.util.HashSet;
     54 import java.util.Map;
     55 import java.util.Set;
     56 import java.util.Map.Entry;
     57 
     58 import com.google.android.mms.pdu.EncodedStringValue;
     59 
     60 /**
     61  * This class is the high-level manager of PDU storage.
     62  */
     63 public class PduPersister {
     64     private static final String TAG = "PduPersister";
     65     private static final boolean DEBUG = false;
     66     private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
     67 
     68     private static final long DUMMY_THREAD_ID = Long.MAX_VALUE;
     69 
     70     /**
     71      * The uri of temporary drm objects.
     72      */
     73     public static final String TEMPORARY_DRM_OBJECT_URI =
     74         "content://mms/" + Long.MAX_VALUE + "/part";
     75     /**
     76      * Indicate that we transiently failed to process a MM.
     77      */
     78     public static final int PROC_STATUS_TRANSIENT_FAILURE   = 1;
     79     /**
     80      * Indicate that we permanently failed to process a MM.
     81      */
     82     public static final int PROC_STATUS_PERMANENTLY_FAILURE = 2;
     83     /**
     84      * Indicate that we have successfully processed a MM.
     85      */
     86     public static final int PROC_STATUS_COMPLETED           = 3;
     87 
     88     private static PduPersister sPersister;
     89     private static final PduCache PDU_CACHE_INSTANCE;
     90 
     91     private static final int[] ADDRESS_FIELDS = new int[] {
     92             PduHeaders.BCC,
     93             PduHeaders.CC,
     94             PduHeaders.FROM,
     95             PduHeaders.TO
     96     };
     97 
     98     private static final String[] PDU_PROJECTION = new String[] {
     99         Mms._ID,
    100         Mms.MESSAGE_BOX,
    101         Mms.THREAD_ID,
    102         Mms.RETRIEVE_TEXT,
    103         Mms.SUBJECT,
    104         Mms.CONTENT_LOCATION,
    105         Mms.CONTENT_TYPE,
    106         Mms.MESSAGE_CLASS,
    107         Mms.MESSAGE_ID,
    108         Mms.RESPONSE_TEXT,
    109         Mms.TRANSACTION_ID,
    110         Mms.CONTENT_CLASS,
    111         Mms.DELIVERY_REPORT,
    112         Mms.MESSAGE_TYPE,
    113         Mms.MMS_VERSION,
    114         Mms.PRIORITY,
    115         Mms.READ_REPORT,
    116         Mms.READ_STATUS,
    117         Mms.REPORT_ALLOWED,
    118         Mms.RETRIEVE_STATUS,
    119         Mms.STATUS,
    120         Mms.DATE,
    121         Mms.DELIVERY_TIME,
    122         Mms.EXPIRY,
    123         Mms.MESSAGE_SIZE,
    124         Mms.SUBJECT_CHARSET,
    125         Mms.RETRIEVE_TEXT_CHARSET,
    126     };
    127 
    128     private static final int PDU_COLUMN_ID                    = 0;
    129     private static final int PDU_COLUMN_MESSAGE_BOX           = 1;
    130     private static final int PDU_COLUMN_THREAD_ID             = 2;
    131     private static final int PDU_COLUMN_RETRIEVE_TEXT         = 3;
    132     private static final int PDU_COLUMN_SUBJECT               = 4;
    133     private static final int PDU_COLUMN_CONTENT_LOCATION      = 5;
    134     private static final int PDU_COLUMN_CONTENT_TYPE          = 6;
    135     private static final int PDU_COLUMN_MESSAGE_CLASS         = 7;
    136     private static final int PDU_COLUMN_MESSAGE_ID            = 8;
    137     private static final int PDU_COLUMN_RESPONSE_TEXT         = 9;
    138     private static final int PDU_COLUMN_TRANSACTION_ID        = 10;
    139     private static final int PDU_COLUMN_CONTENT_CLASS         = 11;
    140     private static final int PDU_COLUMN_DELIVERY_REPORT       = 12;
    141     private static final int PDU_COLUMN_MESSAGE_TYPE          = 13;
    142     private static final int PDU_COLUMN_MMS_VERSION           = 14;
    143     private static final int PDU_COLUMN_PRIORITY              = 15;
    144     private static final int PDU_COLUMN_READ_REPORT           = 16;
    145     private static final int PDU_COLUMN_READ_STATUS           = 17;
    146     private static final int PDU_COLUMN_REPORT_ALLOWED        = 18;
    147     private static final int PDU_COLUMN_RETRIEVE_STATUS       = 19;
    148     private static final int PDU_COLUMN_STATUS                = 20;
    149     private static final int PDU_COLUMN_DATE                  = 21;
    150     private static final int PDU_COLUMN_DELIVERY_TIME         = 22;
    151     private static final int PDU_COLUMN_EXPIRY                = 23;
    152     private static final int PDU_COLUMN_MESSAGE_SIZE          = 24;
    153     private static final int PDU_COLUMN_SUBJECT_CHARSET       = 25;
    154     private static final int PDU_COLUMN_RETRIEVE_TEXT_CHARSET = 26;
    155 
    156     private static final String[] PART_PROJECTION = new String[] {
    157         Part._ID,
    158         Part.CHARSET,
    159         Part.CONTENT_DISPOSITION,
    160         Part.CONTENT_ID,
    161         Part.CONTENT_LOCATION,
    162         Part.CONTENT_TYPE,
    163         Part.FILENAME,
    164         Part.NAME,
    165         Part.TEXT
    166     };
    167 
    168     private static final int PART_COLUMN_ID                  = 0;
    169     private static final int PART_COLUMN_CHARSET             = 1;
    170     private static final int PART_COLUMN_CONTENT_DISPOSITION = 2;
    171     private static final int PART_COLUMN_CONTENT_ID          = 3;
    172     private static final int PART_COLUMN_CONTENT_LOCATION    = 4;
    173     private static final int PART_COLUMN_CONTENT_TYPE        = 5;
    174     private static final int PART_COLUMN_FILENAME            = 6;
    175     private static final int PART_COLUMN_NAME                = 7;
    176     private static final int PART_COLUMN_TEXT                = 8;
    177 
    178     private static final HashMap<Uri, Integer> MESSAGE_BOX_MAP;
    179     // These map are used for convenience in persist() and load().
    180     private static final HashMap<Integer, Integer> CHARSET_COLUMN_INDEX_MAP;
    181     private static final HashMap<Integer, Integer> ENCODED_STRING_COLUMN_INDEX_MAP;
    182     private static final HashMap<Integer, Integer> TEXT_STRING_COLUMN_INDEX_MAP;
    183     private static final HashMap<Integer, Integer> OCTET_COLUMN_INDEX_MAP;
    184     private static final HashMap<Integer, Integer> LONG_COLUMN_INDEX_MAP;
    185     private static final HashMap<Integer, String> CHARSET_COLUMN_NAME_MAP;
    186     private static final HashMap<Integer, String> ENCODED_STRING_COLUMN_NAME_MAP;
    187     private static final HashMap<Integer, String> TEXT_STRING_COLUMN_NAME_MAP;
    188     private static final HashMap<Integer, String> OCTET_COLUMN_NAME_MAP;
    189     private static final HashMap<Integer, String> LONG_COLUMN_NAME_MAP;
    190 
    191     static {
    192         MESSAGE_BOX_MAP = new HashMap<Uri, Integer>();
    193         MESSAGE_BOX_MAP.put(Mms.Inbox.CONTENT_URI,  Mms.MESSAGE_BOX_INBOX);
    194         MESSAGE_BOX_MAP.put(Mms.Sent.CONTENT_URI,   Mms.MESSAGE_BOX_SENT);
    195         MESSAGE_BOX_MAP.put(Mms.Draft.CONTENT_URI,  Mms.MESSAGE_BOX_DRAFTS);
    196         MESSAGE_BOX_MAP.put(Mms.Outbox.CONTENT_URI, Mms.MESSAGE_BOX_OUTBOX);
    197 
    198         CHARSET_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
    199         CHARSET_COLUMN_INDEX_MAP.put(PduHeaders.SUBJECT, PDU_COLUMN_SUBJECT_CHARSET);
    200         CHARSET_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_TEXT, PDU_COLUMN_RETRIEVE_TEXT_CHARSET);
    201 
    202         CHARSET_COLUMN_NAME_MAP = new HashMap<Integer, String>();
    203         CHARSET_COLUMN_NAME_MAP.put(PduHeaders.SUBJECT, Mms.SUBJECT_CHARSET);
    204         CHARSET_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_TEXT, Mms.RETRIEVE_TEXT_CHARSET);
    205 
    206         // Encoded string field code -> column index/name map.
    207         ENCODED_STRING_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
    208         ENCODED_STRING_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_TEXT, PDU_COLUMN_RETRIEVE_TEXT);
    209         ENCODED_STRING_COLUMN_INDEX_MAP.put(PduHeaders.SUBJECT, PDU_COLUMN_SUBJECT);
    210 
    211         ENCODED_STRING_COLUMN_NAME_MAP = new HashMap<Integer, String>();
    212         ENCODED_STRING_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_TEXT, Mms.RETRIEVE_TEXT);
    213         ENCODED_STRING_COLUMN_NAME_MAP.put(PduHeaders.SUBJECT, Mms.SUBJECT);
    214 
    215         // Text string field code -> column index/name map.
    216         TEXT_STRING_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
    217         TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_LOCATION, PDU_COLUMN_CONTENT_LOCATION);
    218         TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_TYPE, PDU_COLUMN_CONTENT_TYPE);
    219         TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_CLASS, PDU_COLUMN_MESSAGE_CLASS);
    220         TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_ID, PDU_COLUMN_MESSAGE_ID);
    221         TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.RESPONSE_TEXT, PDU_COLUMN_RESPONSE_TEXT);
    222         TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.TRANSACTION_ID, PDU_COLUMN_TRANSACTION_ID);
    223 
    224         TEXT_STRING_COLUMN_NAME_MAP = new HashMap<Integer, String>();
    225         TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_LOCATION, Mms.CONTENT_LOCATION);
    226         TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_TYPE, Mms.CONTENT_TYPE);
    227         TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_CLASS, Mms.MESSAGE_CLASS);
    228         TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_ID, Mms.MESSAGE_ID);
    229         TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.RESPONSE_TEXT, Mms.RESPONSE_TEXT);
    230         TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.TRANSACTION_ID, Mms.TRANSACTION_ID);
    231 
    232         // Octet field code -> column index/name map.
    233         OCTET_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
    234         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_CLASS, PDU_COLUMN_CONTENT_CLASS);
    235         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.DELIVERY_REPORT, PDU_COLUMN_DELIVERY_REPORT);
    236         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_TYPE, PDU_COLUMN_MESSAGE_TYPE);
    237         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.MMS_VERSION, PDU_COLUMN_MMS_VERSION);
    238         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.PRIORITY, PDU_COLUMN_PRIORITY);
    239         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.READ_REPORT, PDU_COLUMN_READ_REPORT);
    240         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.READ_STATUS, PDU_COLUMN_READ_STATUS);
    241         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.REPORT_ALLOWED, PDU_COLUMN_REPORT_ALLOWED);
    242         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_STATUS, PDU_COLUMN_RETRIEVE_STATUS);
    243         OCTET_COLUMN_INDEX_MAP.put(PduHeaders.STATUS, PDU_COLUMN_STATUS);
    244 
    245         OCTET_COLUMN_NAME_MAP = new HashMap<Integer, String>();
    246         OCTET_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_CLASS, Mms.CONTENT_CLASS);
    247         OCTET_COLUMN_NAME_MAP.put(PduHeaders.DELIVERY_REPORT, Mms.DELIVERY_REPORT);
    248         OCTET_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_TYPE, Mms.MESSAGE_TYPE);
    249         OCTET_COLUMN_NAME_MAP.put(PduHeaders.MMS_VERSION, Mms.MMS_VERSION);
    250         OCTET_COLUMN_NAME_MAP.put(PduHeaders.PRIORITY, Mms.PRIORITY);
    251         OCTET_COLUMN_NAME_MAP.put(PduHeaders.READ_REPORT, Mms.READ_REPORT);
    252         OCTET_COLUMN_NAME_MAP.put(PduHeaders.READ_STATUS, Mms.READ_STATUS);
    253         OCTET_COLUMN_NAME_MAP.put(PduHeaders.REPORT_ALLOWED, Mms.REPORT_ALLOWED);
    254         OCTET_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_STATUS, Mms.RETRIEVE_STATUS);
    255         OCTET_COLUMN_NAME_MAP.put(PduHeaders.STATUS, Mms.STATUS);
    256 
    257         // Long field code -> column index/name map.
    258         LONG_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>();
    259         LONG_COLUMN_INDEX_MAP.put(PduHeaders.DATE, PDU_COLUMN_DATE);
    260         LONG_COLUMN_INDEX_MAP.put(PduHeaders.DELIVERY_TIME, PDU_COLUMN_DELIVERY_TIME);
    261         LONG_COLUMN_INDEX_MAP.put(PduHeaders.EXPIRY, PDU_COLUMN_EXPIRY);
    262         LONG_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_SIZE, PDU_COLUMN_MESSAGE_SIZE);
    263 
    264         LONG_COLUMN_NAME_MAP = new HashMap<Integer, String>();
    265         LONG_COLUMN_NAME_MAP.put(PduHeaders.DATE, Mms.DATE);
    266         LONG_COLUMN_NAME_MAP.put(PduHeaders.DELIVERY_TIME, Mms.DELIVERY_TIME);
    267         LONG_COLUMN_NAME_MAP.put(PduHeaders.EXPIRY, Mms.EXPIRY);
    268         LONG_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_SIZE, Mms.MESSAGE_SIZE);
    269 
    270         PDU_CACHE_INSTANCE = PduCache.getInstance();
    271      }
    272 
    273     private final Context mContext;
    274     private final ContentResolver mContentResolver;
    275 
    276     private PduPersister(Context context) {
    277         mContext = context;
    278         mContentResolver = context.getContentResolver();
    279      }
    280 
    281     /** Get(or create if not exist) an instance of PduPersister */
    282     public static PduPersister getPduPersister(Context context) {
    283         if ((sPersister == null) || !context.equals(sPersister.mContext)) {
    284             sPersister = new PduPersister(context);
    285         }
    286 
    287         return sPersister;
    288     }
    289 
    290     private void setEncodedStringValueToHeaders(
    291             Cursor c, int columnIndex,
    292             PduHeaders headers, int mapColumn) {
    293         String s = c.getString(columnIndex);
    294         if ((s != null) && (s.length() > 0)) {
    295             int charsetColumnIndex = CHARSET_COLUMN_INDEX_MAP.get(mapColumn);
    296             int charset = c.getInt(charsetColumnIndex);
    297             EncodedStringValue value = new EncodedStringValue(
    298                     charset, getBytes(s));
    299             headers.setEncodedStringValue(value, mapColumn);
    300         }
    301     }
    302 
    303     private void setTextStringToHeaders(
    304             Cursor c, int columnIndex,
    305             PduHeaders headers, int mapColumn) {
    306         String s = c.getString(columnIndex);
    307         if (s != null) {
    308             headers.setTextString(getBytes(s), mapColumn);
    309         }
    310     }
    311 
    312     private void setOctetToHeaders(
    313             Cursor c, int columnIndex,
    314             PduHeaders headers, int mapColumn) throws InvalidHeaderValueException {
    315         if (!c.isNull(columnIndex)) {
    316             int b = c.getInt(columnIndex);
    317             headers.setOctet(b, mapColumn);
    318         }
    319     }
    320 
    321     private void setLongToHeaders(
    322             Cursor c, int columnIndex,
    323             PduHeaders headers, int mapColumn) {
    324         if (!c.isNull(columnIndex)) {
    325             long l = c.getLong(columnIndex);
    326             headers.setLongInteger(l, mapColumn);
    327         }
    328     }
    329 
    330     private Integer getIntegerFromPartColumn(Cursor c, int columnIndex) {
    331         if (!c.isNull(columnIndex)) {
    332             return c.getInt(columnIndex);
    333         }
    334         return null;
    335     }
    336 
    337     private byte[] getByteArrayFromPartColumn(Cursor c, int columnIndex) {
    338         if (!c.isNull(columnIndex)) {
    339             return getBytes(c.getString(columnIndex));
    340         }
    341         return null;
    342     }
    343 
    344     private PduPart[] loadParts(long msgId) throws MmsException {
    345         Cursor c = SqliteWrapper.query(mContext, mContentResolver,
    346                 Uri.parse("content://mms/" + msgId + "/part"),
    347                 PART_PROJECTION, null, null, null);
    348 
    349         PduPart[] parts = null;
    350 
    351         try {
    352             if ((c == null) || (c.getCount() == 0)) {
    353                 if (LOCAL_LOGV) {
    354                     Log.v(TAG, "loadParts(" + msgId + "): no part to load.");
    355                 }
    356                 return null;
    357             }
    358 
    359             int partCount = c.getCount();
    360             int partIdx = 0;
    361             parts = new PduPart[partCount];
    362             while (c.moveToNext()) {
    363                 PduPart part = new PduPart();
    364                 Integer charset = getIntegerFromPartColumn(
    365                         c, PART_COLUMN_CHARSET);
    366                 if (charset != null) {
    367                     part.setCharset(charset);
    368                 }
    369 
    370                 byte[] contentDisposition = getByteArrayFromPartColumn(
    371                         c, PART_COLUMN_CONTENT_DISPOSITION);
    372                 if (contentDisposition != null) {
    373                     part.setContentDisposition(contentDisposition);
    374                 }
    375 
    376                 byte[] contentId = getByteArrayFromPartColumn(
    377                         c, PART_COLUMN_CONTENT_ID);
    378                 if (contentId != null) {
    379                     part.setContentId(contentId);
    380                 }
    381 
    382                 byte[] contentLocation = getByteArrayFromPartColumn(
    383                         c, PART_COLUMN_CONTENT_LOCATION);
    384                 if (contentLocation != null) {
    385                     part.setContentLocation(contentLocation);
    386                 }
    387 
    388                 byte[] contentType = getByteArrayFromPartColumn(
    389                         c, PART_COLUMN_CONTENT_TYPE);
    390                 if (contentType != null) {
    391                     part.setContentType(contentType);
    392                 } else {
    393                     throw new MmsException("Content-Type must be set.");
    394                 }
    395 
    396                 byte[] fileName = getByteArrayFromPartColumn(
    397                         c, PART_COLUMN_FILENAME);
    398                 if (fileName != null) {
    399                     part.setFilename(fileName);
    400                 }
    401 
    402                 byte[] name = getByteArrayFromPartColumn(
    403                         c, PART_COLUMN_NAME);
    404                 if (name != null) {
    405                     part.setName(name);
    406                 }
    407 
    408                 // Construct a Uri for this part.
    409                 long partId = c.getLong(PART_COLUMN_ID);
    410                 Uri partURI = Uri.parse("content://mms/part/" + partId);
    411                 part.setDataUri(partURI);
    412 
    413                 // For images/audio/video, we won't keep their data in Part
    414                 // because their renderer accept Uri as source.
    415                 String type = toIsoString(contentType);
    416                 if (!ContentType.isImageType(type)
    417                         && !ContentType.isAudioType(type)
    418                         && !ContentType.isVideoType(type)) {
    419                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
    420                     InputStream is = null;
    421 
    422                     // Store simple string values directly in the database instead of an
    423                     // external file.  This makes the text searchable and retrieval slightly
    424                     // faster.
    425                     if ("text/plain".equals(type) || "application/smil".equals(type)) {
    426                         String text = c.getString(PART_COLUMN_TEXT);
    427                         byte [] blob = new EncodedStringValue(text != null ? text : "")
    428                             .getTextString();
    429                         baos.write(blob, 0, blob.length);
    430                     } else {
    431 
    432                         try {
    433                             is = mContentResolver.openInputStream(partURI);
    434 
    435                             byte[] buffer = new byte[256];
    436                             int len = is.read(buffer);
    437                             while (len >= 0) {
    438                                 baos.write(buffer, 0, len);
    439                                 len = is.read(buffer);
    440                             }
    441                         } catch (IOException e) {
    442                             Log.e(TAG, "Failed to load part data", e);
    443                             c.close();
    444                             throw new MmsException(e);
    445                         } finally {
    446                             if (is != null) {
    447                                 try {
    448                                     is.close();
    449                                 } catch (IOException e) {
    450                                     Log.e(TAG, "Failed to close stream", e);
    451                                 } // Ignore
    452                             }
    453                         }
    454                     }
    455                     part.setData(baos.toByteArray());
    456                 }
    457                 parts[partIdx++] = part;
    458             }
    459         } finally {
    460             if (c != null) {
    461                 c.close();
    462             }
    463         }
    464 
    465         return parts;
    466     }
    467 
    468     private void loadAddress(long msgId, PduHeaders headers) {
    469         Cursor c = SqliteWrapper.query(mContext, mContentResolver,
    470                 Uri.parse("content://mms/" + msgId + "/addr"),
    471                 new String[] { Addr.ADDRESS, Addr.CHARSET, Addr.TYPE },
    472                 null, null, null);
    473 
    474         if (c != null) {
    475             try {
    476                 while (c.moveToNext()) {
    477                     String addr = c.getString(0);
    478                     if (!TextUtils.isEmpty(addr)) {
    479                         int addrType = c.getInt(2);
    480                         switch (addrType) {
    481                             case PduHeaders.FROM:
    482                                 headers.setEncodedStringValue(
    483                                         new EncodedStringValue(c.getInt(1), getBytes(addr)),
    484                                         addrType);
    485                                 break;
    486                             case PduHeaders.TO:
    487                             case PduHeaders.CC:
    488                             case PduHeaders.BCC:
    489                                 headers.appendEncodedStringValue(
    490                                         new EncodedStringValue(c.getInt(1), getBytes(addr)),
    491                                         addrType);
    492                                 break;
    493                             default:
    494                                 Log.e(TAG, "Unknown address type: " + addrType);
    495                                 break;
    496                         }
    497                     }
    498                 }
    499             } finally {
    500                 c.close();
    501             }
    502         }
    503     }
    504 
    505     /**
    506      * Load a PDU from storage by given Uri.
    507      *
    508      * @param uri The Uri of the PDU to be loaded.
    509      * @return A generic PDU object, it may be cast to dedicated PDU.
    510      * @throws MmsException Failed to load some fields of a PDU.
    511      */
    512     public GenericPdu load(Uri uri) throws MmsException {
    513         PduCacheEntry cacheEntry = PDU_CACHE_INSTANCE.get(uri);
    514         if (cacheEntry != null) {
    515             return cacheEntry.getPdu();
    516         }
    517 
    518         Cursor c = SqliteWrapper.query(mContext, mContentResolver, uri,
    519                         PDU_PROJECTION, null, null, null);
    520         PduHeaders headers = new PduHeaders();
    521         Set<Entry<Integer, Integer>> set;
    522         long msgId = ContentUris.parseId(uri);
    523         int msgBox;
    524         long threadId;
    525 
    526         try {
    527             if ((c == null) || (c.getCount() != 1) || !c.moveToFirst()) {
    528                 throw new MmsException("Bad uri: " + uri);
    529             }
    530 
    531             msgBox = c.getInt(PDU_COLUMN_MESSAGE_BOX);
    532             threadId = c.getLong(PDU_COLUMN_THREAD_ID);
    533 
    534             set = ENCODED_STRING_COLUMN_INDEX_MAP.entrySet();
    535             for (Entry<Integer, Integer> e : set) {
    536                 setEncodedStringValueToHeaders(
    537                         c, e.getValue(), headers, e.getKey());
    538             }
    539 
    540             set = TEXT_STRING_COLUMN_INDEX_MAP.entrySet();
    541             for (Entry<Integer, Integer> e : set) {
    542                 setTextStringToHeaders(
    543                         c, e.getValue(), headers, e.getKey());
    544             }
    545 
    546             set = OCTET_COLUMN_INDEX_MAP.entrySet();
    547             for (Entry<Integer, Integer> e : set) {
    548                 setOctetToHeaders(
    549                         c, e.getValue(), headers, e.getKey());
    550             }
    551 
    552             set = LONG_COLUMN_INDEX_MAP.entrySet();
    553             for (Entry<Integer, Integer> e : set) {
    554                 setLongToHeaders(
    555                         c, e.getValue(), headers, e.getKey());
    556             }
    557         } finally {
    558             if (c != null) {
    559                 c.close();
    560             }
    561         }
    562 
    563         // Check whether 'msgId' has been assigned a valid value.
    564         if (msgId == -1L) {
    565             throw new MmsException("Error! ID of the message: -1.");
    566         }
    567 
    568         // Load address information of the MM.
    569         loadAddress(msgId, headers);
    570 
    571         int msgType = headers.getOctet(PduHeaders.MESSAGE_TYPE);
    572         PduBody body = new PduBody();
    573 
    574         // For PDU which type is M_retrieve.conf or Send.req, we should
    575         // load multiparts and put them into the body of the PDU.
    576         if ((msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF)
    577                 || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) {
    578             PduPart[] parts = loadParts(msgId);
    579             if (parts != null) {
    580                 int partsNum = parts.length;
    581                 for (int i = 0; i < partsNum; i++) {
    582                     body.addPart(parts[i]);
    583                 }
    584             }
    585         }
    586 
    587         GenericPdu pdu = null;
    588         switch (msgType) {
    589             case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
    590                 pdu = new NotificationInd(headers);
    591                 break;
    592             case PduHeaders.MESSAGE_TYPE_DELIVERY_IND:
    593                 pdu = new DeliveryInd(headers);
    594                 break;
    595             case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND:
    596                 pdu = new ReadOrigInd(headers);
    597                 break;
    598             case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
    599                 pdu = new RetrieveConf(headers, body);
    600                 break;
    601             case PduHeaders.MESSAGE_TYPE_SEND_REQ:
    602                 pdu = new SendReq(headers, body);
    603                 break;
    604             case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND:
    605                 pdu = new AcknowledgeInd(headers);
    606                 break;
    607             case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND:
    608                 pdu = new NotifyRespInd(headers);
    609                 break;
    610             case PduHeaders.MESSAGE_TYPE_READ_REC_IND:
    611                 pdu = new ReadRecInd(headers);
    612                 break;
    613             case PduHeaders.MESSAGE_TYPE_SEND_CONF:
    614             case PduHeaders.MESSAGE_TYPE_FORWARD_REQ:
    615             case PduHeaders.MESSAGE_TYPE_FORWARD_CONF:
    616             case PduHeaders.MESSAGE_TYPE_MBOX_STORE_REQ:
    617             case PduHeaders.MESSAGE_TYPE_MBOX_STORE_CONF:
    618             case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_REQ:
    619             case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_CONF:
    620             case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_REQ:
    621             case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_CONF:
    622             case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_REQ:
    623             case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_CONF:
    624             case PduHeaders.MESSAGE_TYPE_MBOX_DESCR:
    625             case PduHeaders.MESSAGE_TYPE_DELETE_REQ:
    626             case PduHeaders.MESSAGE_TYPE_DELETE_CONF:
    627             case PduHeaders.MESSAGE_TYPE_CANCEL_REQ:
    628             case PduHeaders.MESSAGE_TYPE_CANCEL_CONF:
    629                 throw new MmsException(
    630                         "Unsupported PDU type: " + Integer.toHexString(msgType));
    631 
    632             default:
    633                 throw new MmsException(
    634                         "Unrecognized PDU type: " + Integer.toHexString(msgType));
    635         }
    636 
    637         cacheEntry = new PduCacheEntry(pdu, msgBox, threadId);
    638         PDU_CACHE_INSTANCE.put(uri, cacheEntry);
    639         return pdu;
    640     }
    641 
    642     private void persistAddress(
    643             long msgId, int type, EncodedStringValue[] array) {
    644         ContentValues values = new ContentValues(3);
    645 
    646         for (EncodedStringValue addr : array) {
    647             values.clear(); // Clear all values first.
    648             values.put(Addr.ADDRESS, toIsoString(addr.getTextString()));
    649             values.put(Addr.CHARSET, addr.getCharacterSet());
    650             values.put(Addr.TYPE, type);
    651 
    652             Uri uri = Uri.parse("content://mms/" + msgId + "/addr");
    653             SqliteWrapper.insert(mContext, mContentResolver, uri, values);
    654         }
    655     }
    656 
    657     public Uri persistPart(PduPart part, long msgId)
    658             throws MmsException {
    659         Uri uri = Uri.parse("content://mms/" + msgId + "/part");
    660         ContentValues values = new ContentValues(8);
    661 
    662         int charset = part.getCharset();
    663         if (charset != 0 ) {
    664             values.put(Part.CHARSET, charset);
    665         }
    666 
    667         String contentType = null;
    668         if (part.getContentType() != null) {
    669             contentType = toIsoString(part.getContentType());
    670             values.put(Part.CONTENT_TYPE, contentType);
    671             // To ensure the SMIL part is always the first part.
    672             if (ContentType.APP_SMIL.equals(contentType)) {
    673                 values.put(Part.SEQ, -1);
    674             }
    675         } else {
    676             throw new MmsException("MIME type of the part must be set.");
    677         }
    678 
    679         if (part.getFilename() != null) {
    680             String fileName = new String(part.getFilename());
    681             values.put(Part.FILENAME, fileName);
    682         }
    683 
    684         if (part.getName() != null) {
    685             String name = new String(part.getName());
    686             values.put(Part.NAME, name);
    687         }
    688 
    689         Object value = null;
    690         if (part.getContentDisposition() != null) {
    691             value = toIsoString(part.getContentDisposition());
    692             values.put(Part.CONTENT_DISPOSITION, (String) value);
    693         }
    694 
    695         if (part.getContentId() != null) {
    696             value = toIsoString(part.getContentId());
    697             values.put(Part.CONTENT_ID, (String) value);
    698         }
    699 
    700         if (part.getContentLocation() != null) {
    701             value = toIsoString(part.getContentLocation());
    702             values.put(Part.CONTENT_LOCATION, (String) value);
    703         }
    704 
    705         Uri res = SqliteWrapper.insert(mContext, mContentResolver, uri, values);
    706         if (res == null) {
    707             throw new MmsException("Failed to persist part, return null.");
    708         }
    709 
    710         persistData(part, res, contentType);
    711         // After successfully store the data, we should update
    712         // the dataUri of the part.
    713         part.setDataUri(res);
    714 
    715         return res;
    716     }
    717 
    718     /**
    719      * Save data of the part into storage. The source data may be given
    720      * by a byte[] or a Uri. If it's a byte[], directly save it
    721      * into storage, otherwise load source data from the dataUri and then
    722      * save it. If the data is an image, we may scale down it according
    723      * to user preference.
    724      *
    725      * @param part The PDU part which contains data to be saved.
    726      * @param uri The URI of the part.
    727      * @param contentType The MIME type of the part.
    728      * @throws MmsException Cannot find source data or error occurred
    729      *         while saving the data.
    730      */
    731     private void persistData(PduPart part, Uri uri,
    732             String contentType)
    733             throws MmsException {
    734         OutputStream os = null;
    735         InputStream is = null;
    736 
    737         try {
    738             byte[] data = part.getData();
    739             if ("text/plain".equals(contentType) || "application/smil".equals(contentType)) {
    740                 ContentValues cv = new ContentValues();
    741                 cv.put(Telephony.Mms.Part.TEXT, new EncodedStringValue(data).getString());
    742                 if (mContentResolver.update(uri, cv, null, null) != 1) {
    743                     throw new MmsException("unable to update " + uri.toString());
    744                 }
    745             } else {
    746                 os = mContentResolver.openOutputStream(uri);
    747                 if (data == null) {
    748                     Uri dataUri = part.getDataUri();
    749                     if ((dataUri == null) || (dataUri == uri)) {
    750                         Log.w(TAG, "Can't find data for this part.");
    751                         return;
    752                     }
    753                     is = mContentResolver.openInputStream(dataUri);
    754 
    755                     if (LOCAL_LOGV) {
    756                         Log.v(TAG, "Saving data to: " + uri);
    757                     }
    758 
    759                     byte[] buffer = new byte[256];
    760                     for (int len = 0; (len = is.read(buffer)) != -1; ) {
    761                         os.write(buffer, 0, len);
    762                     }
    763                 } else {
    764                     if (LOCAL_LOGV) {
    765                         Log.v(TAG, "Saving data to: " + uri);
    766                     }
    767                     os.write(data);
    768                 }
    769             }
    770         } catch (FileNotFoundException e) {
    771             Log.e(TAG, "Failed to open Input/Output stream.", e);
    772             throw new MmsException(e);
    773         } catch (IOException e) {
    774             Log.e(TAG, "Failed to read/write data.", e);
    775             throw new MmsException(e);
    776         } finally {
    777             if (os != null) {
    778                 try {
    779                     os.close();
    780                 } catch (IOException e) {
    781                     Log.e(TAG, "IOException while closing: " + os, e);
    782                 } // Ignore
    783             }
    784             if (is != null) {
    785                 try {
    786                     is.close();
    787                 } catch (IOException e) {
    788                     Log.e(TAG, "IOException while closing: " + is, e);
    789                 } // Ignore
    790             }
    791         }
    792     }
    793 
    794     private void updateAddress(
    795             long msgId, int type, EncodedStringValue[] array) {
    796         // Delete old address information and then insert new ones.
    797         SqliteWrapper.delete(mContext, mContentResolver,
    798                 Uri.parse("content://mms/" + msgId + "/addr"),
    799                 Addr.TYPE + "=" + type, null);
    800 
    801         persistAddress(msgId, type, array);
    802     }
    803 
    804     /**
    805      * Update headers of a SendReq.
    806      *
    807      * @param uri The PDU which need to be updated.
    808      * @param pdu New headers.
    809      * @throws MmsException Bad URI or updating failed.
    810      */
    811     public void updateHeaders(Uri uri, SendReq sendReq) {
    812         PDU_CACHE_INSTANCE.purge(uri);
    813 
    814         ContentValues values = new ContentValues(10);
    815         byte[] contentType = sendReq.getContentType();
    816         if (contentType != null) {
    817             values.put(Mms.CONTENT_TYPE, toIsoString(contentType));
    818         }
    819 
    820         long date = sendReq.getDate();
    821         if (date != -1) {
    822             values.put(Mms.DATE, date);
    823         }
    824 
    825         int deliveryReport = sendReq.getDeliveryReport();
    826         if (deliveryReport != 0) {
    827             values.put(Mms.DELIVERY_REPORT, deliveryReport);
    828         }
    829 
    830         long expiry = sendReq.getExpiry();
    831         if (expiry != -1) {
    832             values.put(Mms.EXPIRY, expiry);
    833         }
    834 
    835         byte[] msgClass = sendReq.getMessageClass();
    836         if (msgClass != null) {
    837             values.put(Mms.MESSAGE_CLASS, toIsoString(msgClass));
    838         }
    839 
    840         int priority = sendReq.getPriority();
    841         if (priority != 0) {
    842             values.put(Mms.PRIORITY, priority);
    843         }
    844 
    845         int readReport = sendReq.getReadReport();
    846         if (readReport != 0) {
    847             values.put(Mms.READ_REPORT, readReport);
    848         }
    849 
    850         byte[] transId = sendReq.getTransactionId();
    851         if (transId != null) {
    852             values.put(Mms.TRANSACTION_ID, toIsoString(transId));
    853         }
    854 
    855         EncodedStringValue subject = sendReq.getSubject();
    856         if (subject != null) {
    857             values.put(Mms.SUBJECT, toIsoString(subject.getTextString()));
    858             values.put(Mms.SUBJECT_CHARSET, subject.getCharacterSet());
    859         } else {
    860             values.put(Mms.SUBJECT, "");
    861         }
    862 
    863         long messageSize = sendReq.getMessageSize();
    864         if (messageSize > 0) {
    865             values.put(Mms.MESSAGE_SIZE, messageSize);
    866         }
    867 
    868         PduHeaders headers = sendReq.getPduHeaders();
    869         HashSet<String> recipients = new HashSet<String>();
    870         for (int addrType : ADDRESS_FIELDS) {
    871             EncodedStringValue[] array = null;
    872             if (addrType == PduHeaders.FROM) {
    873                 EncodedStringValue v = headers.getEncodedStringValue(addrType);
    874                 if (v != null) {
    875                     array = new EncodedStringValue[1];
    876                     array[0] = v;
    877                 }
    878             } else {
    879                 array = headers.getEncodedStringValues(addrType);
    880             }
    881 
    882             if (array != null) {
    883                 long msgId = ContentUris.parseId(uri);
    884                 updateAddress(msgId, addrType, array);
    885                 if (addrType == PduHeaders.TO) {
    886                     for (EncodedStringValue v : array) {
    887                         if (v != null) {
    888                             recipients.add(v.getString());
    889                         }
    890                     }
    891                 }
    892             }
    893         }
    894 
    895         long threadId = Threads.getOrCreateThreadId(mContext, recipients);
    896         values.put(Mms.THREAD_ID, threadId);
    897 
    898         SqliteWrapper.update(mContext, mContentResolver, uri, values, null, null);
    899     }
    900 
    901     private void updatePart(Uri uri, PduPart part) throws MmsException {
    902         ContentValues values = new ContentValues(7);
    903 
    904         int charset = part.getCharset();
    905         if (charset != 0 ) {
    906             values.put(Part.CHARSET, charset);
    907         }
    908 
    909         String contentType = null;
    910         if (part.getContentType() != null) {
    911             contentType = toIsoString(part.getContentType());
    912             values.put(Part.CONTENT_TYPE, contentType);
    913         } else {
    914             throw new MmsException("MIME type of the part must be set.");
    915         }
    916 
    917         if (part.getFilename() != null) {
    918             String fileName = new String(part.getFilename());
    919             values.put(Part.FILENAME, fileName);
    920         }
    921 
    922         if (part.getName() != null) {
    923             String name = new String(part.getName());
    924             values.put(Part.NAME, name);
    925         }
    926 
    927         Object value = null;
    928         if (part.getContentDisposition() != null) {
    929             value = toIsoString(part.getContentDisposition());
    930             values.put(Part.CONTENT_DISPOSITION, (String) value);
    931         }
    932 
    933         if (part.getContentId() != null) {
    934             value = toIsoString(part.getContentId());
    935             values.put(Part.CONTENT_ID, (String) value);
    936         }
    937 
    938         if (part.getContentLocation() != null) {
    939             value = toIsoString(part.getContentLocation());
    940             values.put(Part.CONTENT_LOCATION, (String) value);
    941         }
    942 
    943         SqliteWrapper.update(mContext, mContentResolver, uri, values, null, null);
    944 
    945         // Only update the data when:
    946         // 1. New binary data supplied or
    947         // 2. The Uri of the part is different from the current one.
    948         if ((part.getData() != null)
    949                 || (uri != part.getDataUri())) {
    950             persistData(part, uri, contentType);
    951         }
    952     }
    953 
    954     /**
    955      * Update all parts of a PDU.
    956      *
    957      * @param uri The PDU which need to be updated.
    958      * @param body New message body of the PDU.
    959      * @throws MmsException Bad URI or updating failed.
    960      */
    961     public void updateParts(Uri uri, PduBody body)
    962             throws MmsException {
    963         PduCacheEntry cacheEntry = PDU_CACHE_INSTANCE.get(uri);
    964         if (cacheEntry != null) {
    965             ((MultimediaMessagePdu) cacheEntry.getPdu()).setBody(body);
    966         }
    967 
    968         ArrayList<PduPart> toBeCreated = new ArrayList<PduPart>();
    969         HashMap<Uri, PduPart> toBeUpdated = new HashMap<Uri, PduPart>();
    970 
    971         int partsNum = body.getPartsNum();
    972         StringBuilder filter = new StringBuilder().append('(');
    973         for (int i = 0; i < partsNum; i++) {
    974             PduPart part = body.getPart(i);
    975             Uri partUri = part.getDataUri();
    976             if ((partUri == null) || !partUri.getAuthority().startsWith("mms")) {
    977                 toBeCreated.add(part);
    978             } else {
    979                 toBeUpdated.put(partUri, part);
    980 
    981                 // Don't use 'i > 0' to determine whether we should append
    982                 // 'AND' since 'i = 0' may be skipped in another branch.
    983                 if (filter.length() > 1) {
    984                     filter.append(" AND ");
    985                 }
    986 
    987                 filter.append(Part._ID);
    988                 filter.append("!=");
    989                 DatabaseUtils.appendEscapedSQLString(filter, partUri.getLastPathSegment());
    990             }
    991         }
    992         filter.append(')');
    993 
    994         long msgId = ContentUris.parseId(uri);
    995 
    996         // Remove the parts which doesn't exist anymore.
    997         SqliteWrapper.delete(mContext, mContentResolver,
    998                 Uri.parse(Mms.CONTENT_URI + "/" + msgId + "/part"),
    999                 filter.length() > 2 ? filter.toString() : null, null);
   1000 
   1001         // Create new parts which didn't exist before.
   1002         for (PduPart part : toBeCreated) {
   1003             persistPart(part, msgId);
   1004         }
   1005 
   1006         // Update the modified parts.
   1007         for (Map.Entry<Uri, PduPart> e : toBeUpdated.entrySet()) {
   1008             updatePart(e.getKey(), e.getValue());
   1009         }
   1010     }
   1011 
   1012     /**
   1013      * Persist a PDU object to specific location in the storage.
   1014      *
   1015      * @param pdu The PDU object to be stored.
   1016      * @param uri Where to store the given PDU object.
   1017      * @return A Uri which can be used to access the stored PDU.
   1018      */
   1019     public Uri persist(GenericPdu pdu, Uri uri) throws MmsException {
   1020         if (uri == null) {
   1021             throw new MmsException("Uri may not be null.");
   1022         }
   1023 
   1024         Integer msgBox = MESSAGE_BOX_MAP.get(uri);
   1025         if (msgBox == null) {
   1026             throw new MmsException(
   1027                     "Bad destination, must be one of "
   1028                     + "content://mms/inbox, content://mms/sent, "
   1029                     + "content://mms/drafts, content://mms/outbox, "
   1030                     + "content://mms/temp.");
   1031         }
   1032         PDU_CACHE_INSTANCE.purge(uri);
   1033 
   1034         PduHeaders header = pdu.getPduHeaders();
   1035         PduBody body = null;
   1036         ContentValues values = new ContentValues();
   1037         Set<Entry<Integer, String>> set;
   1038 
   1039         set = ENCODED_STRING_COLUMN_NAME_MAP.entrySet();
   1040         for (Entry<Integer, String> e : set) {
   1041             int field = e.getKey();
   1042             EncodedStringValue encodedString = header.getEncodedStringValue(field);
   1043             if (encodedString != null) {
   1044                 String charsetColumn = CHARSET_COLUMN_NAME_MAP.get(field);
   1045                 values.put(e.getValue(), toIsoString(encodedString.getTextString()));
   1046                 values.put(charsetColumn, encodedString.getCharacterSet());
   1047             }
   1048         }
   1049 
   1050         set = TEXT_STRING_COLUMN_NAME_MAP.entrySet();
   1051         for (Entry<Integer, String> e : set){
   1052             byte[] text = header.getTextString(e.getKey());
   1053             if (text != null) {
   1054                 values.put(e.getValue(), toIsoString(text));
   1055             }
   1056         }
   1057 
   1058         set = OCTET_COLUMN_NAME_MAP.entrySet();
   1059         for (Entry<Integer, String> e : set){
   1060             int b = header.getOctet(e.getKey());
   1061             if (b != 0) {
   1062                 values.put(e.getValue(), b);
   1063             }
   1064         }
   1065 
   1066         set = LONG_COLUMN_NAME_MAP.entrySet();
   1067         for (Entry<Integer, String> e : set){
   1068             long l = header.getLongInteger(e.getKey());
   1069             if (l != -1L) {
   1070                 values.put(e.getValue(), l);
   1071             }
   1072         }
   1073 
   1074         HashMap<Integer, EncodedStringValue[]> addressMap =
   1075                 new HashMap<Integer, EncodedStringValue[]>(ADDRESS_FIELDS.length);
   1076         // Save address information.
   1077         for (int addrType : ADDRESS_FIELDS) {
   1078             EncodedStringValue[] array = null;
   1079             if (addrType == PduHeaders.FROM) {
   1080                 EncodedStringValue v = header.getEncodedStringValue(addrType);
   1081                 if (v != null) {
   1082                     array = new EncodedStringValue[1];
   1083                     array[0] = v;
   1084                 }
   1085             } else {
   1086                 array = header.getEncodedStringValues(addrType);
   1087             }
   1088             addressMap.put(addrType, array);
   1089         }
   1090 
   1091         HashSet<String> recipients = new HashSet<String>();
   1092         long threadId = DUMMY_THREAD_ID;
   1093         int msgType = pdu.getMessageType();
   1094         // Here we only allocate thread ID for M-Notification.ind,
   1095         // M-Retrieve.conf and M-Send.req.
   1096         // Some of other PDU types may be allocated a thread ID outside
   1097         // this scope.
   1098         if ((msgType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND)
   1099                 || (msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF)
   1100                 || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) {
   1101             EncodedStringValue[] array = null;
   1102             switch (msgType) {
   1103                 case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND:
   1104                 case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF:
   1105                     array = addressMap.get(PduHeaders.FROM);
   1106                     break;
   1107                 case PduHeaders.MESSAGE_TYPE_SEND_REQ:
   1108                     array = addressMap.get(PduHeaders.TO);
   1109                     break;
   1110             }
   1111 
   1112             if (array != null) {
   1113                 for (EncodedStringValue v : array) {
   1114                     if (v != null) {
   1115                         recipients.add(v.getString());
   1116                     }
   1117                 }
   1118             }
   1119             threadId = Threads.getOrCreateThreadId(mContext, recipients);
   1120         }
   1121         values.put(Mms.THREAD_ID, threadId);
   1122 
   1123         // Save parts first to avoid inconsistent message is loaded
   1124         // while saving the parts.
   1125         long dummyId = System.currentTimeMillis(); // Dummy ID of the msg.
   1126         // Get body if the PDU is a RetrieveConf or SendReq.
   1127         if (pdu instanceof MultimediaMessagePdu) {
   1128             body = ((MultimediaMessagePdu) pdu).getBody();
   1129             // Start saving parts if necessary.
   1130             if (body != null) {
   1131                 int partsNum = body.getPartsNum();
   1132                 for (int i = 0; i < partsNum; i++) {
   1133                     PduPart part = body.getPart(i);
   1134                     persistPart(part, dummyId);
   1135                 }
   1136             }
   1137         }
   1138 
   1139         Uri res = SqliteWrapper.insert(mContext, mContentResolver, uri, values);
   1140         if (res == null) {
   1141             throw new MmsException("persist() failed: return null.");
   1142         }
   1143 
   1144         // Get the real ID of the PDU and update all parts which were
   1145         // saved with the dummy ID.
   1146         long msgId = ContentUris.parseId(res);
   1147         values = new ContentValues(1);
   1148         values.put(Part.MSG_ID, msgId);
   1149         SqliteWrapper.update(mContext, mContentResolver,
   1150                              Uri.parse("content://mms/" + dummyId + "/part"),
   1151                              values, null, null);
   1152         // We should return the longest URI of the persisted PDU, for
   1153         // example, if input URI is "content://mms/inbox" and the _ID of
   1154         // persisted PDU is '8', we should return "content://mms/inbox/8"
   1155         // instead of "content://mms/8".
   1156         // FIXME: Should the MmsProvider be responsible for this???
   1157         res = Uri.parse(uri + "/" + msgId);
   1158 
   1159         // Save address information.
   1160         for (int addrType : ADDRESS_FIELDS) {
   1161             EncodedStringValue[] array = addressMap.get(addrType);
   1162             if (array != null) {
   1163                 persistAddress(msgId, addrType, array);
   1164             }
   1165         }
   1166 
   1167         return res;
   1168     }
   1169 
   1170     /**
   1171      * Move a PDU object from one location to another.
   1172      *
   1173      * @param from Specify the PDU object to be moved.
   1174      * @param to The destination location, should be one of the following:
   1175      *        "content://mms/inbox", "content://mms/sent",
   1176      *        "content://mms/drafts", "content://mms/outbox",
   1177      *        "content://mms/trash".
   1178      * @return New Uri of the moved PDU.
   1179      * @throws MmsException Error occurred while moving the message.
   1180      */
   1181     public Uri move(Uri from, Uri to) throws MmsException {
   1182         // Check whether the 'msgId' has been assigned a valid value.
   1183         long msgId = ContentUris.parseId(from);
   1184         if (msgId == -1L) {
   1185             throw new MmsException("Error! ID of the message: -1.");
   1186         }
   1187 
   1188         // Get corresponding int value of destination box.
   1189         Integer msgBox = MESSAGE_BOX_MAP.get(to);
   1190         if (msgBox == null) {
   1191             throw new MmsException(
   1192                     "Bad destination, must be one of "
   1193                     + "content://mms/inbox, content://mms/sent, "
   1194                     + "content://mms/drafts, content://mms/outbox, "
   1195                     + "content://mms/temp.");
   1196         }
   1197 
   1198         ContentValues values = new ContentValues(1);
   1199         values.put(Mms.MESSAGE_BOX, msgBox);
   1200         SqliteWrapper.update(mContext, mContentResolver, from, values, null, null);
   1201         return ContentUris.withAppendedId(to, msgId);
   1202     }
   1203 
   1204     /**
   1205      * Wrap a byte[] into a String.
   1206      */
   1207     public static String toIsoString(byte[] bytes) {
   1208         try {
   1209             return new String(bytes, CharacterSets.MIMENAME_ISO_8859_1);
   1210         } catch (UnsupportedEncodingException e) {
   1211             // Impossible to reach here!
   1212             Log.e(TAG, "ISO_8859_1 must be supported!", e);
   1213             return "";
   1214         }
   1215     }
   1216 
   1217     /**
   1218      * Unpack a given String into a byte[].
   1219      */
   1220     public static byte[] getBytes(String data) {
   1221         try {
   1222             return data.getBytes(CharacterSets.MIMENAME_ISO_8859_1);
   1223         } catch (UnsupportedEncodingException e) {
   1224             // Impossible to reach here!
   1225             Log.e(TAG, "ISO_8859_1 must be supported!", e);
   1226             return new byte[0];
   1227         }
   1228     }
   1229 
   1230     /**
   1231      * Remove all objects in the temporary path.
   1232      */
   1233     public void release() {
   1234         Uri uri = Uri.parse(TEMPORARY_DRM_OBJECT_URI);
   1235         SqliteWrapper.delete(mContext, mContentResolver, uri, null, null);
   1236     }
   1237 
   1238     /**
   1239      * Find all messages to be sent or downloaded before certain time.
   1240      */
   1241     public Cursor getPendingMessages(long dueTime) {
   1242         Uri.Builder uriBuilder = PendingMessages.CONTENT_URI.buildUpon();
   1243         uriBuilder.appendQueryParameter("protocol", "mms");
   1244 
   1245         String selection = PendingMessages.ERROR_TYPE + " < ?"
   1246                 + " AND " + PendingMessages.DUE_TIME + " <= ?";
   1247 
   1248         String[] selectionArgs = new String[] {
   1249                 String.valueOf(MmsSms.ERR_TYPE_GENERIC_PERMANENT),
   1250                 String.valueOf(dueTime)
   1251         };
   1252 
   1253         return SqliteWrapper.query(mContext, mContentResolver,
   1254                 uriBuilder.build(), null, selection, selectionArgs,
   1255                 PendingMessages.DUE_TIME);
   1256     }
   1257 }
   1258