Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions src/main/java/android/content/ContentResolver.java

This file was deleted.

63 changes: 63 additions & 0 deletions src/main/java/android/content/ContentResolver.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package android.content

import android.net.Uri
import android.os.ParcelFileDescriptor
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.InputStream
import java.io.OutputStream
import java.net.URLConnection
import java.nio.file.Files
import java.nio.file.StandardOpenOption

/**
* Resolves content URIs on the JVM, where there are no content providers: only `file:` URIs (and URIs with no scheme,
* taken as paths) name anything. Firebase Storage's `putFile(Uri)` reads the uploaded file through this.
*/
open class ContentResolver {

/** The file descriptor for [uri] opened with [mode] (`"r"`, `"w"`, `"wt"`, `"wa"`, `"rw"` or `"rwt"`). */
@Throws(FileNotFoundException::class)
open fun openFileDescriptor(uri: Uri, mode: String): ParcelFileDescriptor? =
ParcelFileDescriptor.open(fileFor(uri), ParcelFileDescriptor.parseMode(mode))

@Throws(FileNotFoundException::class)
open fun openInputStream(uri: Uri): InputStream? = FileInputStream(fileFor(uri))

@Throws(FileNotFoundException::class)
open fun openOutputStream(uri: Uri): OutputStream? = openOutputStream(uri, "w")

/**
* An output stream on [uri] opened with [mode]: `"w"` and `"wt"` truncate, `"wa"` appends, `"rw"` writes in place
* from the start and `"rwt"` truncates; `"r"` cannot open an output stream.
*/
@Throws(FileNotFoundException::class)
open fun openOutputStream(uri: Uri, mode: String): OutputStream? {
val flags = ParcelFileDescriptor.parseMode(mode)
require(flags and ParcelFileDescriptor.MODE_WRITE_ONLY != 0) { "Mode '$mode' cannot open an output stream" }
val file = fileFor(uri)
if (!file.exists() && flags and ParcelFileDescriptor.MODE_CREATE == 0) throw FileNotFoundException(file.path)
val options = buildList {
add(StandardOpenOption.WRITE)
if (flags and ParcelFileDescriptor.MODE_CREATE != 0) add(StandardOpenOption.CREATE)
if (flags and ParcelFileDescriptor.MODE_TRUNCATE != 0) add(StandardOpenOption.TRUNCATE_EXISTING)
if (flags and ParcelFileDescriptor.MODE_APPEND != 0) add(StandardOpenOption.APPEND)
}
return Files.newOutputStream(file.toPath(), *options.toTypedArray())
}

/** The MIME type guessed from the file name, or null when there is no guess. */
open fun getType(uri: Uri): String? = uri.lastPathSegment?.let(URLConnection::guessContentTypeFromName)

private fun fileFor(uri: Uri): File = when (uri.scheme) {
null, SCHEME_FILE -> File(uri.path ?: throw FileNotFoundException("No path in $uri"))
else -> throw FileNotFoundException("Cannot open ${uri.scheme}: URIs on the JVM: $uri")
}

companion object {
const val SCHEME_CONTENT = "content"
const val SCHEME_ANDROID_RESOURCE = "android.resource"
const val SCHEME_FILE = "file"
}
}
82 changes: 82 additions & 0 deletions src/main/java/android/os/ParcelFileDescriptor.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package android.os

import java.io.Closeable
import java.io.File
import java.io.FileDescriptor
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.RandomAccessFile

