Skip to content

Commit

Permalink
Merge pull request #28 from OSGP/feature/FDP-1673-spotless
Browse files Browse the repository at this point in the history
FDP-1673: Implement Spotless
  • Loading branch information
loesimmens authored May 29, 2024
2 parents aa86403 + 6713dfe commit f7f10a3
Show file tree
Hide file tree
Showing 37 changed files with 301 additions and 413 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice

import java.time.Instant
import org.assertj.core.api.Assertions.assertThat
import org.gxf.crestdeviceservice.IntegrationTestHelper.getFileContentAsString
import org.gxf.crestdeviceservice.psk.entity.PreSharedKey
Expand All @@ -21,11 +21,10 @@ import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.kafka.test.context.EmbeddedKafka
import org.springframework.test.annotation.DirtiesContext
import java.time.Instant

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EmbeddedKafka(
topics = ["\${crest-device-service.kafka.message-producer.topic-name}"],
topics = ["\${crest-device-service.kafka.message-producer.topic-name}"],
)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class CoapMessageHandlingTest {
Expand All @@ -37,24 +36,15 @@ class CoapMessageHandlingTest {
private const val SECRET = "123456789"
}

@Autowired
private lateinit var restTemplate: TestRestTemplate
@Autowired private lateinit var restTemplate: TestRestTemplate

@Autowired
private lateinit var pskRepository: PskRepository
@Autowired private lateinit var pskRepository: PskRepository

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

@AfterEach
Expand All @@ -66,14 +56,7 @@ class CoapMessageHandlingTest {
fun shouldReturnADownLinkContainingAPskSetCommandWhenTheKeyHasNotChangedYet() {
pskRepository.save(
PreSharedKey(
IDENTITY,
1,
Instant.now(),
PRE_SHARED_KEY_NEW,
SECRET,
PreSharedKeyStatus.READY
)
)
IDENTITY, 1, Instant.now(), PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.READY))

val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_JSON }
val request = HttpEntity<String>(getFileContentAsString("message.json"), headers)
Expand All @@ -88,14 +71,7 @@ class CoapMessageHandlingTest {
// pending psk, waiting for URC in next message from device
pskRepository.save(
PreSharedKey(
IDENTITY,
1,
Instant.now(),
PRE_SHARED_KEY_NEW,
SECRET,
PreSharedKeyStatus.PENDING
)
)
IDENTITY, 1, Instant.now(), PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.PENDING))

val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_JSON }
val request =
Expand All @@ -116,14 +92,7 @@ class CoapMessageHandlingTest {
// pending psk, waiting for URC in next message from device
pskRepository.save(
PreSharedKey(
IDENTITY,
1,
Instant.MIN,
PRE_SHARED_KEY_NEW,
SECRET,
PreSharedKeyStatus.PENDING
)
)
IDENTITY, 1, Instant.MIN, PRE_SHARED_KEY_NEW, SECRET, PreSharedKeyStatus.PENDING))

val headers = HttpHeaders().apply { contentType = MediaType.APPLICATION_JSON }
val request =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice

import java.time.Instant
import org.assertj.core.api.Assertions.assertThat
import org.gxf.crestdeviceservice.psk.entity.PreSharedKey
import org.gxf.crestdeviceservice.psk.entity.PreSharedKeyStatus
Expand All @@ -19,12 +19,10 @@ import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.kafka.test.context.EmbeddedKafka
import java.time.Instant


