Folder.java revision 9b87568c9e9f1c32a9672b315229866a58a1e757
1/*******************************************************************************
2 *      Copyright (C) 2012 Google Inc.
3 *      Licensed to 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
18package com.android.mail.providers;
19
20import com.google.common.collect.Maps;
21
22import android.database.Cursor;
23import android.os.Parcel;
24import android.os.Parcelable;
25import android.text.TextUtils;
26
27import com.android.mail.utils.LogUtils;
28
29import java.util.Collection;
30import java.util.Map;
31import java.util.regex.Pattern;
32
33/**
34 * A folder is a collection of conversations, and perhaps other folders.
35 */
36public class Folder implements Parcelable {
37    /**
38     *
39     */
40    private static final String FOLDER_UNINITIALIZED = "Uninitialized!";
41
42    // Try to match the order of members with the order of constants in UIProvider.
43
44    /**
45     * Unique id of this folder.
46     */
47    public String id;
48
49    /**
50     * The content provider URI that returns this folder for this account.
51     */
52    public String uri;
53
54    /**
55     * The human visible name for this folder.
56     */
57    public String name;
58
59    /**
60     * The possible capabilities that this folder supports.
61     */
62    public int capabilities;
63
64    /**
65     * Whether or not this folder has children folders.
66     */
67    public boolean hasChildren;
68
69    /**
70     * How often this folder should be synchronized with the server.
71     */
72    public int syncFrequency;
73
74    /**
75     * How large the synchronization window is: how many days worth of data is retained on the
76     * device.
77     */
78    public int syncWindow;
79
80    /**
81     * The content provider URI to return the list of conversations in this
82     * folder.
83     */
84    public String conversationListUri;
85
86    /**
87     * The content provider URI to return the list of child folders of this folder.
88     */
89    public String childFoldersListUri;
90
91    /**
92     * The number of messages that are unread in this folder.
93     */
94    public int unreadCount;
95
96    /**
97     * The total number of messages in this folder.
98     */
99    public int totalCount;
100
101    /**
102     * Total number of members that comprise an instance of a folder. Count up the members above.
103     * This is the number of members that need to be serialized or parceled.
104     */
105    private static final int NUMBER_MEMBERS = 10;
106
107    /**
108     * Used only for debugging.
109     */
110    private static final String LOG_TAG = new LogUtils().getLogTag();
111
112    /**
113     * Examples of expected format for the joined label strings
114     *
115     * Example of a joined label string:
116     *       630107622^*^^i^*^^i^*^0
117     *       <id>^*^<canonical name>^*^<name>^*^<color index>
118     *
119     * The sqlite queries will return a list of labels strings separated with "^**^"
120     * Example of a query result:
121     *     630107622^*^^i^*^^i^*^0^**^630107626^*^^u^*^^u^*^0^**^630107627^*^^f^*^^f^*^0
122     */
123    private static final String LABEL_COMPONENT_SEPARATOR = "^*^";
124    private static final Pattern LABEL_COMPONENT_SEPARATOR_PATTERN =
125            Pattern.compile("\\^\\*\\^");
126
127    private static final String LABEL_SEPARATOR = "^**^";
128    private static final Pattern LABEL_SEPARATOR_PATTERN = Pattern.compile("\\^\\*\\*\\^");
129
130    public Folder(Parcel in) {
131        id = in.readString();
132        uri = in.readString();
133        name = in.readString();
134        capabilities = in.readInt();
135        // 1 for true, 0 for false.
136        hasChildren = in.readInt() == 1;
137        syncFrequency = in.readInt();
138        syncWindow = in.readInt();
139        conversationListUri = in.readString();
140        childFoldersListUri = in.readString();
141        unreadCount = in.readInt();
142        totalCount = in.readInt();
143    }
144
145    public Folder(Cursor cursor) {
146        id = cursor.getString(UIProvider.FOLDER_ID_COLUMN);
147        uri = cursor.getString(UIProvider.FOLDER_URI_COLUMN);
148        name = cursor.getString(UIProvider.FOLDER_NAME_COLUMN);
149        capabilities = cursor.getInt(UIProvider.FOLDER_CAPABILITIES_COLUMN);
150        // 1 for true, 0 for false.
151        hasChildren = cursor.getInt(UIProvider.FOLDER_HAS_CHILDREN_COLUMN) == 1;
152        syncFrequency = cursor.getInt(UIProvider.FOLDER_SYNC_FREQUENCY_COLUMN);
153        syncWindow = cursor.getInt(UIProvider.FOLDER_SYNC_WINDOW_COLUMN);
154        conversationListUri = cursor.getString(UIProvider.FOLDER_CONVERSATION_LIST_URI_COLUMN);
155        childFoldersListUri = cursor.getString(UIProvider.FOLDER_CHILD_FOLDERS_LIST_COLUMN);
156        unreadCount = cursor.getInt(UIProvider.FOLDER_UNREAD_COUNT_COLUMN);
157        totalCount = cursor.getInt(UIProvider.FOLDER_TOTAL_COUNT_COLUMN);
158    }
159
160    @Override
161    public void writeToParcel(Parcel dest, int flags) {
162        dest.writeString(id);
163        dest.writeString(uri);
164        dest.writeString(name);
165        dest.writeInt(capabilities);
166        // 1 for true, 0 for false.
167        dest.writeInt(hasChildren ? 1 : 0);
168        dest.writeInt(syncFrequency);
169        dest.writeInt(syncWindow);
170        dest.writeString(conversationListUri);
171        dest.writeString(childFoldersListUri);
172        dest.writeInt(unreadCount);
173        dest.writeInt(totalCount);
174    }
175
176    /**
177     * Return a serialized String for this folder.
178     */
179    public synchronized String serialize(){
180        StringBuilder out = new StringBuilder();
181        out.append(id).append(LABEL_COMPONENT_SEPARATOR);
182        out.append(uri).append(LABEL_COMPONENT_SEPARATOR);
183        out.append(name).append(LABEL_COMPONENT_SEPARATOR);
184        out.append(capabilities).append(LABEL_COMPONENT_SEPARATOR);
185        out.append(hasChildren ? "1": "0").append(LABEL_COMPONENT_SEPARATOR);
186        out.append(syncFrequency).append(LABEL_COMPONENT_SEPARATOR);
187        out.append(syncWindow).append(LABEL_COMPONENT_SEPARATOR);
188        out.append(conversationListUri).append(LABEL_COMPONENT_SEPARATOR);
189        out.append(childFoldersListUri).append(LABEL_COMPONENT_SEPARATOR);
190        out.append(unreadCount).append(LABEL_COMPONENT_SEPARATOR);
191        out.append(totalCount).append(LABEL_COMPONENT_SEPARATOR);
192        return out.toString();
193    }
194
195    /**
196     * Construct a new Folder instance from a previously serialized string.
197     * @param serializedFolder string obtained from {@link #serialize()} on a valid folder.
198     */
199    private Folder(String serializedFolder){
200        String[] folderMembers = TextUtils.split(serializedFolder, LABEL_SEPARATOR_PATTERN);
201        if (folderMembers.length != NUMBER_MEMBERS) {
202            // This is a problem.
203            // TODO(viki): Find out the appropriate exception for this.
204            return;
205        }
206        uri = folderMembers[0];
207        name = folderMembers[1];
208        capabilities = Integer.valueOf(folderMembers[2]);
209        // 1 for true, 0 for false
210        hasChildren = folderMembers[3] == "1";
211        syncFrequency = Integer.valueOf(folderMembers[4]);
212        syncWindow = Integer.valueOf(folderMembers[5]);
213        conversationListUri = folderMembers[6];
214        childFoldersListUri = folderMembers[7];
215        unreadCount = Integer.valueOf(folderMembers[8]);
216        totalCount = Integer.valueOf(folderMembers[9]);
217    }
218
219    /**
220     * Constructor that leaves everything uninitialized. For use only by {@link #serialize()}
221     * which is responsible for filling in all the fields
222     */
223    public Folder() {
224        name = FOLDER_UNINITIALIZED;
225    }
226
227    @SuppressWarnings("hiding")
228    public static final Creator<Folder> CREATOR = new Creator<Folder>() {
229        @Override
230        public Folder createFromParcel(Parcel source) {
231            return new Folder(source);
232        }
233
234        @Override
235        public Folder[] newArray(int size) {
236            return new Folder[size];
237        }
238    };
239
240    @Override
241    public int describeContents() {
242        // Return a sort of version number for this parcelable folder. Starting with zero.
243        return 0;
244    }
245
246    /**
247     * Create a Folder map from a string of serialized folders. This can only be done on the output
248     * of {@link #serialize(Map)}.
249     * @param serializedFolder A string obtained from {@link #serialize(Map)}
250     * @return a Map of folder name to folder.
251     */
252    public static Map<String, Folder> parseFoldersFromString(String serializedFolder) {
253        LogUtils.d(LOG_TAG, "label query result: %s", serializedFolder);
254
255        Map<String, Folder> folderMap = Maps.newHashMap();
256        if (serializedFolder == null || serializedFolder == "") {
257            return folderMap;
258        }
259        String[] folderPieces = TextUtils.split(
260                serializedFolder, LABEL_COMPONENT_SEPARATOR_PATTERN);
261        for (int i = 0, n = folderPieces.length; i < n; i++) {
262            Folder folder = new Folder(folderPieces[i]);
263            if (folder.name != FOLDER_UNINITIALIZED) {
264                folderMap.put(folder.name, folder);
265            }
266        }
267        return folderMap;
268    }
269
270    /**
271     * Serialize the given list of folders
272     * @param folderMap A valid map of folder names to Folders
273     * @return a string containing a serialized output of folder maps.
274     */
275    public static String serialize(Map<String, Folder> folderMap) {
276        Collection<Folder> folderCollection = folderMap.values();
277        Folder[] folderList = folderCollection.toArray(new Folder[]{} );
278        int numLabels = folderList.length;
279        StringBuilder result = new StringBuilder();
280        for (int i = 0; i < numLabels; i++) {
281          if (i > 0) {
282              result.append(LABEL_SEPARATOR);
283          }
284          Folder folder = folderList[i];
285          result.append(folder.serialize());
286        }
287        return result.toString();
288    }
289}
290