blob: 25544deac10d1ee2eb2eacdf6dd371bbd3fe0cd6 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
19import android.content.pm.PackageManager;
20import android.content.pm.ProviderInfo;
21import android.content.res.AssetFileDescriptor;
22import android.content.res.Configuration;
23import android.database.Cursor;
24import android.database.CursorToBulkCursorAdaptor;
25import android.database.CursorWindow;
26import android.database.IBulkCursor;
27import android.database.IContentObserver;
28import android.database.SQLException;
29import android.net.Uri;
30import android.os.Binder;
31import android.os.ParcelFileDescriptor;
32
33import java.io.File;
34import java.io.FileNotFoundException;
35
36/**
37 * Content providers are one of the primary building blocks of Android applications, providing
38 * content to applications. They encapsulate data and provide it to applications through the single
39 * {@link ContentResolver} interface. A content provider is only required if you need to share
40 * data between multiple applications. For example, the contacts data is used by multiple
41 * applications and must be stored in a content provider. If you don't need to share data amongst
42 * multiple applications you can use a database directly via
43 * {@link android.database.sqlite.SQLiteDatabase}.
44 *
45 * <p>For more information, read <a href="{@docRoot}guide/topics/providers/content-providers.html">Content
46 * Providers</a>.</p>
47 *
48 * <p>When a request is made via
49 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
50 * request to the content provider registered with the authority. The content provider can interpret
51 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
52 * URIs.</p>
53 *
54 * <p>The primary methods that need to be implemented are:
55 * <ul>
56 * <li>{@link #query} which returns data to the caller</li>
57 * <li>{@link #insert} which inserts new data into the content provider</li>
58 * <li>{@link #update} which updates existing data in the content provider</li>
59 * <li>{@link #delete} which deletes data from the content provider</li>
60 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
61 * </ul></p>
62 *
63 * <p>This class takes care of cross process calls so subclasses don't have to worry about which
64 * process a request is coming from.</p>
65 */
66public abstract class ContentProvider implements ComponentCallbacks {
67 private Context mContext = null;
68 private String mReadPermission;
69 private String mWritePermission;
70
71 private Transport mTransport = new Transport();
72
73 /**
74 * Given an IContentProvider, try to coerce it back to the real
75 * ContentProvider object if it is running in the local process. This can
76 * be used if you know you are running in the same process as a provider,
77 * and want to get direct access to its implementation details. Most
78 * clients should not nor have a reason to use it.
79 *
80 * @param abstractInterface The ContentProvider interface that is to be
81 * coerced.
82 * @return If the IContentProvider is non-null and local, returns its actual
83 * ContentProvider instance. Otherwise returns null.
84 * @hide
85 */
86 public static ContentProvider coerceToLocalContentProvider(
87 IContentProvider abstractInterface) {
88 if (abstractInterface instanceof Transport) {
89 return ((Transport)abstractInterface).getContentProvider();
90 }
91 return null;
92 }
93
94 /**
95 * Binder object that deals with remoting.
96 *
97 * @hide
98 */
99 class Transport extends ContentProviderNative {
100 ContentProvider getContentProvider() {
101 return ContentProvider.this;
102 }
103
104 /**
105 * Remote version of a query, which returns an IBulkCursor. The bulk
106 * cursor should be wrapped with BulkCursorToCursorAdaptor before use.
107 */
108 public IBulkCursor bulkQuery(Uri uri, String[] projection,
109 String selection, String[] selectionArgs, String sortOrder,
110 IContentObserver observer, CursorWindow window) {
111 checkReadPermission(uri);
112 Cursor cursor = ContentProvider.this.query(uri, projection,
113 selection, selectionArgs, sortOrder);
114 if (cursor == null) {
115 return null;
116 }
117 String wperm = getWritePermission();
118 return new CursorToBulkCursorAdaptor(cursor, observer,
119 ContentProvider.this.getClass().getName(),
120 wperm == null ||
121 getContext().checkCallingOrSelfPermission(getWritePermission())
122 == PackageManager.PERMISSION_GRANTED,
123 window);
124 }
125
126 public Cursor query(Uri uri, String[] projection,
127 String selection, String[] selectionArgs, String sortOrder) {
128 checkReadPermission(uri);
129 return ContentProvider.this.query(uri, projection, selection,
130 selectionArgs, sortOrder);
131 }
132
133 public String getType(Uri uri) {
134 return ContentProvider.this.getType(uri);
135 }
136
137
138 public Uri insert(Uri uri, ContentValues initialValues) {
139 checkWritePermission(uri);
140 return ContentProvider.this.insert(uri, initialValues);
141 }
142
143 public int bulkInsert(Uri uri, ContentValues[] initialValues) {
144 checkWritePermission(uri);
145 return ContentProvider.this.bulkInsert(uri, initialValues);
146 }
147
148 public int delete(Uri uri, String selection, String[] selectionArgs) {
149 checkWritePermission(uri);
150 return ContentProvider.this.delete(uri, selection, selectionArgs);
151 }
152
153 public int update(Uri uri, ContentValues values, String selection,
154 String[] selectionArgs) {
155 checkWritePermission(uri);
156 return ContentProvider.this.update(uri, values, selection, selectionArgs);
157 }
158
159 public ParcelFileDescriptor openFile(Uri uri, String mode)
160 throws FileNotFoundException {
161 if (mode != null && mode.startsWith("rw")) checkWritePermission(uri);
162 else checkReadPermission(uri);
163 return ContentProvider.this.openFile(uri, mode);
164 }
165
166 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
167 throws FileNotFoundException {
168 if (mode != null && mode.startsWith("rw")) checkWritePermission(uri);
169 else checkReadPermission(uri);
170 return ContentProvider.this.openAssetFile(uri, mode);
171 }
172
173 public ISyncAdapter getSyncAdapter() {
174 checkWritePermission(null);
175 return ContentProvider.this.getSyncAdapter().getISyncAdapter();
176 }
177
178 private void checkReadPermission(Uri uri) {
179 final String rperm = getReadPermission();
180 final int pid = Binder.getCallingPid();
181 final int uid = Binder.getCallingUid();
182 if (getContext().checkUriPermission(uri, rperm, null, pid, uid,
183 Intent.FLAG_GRANT_READ_URI_PERMISSION)
184 == PackageManager.PERMISSION_GRANTED) {
185 return;
186 }
187 String msg = "Permission Denial: reading "
188 + ContentProvider.this.getClass().getName()
189 + " uri " + uri + " from pid=" + Binder.getCallingPid()
190 + ", uid=" + Binder.getCallingUid()
191 + " requires " + rperm;
192 throw new SecurityException(msg);
193 }
194
195 private void checkWritePermission(Uri uri) {
196 final String wperm = getWritePermission();
197 final int pid = Binder.getCallingPid();
198 final int uid = Binder.getCallingUid();
199 if (getContext().checkUriPermission(uri, null, wperm, pid, uid,
200 Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
201 == PackageManager.PERMISSION_GRANTED) {
202 return;
203 }
204 String msg = "Permission Denial: writing "
205 + ContentProvider.this.getClass().getName()
206 + " uri " + uri + " from pid=" + Binder.getCallingPid()
207 + ", uid=" + Binder.getCallingUid()
208 + " requires " + wperm;
209 throw new SecurityException(msg);
210 }
211 }
212
213
214 /**
215 * Retrieve the Context this provider is running in. Only available once
216 * onCreate(Map icicle) has been called -- this will be null in the
217 * constructor.
218 */
219 public final Context getContext() {
220 return mContext;
221 }
222
223 /**
224 * Change the permission required to read data from the content
225 * provider. This is normally set for you from its manifest information
226 * when the provider is first created.
227 *
228 * @param permission Name of the permission required for read-only access.
229 */
230 protected final void setReadPermission(String permission) {
231 mReadPermission = permission;
232 }
233
234 /**
235 * Return the name of the permission required for read-only access to
236 * this content provider. This method can be called from multiple
237 * threads, as described in
238 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
239 * Processes and Threads</a>.
240 */
241 public final String getReadPermission() {
242 return mReadPermission;
243 }
244
245 /**
246 * Change the permission required to read and write data in the content
247 * provider. This is normally set for you from its manifest information
248 * when the provider is first created.
249 *
250 * @param permission Name of the permission required for read/write access.
251 */
252 protected final void setWritePermission(String permission) {
253 mWritePermission = permission;
254 }
255
256 /**
257 * Return the name of the permission required for read/write access to
258 * this content provider. This method can be called from multiple
259 * threads, as described in
260 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
261 * Processes and Threads</a>.
262 */
263 public final String getWritePermission() {
264 return mWritePermission;
265 }
266
267 /**
268 * Called when the provider is being started.
269 *
270 * @return true if the provider was successfully loaded, false otherwise
271 */
272 public abstract boolean onCreate();
273
274 public void onConfigurationChanged(Configuration newConfig) {
275 }
276
277 public void onLowMemory() {
278 }
279
280 /**
281 * Receives a query request from a client in a local process, and
282 * returns a Cursor. This is called internally by the {@link ContentResolver}.
283 * This method can be called from multiple
284 * threads, as described in
285 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
286 * Processes and Threads</a>.
287 * <p>
288 * Example client call:<p>
289 * <pre>// Request a specific record.
290 * Cursor managedCursor = managedQuery(
291 Contacts.People.CONTENT_URI.addId(2),
292 projection, // Which columns to return.
293 null, // WHERE clause.
294 People.NAME + " ASC"); // Sort order.</pre>
295 * Example implementation:<p>
296 * <pre>// SQLiteQueryBuilder is a helper class that creates the
297 // proper SQL syntax for us.
298 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
299
300 // Set the table we're querying.
301 qBuilder.setTables(DATABASE_TABLE_NAME);
302
303 // If the query ends in a specific record number, we're
304 // being asked for a specific record, so set the
305 // WHERE clause in our query.
306 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
307 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
308 }
309
310 // Make the query.
311 Cursor c = qBuilder.query(mDb,
312 projection,
313 selection,
314 selectionArgs,
315 groupBy,
316 having,
317 sortOrder);
318 c.setNotificationUri(getContext().getContentResolver(), uri);
319 return c;</pre>
320 *
321 * @param uri The URI to query. This will be the full URI sent by the client;
322 * if the client is requesting a specific record, the URI will end in a record number
323 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
324 * that _id value.
325 * @param projection The list of columns to put into the cursor. If
326 * null all columns are included.
327 * @param selection A selection criteria to apply when filtering rows.
328 * If null then all rows are included.
329 * @param sortOrder How the rows in the cursor should be sorted.
330 * If null then the provider is free to define the sort order.
331 * @return a Cursor or null.
332 */
333 public abstract Cursor query(Uri uri, String[] projection,
334 String selection, String[] selectionArgs, String sortOrder);
335
336 /**
337 * Return the MIME type of the data at the given URI. This should start with
338 * <code>vnd.android.cursor.item</code> for a single record,
339 * or <code>vnd.android.cursor.dir/</code> for multiple items.
340 * This method can be called from multiple
341 * threads, as described in
342 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
343 * Processes and Threads</a>.
344 *
345 * @param uri the URI to query.
346 * @return a MIME type string, or null if there is no type.
347 */
348 public abstract String getType(Uri uri);
349
350 /**
351 * Implement this to insert a new row.
352 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
353 * after inserting.
354 * This method can be called from multiple
355 * threads, as described in
356 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
357 * Processes and Threads</a>.
358 * @param uri The content:// URI of the insertion request.
359 * @param values A set of column_name/value pairs to add to the database.
360 * @return The URI for the newly inserted item.
361 */
362 public abstract Uri insert(Uri uri, ContentValues values);
363
364 /**
365 * Implement this to insert a set of new rows, or the default implementation will
366 * iterate over the values and call {@link #insert} on each of them.
367 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
368 * after inserting.
369 * This method can be called from multiple
370 * threads, as described in
371 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
372 * Processes and Threads</a>.
373 *
374 * @param uri The content:// URI of the insertion request.
375 * @param values An array of sets of column_name/value pairs to add to the database.
376 * @return The number of values that were inserted.
377 */
378 public int bulkInsert(Uri uri, ContentValues[] values) {
379 int numValues = values.length;
380 for (int i = 0; i < numValues; i++) {
381 insert(uri, values[i]);
382 }
383 return numValues;
384 }
385
386 /**
387 * A request to delete one or more rows. The selection clause is applied when performing
388 * the deletion, allowing the operation to affect multiple rows in a
389 * directory.
390 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
391 * after deleting.
392 * This method can be called from multiple
393 * threads, as described in
394 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
395 * Processes and Threads</a>.
396 *
397 * <p>The implementation is responsible for parsing out a row ID at the end
398 * of the URI, if a specific row is being deleted. That is, the client would
399 * pass in <code>content://contacts/people/22</code> and the implementation is
400 * responsible for parsing the record number (22) when creating a SQL statement.
401 *
402 * @param uri The full URI to query, including a row ID (if a specific record is requested).
403 * @param selection An optional restriction to apply to rows when deleting.
404 * @return The number of rows affected.
405 * @throws SQLException
406 */
407 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
408
409 /**
410 * Update a content URI. All rows matching the optionally provided selection
411 * will have their columns listed as the keys in the values map with the
412 * values of those keys.
413 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
414 * after updating.
415 * This method can be called from multiple
416 * threads, as described in
417 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
418 * Processes and Threads</a>.
419 *
420 * @param uri The URI to query. This can potentially have a record ID if this
421 * is an update request for a specific record.
422 * @param values A Bundle mapping from column names to new column values (NULL is a
423 * valid value).
424 * @param selection An optional filter to match rows to update.
425 * @return the number of rows affected.
426 */
427 public abstract int update(Uri uri, ContentValues values, String selection,
428 String[] selectionArgs);
429
430 /**
431 * Open a file blob associated with a content URI.
432 * This method can be called from multiple
433 * threads, as described in
434 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
435 * Processes and Threads</a>.
436 *
437 * <p>Returns a
438 * ParcelFileDescriptor, from which you can obtain a
439 * {@link java.io.FileDescriptor} for use with
440 * {@link java.io.FileInputStream}, {@link java.io.FileOutputStream}, etc.
441 * This can be used to store large data (such as an image) associated with
442 * a particular piece of content.
443 *
444 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
445 * their responsibility to close it when done. That is, the implementation
446 * of this method should create a new ParcelFileDescriptor for each call.
447 *
448 * @param uri The URI whose file is to be opened.
449 * @param mode Access mode for the file. May be "r" for read-only access,
450 * "rw" for read and write access, or "rwt" for read and write access
451 * that truncates any existing file.
452 *
453 * @return Returns a new ParcelFileDescriptor which you can use to access
454 * the file.
455 *
456 * @throws FileNotFoundException Throws FileNotFoundException if there is
457 * no file associated with the given URI or the mode is invalid.
458 * @throws SecurityException Throws SecurityException if the caller does
459 * not have permission to access the file.
460 *
461 * @see #openAssetFile(Uri, String)
462 * @see #openFileHelper(Uri, String)
463 */
464 public ParcelFileDescriptor openFile(Uri uri, String mode)
465 throws FileNotFoundException {
466 throw new FileNotFoundException("No files supported by provider at "
467 + uri);
468 }
469
470 /**
471 * This is like {@link #openFile}, but can be implemented by providers
472 * that need to be able to return sub-sections of files, often assets
473 * inside of their .apk. Note that when implementing this your clients
474 * must be able to deal with such files, either directly with
475 * {@link ContentResolver#openAssetFileDescriptor
476 * ContentResolver.openAssetFileDescriptor}, or by using the higher-level
477 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
478 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
479 * methods.
480 *
481 * <p><em>Note: if you are implementing this to return a full file, you
482 * should create the AssetFileDescriptor with
483 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
484 * applications that can not handle sub-sections of files.</em></p>
485 *
486 * @param uri The URI whose file is to be opened.
487 * @param mode Access mode for the file. May be "r" for read-only access,
488 * "w" for write-only access (erasing whatever data is currently in
489 * the file), "wa" for write-only access to append to any existing data,
490 * "rw" for read and write access on any existing data, and "rwt" for read
491 * and write access that truncates any existing file.
492 *
493 * @return Returns a new AssetFileDescriptor which you can use to access
494 * the file.
495 *
496 * @throws FileNotFoundException Throws FileNotFoundException if there is
497 * no file associated with the given URI or the mode is invalid.
498 * @throws SecurityException Throws SecurityException if the caller does
499 * not have permission to access the file.
500 *
501 * @see #openFile(Uri, String)
502 * @see #openFileHelper(Uri, String)
503 */
504 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
505 throws FileNotFoundException {
506 ParcelFileDescriptor fd = openFile(uri, mode);
507 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
508 }
509
510 /**
511 * Convenience for subclasses that wish to implement {@link #openFile}
512 * by looking up a column named "_data" at the given URI.
513 *
514 * @param uri The URI to be opened.
515 * @param mode The file mode. May be "r" for read-only access,
516 * "w" for write-only access (erasing whatever data is currently in
517 * the file), "wa" for write-only access to append to any existing data,
518 * "rw" for read and write access on any existing data, and "rwt" for read
519 * and write access that truncates any existing file.
520 *
521 * @return Returns a new ParcelFileDescriptor that can be used by the
522 * client to access the file.
523 */
524 protected final ParcelFileDescriptor openFileHelper(Uri uri,
525 String mode) throws FileNotFoundException {
526 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
527 int count = (c != null) ? c.getCount() : 0;
528 if (count != 1) {
529 // If there is not exactly one result, throw an appropriate
530 // exception.
531 if (c != null) {
532 c.close();
533 }
534 if (count == 0) {
535 throw new FileNotFoundException("No entry for " + uri);
536 }
537 throw new FileNotFoundException("Multiple items at " + uri);
538 }
539
540 c.moveToFirst();
541 int i = c.getColumnIndex("_data");
542 String path = (i >= 0 ? c.getString(i) : null);
543 c.close();
544 if (path == null) {
545 throw new FileNotFoundException("Column _data not found.");
546 }
547
548 int modeBits = ContentResolver.modeToMode(uri, mode);
549 return ParcelFileDescriptor.open(new File(path), modeBits);
550 }
551
552 /**
553 * Get the sync adapter that is to be used by this content provider.
554 * This is intended for use by the sync system. If null then this
555 * content provider is considered not syncable.
556 * This method can be called from multiple
557 * threads, as described in
558 * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
559 * Processes and Threads</a>.
560 *
561 * @return the SyncAdapter that is to be used by this ContentProvider, or null
562 * if this ContentProvider is not syncable
563 * @hide
564 */
565 public SyncAdapter getSyncAdapter() {
566 return null;
567 }
568
569 /**
570 * Returns true if this instance is a temporary content provider.
571 * @return true if this instance is a temporary content provider
572 */
573 protected boolean isTemporary() {
574 return false;
575 }
576
577 /**
578 * Returns the Binder object for this provider.
579 *
580 * @return the Binder object for this provider
581 * @hide
582 */
583 public IContentProvider getIContentProvider() {
584 return mTransport;
585 }
586
587 /**
588 * After being instantiated, this is called to tell the content provider
589 * about itself.
590 *
591 * @param context The context this provider is running in
592 * @param info Registered information about this content provider
593 */
594 public void attachInfo(Context context, ProviderInfo info) {
595
596 /*
597 * Only allow it to be set once, so after the content service gives
598 * this to us clients can't change it.
599 */
600 if (mContext == null) {
601 mContext = context;
602 if (info != null) {
603 setReadPermission(info.readPermission);
604 setWritePermission(info.writePermission);
605 }
606 ContentProvider.this.onCreate();
607 }
608 }
609}