Skip to content

Commit

Permalink
Fix tests and linting
Browse files Browse the repository at this point in the history
  • Loading branch information
ugur93 committed Nov 20, 2023
1 parent 73d13a6 commit aed9052
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 47 deletions.
30 changes: 19 additions & 11 deletions src/main/kotlin/no/nav/pdfgen/core/Environment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
Expand All @@ -34,6 +34,7 @@ class Environment(
val resources: Map<String, ByteArray> = loadResources(resourcesRoot)
val fonts: List<FontMetadata> = 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
Expand All @@ -49,30 +50,37 @@ 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()

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())
}
}

Expand Down
1 change: 0 additions & 1 deletion src/main/kotlin/no/nav/pdfgen/core/MetricRegistry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ val OPENHTMLTOPDF_RENDERING_SUMMARY: Summary =
.help("Time it takes to render a PDF")
.labelNames("application_name", "template_type")
.register()

3 changes: 2 additions & 1 deletion src/main/kotlin/no/nav/pdfgen/core/PDFGenCore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
Expand Down
21 changes: 12 additions & 9 deletions src/main/kotlin/no/nav/pdfgen/core/pdf/CreateHtml.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}

Expand All @@ -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)}" }
Expand Down
41 changes: 24 additions & 17 deletions src/main/kotlin/no/nav/pdfgen/core/template/Helpers.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@ 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")
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))
Expand All @@ -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<String, Helper<*>> = emptyMap()) {
fun registerNavHelpers(
handlebars: Handlebars,
additionalHelpers: Map<String, Helper<*>> = emptyMap()
) {
handlebars.apply {
registerHelper(
"iso_to_nor_date",
Expand Down Expand Up @@ -108,7 +113,8 @@ fun registerNavHelpers(handlebars: Handlebars, additionalHelpers: Map<String, He
if (periode.fom == null) return@Helper ""
return@Helper periode.fom.format(dateFormat) +
" - " +
(periode.tom?.format(dateFormat) ?: periode.til?.format(dateFormat) ?: "")
(periode.tom?.format(dateFormat)
?: periode.til?.format(dateFormat) ?: "")
}
}
},
Expand Down Expand Up @@ -356,12 +362,9 @@ fun registerNavHelpers(handlebars: Handlebars, additionalHelpers: Map<String, He
val filterByValue = options.param(1, null as String?)
val buffer = options.buffer()
if (list is JsonNode) {
val filteredList = list.filter {
getParameterValue(it, filterByField) == filterByValue
}
filteredList.forEachIndexed { _, it ->
buffer.append(options.fn(it))
}
val filteredList =
list.filter { getParameterValue(it, filterByField) == filterByValue }
filteredList.forEachIndexed { _, it -> buffer.append(options.fn(it)) }
}

buffer
Expand All @@ -376,15 +379,19 @@ fun registerNavHelpers(handlebars: Handlebars, additionalHelpers: Map<String, He
)
registerHelper(
"stringify",
Helper<Any> { value, _ ->
objectMapper.writeValueAsString(value)
},
Helper<Any> { 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)
Expand Down
18 changes: 13 additions & 5 deletions src/main/kotlin/no/nav/pdfgen/core/template/Templates.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pair<String, String>, Template>
fun loadTemplates(templateRoot: PDFGenResource, additionalHandlebarHelpers: Map<String, Helper<*>>): TemplateMap =

fun loadTemplates(
templateRoot: PDFGenResource,
additionalHandlebarHelpers: Map<String, Helper<*>>
): TemplateMap =
Files.list(templateRoot.getPath())
.filter { !Files.isHidden(it) && Files.isDirectory(it) }
.map {
Expand All @@ -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<String, Helper<*>>) =
private fun setupHandlebars(
templateRoot: PDFGenResource,
additionalHandlebarHelpers: Map<String, Helper<*>>
) =
Handlebars(FileTemplateLoader(templateRoot.toFile())).apply {
registerNavHelpers(this, additionalHandlebarHelpers)
infiniteLoops(true)
}

3 changes: 2 additions & 1 deletion src/main/kotlin/no/nav/pdfgen/core/util/FontMetadata.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
4 changes: 2 additions & 2 deletions src/test/kotlin/no/nav/pdfgen/HelperTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -25,7 +25,7 @@ internal class HelperTest {

@BeforeEach
fun init() {
PDFgen.init(Environment())
PDFGenCore.init(Environment())
}

private fun jsonContext(jsonNode: JsonNode): Context {
Expand Down

0 comments on commit aed9052

Please sign in to comment.