@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EmbeddedKafka(
topics = ["\${crest-device-service.kafka.message-producer.topic-name}"],
topics = ["\${crest-device-service.kafka.message-producer.topic-name}"],
)
class DeviceCredentialsRetrievalTest {

Expand All @@ -34,24 +32,15 @@ class DeviceCredentialsRetrievalTest {
private const val SECRET = "123456789"
}

@Autowired
private lateinit var restTemplate: TestRestTemplate
@Autowired private lateinit var restTemplate: TestRestTemplate

@Autowired
private lateinit var pskRepository: PskRepository
@Autowired private lateinit var pskRepository: PskRepository

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

@AfterEach
Expand All @@ -64,27 +53,22 @@ class DeviceCredentialsRetrievalTest {
// create second PSK for identity this one should be returned
pskRepository.save(
PreSharedKey(
IDENTITY,
1,
Instant.MIN,
"0000111122223333",
SECRET,
PreSharedKeyStatus.ACTIVE
)
)
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
@@ -1,7 +1,6 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice

import com.gxf.utilities.kafka.avro.AvroDeserializer
Expand All @@ -15,15 +14,14 @@ import org.springframework.util.ResourceUtils

object IntegrationTestHelper {

fun createKafkaConsumer(embeddedKafkaBroker: EmbeddedKafkaBroker, topic: String): Consumer<String, DeviceMessage> {
val testProperties =
KafkaTestUtils.consumerProps("testGroup", "true", embeddedKafkaBroker)
fun createKafkaConsumer(
embeddedKafkaBroker: EmbeddedKafkaBroker,
topic: String
): Consumer<String, DeviceMessage> {
val testProperties = KafkaTestUtils.consumerProps("testGroup", "true", embeddedKafkaBroker)
val consumerFactory =
DefaultKafkaConsumerFactory(
testProperties,
StringDeserializer(),
AvroDeserializer(DeviceMessage.getDecoder())
)
DefaultKafkaConsumerFactory(
testProperties, StringDeserializer(), AvroDeserializer(DeviceMessage.getDecoder()))
val consumer = consumerFactory.createConsumer()
embeddedKafkaBroker.consumeFromAnEmbeddedTopic(consumer, topic)
return consumer
Expand All @@ -32,5 +30,4 @@ object IntegrationTestHelper {
fun getFileContentAsString(path: String): String {
return ResourceUtils.getFile("classpath:$path").readText()
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice

import java.time.Duration
import org.assertj.core.api.Assertions.assertThat
import org.gxf.crestdeviceservice.IntegrationTestHelper.createKafkaConsumer
import org.gxf.crestdeviceservice.IntegrationTestHelper.getFileContentAsString
Expand All @@ -21,24 +21,20 @@ import org.springframework.kafka.test.EmbeddedKafkaBroker
import org.springframework.kafka.test.context.EmbeddedKafka
import org.springframework.test.annotation.DirtiesContext
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper
import java.time.Duration

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EmbeddedKafka(
topics = ["\${crest-device-service.kafka.message-producer.topic-name}"],
topics = ["\${crest-device-service.kafka.message-producer.topic-name}"],
)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@EnableConfigurationProperties(KafkaProducerProperties::class)
class MessageHandlingTest {

@Autowired
private lateinit var kafkaProducerProperties: KafkaProducerProperties
@Autowired private lateinit var kafkaProducerProperties: KafkaProducerProperties

@Autowired
private lateinit var embeddedKafkaBroker: EmbeddedKafkaBroker
@Autowired private lateinit var embeddedKafkaBroker: EmbeddedKafkaBroker

@Autowired
private lateinit var testRestTemplate: TestRestTemplate
@Autowired private lateinit var testRestTemplate: TestRestTemplate

@Test
fun shouldProduceMessageForValidRequest() {
Expand All @@ -55,7 +51,10 @@ class MessageHandlingTest {
assertThat(records.records(kafkaProducerProperties.topicName)).hasSize(1)

val expectedJsonNode = ObjectMapper().readTree(getFileContentAsString("message.json"))
val payloadJsonNode = ObjectMapper().readTree(records.records(kafkaProducerProperties.topicName).first().value().payload)
val payloadJsonNode =
ObjectMapper()
.readTree(
records.records(kafkaProducerProperties.topicName).first().value().payload)

assertThat(payloadJsonNode).isEqualTo(expectedJsonNode)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication

@ConfigurationPropertiesScan
@SpringBootApplication
class CrestDeviceServiceApplication
@ConfigurationPropertiesScan @SpringBootApplication class CrestDeviceServiceApplication

fun main(args: Array<String>) {
runApplication<CrestDeviceServiceApplication>(*args)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice.coap

import com.fasterxml.jackson.databind.JsonNode
Expand All @@ -12,11 +11,9 @@ import org.gxf.crestdeviceservice.psk.exception.NoExistingPskException
import org.springframework.stereotype.Service

@Service
class DownlinkService(
private val pskService: PskService
) {
class DownlinkService(private val pskService: PskService) {

companion object{
companion object {
private const val RESPONSE_SUCCESS = "0"
}

Expand All @@ -28,12 +25,16 @@ class DownlinkService(
logger.debug { "Check if device $identity needs key change" }
if (pskService.needsKeyChange(identity)) {
logger.info { "Device $identity needs key change" }
val oldKey = pskService.getCurrentActiveKey(identity)
?: throw NoExistingPskException("No current key found to calculate hash")
val oldKey =
pskService.getCurrentActiveKey(identity)
?: throw NoExistingPskException("No current key found to calculate hash")
val newKey = pskService.setReadyKeyForIdentityAsPending(identity)

// After setting a new psk, the device will send a new message if the psk set was successful
logger.debug { "Create PSK set command for key for device ${newKey.identity} with revision ${newKey.revision} and status ${newKey.status}" }
// After setting a new psk, the device will send a new message if the psk set was
// successful
logger.debug {
"Create PSK set command for key for device ${newKey.identity} with revision ${newKey.revision} and status ${newKey.status}"
}
return PskCommandCreator.createPskSetCommand(newKey, oldKey)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// SPDX-FileCopyrightText: Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0

package org.gxf.crestdeviceservice.coap

import com.fasterxml.jackson.databind.JsonNode
Expand All @@ -13,21 +12,24 @@ import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/sng")
class MessageController(
private val messageService: MessageService,
private val downlinkService: DownlinkService,
private val urcService: UrcService
private val messageService: MessageService,
private val downlinkService: DownlinkService,
private val urcService: UrcService
) {

private val logger = KotlinLogging.logger {}

private val locks: MutableMap<String, Any> = mutableMapOf()

/**
* This endpoint handles incoming crest device messages.
* Responses are generated synchronously to avoid sending the same downlink twice.
* This endpoint handles incoming crest device messages. Responses are generated synchronously
* to avoid sending the same downlink twice.
*/
@PostMapping("/{identity}")
fun post(@NonNull @PathVariable identity: String, @NonNull @RequestBody body: JsonNode): ResponseEntity<String> {
fun post(
@NonNull @PathVariable identity: String,
@NonNull @RequestBody body: JsonNode
): ResponseEntity<String> {

logger.debug { "Processing message $body" }
messageService.handleMessage(body)
Expand All @@ -39,13 +41,15 @@ class MessageController(
val downlink = downlinkService.getDownlinkForIdentity(identity, body)
return ResponseEntity.ok(downlink)
} catch (e: Exception) {
logger.error(e) { "Exception occurred while creating downlink for device $identity" }
logger.error(e) {
"Exception occurred while creating downlink for device $identity"
}
return ResponseEntity.internalServerError().build()
}
}
}

@Synchronized
private fun lock(substationIdentification: String) = locks.computeIfAbsent(substationIdentification) { _ -> Any() }

private fun lock(substationIdentification: String) =
locks.computeIfAbsent(substationIdentification) { _ -> Any() }
}
Loading

0 comments on commit f7f10a3

Please sign in to comment.