Skip to content

Commit

Permalink
Use ktfmt for formatting code
Browse files Browse the repository at this point in the history
  • Loading branch information
MikAoJk committed Jun 20, 2023
1 parent 3f9e5d9 commit 80ee366
Show file tree
Hide file tree
Showing 14 changed files with 1,383 additions and 924 deletions.
97 changes: 93 additions & 4 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -1,4 +1,93 @@
[*.{kt,kts}]
indent_size=4
insert_final_newline=true
disabled_rules=no-wildcard-imports
# This .editorconfig section approximates ktfmt's formatting rules. You can include it in an
# existing .editorconfig file or use it standalone by copying it to <project root>/.editorconfig
# and making sure your editor is set to read settings from .editorconfig files.
#
# It includes editor-specific config options for IntelliJ IDEA.
#
# If any option is wrong, PR are welcome

[{*.kt,*.kts}]
indent_style = space
insert_final_newline = true
max_line_length = 100
indent_size = 4
ij_continuation_indent_size = 4
ij_java_names_count_to_use_import_on_demand = 9999
ij_kotlin_align_in_columns_case_branch = false
ij_kotlin_align_multiline_binary_operation = false
ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true
ij_kotlin_assignment_wrap = normal
ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0
ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1
ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = true
ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = on_every_item
ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true
ij_kotlin_continuation_indent_in_elvis = false
ij_kotlin_continuation_indent_in_if_conditions = false
ij_kotlin_continuation_indent_in_parameter_lists = false
ij_kotlin_continuation_indent_in_supertype_lists = false
ij_kotlin_else_on_new_line = false
ij_kotlin_enum_constants_wrap = off
ij_kotlin_extends_list_wrap = normal
ij_kotlin_field_annotation_wrap = split_into_lines
ij_kotlin_finally_on_new_line = false
ij_kotlin_if_rparen_on_new_line = false
ij_kotlin_import_nested_classes = false
ij_kotlin_insert_whitespaces_in_simple_one_line_method = true
ij_kotlin_keep_blank_lines_before_right_brace = 2
ij_kotlin_keep_blank_lines_in_code = 2
ij_kotlin_keep_blank_lines_in_declarations = 2
ij_kotlin_keep_first_column_comment = true
ij_kotlin_keep_indents_on_empty_lines = false
ij_kotlin_keep_line_breaks = true
ij_kotlin_lbrace_on_next_line = false
ij_kotlin_line_comment_add_space = false
ij_kotlin_line_comment_at_first_column = true
ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = normal
ij_kotlin_method_parameters_new_line_after_left_paren = true
ij_kotlin_method_parameters_right_paren_on_new_line = true
ij_kotlin_method_parameters_wrap = on_every_item
ij_kotlin_name_count_to_use_star_import = 9999
ij_kotlin_name_count_to_use_star_import_for_members = 9999
ij_kotlin_parameter_annotation_wrap = off
ij_kotlin_space_after_comma = true
ij_kotlin_space_after_extend_colon = true
ij_kotlin_space_after_type_colon = true
ij_kotlin_space_before_catch_parentheses = true
ij_kotlin_space_before_comma = false
ij_kotlin_space_before_extend_colon = true
ij_kotlin_space_before_for_parentheses = true
ij_kotlin_space_before_if_parentheses = true
ij_kotlin_space_before_lambda_arrow = true
ij_kotlin_space_before_type_colon = false
ij_kotlin_space_before_when_parentheses = true
ij_kotlin_space_before_while_parentheses = true
ij_kotlin_spaces_around_additive_operators = true
ij_kotlin_spaces_around_assignment_operators = true
ij_kotlin_spaces_around_equality_operators = true
ij_kotlin_spaces_around_function_type_arrow = true
ij_kotlin_spaces_around_logical_operators = true
ij_kotlin_spaces_around_multiplicative_operators = true
ij_kotlin_spaces_around_range = false
ij_kotlin_spaces_around_relational_operators = true
ij_kotlin_spaces_around_unary_operator = false
ij_kotlin_spaces_around_when_arrow = true
ij_kotlin_variable_annotation_wrap = off
ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 1
ij_kotlin_wrap_first_method_in_call_chain = false
11 changes: 10 additions & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ val openHtmlToPdfVersion = "1.0.10"
val prometheusVersion = "0.16.0"
val junitJupiterVersion = "5.9.3"
val verapdfVersion = "1.22.2"
val ktfmtVersion = "0.44"


