• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 Google LLC
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 package com.google.android.libraries.mobiledatadownload.file.backends;
17 
18 import android.net.Uri;
19 import android.os.ParcelFileDescriptor;
20 import android.util.Pair;
21 import com.google.android.libraries.mobiledatadownload.file.common.MalformedUriException;
22 import java.io.Closeable;
23 
24 /**
25  * Helper class for "fd:" URIs that refer to file descriptors. The opaque part of these URIs is
26  * simply the file descriptor int value stringified. These URIs are transient and should never be
27  * stored.
28  *
29  * <p>The primary use case is fetching a ParcelFileDescriptor from Java and passing that down to
30  * native code. The URI is paired with a closer which must be called to free system resources. Java
31  * can do so immediately after passing the URI to native; if the native fd backend needs to keep the
32  * file descriptor for longer, it will make a duplicate.
33  *
34  * <p>TODO: Java implementation of file descriptor backend.
35  */
36 public final class FileDescriptorUri {
37 
38   /** Create a pair of URI and closer for underlying resources from a ParcelFileDescriptor. */
fromParcelFileDescriptor(ParcelFileDescriptor pfd)39   public static Pair<Uri, Closeable> fromParcelFileDescriptor(ParcelFileDescriptor pfd) {
40     int fd = pfd.getFd();
41     Uri uri = new Uri.Builder().scheme("fd").opaquePart(String.valueOf(fd)).build();
42     // NOTE: ParcelFileDescriptor doesn't implement Closeable on SDK 15, so we need to wrap
43     return Pair.create(uri, () -> pfd.close());
44   }
45 
46   /** Gets the integer file descriptor from this URI. */
getFd(Uri uri)47   public static int getFd(Uri uri) throws MalformedUriException {
48     if (!uri.getScheme().equals("fd")) {
49       throw new MalformedUriException("Scheme must be 'fd'");
50     }
51     try {
52       return Integer.parseInt(uri.getSchemeSpecificPart());
53     } catch (NumberFormatException e) {
54       throw new MalformedUriException(e);
55     }
56   }
57 
FileDescriptorUri()58   private FileDescriptorUri() {}
59 }
60