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
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.browser;
import java.io.IOException;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.database.Cursor;
import android.os.ParcelFileDescriptor;
import android.provider.Browser;
import android.provider.Browser.BookmarkColumns;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.CRC32;
/**
* Settings backup agent for the Android browser. Currently the only thing
* stored is the set of bookmarks. It's okay if I/O exceptions are thrown
* out of the agent; the calling code handles it and the backup operation
* simply fails.
*
* @hide
*/
public class BrowserBackupAgent extends BackupAgent {
static final String TAG = "BrowserBackupAgent";
static final boolean DEBUG = false;
static final String BOOKMARK_KEY = "_bookmarks_";
/** this version num MUST be incremented if the flattened-file schema ever changes */
static final int BACKUP_AGENT_VERSION = 0;
/**
* In order to determine whether the bookmark set has changed since the
* last time we did a backup, we store the following bits of info in the
* state file after a backup:
*
* 1. the size of the flattened bookmark file
* 2. the CRC32 of that file
* 3. the agent version number [relevant following an OTA]
*
* After we flatten the bookmarks file here in onBackup, we compare its
* metrics with the values from the saved state. If they match, it means
* the bookmarks didn't really change and we don't need to send the data.
* (If they don't match, of course, then they've changed and we do indeed
* send the new flattened file to be backed up.)
*/
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState) throws IOException {
long savedFileSize = -1;
long savedCrc = -1;
int savedVersion = -1;
// Extract the previous bookmark file size & CRC from the saved state
DataInputStream in = new DataInputStream(
new FileInputStream(oldState.getFileDescriptor()));
try {
savedFileSize = in.readLong();
savedCrc = in.readLong();
savedVersion = in.readInt();
} catch (EOFException e) {
// It means we had no previous state; that's fine
} finally {
if (in != null) {
in.close();
}
}
// Build a flattened representation of the bookmarks table
File tmpfile = File.createTempFile("bkp", null, getCacheDir());
try {
FileOutputStream outfstream = new FileOutputStream(tmpfile);
long newCrc = buildBookmarkFile(outfstream);
outfstream.close();
// Any changes since the last backup?
if ((savedVersion != BACKUP_AGENT_VERSION)
|| (newCrc != savedCrc)
|| (tmpfile.length() != savedFileSize)) {
// Different checksum or different size, so we need to back it up
copyFileToBackup(BOOKMARK_KEY, tmpfile, data);
}
// Record our backup state and we're done
writeBackupState(tmpfile.length(), newCrc, newState);
} finally {
// Make sure to tidy up when we're done
tmpfile.delete();
}
}
/**
* Restore from backup -- reads in the flattened bookmark file as supplied from
* the backup service, parses that out, and rebuilds the bookmarks table in the
* browser database from it.
*/
@Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
long crc = -1;
File tmpfile = File.createTempFile("rst", null, getFilesDir());
try {
while (data.readNextHeader()) {
if (BOOKMARK_KEY.equals(data.getKey())) {
// Read the flattened bookmark data into a temp file
crc = copyBackupToFile(data, tmpfile, data.getDataSize());
FileInputStream infstream = new FileInputStream(tmpfile);
DataInputStream in = new DataInputStream(infstream);
try {
int count = in.readInt();
ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>(count);
// Read all the bookmarks, then process later -- if we can't read
// all the data successfully, we don't touch the bookmarks table
for (int i = 0; i < count; i++) {
Bookmark mark = new Bookmark();
mark.url = in.readUTF();
mark.visits = in.readInt();
mark.date = in.readLong();
mark.created = in.readLong();
mark.title = in.readUTF();
bookmarks.add(mark);
}
// Okay, we have all the bookmarks -- now see if we need to add
// them to the browser's database
int N = bookmarks.size();
int nUnique = 0;
if (DEBUG) Log.v(TAG, "Restoring " + N + " bookmarks");
String[] urlCol = new String[] { BookmarkColumns.URL };
for (int i = 0; i < N; i++) {
Bookmark mark = bookmarks.get(i);
// Does this URL exist in the bookmark table?
Cursor cursor = getContentResolver().query(Browser.BOOKMARKS_URI,
urlCol, BookmarkColumns.URL + " == '" + mark.url + "' AND " +
BookmarkColumns.BOOKMARK + " == 1 ", null, null);
// if not, insert it
if (cursor.getCount() <= 0) {
if (DEBUG) Log.v(TAG, "Did not see url: " + mark.url);
// Right now we do not reconstruct the db entry in its
// entirety; we just add a new bookmark with the same data
// FIXME: This file needs to be reworked
// anyway For now, add the bookmark at
// the root level.
Bookmarks.addBookmark(this, false,
mark.url, mark.title, null, false, 0);
nUnique++;
} else {
if (DEBUG) Log.v(TAG, "Skipping extant url: " + mark.url);
}
cursor.close();
}
Log.i(TAG, "Restored " + nUnique + " of " + N + " bookmarks");
} catch (IOException ioe) {
Log.w(TAG, "Bad backup data; not restoring");
crc = -1;
} finally {
if (in != null) {
in.close();
}
}
}
// Last, write the state we just restored from so we can discern
// changes whenever we get invoked for backup in the future
writeBackupState(tmpfile.length(), crc, newState);
}
} finally {
// Whatever happens, delete the temp file
tmpfile.delete();
}
}
static class Bookmark {
public String url;
public int visits;
public long date;
public long created;
public String title;
}
/*
* Utility functions
*/
// Flatten the bookmarks table into the given file, calculating its CRC in the process
private long buildBookmarkFile(FileOutputStream outfstream) throws IOException {
CRC32 crc = new CRC32();
ByteArrayOutputStream bufstream = new ByteArrayOutputStream(512);
DataOutputStream bout = new DataOutputStream(bufstream);
Cursor cursor = getContentResolver().query(Browser.BOOKMARKS_URI,
new String[] { BookmarkColumns.URL, BookmarkColumns.VISITS,
BookmarkColumns.DATE, BookmarkColumns.CREATED,
BookmarkColumns.TITLE },
BookmarkColumns.BOOKMARK + " == 1 ", null, null);
// The first thing in the file is the row count...
int count = cursor.getCount();
if (DEBUG) Log.v(TAG, "Backing up " + count + " bookmarks");
bout.writeInt(count);
byte[] record = bufstream.toByteArray();
crc.update(record);
outfstream.write(record);
// ... followed by the data for each row
for (int i = 0; i < count; i++) {
cursor.moveToNext();
String url = cursor.getString(0);
int visits = cursor.getInt(1);
long date = cursor.getLong(2);
long created = cursor.getLong(3);
String title = cursor.getString(4);
// construct the flattened record in a byte array
bufstream.reset();
bout.writeUTF(url);
bout.writeInt(visits);
bout.writeLong(date);
bout.writeLong(created);
bout.writeUTF(title);
// Update the CRC and write the record to the temp file
record = bufstream.toByteArray();
crc.update(record);
outfstream.write(record);
if (DEBUG) Log.v(TAG, " wrote url " + url);
}
cursor.close();
return crc.getValue();
}
// Write the file to backup as a single record under the given key
private void copyFileToBackup(String key, File file, BackupDataOutput data)
throws IOException {
final int CHUNK = 8192;
byte[] buf = new byte[CHUNK];
int toCopy = (int) file.length();
data.writeEntityHeader(key, toCopy);
FileInputStream in = new FileInputStream(file);
try {
int nRead;
while (toCopy > 0) {
nRead = in.read(buf, 0, CHUNK);
data.writeEntityData(buf, nRead);
toCopy -= nRead;
}
} finally {
if (in != null) {
in.close();
}
}
}
// Read the given file from backup to a file, calculating a CRC32 along the way
private long copyBackupToFile(BackupDataInput data, File file, int toRead)
throws IOException {
final int CHUNK = 8192;
byte[] buf = new byte[CHUNK];
CRC32 crc = new CRC32();
FileOutputStream out = new FileOutputStream(file);
try {
while (toRead > 0) {
int numRead = data.readEntityData(buf, 0, CHUNK);
crc.update(buf, 0, numRead);
out.write(buf, 0, numRead);
toRead -= numRead;
}
} finally {
if (out != null) {
out.close();
}
}
return crc.getValue();
}
// Write the given metrics to the new state file
private void writeBackupState(long fileSize, long crc, ParcelFileDescriptor stateFile)
throws IOException {
DataOutputStream out = new DataOutputStream(
new FileOutputStream(stateFile.getFileDescriptor()));
try {
out.writeLong(fileSize);
out.writeLong(crc);
out.writeInt(BACKUP_AGENT_VERSION);
} finally {
if (out != null) {
out.close();
}
}
}
}
|