plugins {
kotlin("jvm") version "1.8.22"
id("org.jmailen.kotlinter") version "3.15.0"
id("com.diffplug.spotless") version "6.19.0"
id("com.github.johnrengelman.shadow") version "8.1.1"
id("com.github.ben-manes.versions") version "0.47.0"
}
Expand All @@ -43,6 +45,13 @@ tasks {
withType<Jar> {
manifest.attributes("Main-Class" to "no.nav.pdfgen.BootstrapKt")
}

spotless {
kotlin { ktfmt(ktfmtVersion).kotlinlangStyle() }
check {
dependsOn("spotlessApply")
}
}
}

repositories {
Expand Down
36 changes: 16 additions & 20 deletions src/main/kotlin/no/nav/pdfgen/Bootstrap.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.verapdf.gf.foundry.VeraGreenfieldFoundryProvider

val objectMapper: ObjectMapper = ObjectMapper()
.registerKotlinModule()
val objectMapper: ObjectMapper = ObjectMapper().registerKotlinModule()

val log: Logger = LoggerFactory.getLogger("pdfgen")

Expand All @@ -57,41 +56,37 @@ fun initializeApplication(port: Int): ApplicationEngine {
XRLog.setLoggerImpl(Slf4jLogger())

return embeddedServer(
Netty, port,
Netty,
port,
configure = {
responseWriteTimeoutSeconds = 60 // Increase timeout of Netty to handle large content bodies
}
responseWriteTimeoutSeconds =
60 // Increase timeout of Netty to handle large content bodies
},
) {
install(ContentNegotiation) {
jackson {}
}
install(ContentNegotiation) { jackson {} }

install(StatusPages) {
status(HttpStatusCode.NotFound) { call, _ ->
call.respond(
TextContent(
messageFor404(templates, call.request.path()),
ContentType.Text.Plain.withCharset(Charsets.UTF_8),
HttpStatusCode.NotFound
)
HttpStatusCode.NotFound,
),
)
}
}
routing {
get("/internal/is_ready") {
call.respondText("I'm ready")
}
get("/internal/is_alive") {
call.respondText("I'm alive")
}
get("/internal/is_ready") { call.respondText("I'm ready") }
get("/internal/is_alive") { call.respondText("I'm alive") }
get("/internal/prometheus") {
val names = call.request.queryParameters.getAll("name[]")?.toSet() ?: setOf()
call.respondTextWriter(ContentType.parse(TextFormat.CONTENT_TYPE_004)) {
CoroutineScope(Dispatchers.IO).launch {
runCatching {
TextFormat.write004(
this@respondTextWriter,
collectorRegistry.filteredMetricFamilySamples(names)
collectorRegistry.filteredMetricFamilySamples(names),
)
}
}
Expand All @@ -103,6 +98,7 @@ fun initializeApplication(port: Int): ApplicationEngine {
}

private fun messageFor404(templates: Map<Pair<String, String>, Template>, path: String) =
"Unkown path '$path'. Known templates:\n" + templates.map { (app, _) ->
"/api/v1/genpdf/%s/%s".format(app.first, app.second)
}.joinToString("\n")
"Unkown path '$path'. Known templates:\n" +
templates
.map { (app, _) -> "/api/v1/genpdf/%s/%s".format(app.first, app.second) }
.joinToString("\n")
68 changes: 36 additions & 32 deletions src/main/kotlin/no/nav/pdfgen/Environment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package no.nav.pdfgen

import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.util.*
import no.nav.pdfgen.util.FontMetadata
import org.apache.pdfbox.io.IOUtils
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import kotlin.streams.toList
import no.nav.pdfgen.util.FontMetadata
import org.apache.pdfbox.io.IOUtils

val templateRoot: Path = Paths.get("templates/")
val imagesRoot: Path = Paths.get("resources/")
Expand All @@ -17,10 +17,13 @@ val fontsRoot: Path = Paths.get("fonts/")
data class Environment(
val images: Map<String, String> = loadImages(),
val resources: Map<String, ByteArray> = loadResources(),
val colorProfile: ByteArray = IOUtils.toByteArray(Environment::class.java.getResourceAsStream("/sRGB2014.icc")),
val fonts: List<FontMetadata> = objectMapper.readValue(Files.newInputStream(fontsRoot.resolve("config.json"))),
val colorProfile: ByteArray =
IOUtils.toByteArray(Environment::class.java.getResourceAsStream("/sRGB2014.icc")),
val fonts: List<FontMetadata> =
objectMapper.readValue(Files.newInputStream(fontsRoot.resolve("config.json"))),
val disablePdfGet: Boolean = System.getenv("DISABLE_PDF_GET")?.let { it == "true" } ?: false,
val enableHtmlEndpoint: Boolean = System.getenv("ENABLE_HTML_ENDPOINT")?.let { it == "true" } ?: false
val enableHtmlEndpoint: Boolean =
System.getenv("ENABLE_HTML_ENDPOINT")?.let { it == "true" } ?: false,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
Expand All @@ -38,32 +41,33 @@ data class Environment(
}
}

fun loadImages() = Files.list(imagesRoot)
.filter {
val validExtensions = setOf("jpg", "jpeg", "png", "bmp", "svg")
!Files.isHidden(it) && it.fileName.extension in validExtensions
}
.map {
val fileName = it.fileName.toString()
val extension = when (it.fileName.extension) {
"jpg" -> "jpeg" // jpg is not a valid mime-type
"svg" -> "svg+xml"
else -> it.fileName.extension
fun loadImages() =
Files.list(imagesRoot)
.filter {
val validExtensions = setOf("jpg", "jpeg", "png", "bmp", "svg")
!Files.isHidden(it) && it.fileName.extension in validExtensions
}
val base64string = Base64.getEncoder().encodeToString(Files.readAllBytes(it))
val base64 = "data:image/$extension;base64,$base64string"
fileName to base64
}
.toList()
.toMap()
.map {
val fileName = it.fileName.toString()
val extension =
when (it.fileName.extension) {
"jpg" -> "jpeg" // jpg is not a valid mime-type
"svg" -> "svg+xml"
else -> it.fileName.extension
}
val base64string = Base64.getEncoder().encodeToString(Files.readAllBytes(it))
val base64 = "data:image/$extension;base64,$base64string"
fileName to base64
}
.toList()
.toMap()

fun loadResources() = Files.list(imagesRoot)
.filter {
val validExtensions = setOf("svg")
!Files.isHidden(it) && it.fileName.extension in validExtensions
}
.map {
it.fileName.toString() to Files.readAllBytes(it)
}
.toList()
.toMap()
fun loadResources() =
Files.list(imagesRoot)
.filter {
val validExtensions = setOf("svg")
!Files.isHidden(it) && it.fileName.extension in validExtensions
}
.map { it.fileName.toString() to Files.readAllBytes(it) }
.toList()
.toMap()
29 changes: 16 additions & 13 deletions src/main/kotlin/no/nav/pdfgen/MetricRegistry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ package no.nav.pdfgen

import io.prometheus.client.Summary

val HANDLEBARS_RENDERING_SUMMARY: Summary = Summary.Builder()
.name("handlebars_rendering")
.help("Time it takes for handlebars to render the template")
.register()
val OPENHTMLTOPDF_RENDERING_SUMMARY: Summary = Summary.Builder()
.name("openhtmltopdf_rendering_summary")
.help("Time it takes to render a PDF")
.labelNames("application_name", "template_type")
.register()
val JSOUP_PARSE_SUMMARY: Summary = Summary.Builder()
.name("jsoup_parse")
.help("Time it takes jsoup to parse the template")
.register()
val HANDLEBARS_RENDERING_SUMMARY: Summary =
Summary.Builder()
.name("handlebars_rendering")
.help("Time it takes for handlebars to render the template")
.register()
val OPENHTMLTOPDF_RENDERING_SUMMARY: Summary =
Summary.Builder()
.name("openhtmltopdf_rendering_summary")
.help("Time it takes to render a PDF")
.labelNames("application_name", "template_type")
.register()
val JSOUP_PARSE_SUMMARY: Summary =
Summary.Builder()
.name("jsoup_parse")
.help("Time it takes jsoup to parse the template")
.register()
Loading

0 comments on commit 80ee366

Please sign in to comment.