/**
* A file descriptor on the JVM. There is no Parcel to carry it across processes, so it simply holds the stream opened
* on the file, with the access the `MODE_*` flags ask for: a [FileInputStream] for read-only, a [FileOutputStream] for
* write-only (appending through the descriptor when `MODE_APPEND` is set) and a [RandomAccessFile] for read-write.
* Firebase Storage opens one to learn the size of a file it uploads.
*/
class ParcelFileDescriptor private constructor(
private val stream: Closeable,
val fileDescriptor: FileDescriptor,
private val size: () -> Long
) : Closeable {

/** The size of the file in bytes, or -1 when it cannot be determined. */
val statSize: Long
get() = try {
size()
} catch (e: IOException) {
-1
}

@Throws(IOException::class)
override fun close() = stream.close()

companion object {
const val MODE_WORLD_READABLE = 0x00000001
const val MODE_WORLD_WRITEABLE = 0x00000002
const val MODE_READ_ONLY = 0x10000000
const val MODE_WRITE_ONLY = 0x20000000
const val MODE_READ_WRITE = 0x30000000
const val MODE_CREATE = 0x08000000
const val MODE_TRUNCATE = 0x04000000
const val MODE_APPEND = 0x02000000

/** Opens [file] with the `MODE_*` flags in [mode], failing like Android when it is missing and may not be created. */
@JvmStatic
@Throws(FileNotFoundException::class)
fun open(file: File, mode: Int): ParcelFileDescriptor {
val readable = mode and MODE_READ_ONLY != 0
val writable = mode and MODE_WRITE_ONLY != 0
require(readable || writable) { "Bad mode: $mode" }
if (!file.exists() && (!writable || mode and MODE_CREATE == 0)) throw FileNotFoundException(file.path)
val truncate = mode and MODE_TRUNCATE != 0
val append = mode and MODE_APPEND != 0
return when {
!writable -> FileInputStream(file).let { ParcelFileDescriptor(it, it.fd) { it.channel.size() } }
// The output stream truncates unless it appends, which is what the write-only modes ("w", "wt", "wa") ask for.
!readable && (truncate || append) -> FileOutputStream(file, append).let { ParcelFileDescriptor(it, it.fd) { it.channel.size() } }
else -> RandomAccessFile(file, "rw").let {
if (truncate) it.setLength(0)
if (append) it.seek(it.length())
ParcelFileDescriptor(it, it.fd) { it.length() }
}
}
}

/** The `MODE_*` flags for a mode string of `ContentResolver.openFileDescriptor`, as Android parses it. */
@JvmStatic
fun parseMode(mode: String): Int = when (mode) {
"r" -> MODE_READ_ONLY
"w", "wt" -> MODE_WRITE_ONLY or MODE_CREATE or MODE_TRUNCATE
"wa" -> MODE_WRITE_ONLY or MODE_CREATE or MODE_APPEND
"rw" -> MODE_READ_WRITE or MODE_CREATE
"rwt" -> MODE_READ_WRITE or MODE_CREATE or MODE_TRUNCATE
else -> throw IllegalArgumentException("Bad mode: $mode")
}

/** Unsupported: a raw descriptor number cannot be adopted on the JVM. SQLite's blob descriptors are not implemented. */
@JvmStatic
fun adoptFd(fd: Int): ParcelFileDescriptor = throw UnsupportedOperationException("Adopting a raw file descriptor ($fd) is not supported on the JVM")
}
}
129 changes: 129 additions & 0 deletions src/test/kotlin/ContentResolverTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Tests for the android.content.ContentResolver shim, through which Firebase Storage reads the file behind a
* putFile(Uri) upload: the file's size via a ParcelFileDescriptor, its content type and its bytes.
*/
import android.app.Application
import android.net.Uri
import android.os.ParcelFileDescriptor
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream

