From aed905203f94e4ac538fc8bbcfb1d0844600a465 Mon Sep 17 00:00:00 2001 From: Ugur Cenar Date: Mon, 20 Nov 2023 09:33:16 +0100 Subject: [PATCH] Fix tests and linting --- .../kotlin/no/nav/pdfgen/core/Environment.kt | 30 +++++++++----- .../no/nav/pdfgen/core/MetricRegistry.kt | 1 - .../kotlin/no/nav/pdfgen/core/PDFGenCore.kt | 3 +- .../no/nav/pdfgen/core/pdf/CreateHtml.kt | 21 ++++++---- .../no/nav/pdfgen/core/template/Helpers.kt | 41 +++++++++++-------- .../no/nav/pdfgen/core/template/Templates.kt | 18 +++++--- .../no/nav/pdfgen/core/util/FontMetadata.kt | 3 +- src/test/kotlin/no/nav/pdfgen/HelperTest.kt | 4 +- 8 files changed, 74 insertions(+), 47 deletions(-) diff --git a/src/main/kotlin/no/nav/pdfgen/core/Environment.kt b/src/main/kotlin/no/nav/pdfgen/core/Environment.kt index 5b3dacd..0aa0c47 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/Environment.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/Environment.kt @@ -5,9 +5,6 @@ import com.fasterxml.jackson.module.kotlin.readValue import com.fasterxml.jackson.module.kotlin.registerKotlinModule import com.github.jknack.handlebars.Helper import io.github.oshai.kotlinlogging.KotlinLogging -import no.nav.pdfgen.core.template.loadTemplates -import no.nav.pdfgen.core.util.FontMetadata -import org.apache.pdfbox.io.IOUtils import java.io.File import java.nio.file.Files import java.nio.file.Path @@ -17,6 +14,9 @@ import kotlin.io.path.exists import kotlin.io.path.extension import kotlin.io.path.pathString import kotlin.io.path.readBytes +import no.nav.pdfgen.core.template.loadTemplates +import no.nav.pdfgen.core.util.FontMetadata +import org.apache.pdfbox.io.IOUtils private val log = KotlinLogging.logger {} val objectMapper: ObjectMapper = ObjectMapper().findAndRegisterModules().registerKotlinModule() @@ -34,6 +34,7 @@ class Environment( val resources: Map = loadResources(resourcesRoot) val fonts: List = objectMapper.readValue(fontsRoot.readAllBytes("config.json")) val templates = loadTemplates(templateRoot, additionalHandlebarHelpers) + override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false @@ -49,22 +50,28 @@ class Environment( fun copy(): Environment { return Environment( - additionalHandlebarHelpers = additionalHandlebarHelpers, - templateRoot = templateRoot, - resourcesRoot = resourcesRoot, - fontsRoot = fontsRoot, - dataRoot = dataRoot, + additionalHandlebarHelpers = additionalHandlebarHelpers, + templateRoot = templateRoot, + resourcesRoot = resourcesRoot, + fontsRoot = fontsRoot, + dataRoot = dataRoot, ) } - } data class PDFGenResource(val path: String) { private val _path: Path = Paths.get(path) + fun readAllBytes(filename: String? = null): ByteArray { val filePath = filename?.let { _path.resolve(it) } ?: _path - return if (filePath.exists()) filePath.readBytes() else Environment::class.java.classLoader.getResourceAsStream(filePath.pathString)!!.readAllBytes() + return if (filePath.exists()) filePath.readBytes() + else + Environment::class + .java + .classLoader + .getResourceAsStream(filePath.pathString)!! + .readAllBytes() } fun toFile(filename: String? = null): File = getPath(filename).toFile() @@ -72,7 +79,8 @@ data class PDFGenResource(val path: String) { fun getPath(filename: String? = null): Path { val filePath = filename?.let { _path.resolve(it) } ?: _path log.info { "Reading file from path $filePath. File exists on path = ${filePath.exists()}" } - return if (filePath.exists()) filePath else Path.of(Environment::class.java.classLoader.getResource(filePath.pathString)!!.toURI()) + return if (filePath.exists()) filePath + else Path.of(Environment::class.java.classLoader.getResource(filePath.pathString)!!.toURI()) } } diff --git a/src/main/kotlin/no/nav/pdfgen/core/MetricRegistry.kt b/src/main/kotlin/no/nav/pdfgen/core/MetricRegistry.kt index f015ac9..264ac74 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/MetricRegistry.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/MetricRegistry.kt @@ -13,4 +13,3 @@ val OPENHTMLTOPDF_RENDERING_SUMMARY: Summary = .help("Time it takes to render a PDF") .labelNames("application_name", "template_type") .register() - diff --git a/src/main/kotlin/no/nav/pdfgen/core/PDFGenCore.kt b/src/main/kotlin/no/nav/pdfgen/core/PDFGenCore.kt index 401d9e1..71c8f60 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/PDFGenCore.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/PDFGenCore.kt @@ -3,13 +3,14 @@ package no.nav.pdfgen.core import java.util.concurrent.atomic.AtomicReference val environment = AtomicReference(Environment()) + class PDFGenCore { companion object { fun init(initialEnvironment: Environment) { environment.set(initialEnvironment) } - fun reloadEnvironment(){ + fun reloadEnvironment() { environment.set(environment.get().copy()) } } diff --git a/src/main/kotlin/no/nav/pdfgen/core/pdf/CreateHtml.kt b/src/main/kotlin/no/nav/pdfgen/core/pdf/CreateHtml.kt index a51a9f6..fbde3c0 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/pdf/CreateHtml.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/pdf/CreateHtml.kt @@ -5,11 +5,11 @@ import com.github.jknack.handlebars.Context import com.github.jknack.handlebars.JsonNodeValueResolver import com.github.jknack.handlebars.context.MapValueResolver import io.github.oshai.kotlinlogging.KotlinLogging +import java.nio.file.Files import net.logstash.logback.argument.StructuredArguments import no.nav.pdfgen.core.HANDLEBARS_RENDERING_SUMMARY import no.nav.pdfgen.core.environment import no.nav.pdfgen.core.objectMapper -import java.nio.file.Files private val log = KotlinLogging.logger {} @@ -27,14 +27,17 @@ fun createHtmlFromTemplateData(template: String, directoryName: String): String? fun render(directoryName: String, template: String, jsonNode: JsonNode): String? { return HANDLEBARS_RENDERING_SUMMARY.startTimer() .use { - environment.get().templates[directoryName to template]?.apply( - Context.newBuilder(jsonNode) - .resolver( - JsonNodeValueResolver.INSTANCE, - MapValueResolver.INSTANCE, - ) - .build(), - ) + environment + .get() + .templates[directoryName to template] + ?.apply( + Context.newBuilder(jsonNode) + .resolver( + JsonNodeValueResolver.INSTANCE, + MapValueResolver.INSTANCE, + ) + .build(), + ) } ?.let { html -> log.debug { "${"Generated HTML {}"} ${StructuredArguments.keyValue("html", html)}" } diff --git a/src/main/kotlin/no/nav/pdfgen/core/template/Helpers.kt b/src/main/kotlin/no/nav/pdfgen/core/template/Helpers.kt index 5c4e9d3..b2278a7 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/template/Helpers.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/template/Helpers.kt @@ -6,14 +6,14 @@ import com.github.jknack.handlebars.Context import com.github.jknack.handlebars.Handlebars import com.github.jknack.handlebars.Helper import com.github.jknack.handlebars.Options -import no.nav.pdfgen.core.domain.Periode -import no.nav.pdfgen.core.domain.PeriodeMapper -import no.nav.pdfgen.core.environment -import no.nav.pdfgen.core.objectMapper import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.Locale +import no.nav.pdfgen.core.domain.Periode +import no.nav.pdfgen.core.domain.PeriodeMapper +import no.nav.pdfgen.core.environment +import no.nav.pdfgen.core.objectMapper val dateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") val yearMonthFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("MM.yyyy") @@ -21,6 +21,7 @@ val dateFormatLong: DateTimeFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy").withLocale(Locale.of("no", "NO")) val datetimeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm") val yearMonthFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM") + fun formatDateTime(formatter: DateTimeFormatter, context: CharSequence): String = try { formatter.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parseBest(context)) @@ -31,13 +32,17 @@ fun formatDateTime(formatter: DateTimeFormatter, context: CharSequence): String fun formatDate(formatter: DateTimeFormatter, context: CharSequence): String { val dateSplit = context.split("-") return try { - if (dateSplit.size == 2) formatter.format(yearMonthFormatter.parse(context)) else formatter.format(DateTimeFormatter.ISO_DATE.parse(context)) + if (dateSplit.size == 2) formatter.format(yearMonthFormatter.parse(context)) + else formatter.format(DateTimeFormatter.ISO_DATE.parse(context)) } catch (e: Exception) { formatter.format(DateTimeFormatter.ISO_DATE.parse("$context-01")) } } -fun registerNavHelpers(handlebars: Handlebars, additionalHelpers: Map> = emptyMap()) { +fun registerNavHelpers( + handlebars: Handlebars, + additionalHelpers: Map> = emptyMap() +) { handlebars.apply { registerHelper( "iso_to_nor_date", @@ -108,7 +113,8 @@ fun registerNavHelpers(handlebars: Handlebars, additionalHelpers: Map - buffer.append(options.fn(it)) - } + val filteredList = + list.filter { getParameterValue(it, filterByField) == filterByValue } + filteredList.forEachIndexed { _, it -> buffer.append(options.fn(it)) } } buffer @@ -376,15 +379,19 @@ fun registerNavHelpers(handlebars: Handlebars, additionalHelpers: Map { value, _ -> - objectMapper.writeValueAsString(value) - }, + Helper { value, _ -> objectMapper.writeValueAsString(value) }, ) additionalHelpers.forEach { (t, u) -> registerHelper(t, u) } } } -private fun buildContext(options: Options, value: Any, index: Int, key: String, isLast: Boolean = false): Context { +private fun buildContext( + options: Options, + value: Any, + index: Int, + key: String, + isLast: Boolean = false +): Context { val parent = options.context val first = true return Context.newBuilder(parent, value) diff --git a/src/main/kotlin/no/nav/pdfgen/core/template/Templates.kt b/src/main/kotlin/no/nav/pdfgen/core/template/Templates.kt index e48fb4e..ffab358 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/template/Templates.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/template/Templates.kt @@ -5,12 +5,16 @@ import com.github.jknack.handlebars.Helper import com.github.jknack.handlebars.Template import com.github.jknack.handlebars.io.FileTemplateLoader import com.github.jknack.handlebars.io.StringTemplateSource -import no.nav.pdfgen.core.PDFGenResource import java.nio.file.Files import kotlin.io.path.extension +import no.nav.pdfgen.core.PDFGenResource typealias TemplateMap = Map, Template> -fun loadTemplates(templateRoot: PDFGenResource, additionalHandlebarHelpers: Map>): TemplateMap = + +fun loadTemplates( + templateRoot: PDFGenResource, + additionalHandlebarHelpers: Map> +): TemplateMap = Files.list(templateRoot.getPath()) .filter { !Files.isHidden(it) && Files.isDirectory(it) } .map { @@ -21,16 +25,20 @@ fun loadTemplates(templateRoot: PDFGenResource, additionalHandlebarHelpers: Map< val fileName = it.fileName.toString() val templateName = fileName.substring(0..fileName.length - 5) val templateBytes = Files.readAllBytes(it).toString(Charsets.UTF_8) - val xhtml = setupHandlebars(templateRoot, additionalHandlebarHelpers).compile(StringTemplateSource(fileName, templateBytes)) + val xhtml = + setupHandlebars(templateRoot, additionalHandlebarHelpers) + .compile(StringTemplateSource(fileName, templateBytes)) (applicationName to templateName) to xhtml } } .toList() .toMap() -private fun setupHandlebars(templateRoot: PDFGenResource, additionalHandlebarHelpers: Map>) = +private fun setupHandlebars( + templateRoot: PDFGenResource, + additionalHandlebarHelpers: Map> +) = Handlebars(FileTemplateLoader(templateRoot.toFile())).apply { registerNavHelpers(this, additionalHandlebarHelpers) infiniteLoops(true) } - diff --git a/src/main/kotlin/no/nav/pdfgen/core/util/FontMetadata.kt b/src/main/kotlin/no/nav/pdfgen/core/util/FontMetadata.kt index 0b1a809..4f2929d 100644 --- a/src/main/kotlin/no/nav/pdfgen/core/util/FontMetadata.kt +++ b/src/main/kotlin/no/nav/pdfgen/core/util/FontMetadata.kt @@ -10,5 +10,6 @@ data class FontMetadata( val style: BaseRendererBuilder.FontStyle, val subset: Boolean, ) { - val bytes: ByteArray get() = environment.get().fontsRoot.readAllBytes(path) + val bytes: ByteArray + get() = environment.get().fontsRoot.readAllBytes(path) } diff --git a/src/test/kotlin/no/nav/pdfgen/HelperTest.kt b/src/test/kotlin/no/nav/pdfgen/HelperTest.kt index 7740eeb..5c9f89e 100644 --- a/src/test/kotlin/no/nav/pdfgen/HelperTest.kt +++ b/src/test/kotlin/no/nav/pdfgen/HelperTest.kt @@ -9,7 +9,7 @@ import com.github.jknack.handlebars.JsonNodeValueResolver import com.github.jknack.handlebars.context.MapValueResolver import com.github.jknack.handlebars.io.ClassPathTemplateLoader import no.nav.pdfgen.core.Environment -import no.nav.pdfgen.core.PDFgen +import no.nav.pdfgen.core.PDFGenCore import no.nav.pdfgen.core.template.registerNavHelpers import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach @@ -25,7 +25,7 @@ internal class HelperTest { @BeforeEach fun init() { - PDFgen.init(Environment()) + PDFGenCore.init(Environment()) } private fun jsonContext(jsonNode: JsonNode): Context {