All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.http4k.multipart.DiskLocation.kt Maven / Gradle / Ivy

There is a newer version: 5.41.0.0
Show newest version
package org.http4k.multipart

import java.io.Closeable
import java.io.File
import java.nio.file.FileSystemException
import java.nio.file.Files
import java.util.UUID

/**
 * Provides the management of the on-disk persistence for mulitpart files which are too big
 * to be processed in-memory.
 */
interface DiskLocation : Closeable {
    fun createFile(filename: String?): MultipartFile

    companion object {
        fun Temp(diskDir: File = Files.createTempDirectory("http4k-mp").toFile()) =
            object : DiskLocation {
                override fun createFile(filename: String?): MultipartFile =
                    TempFile(
                        File.createTempFile(
                            filename ?: (UUID.randomUUID().toString() + "-"),
                            ".tmp", diskDir
                        )
                    )

                override fun close() {
                    diskDir.listFiles()?.forEach { it.delete() }
                    diskDir.delete()
                }
            }

        fun Permanent(diskDir: File = Files.createTempDirectory("http4k-mp").toFile()) =
            object : DiskLocation {
                override fun createFile(filename: String?): MultipartFile =
                    PermanentFile(
                        File.createTempFile(
                            filename ?: (UUID.randomUUID().toString() + "-"),
                            ".tmp", diskDir
                        )
                    )

                override fun close() {}
            }
    }
}

interface MultipartFile : Closeable {
    fun file(): File
    override fun close()
}

internal class TempFile(private val file: File) : MultipartFile {

    override fun file() = file

    override fun close() {
        if (file.exists() && !file.delete()) throw FileSystemException("Failed to delete file")
    }
}

internal class PermanentFile(private val file: File) : MultipartFile {
    override fun file() = file

    override fun close() {
        // do nothing
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy