CORDA-1639: Resolve ProviderMismatchException when copying a file into a ZIP. (#3421)

* Resolve ProviderMismatchException when copying a file into a ZIP.
* Review tweaks.
This commit is contained in:
Chris Rankin 2018-06-22 12:12:31 +01:00 committed by GitHub
parent 687ed95994
commit 02348a584d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 1 deletions

View File

@ -43,7 +43,16 @@ fun Path.exists(vararg options: LinkOption): Boolean = Files.exists(this, *optio
/** Copy the file into the target directory using [Files.copy]. */
fun Path.copyToDirectory(targetDir: Path, vararg options: CopyOption): Path {
require(targetDir.isDirectory()) { "$targetDir is not a directory" }
val targetFile = targetDir.resolve(fileName)
/*
* We must use fileName.toString() here because resolve(Path)
* will throw ProviderMismatchException if the Path parameter
* and targetDir have different Path providers, e.g. a file
* on the filesystem vs an entry in a ZIP file.
*
* Path.toString() is assumed safe because fileName should
* not include any path separator characters.
*/
val targetFile = targetDir.resolve(fileName.toString())
Files.copy(this, targetFile, *options)
return targetFile
}

View File

@ -4,6 +4,9 @@ import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.net.URI
import java.nio.file.FileSystems
import java.nio.file.Path
class PathUtilsTest {
@Rule
@ -59,4 +62,21 @@ class PathUtilsTest {
dir.deleteRecursively()
assertThat(dir).doesNotExist()
}
@Test
fun `copyToDirectory - copy into zip directory`() {
val source: Path = tempFolder.newFile("source.txt").let {
it.writeText("Example Text")
it.toPath()
}
val target = tempFolder.root.toPath() / "target.zip"
FileSystems.newFileSystem(URI.create("jar:${target.toUri()}"), mapOf("create" to "true")).use { fs ->
val dir = fs.getPath("dir").createDirectories()
val result = source.copyToDirectory(dir)
assertThat(result)
.isRegularFile()
.hasParent(dir)
.hasSameContentAs(source)
}
}
}