cpe
03/30/2020, 8:38 AMPhilipp Mayer
03/31/2020, 11:33 AM@GetMapping("/{id}")
fun getEmployeeById(@PathVariable id: Long): ResponseEntity<EntityModel<Employee>> {
runCatching { getUseCase.getEmployee(id) }
.onFailure { throw ResourceNotFoundException("User with id $id not found.") }
.onSuccess {
val entityModel = EntityModel(it, linkTo<EmployeeController> { getEmployeeById(id) }.withSelfRel())
return ResponseEntity(entityModel, HttpStatus.OK)
}
}
getUseCase.getEmployee(id)
can throw an exception that I want to map to an ResourceNotFoundException. I tried to do it in idiomatic Kotlin, but I got stuck at that point. I guess there is another way of achieving this that didn't come up to my mind yet.
When there's no exception, the entityModel should be created and returned in an ResponseEntity.JP
03/31/2020, 12:25 PMJP
04/02/2020, 12:44 PM@RestController
class RestWebController {
val custStore = mutableListOf<Customer>()
@GetMapping("/getallcustomer")
fun getAllCustomer(): Response {
println("GET: getallcustomer $custStore")
return Response("Done", custStore)
}
@PostMapping("/postcustomer")
fun postCustomer(@RequestBody customer: Customer): Response {
println("POST: postcustomer $customer")
custStore.add(customer)
return Response("Done", customer)
}
}
data class Response(
val status: String = "",
val data : Any
)
data class Customer(
val firstname: String = "",
val lastname: String = ""
)
Stian N
04/06/2020, 8:41 AMdr.dreigh
04/06/2020, 12:28 PM@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@Component
class NormalComponent() {
fun value() = "Hi"
}
Test:
@TestConfiguration
class TestConfig {
@Bean
fun normalComponentMock(): NormalComponent {
val mock = mock(NormalComponent::class.java)
`when`(mock.value()).thenReturn("I AM A MOCK!")
return mock
}
}
@SpringBootTest
@Import(TestConfig::class)
class DemoApplicationTests(
@Autowired val norm: NormalComponent
) {
@Test
fun normInjectedIntoTest() {
assertEquals("I AM A MOCK!", norm.value())
}
}
The error:
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [com.example.demo.NormalComponent norm] in constructor [public com.example.demo.DemoApplicationTests(com.example.demo.NormalComponent)]: No qualifying bean of type 'com.example.demo.NormalComponent' available: expected single matching bean but found 2: normalComponent,normalComponentMock
I know I could use @MockBean
- this is just a simple example where the bean I want to inject to the instance.
Bit confused why the mock conflict is happening when I have using the @TestConfiguration
and the @Import
annotation - thanks in advance 🙏Stian N
04/08/2020, 10:30 AMNo default constructor for entity
. Is there anything else I need to to concider?Philipp Mayer
04/08/2020, 2:45 PM<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
Cannot resolve directory '$'{'project.basedir}'
I guess it's something with my configuration but I just can't point the finger at it. Any ideas? Thanks ahead!nfrankel
04/08/2020, 5:32 PMhooliooo
04/14/2020, 10:46 AMDariusz Kuc
04/14/2020, 7:43 PM@Configuration @Import([A, B])
class TopLevelConfig {
// uses beans from A/B
// defines beans used commonly by A and B
}
or
@Configuration
class CommonConfig { // common beans }
@Configuration @Import(CommonConfig)
class A
@Configuration @Import(CommonConfig)
class B
@Configuration @Import([A, B])
class TopLevelConfig { // use beans from A/B }
Dennis Schröder
04/20/2020, 3:40 PMkotlinx.coroutins.reactor
package to bridge both worlds (reactive -> Coroutines).
Now we want to build an custom ReactiveHealthIndicator
. Therefore we inherit this interface ReactiveHealthIndicator
from package org.springframework.boot.actuate.health
which expects to implement an method with the signature of fun health(): Mono<Health>
.
So far, so good. The problem is that we need to call an suspending function Inside the health()
method. Here is a little snippet, which should explain the problem a bit further:
@Component
class ClientHealthIndicator(private val client: SomeClient) : ReactiveHealthIndicator {
private val logger = KotlinLogging.logger { }
override fun health(): Mono<Health> =
try {
client.getPage("home") // THIS IS THE SUSPEND FUNCTION
Health.up().build().let { Mono.just(it) }
} catch (e: Exception) {
logger.error(e) { "ContentClient health check failed" }
Health.down(e).build().let { Mono.just(it) }
}
}
We tried to use the MonoCoroutine Builder function from kotlinx.coroutins.reactor
to build an scope which returns a Mono.
@Component
class ContentClientHealthIndicator(private val contentJsonClient: ContentJsonClient) : ReactiveHealthIndicator {
private val logger = KotlinLogging.logger { }
override fun health(): Mono<Health> = mono {
try {
contentJsonClient.getPage(it)
Health.up().build()
} catch (e: Exception) {
logger.error(e) { "ContentClient health check failed" }
Health.down(e).build()
}
}
}
This does look good, but fails as fullfiling solution because the only thing that get´s catched is this:
kotlinx.coroutines.JobCancellationException: MonoCoroutine was cancelled
I am a bit helpless here and would appreciate any help.
Thanks in advance
DennisRobert Jaros
04/22/2020, 1:59 PMzipFile.delete()
? Currently I have this:
suspend fun download(request: ServerRequest): ServerResponse {
val zipFile = // get the temporary <http://java.io|java.io>.File from a different service
ServerResponse.ok().contentLength(zipFile.length())
.contentType(MediaType.parseMediaType("application/zip"))
.header("Content-Disposition", "attachment; filename=\"file.zip\"")
.bodyValueAndAwait(FileSystemResource(zipFile))
}
Is there any callback I can use? I don't want to read the file into temporary ByteArray
.Dariusz Kuc
04/22/2020, 4:36 PMBeanPostProcessor
that my application context fails to load up as it fails to resolve some of the post processor dependencies complaining about unability to parse out SPeL
value passed for one its parameters. My understanding is that Spring post processors should be applied at that point as they are PriorityOrdered
so they take precedence over the regular ordered beans. Using Spring Boot 2.2.5.RELEASE
It’s a longshot but just wondering if anyone here hit some similar issue.Artyom Gornostayev
04/29/2020, 2:10 PM@RestControllerAdvice
class ExceptionHandlingAdvice {
@ExceptionHandler(NotImplementedError::class)
fun notImplementedYet(exception: NotImplementedError): ResponseEntity<ErrorResponse> =
exception.toNotImplementedErrorResponse()
@ExceptionHandler(Throwable::class)
fun unexpectedException(exception: Throwable): ResponseEntity<ErrorResponse> =
exception.toInternalServerErrorResponse()
}
When I call TODO()
method somewhere in the application the kotlin.NotImplementedError
is occurred. However, the first hadler does not get it.
Does anybody has such a problem?Stian N
05/06/2020, 2:21 PMEricJTurley
05/06/2020, 6:10 PMtestCoroutineScope
in a @SpringBootTest
. Having trouble.
To get started, do you know any examples or docs for this?Sandy
05/07/2020, 10:40 PMTimur Atakishiev
05/09/2020, 6:31 AMDsittel
05/26/2020, 1:56 PMsdeleuze
05/26/2020, 1:58 PMviralshah
05/27/2020, 2:24 AM@Configuration
class DataSourceConfig {
companion object {
private val logger = LoggerFactory.getLogger(DataSourceConfig::class.java)
}
@ConstructorBinding
@ConfigurationProperties(prefix = "datasource.default")
data class DefaultDataSource(
val host: String,
val port: Int,
val database: String,
val username: String,
val password: String
) {
init {
<http://logger.info|logger.info>(toString())
}
}
@ConstructorBinding
@ConfigurationProperties(prefix = "datasource.write")
data class WriteDataSource(
val host: String,
val port: Int,
val database: String,
val username: String,
val password: String
) {
init {
<http://logger.info|logger.info>(toString())
}
}
@Bean
fun defaultFactory(defaultDataSource: DefaultDataSource): ConnectionFactory {
return ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(ConnectionFactoryOptions.DRIVER, "pool")
.option(ConnectionFactoryOptions.PROTOCOL, "postgresql")
.option(ConnectionFactoryOptions.HOST, defaultDataSource.host)
.option(ConnectionFactoryOptions.PORT, defaultDataSource.port)
.option(ConnectionFactoryOptions.USER, defaultDataSource.username)
.option(ConnectionFactoryOptions.PASSWORD, defaultDataSource.password)
.option(ConnectionFactoryOptions.DATABASE, defaultDataSource.database)
.build()
)
}
@Bean
fun writeFactory(writeDataSource: WriteDataSource): ConnectionFactory {
return ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(ConnectionFactoryOptions.DRIVER, "pool")
.option(
ConnectionFactoryOptions.PROTOCOL,
"postgresql"
)
.option(ConnectionFactoryOptions.HOST, writeDataSource.host)
.option(ConnectionFactoryOptions.PORT, writeDataSource.port)
.option(ConnectionFactoryOptions.USER, writeDataSource.username)
.option(ConnectionFactoryOptions.PASSWORD, writeDataSource.password)
.option(ConnectionFactoryOptions.DATABASE, writeDataSource.database)
.build()
)
}
@Bean
@Primary
fun databaseClient(@Qualifier("defaultFactory") connectionFactory: ConnectionFactory) =
DatabaseClient.create(connectionFactory)
@Bean
fun writeDatabaseClient(@Qualifier("writeFactory") connectionFactory: ConnectionFactory) =
DatabaseClient.create(connectionFactory)
}
Can I clean this up into something that scales when I need to coneect to multiple dbskenkyee
05/28/2020, 10:21 PMAnele
06/01/2020, 3:19 AMKepha
06/09/2020, 12:49 AMJP
06/10/2020, 2:39 PM@Entity
class:
1. Should one NOT use data class
for defining @Entity
class? I’ve found some articles which say that one shouldn’t, but then I’ve also seen many sources just using them.
2. When defining the properties for an @Entity
class, is there a rule to be followed for either using val
or var
?
3. For @Id
@GeneratedValue
property, what is the better way to define it: either as a nullable property initialized with null
? or as a non-nullable property initialized with other dummy value?sdeleuze
06/10/2020, 3:25 PMnfrankel
06/14/2020, 12:42 PMsh3lan
06/14/2020, 1:03 PMJP
06/15/2020, 11:44 AMcom.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.0.jar:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4624) ~[jackson-databind-2.11.0.jar:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4469) ~[jackson-databind-2.11.0.jar:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3479) ~[jackson-databind-2.11.0.jar:2.11.0]
at LoginFilter.attemptAuthentication(LoginFilter.kt:54) ~[main/:na]
What is the problem? I will put the code snippets in threadJP
06/15/2020, 11:44 AMcom.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.0.jar:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4624) ~[jackson-databind-2.11.0.jar:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4469) ~[jackson-databind-2.11.0.jar:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3479) ~[jackson-databind-2.11.0.jar:2.11.0]
at LoginFilter.attemptAuthentication(LoginFilter.kt:54) ~[main/:na]
What is the problem? I will put the code snippets in threadkqr
06/15/2020, 1:38 PMWesley Acheson
06/24/2020, 5:26 PM