ContentUriUtils.java revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package org.chromium.base;
6
7import android.content.ContentResolver;
8import android.content.Context;
9import android.net.Uri;
10import android.os.ParcelFileDescriptor;
11import android.util.Log;
12
13import org.chromium.base.CalledByNative;
14
15/**
16 * This class provides methods to access content URI schemes.
17 */
18abstract class ContentUriUtils {
19    private static final String TAG = "ContentUriUtils";
20
21    // Prevent instantiation.
22    private ContentUriUtils() {}
23
24    /**
25     * Opens the content URI for reading, and returns the file descriptor to
26     * the caller. The caller is responsible for closing the file desciptor.
27     *
28     * @param context {@link Context} in interest
29     * @param uriString the content URI to open
30     * @returns file desciptor upon sucess, or -1 otherwise.
31     */
32    @CalledByNative
33    public static int openContentUriForRead(Context context, String uriString) {
34        ParcelFileDescriptor pfd = getParcelFileDescriptor(context, uriString);
35        if (pfd != null) {
36            return pfd.detachFd();
37        }
38        return -1;
39    }
40
41    /**
42     * Check whether a content URI exists.
43     *
44     * @param context {@link Context} in interest.
45     * @param uriString the content URI to query.
46     * @returns true if the uri exists, or false otherwise.
47     */
48    @CalledByNative
49    public static boolean contentUriExists(Context context, String uriString) {
50        ParcelFileDescriptor pfd = getParcelFileDescriptor(context, uriString);
51        if (pfd == null) {
52            return false;
53        }
54        return true;
55    }
56
57    /**
58     * Helper method to open a content URI and return the ParcelFileDescriptor.
59     *
60     * @param context {@link Context} in interest.
61     * @param uriString the content URI to open.
62     * @returns ParcelFileDescriptor of the content URI, or NULL if the file does not exist.
63     */
64    private static ParcelFileDescriptor getParcelFileDescriptor(Context context, String uriString) {
65        ContentResolver resolver = context.getContentResolver();
66        Uri uri = Uri.parse(uriString);
67
68        ParcelFileDescriptor pfd = null;
69        try {
70            pfd = resolver.openFileDescriptor(uri, "r");
71        } catch (java.io.FileNotFoundException e) {
72            Log.w(TAG, "Cannot find content uri: " + uriString, e);
73        }
74        return pfd;
75    }
76}
77