Skip to content

Commit

Permalink
Merge pull request #22 from OSGP/feature/FDP-2318-spotless
Browse files Browse the repository at this point in the history
FDP-2318: Spotless
  • Loading branch information
smvdheijden authored Oct 3, 2024
2 parents 661fe32 + fcec6d5 commit 1146ce0
Show file tree
Hide file tree
Showing 34 changed files with 317 additions and 309 deletions.
35 changes: 33 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import com.diffplug.gradle.spotless.SpotlessExtension
import io.spring.gradle.dependencymanagement.internal.dsl.StandardDependencyManagementExtension
import org.jetbrains.kotlin.com.github.gundy.semver4j.SemVer
import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import java.net.URI

plugins {
id("io.spring.dependency-management") version "1.1.5" apply false
kotlin("jvm") version "2.0.0" apply false
kotlin("plugin.spring") version "2.0.0" apply false
id("org.sonarqube") version "5.0.0.4638"
id("com.diffplug.spotless") version("6.25.0")
}

sonar {
Expand All @@ -31,6 +34,7 @@ subprojects {
apply(plugin = "org.gradle.maven-publish")
apply(plugin = "jacoco")
apply(plugin = "jacoco-report-aggregation")
apply(plugin = "com.diffplug.spotless")

group = rootProject.group
version = rootProject.version
Expand Down Expand Up @@ -59,8 +63,18 @@ subprojects {
}
}

tasks.withType<Test> {
useJUnitPlatform()

extensions.configure<SpotlessExtension> {
kotlin {
// by default the target is every '.kt' and '.kts' file in the java source sets
ktfmt().dropboxStyle().configure {
it.setMaxWidth(120)
}
licenseHeaderFile(
"${project.rootDir}/license-template.kt",
"package")
.updateYearWithLatest(false)
}
}

extensions.configure<PublishingExtension> {
Expand All @@ -81,4 +95,21 @@ subprojects {
}
}
}

tasks.withType<Test> {
useJUnitPlatform()
}

tasks.register<Copy>("updateGitHooks") {
description = "Copies the pre-commit Git Hook to the .git/hooks folder."
group = "verification"
from("${project.rootDir}/scripts/pre-commit")
into("${project.rootDir}/.git/hooks")
}

tasks.withType<KotlinCompile> {
dependsOn(
tasks.named("updateGitHooks")
)
}
}
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
9 changes: 9 additions & 0 deletions kafka-avro/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import com.github.davidmc24.gradle.plugin.avro.GenerateAvroJavaTask
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("com.github.davidmc24.gradle.plugin.avro") version "1.9.1"
}
Expand All @@ -15,3 +18,9 @@ dependencies {

testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.withType<KotlinCompile> {
dependsOn(
tasks.withType<GenerateAvroJavaTask>()
)
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/*
SPDX-FileCopyrightText: Contributors to the GXF project
SPDX-License-Identifier: Apache-2.0
*/
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.avro

import org.apache.avro.Schema
Expand All @@ -21,14 +19,11 @@ class AvroDeserializer(deserializerSchemas: List<Schema>) : Deserializer<Specifi
private val decoder = BinaryMessageDecoder<SpecificRecordBase>(SpecificData(), null)

init {
// Add all schema's to the decoder
deserializerSchemas
.forEach { decoder.addSchema(it) }
// Add all schemas to the decoder
deserializerSchemas.forEach { decoder.addSchema(it) }
}

/**
* Deserializes a Byte Array to an Avro SpecificRecordBase
*/
/** Deserializes a Byte Array to an Avro SpecificRecordBase */
override fun deserialize(topic: String, payload: ByteArray): SpecificRecordBase {
try {
logger.trace("Deserializing for {}", topic)
Expand All @@ -38,4 +33,3 @@ class AvroDeserializer(deserializerSchemas: List<Schema>) : Deserializer<Specifi
}
}
}

Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.avro

import java.io.IOException
import java.io.OutputStream
import kotlin.reflect.KClass
import org.apache.avro.message.BinaryMessageEncoder
import org.apache.avro.specific.SpecificData
import org.apache.avro.specific.SpecificRecordBase
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.OutputStream
import kotlin.reflect.KClass

object AvroEncoder {
val encoders: HashMap<KClass<out SpecificRecordBase>, BinaryMessageEncoder<SpecificRecordBase>> = HashMap()
Expand All @@ -31,7 +34,7 @@ object AvroEncoder {
private fun getEncoder(message: SpecificRecordBase): BinaryMessageEncoder<SpecificRecordBase> {
val existingEncoder = encoders[message::class]

if(existingEncoder != null) {
if (existingEncoder != null) {
return existingEncoder
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
/*
SPDX-FileCopyrightText: Contributors to the GXF project
SPDX-License-Identifier: Apache-2.0
*/
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.avro

import java.io.ByteArrayOutputStream
import org.apache.avro.specific.SpecificRecordBase
import org.apache.kafka.common.errors.SerializationException
import org.apache.kafka.common.serialization.Serializer
import org.slf4j.LoggerFactory
import java.io.ByteArrayOutputStream

class AvroSerializer : Serializer<SpecificRecordBase> {
companion object {
private val logger = LoggerFactory.getLogger(AvroSerializer::class.java)
}

/**
* Serializes a Byte Array to an Avro specific record
*/
/** Serializes a Byte Array to an Avro specific record */
override fun serialize(topic: String?, data: SpecificRecordBase): ByteArray {
try {
logger.trace("Serializing for {}", topic)
Expand All @@ -30,4 +26,3 @@ class AvroSerializer : Serializer<SpecificRecordBase> {
}
}
}

Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.avro

import com.alliander.gxf.utilities.kafka.avro.AvroSchema1
Expand All @@ -17,14 +20,11 @@ class AvroDeserializerTest {
val message3 = AvroSchema3("message in a bottle")
val deserializer = AvroDeserializer(listOf(AvroSchema1.getClassSchema(), AvroSchema2.getClassSchema()))

assertThat(deserializer.deserialize("topic1", message1.toByteBuffer().array()))
.isEqualTo(message1)
assertThat(deserializer.deserialize("topic2", message2.toByteBuffer().array()))
.isEqualTo(message2)
assertThat(deserializer.deserialize("topic1", message1.toByteBuffer().array())).isEqualTo(message1)
assertThat(deserializer.deserialize("topic2", message2.toByteBuffer().array())).isEqualTo(message2)

assertThatThrownBy({deserializer.deserialize("topic3", message3.toByteBuffer().array())})
assertThatThrownBy({ deserializer.deserialize("topic3", message3.toByteBuffer().array()) })
.isInstanceOf(SerializationException::class.java)
.hasMessageContaining("Error deserializing Avro message for topic: topic3");

.hasMessageContaining("Error deserializing Avro message for topic: topic3")
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.avro

import com.alliander.gxf.utilities.kafka.avro.AvroSchema1
import com.alliander.gxf.utilities.kafka.avro.AvroSchema2
import org.assertj.core.api.AbstractIntegerAssert
import java.io.ByteArrayOutputStream
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.io.ByteArrayOutputStream

class AvroEncoderTest {
@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.avro

import com.alliander.gxf.utilities.kafka.avro.AvroSchema1
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/*
SPDX-FileCopyrightText: Contributors to the GXF project
SPDX-License-Identifier: Apache-2.0
*/
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.oauth.handler

class KafkaOAuthException(s: String, e: Exception) : Throwable(s, e)
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
/*
SPDX-FileCopyrightText: Contributors to the GXF project
SPDX-License-Identifier: Apache-2.0
*/
// SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package com.gxf.utilities.kafka.oauth.handler

import com.microsoft.aad.msal4j.ClientCredentialFactory
import com.microsoft.aad.msal4j.ClientCredentialParameters
import com.microsoft.aad.msal4j.ConfidentialClientApplication
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import javax.security.auth.callback.Callback
import javax.security.auth.callback.UnsupportedCallbackException
import javax.security.auth.login.AppConfigurationEntry
import org.apache.kafka.common.config.ConfigException
import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler
import org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule
Expand All @@ -16,13 +21,6 @@ import org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback
import org.apache.kafka.common.security.oauthbearer.OAuthBearerValidatorCallback
import org.apache.kafka.common.security.oauthbearer.internals.secured.BasicOAuthBearerToken
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import javax.security.auth.callback.Callback
import javax.security.auth.callback.UnsupportedCallbackException
import javax.security.auth.login.AppConfigurationEntry

class OAuthAuthenticateCallbackHandler : AuthenticateCallbackHandler {
internal lateinit var tokenFilePath: String
Expand All @@ -44,13 +42,10 @@ class OAuthAuthenticateCallbackHandler : AuthenticateCallbackHandler {
saslMechanism: String,
jaasConfigEntries: List<AppConfigurationEntry>
) {
getOptions(saslMechanism, jaasConfigEntries)
.let { setFields(it) }
getOptions(saslMechanism, jaasConfigEntries).let { setFields(it) }
}

private fun getOptions(
saslMechanism: String, jaasConfigEntries: List<AppConfigurationEntry>
): Map<String, Any?> {
private fun getOptions(saslMechanism: String, jaasConfigEntries: List<AppConfigurationEntry>): Map<String, Any?> {
require(saslMechanism == OAuthBearerLoginModule.OAUTHBEARER_MECHANISM) {
"Unexpected SASL mechanism: ${saslMechanism}"
}
Expand All @@ -63,10 +58,7 @@ class OAuthAuthenticateCallbackHandler : AuthenticateCallbackHandler {
private fun setFields(options: Map<String, Any?>) {
clientId = options.getProperty(CLIENT_ID_CONFIG)
tokenEndpoint = options.getProperty(TOKEN_ENDPOINT_CONFIG)
scopes = options.getProperty(SCOPE_CONFIG)
.split(",".toRegex())
.dropLastWhile { it.isEmpty() }
.toSet()
scopes = options.getProperty(SCOPE_CONFIG).split(",".toRegex()).dropLastWhile { it.isEmpty() }.toSet()
tokenFilePath = options.getProperty(TOKEN_FILE_CONFIG)
}

Expand All @@ -89,8 +81,7 @@ class OAuthAuthenticateCallbackHandler : AuthenticateCallbackHandler {
is OAuthBearerTokenCallback -> callback.token(getToken())
is OAuthBearerValidatorCallback ->
throw UnsupportedCallbackException(callback, "Validate callback not yet implemented")
else ->
throw UnsupportedCallbackException(callback, "Unknown callback type ${callback.javaClass.name}")
else -> throw UnsupportedCallbackException(callback, "Unknown callback type ${callback.javaClass.name}")
}
}
}
Expand All @@ -102,18 +93,15 @@ class OAuthAuthenticateCallbackHandler : AuthenticateCallbackHandler {
val token = readTokenFile(tokenFilePath)
val credential = ClientCredentialFactory.createFromClientAssertion(token)
val aadParameters = ClientCredentialParameters.builder(scopes).build()
val aadClient = ConfidentialClientApplication.builder(clientId, credential)
.authority(tokenEndpoint)
.build()
val aadClient = ConfidentialClientApplication.builder(clientId, credential).authority(tokenEndpoint).build()
val authResult = aadClient.acquireToken(aadParameters).get()

return BasicOAuthBearerToken(
authResult.accessToken(),
aadParameters.scopes(),
authResult.expiresOnDate().toInstant().toEpochMilli(),
aadClient.clientId(),
System.currentTimeMillis()
)
System.currentTimeMillis())
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
throw KafkaOAuthException("Retrieving JWT token was interrupted", e)
Expand Down
Loading

0 comments on commit 1146ce0

Please sign in to comment.