class ContentResolverTest {

@get:Rule
val folder = TemporaryFolder()

private val resolver = Application().contentResolver

private fun file(name: String, content: String): File = File(folder.root, name).apply { writeText(content) }

@Test
fun `file descriptor reports the size of a file uri`() {
val file = file("upload.txt", "thirteen byte")
resolver.openFileDescriptor(Uri.parse(file.toURI().toString()), "r")!!.use { descriptor ->
assertEquals(13, descriptor.statSize)
}
}

@Test
fun `file descriptor accepts a triple slash file uri and a bare path`() {
val file = file("upload.txt", "content")
resolver.openFileDescriptor(Uri.parse("file://${file.absolutePath}"), "r")!!.use { assertEquals(7, it.statSize) }
resolver.openFileDescriptor(Uri.parse(file.absolutePath), "r")!!.use { assertEquals(7, it.statSize) }
}

@Test
fun `input stream reads the file`() {
val file = file("upload.bin", "bytes")
val read = resolver.openInputStream(Uri.parse(file.toURI().toString()))!!.use { it.readBytes() }
assertArrayEquals("bytes".toByteArray(), read)
}

@Test
fun `output stream writes and appends`() {
val file = File(folder.root, "download.txt")
val uri = Uri.parse(file.toURI().toString())
resolver.openOutputStream(uri)!!.use { it.write("one".toByteArray()) }
resolver.openOutputStream(uri, "wa")!!.use { it.write("two".toByteArray()) }
assertEquals("onetwo", file.readText())
resolver.openOutputStream(uri, "wt")!!.use { it.write("three".toByteArray()) }
assertEquals("three", file.readText())
}

@Test
fun `read-write output stream overwrites in place without truncating`() {
val file = file("inplace.txt", "abcdef")
val uri = Uri.parse(file.toURI().toString())
resolver.openOutputStream(uri, "rw")!!.use { it.write("X".toByteArray()) }
assertEquals("Xbcdef", file.readText())
resolver.openOutputStream(uri, "rwt")!!.use { it.write("Y".toByteArray()) }
assertEquals("Y", file.readText())
}

@Test
fun `read-only mode cannot open an output stream`() {
val file = file("readonly.txt", "keep")
assertThrows(IllegalArgumentException::class.java) { resolver.openOutputStream(Uri.parse(file.toURI().toString()), "r") }
assertEquals("keep", file.readText())
}

@Test
fun `type is guessed from the file name`() {
assertEquals("text/plain", resolver.getType(Uri.parse("file:///tmp/notes.txt")))
assertEquals("image/png", resolver.getType(Uri.parse("file:///tmp/photo.png")))
assertNull(resolver.getType(Uri.parse("file:///tmp/blob")))
}

@Test
fun `missing files and other schemes are not found`() {
assertThrows(FileNotFoundException::class.java) {
resolver.openFileDescriptor(Uri.parse(File(folder.root, "missing.txt").toURI().toString()), "r")
}
assertThrows(FileNotFoundException::class.java) {
resolver.openInputStream(Uri.parse("content://media/external/images/1"))
}
}

@Test
fun `write modes create truncate and append`() {
val file = File(folder.root, "modes.txt")
assertThrows(FileNotFoundException::class.java) { ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) }
ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("w")).use { assertEquals(0, it.statSize) }
file.writeText("longer content")
ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa")).use { assertEquals(14, it.statSize) }
ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("rw")).use { assertEquals(14, it.statSize) }
assertEquals("longer content", file.readText())
ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wt")).use { assertEquals(0, it.statSize) }
assertThrows(IllegalArgumentException::class.java) { ParcelFileDescriptor.parseMode("x") }
}

@Test
fun `read-only descriptor does not write and appending descriptors interleave`() {
val file = file("append.txt", "start")
ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("r")).use { descriptor ->
assertThrows(java.io.IOException::class.java) { FileOutputStream(descriptor.fileDescriptor).write(1) }
}
assertEquals("start", file.readText())
val first = ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa"))
val second = ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode("wa"))
FileOutputStream(first.fileDescriptor).write("-one".toByteArray())
FileOutputStream(second.fileDescriptor).write("-two".toByteArray())
FileOutputStream(first.fileDescriptor).write("-three".toByteArray())
first.close()
second.close()
assertEquals("start-one-two-three", file.readText())
}

@Test
fun `adopting a raw descriptor is unsupported`() {
assertThrows(UnsupportedOperationException::class.java) { ParcelFileDescriptor.adoptFd(3) }
}
}
Loading