Skip to content

Commit

Permalink
Merge pull request OSGP#48 from OSGP/feature/FDP-2318-line-length
Browse files Browse the repository at this point in the history
FDP-2318: ktfmt max width 120
  • Loading branch information
jasperkamerling authored Sep 30, 2024
2 parents 41f5bfb + e2f7fe9 commit 21d6479
Show file tree
Hide file tree
Showing 35 changed files with 155 additions and 398 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/gradle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up JDK 17
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,12 @@ class CoapMessageHandlingTest {

@Autowired private lateinit var embeddedKafkaBroker: EmbeddedKafkaBroker

@Value("\${kafka.producers.command-feedback.topic}")
private lateinit var commandFeedbackTopic: String
@Value("\${kafka.producers.command-feedback.topic}") private lateinit var commandFeedbackTopic: String

@BeforeEach
fun setup() {
pskRepository.save(
PreSharedKey(
DEVICE_ID, 0, Instant.MIN, PRE_SHARED_KEY_FIRST, SECRET, PreSharedKeyStatus.ACTIVE))
PreSharedKey(DEVICE_ID, 0, Instant.MIN, PRE_SHARED_KEY_FIRST, SECRET, PreSharedKeyStatus.ACTIVE))
}

@AfterEach
Expand All @@ -70,8 +68,7 @@ class CoapMessageHandlingTest {
@Test
fun shouldReturnADownLinkContainingPskCommands() {
pskRepository.save(
PreSharedKey(
DEVICE_ID, 1, Instant.now(), PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.READY))
PreSharedKey(DEVICE_ID, 1, Instant.now(), PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.READY))
commandRepository.save(
Command(
UUID.randomUUID(),
Expand Down Expand Up @@ -103,13 +100,7 @@ class CoapMessageHandlingTest {
fun shouldChangeActiveKey() {
// pending psk, waiting for URC in next message from device
pskRepository.save(
PreSharedKey(
DEVICE_ID,
1,
Instant.now(),
PRE_SHARED_KEY_NEW,
SECRET,
PreSharedKeyStatus.PENDING))
PreSharedKey(DEVICE_ID, 1, Instant.now(), PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.PENDING))
commandRepository.save(
Command(
UUID.randomUUID(),
Expand All @@ -130,8 +121,7 @@ class CoapMessageHandlingTest {
Command.CommandStatus.IN_PROGRESS))

val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_JSON }
val request =
HttpEntity<String>(getFileContentAsString("message_psk_set_success.json"), headers)
val request = HttpEntity<String>(getFileContentAsString("message_psk_set_success.json"), headers)

val result = restTemplate.postForEntity<String>("/sng/${DEVICE_ID}", request)

Expand All @@ -147,8 +137,7 @@ class CoapMessageHandlingTest {
fun shouldSetPendingKeyAsInvalidWhenFailureURCReceived() {
// pending psk, waiting for URC in next message from device
pskRepository.save(
PreSharedKey(
DEVICE_ID, 1, Instant.MIN, PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.PENDING))
PreSharedKey(DEVICE_ID, 1, Instant.MIN, PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.PENDING))
commandRepository.save(
Command(
UUID.randomUUID(),
Expand All @@ -169,8 +158,7 @@ class CoapMessageHandlingTest {
Command.CommandStatus.IN_PROGRESS))

val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_JSON }
val request =
HttpEntity<String>(getFileContentAsString("message_psk_set_failure.json"), headers)
val request = HttpEntity<String>(getFileContentAsString("message_psk_set_failure.json"), headers)

val result = restTemplate.postForEntity<String>("/sng/${DEVICE_ID}", request)

Expand Down Expand Up @@ -218,8 +206,7 @@ class CoapMessageHandlingTest {

@Test
fun shouldSendCommandSuccessFeedbackToMaki() {
val consumer =
IntegrationTestHelper.createKafkaConsumer(embeddedKafkaBroker, commandFeedbackTopic)
val consumer = IntegrationTestHelper.createKafkaConsumer(embeddedKafkaBroker, commandFeedbackTopic)

// command in progress should be in database
val id = UUID.randomUUID()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ class DeviceCredentialsRetrievalTest {

@BeforeEach
fun setup() {
pskRepository.save(
PreSharedKey(
IDENTITY, 0, Instant.MIN, PRE_SHARED_KEY, SECRET, PreSharedKeyStatus.ACTIVE))
pskRepository.save(PreSharedKey(IDENTITY, 0, Instant.MIN, PRE_SHARED_KEY, SECRET, PreSharedKeyStatus.ACTIVE))
}

@AfterEach
Expand All @@ -52,23 +50,18 @@ class DeviceCredentialsRetrievalTest {
fun shouldReturnTheLatestPskWhenThereAreMoreFoundForIdentity() {
// create second PSK for identity this one should be returned
pskRepository.save(
PreSharedKey(
IDENTITY, 1, Instant.MIN, "0000111122223333", SECRET, PreSharedKeyStatus.ACTIVE))
PreSharedKey(IDENTITY, 1, Instant.MIN, "0000111122223333", SECRET, PreSharedKeyStatus.ACTIVE))

val headers = HttpHeaders().apply { add("x-device-identity", IDENTITY) }
val result =
restTemplate.exchange(
"/psk", HttpMethod.GET, HttpEntity<Unit>(headers), String::class.java)
val result = restTemplate.exchange("/psk", HttpMethod.GET, HttpEntity<Unit>(headers), String::class.java)

assertThat(result.body).isEqualTo("0000111122223333")
}

@Test
fun shouldReturn404WhenNoKeyIsFound() {
val headers = HttpHeaders().apply { add("x-device-identity", "12345") }
val result =
restTemplate.exchange(
"/psk", HttpMethod.GET, HttpEntity<Unit>(headers), String::class.java)
val result = restTemplate.exchange("/psk", HttpMethod.GET, HttpEntity<Unit>(headers), String::class.java)

assertThat(result.statusCode).isEqualTo(HttpStatus.NOT_FOUND)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,20 @@ object IntegrationTestHelper {
DefaultKafkaConsumerFactory(
testProperties,
StringDeserializer(),
AvroDeserializer(
listOf(DeviceMessage.getClassSchema(), CommandFeedback.getClassSchema())))
AvroDeserializer(listOf(DeviceMessage.getClassSchema(), CommandFeedback.getClassSchema())))
val consumer = consumerFactory.createConsumer()
embeddedKafkaBroker.consumeFromAnEmbeddedTopic(consumer, topic)
return consumer
}

fun createKafkaProducer(
embeddedKafkaBroker: EmbeddedKafkaBroker
): Producer<String, SpecificRecordBase> {
val producerProps: Map<String, Any> =
HashMap(producerProps(embeddedKafkaBroker.brokersAsString))
val producerFactory =
DefaultKafkaProducerFactory(producerProps, StringSerializer(), AvroSerializer())
fun createKafkaProducer(embeddedKafkaBroker: EmbeddedKafkaBroker): Producer<String, SpecificRecordBase> {
val producerProps: Map<String, Any> = HashMap(producerProps(embeddedKafkaBroker.brokersAsString))
val producerFactory = DefaultKafkaProducerFactory(producerProps, StringSerializer(), AvroSerializer())
return producerFactory.createProducer()
}

/**
* Copy of the com.alliander.gxf.sngmessageprocessor.kafka test util producer props with
* different serializers
* Copy of the com.alliander.gxf.sngmessageprocessor.kafka test util producer props with different serializers
*
* @see KafkaTestUtils.producerProps
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ import org.springframework.kafka.test.utils.KafkaTestUtils
import org.springframework.test.annotation.DirtiesContext

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EmbeddedKafka(
topics = ["\${kafka.consumers.command.topic}", "\${kafka.producers.command-feedback.topic}"])
@EmbeddedKafka(topics = ["\${kafka.consumers.command.topic}", "\${kafka.producers.command-feedback.topic}"])
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class MakiCommandHandlingTest {
companion object {
Expand All @@ -38,8 +37,7 @@ class MakiCommandHandlingTest {

@Value("\${kafka.consumers.command.topic}") private lateinit var commandTopic: String

@Value("\${kafka.producers.command-feedback.topic}")
private lateinit var commandFeedbackTopic: String
@Value("\${kafka.producers.command-feedback.topic}") private lateinit var commandFeedbackTopic: String

@AfterEach
fun cleanup() {
Expand All @@ -59,8 +57,7 @@ class MakiCommandHandlingTest {
.setCommand("reboot")
.setValue("")
.build()
val consumer =
IntegrationTestHelper.createKafkaConsumer(embeddedKafkaBroker, commandFeedbackTopic)
val consumer = IntegrationTestHelper.createKafkaConsumer(embeddedKafkaBroker, commandFeedbackTopic)

producer.send(ProducerRecord(commandTopic, commandFromMaki))

Expand All @@ -85,8 +82,7 @@ class MakiCommandHandlingTest {
Awaitility.await().atMost(Duration.ofSeconds(3)).untilAsserted {
val savedCommand =
commandRepository.findFirstByDeviceIdAndStatusOrderByTimestampIssuedAsc(
DEVICE_ID,
org.gxf.crestdeviceservice.command.entity.Command.CommandStatus.PENDING)
DEVICE_ID, org.gxf.crestdeviceservice.command.entity.Command.CommandStatus.PENDING)

assertThat(savedCommand).isNotNull
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ class MessageHandlingTest {
val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_JSON }
val request = HttpEntity<String>(getFileContentAsString("message.json"), headers)

val consumer =
createKafkaConsumer(embeddedKafkaBroker, kafkaProducerProperties.deviceMessage.topic)
val consumer = createKafkaConsumer(embeddedKafkaBroker, kafkaProducerProperties.deviceMessage.topic)
val response = testRestTemplate.postForEntity<String>("/sng/1", request)

assertThat(response.body).isEqualTo("0")
Expand All @@ -54,8 +53,7 @@ class MessageHandlingTest {

val expectedJsonNode = ObjectMapper().readTree(getFileContentAsString("message.json"))
val deviceMessage =
records.records(kafkaProducerProperties.deviceMessage.topic).first().value()
as DeviceMessage
records.records(kafkaProducerProperties.deviceMessage.topic).first().value() as DeviceMessage
val payloadJsonNode = ObjectMapper().readTree(deviceMessage.payload)

assertThat(payloadJsonNode).isEqualTo(expectedJsonNode)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,14 @@ class CommandConsumer(
) {
private val logger = KotlinLogging.logger {}

@KafkaListener(
id = "command", idIsGroup = false, topics = ["\${kafka.consumers.command.topic}"])
@KafkaListener(id = "command", idIsGroup = false, topics = ["\${kafka.consumers.command.topic}"])
fun handleIncomingCommand(externalCommand: ExternalCommand) {
logger.info {
"Received command ${externalCommand.command} for device: ${externalCommand.deviceId}, with correlation id: ${externalCommand.correlationId}"
}
try {
val pendingCommand =
CommandMapper.externalCommandToCommandEntity(
externalCommand, Command.CommandStatus.PENDING)
CommandMapper.externalCommandToCommandEntity(externalCommand, Command.CommandStatus.PENDING)

commandService.validate(pendingCommand)
commandFeedbackService.sendReceivedFeedback(pendingCommand)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,7 @@ data class Command(
val commandValue: String?,
@Enumerated(EnumType.STRING) var status: CommandStatus,
) {
enum class CommandType(
val downlink: String,
val urcsSuccess: List<String>,
val urcsError: List<String>
) {
enum class CommandType(val downlink: String, val urcsSuccess: List<String>, val urcsError: List<String>) {
PSK("PSK", listOf("PSK:TMP"), listOf("PSK:DLER", "PSK:HSER")),
PSK_SET("PSK:SET", listOf("PSK:SET"), listOf("PSK:DLER", "PSK:HSER", "PSK:EQER")),
REBOOT("CMD:REBOOT", listOf("INIT", "WDR"), listOf())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import org.gxf.crestdeviceservice.command.entity.Command
import org.gxf.crestdeviceservice.command.exception.CommandValidationException

object CommandMapper {
fun externalCommandToCommandEntity(
externalCommand: ExternalCommand,
status: Command.CommandStatus
): Command {
fun externalCommandToCommandEntity(externalCommand: ExternalCommand, status: Command.CommandStatus): Command {
try {
return Command(
id = UUID.randomUUID(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,9 @@ import org.springframework.stereotype.Repository

@Repository
interface CommandRepository : CrudRepository<Command, UUID> {
fun findFirstByDeviceIdAndTypeOrderByTimestampIssuedDesc(
deviceId: String,
type: Command.CommandType
): Command?
fun findFirstByDeviceIdAndTypeOrderByTimestampIssuedDesc(deviceId: String, type: Command.CommandType): Command?

fun findFirstByDeviceIdAndStatusOrderByTimestampIssuedAsc(
deviceId: String,
status: Command.CommandStatus
): Command?
fun findFirstByDeviceIdAndStatusOrderByTimestampIssuedAsc(deviceId: String, status: Command.CommandStatus): Command?

fun findAllByDeviceIdAndStatusOrderByTimestampIssuedAsc(
deviceId: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,18 @@ class CommandFeedbackService(
private val topic = kafkaProducerProperties.commandFeedback.topic

fun sendReceivedFeedback(command: Command) {
val commandFeedback =
commandEntityToCommandFeedback(command, CommandStatus.Received, "Command received")
val commandFeedback = commandEntityToCommandFeedback(command, CommandStatus.Received, "Command received")
sendFeedback(commandFeedback)
}

fun sendCancellationFeedback(command: Command, message: String) {
val commandFeedback =
commandEntityToCommandFeedback(command, CommandStatus.Cancelled, message)
val commandFeedback = commandEntityToCommandFeedback(command, CommandStatus.Cancelled, message)
sendFeedback(commandFeedback)
}

fun sendRejectionFeedback(reason: String, command: ExternalCommand) {
val commandFeedback =
CommandFeedbackMapper.externalCommandToCommandFeedback(
command, CommandStatus.Rejected, reason)
CommandFeedbackMapper.externalCommandToCommandFeedback(command, CommandStatus.Rejected, reason)
sendFeedback(commandFeedback)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,34 +36,28 @@ class CommandService(
}

/**
* Check if the device already has a newer command pending of the same type that was issued at a
* later date. This check prevents issues if commands arrive out of order or if we reset the
* kafka consumer group.
* Check if the device already has a newer command pending of the same type that was issued at a later date. This
* check prevents issues if commands arrive out of order or if we reset the kafka consumer group.
*/
private fun deviceHasNewerSameCommand(
deviceId: String,
commandType: Command.CommandType,
timestampNewCommand: Instant
): Boolean {
val latestCommandInDatabase =
getLatestCommandInDatabase(deviceId, commandType) ?: return false
val latestCommandInDatabase = getLatestCommandInDatabase(deviceId, commandType) ?: return false

// If the device already has a newer command in the database
return latestCommandInDatabase.timestampIssued.isAfter(timestampNewCommand)
}

private fun deviceHasSameCommandAlreadyInProgress(
deviceId: String,
commandType: Command.CommandType
) =
private fun deviceHasSameCommandAlreadyInProgress(deviceId: String, commandType: Command.CommandType) =
commandRepository
.findAllByDeviceIdAndTypeAndStatusOrderByTimestampIssuedAsc(
deviceId, commandType, Command.CommandStatus.IN_PROGRESS)
.isNotEmpty()

private fun getLatestCommandInDatabase(deviceId: String, commandType: Command.CommandType) =
commandRepository.findFirstByDeviceIdAndTypeOrderByTimestampIssuedDesc(
deviceId, commandType)
commandRepository.findFirstByDeviceIdAndTypeOrderByTimestampIssuedDesc(deviceId, commandType)

fun cancelOlderCommandIfNecessary(pendingCommand: Command) {
getSameCommandForDeviceAlreadyPending(pendingCommand)?.let {
Expand All @@ -75,8 +69,7 @@ class CommandService(
}

private fun getSameCommandForDeviceAlreadyPending(command: Command): Command? {
val latestCommandInDatabase =
getLatestCommandInDatabase(command.deviceId, command.type) ?: return null
val latestCommandInDatabase = getLatestCommandInDatabase(command.deviceId, command.type) ?: return null

if (latestCommandInDatabase.status == Command.CommandStatus.PENDING) {
return latestCommandInDatabase
Expand All @@ -86,8 +79,7 @@ class CommandService(
}

private fun cancelCommand(commandToBeCancelled: Command, newCorrelationId: UUID) {
val message =
"Command cancelled by newer same command with correlation id: $newCorrelationId"
val message = "Command cancelled by newer same command with correlation id: $newCorrelationId"
commandFeedbackService.sendCancellationFeedback(commandToBeCancelled, message)
saveCommandWithNewStatus(commandToBeCancelled, Command.CommandStatus.CANCELLED)
}
Expand All @@ -100,8 +92,7 @@ class CommandService(
deviceId, Command.CommandStatus.IN_PROGRESS)

fun getAllPendingCommandsForDevice(deviceId: String) =
commandRepository.findAllByDeviceIdAndStatusOrderByTimestampIssuedAsc(
deviceId, Command.CommandStatus.PENDING)
commandRepository.findAllByDeviceIdAndStatusOrderByTimestampIssuedAsc(deviceId, Command.CommandStatus.PENDING)

fun getAllCommandsInProgressForDevice(deviceId: String) =
commandRepository.findAllByDeviceIdAndStatusOrderByTimestampIssuedAsc(
Expand All @@ -111,8 +102,7 @@ class CommandService(
commandRepository.save(command)
}

fun saveCommandEntities(commands: List<Command>): MutableIterable<Command> =
commandRepository.saveAll(commands)
fun saveCommandEntities(commands: List<Command>): MutableIterable<Command> = commandRepository.saveAll(commands)

fun saveCommandWithNewStatus(command: Command, status: Command.CommandStatus): Command {
command.status = status
Expand Down
Loading

0 comments on commit 21d6479

Please sign in to comment.