1
0

Use stream instead of zip file

This commit is contained in:
Hubert Van De Walle 2020-09-11 17:58:20 +02:00
parent 0d47b51f3f
commit 8a08520267
3 changed files with 19 additions and 28 deletions

View File

@ -3,22 +3,19 @@ package starter
import starter.templates.Template
import starter.utils.ZipOutput
import starter.utils.sanitizeFilename
import java.io.ByteArrayOutputStream
class ProjectZip(private val templates: List<Template>) {
fun createZip(project: Project): String {
val name: String
fun createZip(project: Project): ByteArrayOutputStream {
val projectName = sanitizeFilename(project.name)
ZipOutput(projectName).use { zip ->
name = zip.name
val zipOutput = ZipOutput()
zipOutput.use { zip ->
templates.filter { it.enabled(project) }.forEach { template ->
zip.write(projectName + "/" + template.path(project), template.render(project))
}
}
return name
return zipOutput.outputStream
}
}

View File

@ -2,7 +2,7 @@ package starter
import io.javalin.Javalin
import starter.utils.sanitizeFilename
import java.io.File
import java.io.ByteArrayInputStream
class Server(
private val views: Views,
@ -47,8 +47,9 @@ class Server(
ctx.contentType("application/zip")
ctx.header("Content-Disposition", "attachment; filename=\"${sanitizeFilename(projectName)}.zip\"")
val zipFile = projectZip.createZip(project)
ctx.result(File(zipFile).readBytes())
val outputStream = projectZip.createZip(project)
ctx.result(ByteArrayInputStream(outputStream.toByteArray()))
}
}
}

View File

@ -2,28 +2,21 @@ package starter.utils
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream
import java.io.File
import java.nio.file.Paths
import java.io.ByteArrayOutputStream
class ZipOutput(name: String) : AutoCloseable {
private val baseDir = File(".").canonicalFile
private val zipPath = Paths.get(baseDir.path, "$name.zip")
private val zipFile = zipPath.toAbsolutePath().normalize().toFile().apply {
createNewFile()
}
private val outputStream = ZipArchiveOutputStream(zipFile.outputStream())
val name: String
get() = zipFile.name
class ZipOutput : AutoCloseable {
val outputStream = ByteArrayOutputStream()
private val zipOutputStream = ZipArchiveOutputStream(outputStream)
fun write(path: String, content: String) {
val entry = ZipArchiveEntry(path)
outputStream.putArchiveEntry(entry)
outputStream.write(content.toByteArray())
outputStream.closeArchiveEntry()
zipOutputStream.putArchiveEntry(entry)
zipOutputStream.write(content.toByteArray())
zipOutputStream.closeArchiveEntry()
}
override fun close() {
outputStream.finish()
outputStream.close()
zipOutputStream.finish()
zipOutputStream.close()
}
}
}