sdeleuze
04/06/2023, 9:50 AMThomas Engelmeier
04/07/2023, 12:00 PMCannot inline bytecode built with JVM target 17 into bytecode that is being built with JVM target 1.8. Please specify proper '-jvm-target' option kotlin(INLINE_FROM_HIGHER_PLATFORM)
or the versions other way around.. Any hints to get it to work?Yogeshvu
04/08/2023, 8:20 PMsdeleuze
04/13/2023, 2:05 PMEmil Kantis
04/13/2023, 2:10 PMsdeleuze
04/14/2023, 5:18 AMsdeleuze
04/24/2023, 7:32 AMAxel
04/25/2023, 2:04 PM@Component
in which I want to run a suspend function on app start (@PostConstruct
or @EventListener
) and @Scheduled
but this seem to only work on blocking methods. Is there a workaround?Axel
04/26/2023, 2:05 PMlaunch {}
throws an unexpected exception, the populate()
method is never invoked again, even though its @Scheduled
to recurr. Why is that?
@Component
class PrePopulatedStoreCache(
private val contentManagerClient: ContentManagerClient,
): CoroutineScope, DisposableBean {
private val cache:
PrePopulatedCache<StoreByMerchantIdCacheKey, MinimalStore> =
CaffeineBackedPrePopulatedCache.create(CacheConfiguration("all-stores"))
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Default
override fun destroy() = job.cancel()
@Scheduled(fixedRate = 20, timeUnit = TimeUnit.SECONDS)
private fun populate() {
launch {
<http://log.info|log.info>("Pre populating Store cache")
contentManagerClient.getAllStoresV3()
.onLeft { log.error("Unable to prepopulate Store Cache: $it") }
.onRight { stores ->
cache.invalidateAll()
stores.forEach { cache.put(StoreByMerchantIdCacheKey(it.market, it.merchantExternalId), it) }
<http://log.info|log.info>("Populated cache with ${stores.size} stores in thread ${Thread.currentThread().name}")
}
}
}
suspend fun get(market: Market, merchantId: MerchantExternalId) =
cache.get(StoreByMerchantIdCacheKey(market, merchantId))
}
data class StoreByMerchantIdCacheKey(val market: Market, val merchantExternalId: MerchantExternalId)
Yogeshvu
04/27/2023, 7:54 PMsdeleuze
04/29/2023, 6:38 AMJacob
05/01/2023, 1:56 PMwakingrufus
05/03/2023, 8:44 PMEric
05/04/2023, 12:39 PMCoroutineCrudRepository
and just a simple @RestController
. I'm trying to make sure I'm handling transactions properly. Using @Transactional
isn't supported. I'm injecting a TransactionalOperator
to my controller and using it like this:
@PostMapping("/")
suspend fun create(@Valid @RequestBody info: Info): ResponseEntity<Model> =
doInTransaction { repo.save(convert(info)).created() }
@GetMapping("/{id}")
suspend fun read(@PathVariable id: Id): ResponseEntity<Model> = doInTransaction { repo.findById(id).okOrNotFound() }
@GetMapping
suspend fun readAll(): ResponseEntity<List<Model>> = doInTransaction { repo.findAll().toList().ok() }
private suspend fun <T> doInTransaction(block: suspend () -> T): T =
transactionalOperator.executeAndAwait { block() }
Is using executeAndAwait
like this correct?Eric
05/04/2023, 4:16 PMvalue class
as a PK for R2DBC? I wanted to create one to enforce UUID type:
@JvmInline
value class UUID(val uuid: java.util.UUID) {
init {
require(UuidUtil.getVersion(uuid) == UuidVersion.VERSION_TIME_ORDERED_EPOCH) {
"UUID must be version 7"
}
}
override fun toString(): String = uuid.toString()
constructor() : this(UuidCreator.getTimeOrderedEpochPlus1())
companion object {
fun fromString(uuid: String): UUID = UUID(java.util.UUID.fromString(uuid))
}
}
But the repo returns nothing for a findById
w/ this. Works w/ a regular UUID.Axel
05/08/2023, 2:18 PM@ExtendWith(SpringExtension::class)
@WebMvcTest(GetStoresByMarket::class)
internal class GetStoresByMarketTest {
@Autowired
private lateinit var mockMvc: MockMvc
@MockBean
private lateinit var getStoresByMarketAndConsumerId: GetStoresByMarketAndConsumerId
@MockBean
private lateinit var getStoresByMarketAndCategoryAndConsumerId: GetStoresByMarketAndCategoryAndConsumerId
@Test
fun `when market is unknown a client error should be returned`() {
mockMvc.get("/v1/stores/asd") {
param("consumerId", UUID.randomUUID().toString())
}.andExpect {
status { isBadRequest() }
}
}
}
the endpoint it tests is suspend
, so the test fails with this output:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /v1/stores/asd
Parameters = {consumerId=[2d80c908-3699-4bf2-8eb8-ea1069de108a]}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = com.foo.http.v1.stores.GetStoresByMarket
Method = com.foo.http.v1.stores.GetStoresByMarket#getStoresByMarket(String, String, String, Integer, Integer, Continuation)
Async:
Async started = true
Async result = org.springframework.web.server.ResponseStatusException: 400 BAD_REQUEST
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Status expected:<400> but was:<200>
Expected :400
Actual :200
How do I make sure I get the async result back in the test? I have tried variations of runBlocking
and runTest
to availEric
05/12/2023, 2:41 PM@RequestBody @ValidJsonPatch patch: JsonPatch
I've created the validation annotation and constraint validator:
@Constraint(validatedBy = [JsonPatchValidator::class])
annotation class ValidJsonPatch(
val message: String = "",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
)
class JsonPatchValidator : ConstraintValidator<ValidJsonPatch, JsonPatch> {
override fun isValid(value: JsonPatch, context: ConstraintValidatorContext): Boolean { ... }
}
But the validator never gets invoked.
I've added _implementation_("org.springframework.boot:spring-boot-starter-validation")
to my dependencies and standard jakarta validation annotations work.
edit: scratch that... standard validation annotations are also not working.Luiz Aguiar
05/16/2023, 9:37 AMspring-boot-starter-web
, is it possible to use Coroutines
by adding spring-boot-starter-webflux
?
will it work properly to have a Flow
controller function for data stream?Roque Sosa
05/19/2023, 6:15 PMLucas León
05/20/2023, 7:45 AM<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<id>kapt</id>
<configuration>
<sourceDirs>
<sourceDir>src/main/kotlin</sourceDir>
</sourceDirs>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId><http://com.redis.om|com.redis.om></groupId>
<artifactId>redis-om-spring</artifactId>
<version>0.8.0</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</execution>
</executions>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
But I’m getting this error: exception java.lang.NoSuchFieldException is never thrown in body of corresponding try statement
And this is the generated class
public final class UserInfoHash$ {
public static MetamodelField<UserInfoHash, String> _KEY;
static {
try {
_KEY = new MetamodelField<UserInfoHash, String>("__key", String.class, true);
} catch(NoSuchFieldException | SecurityException e) {
System.err.println(e.getMessage());
}
}
}
Can someone help me with this please?Philipp Mayer
05/23/2023, 8:12 PM@SpringBootTest(classes = [TestConfig::class])
class OrderTests: OtherClass {
val orders = listOf<Order>() //this is just a representation - it's actually part of OtherClass
@Import(Application::class)
class TestConfig {
// I'd like to pass it in here
@Bean
fun orderRepository() = FakeOrderRepository(orders)
}
@Test
fun `works now`() {
println("yay")
}
}
I have a Spring test where I’m replacing a bean. However, I’d like to supply a specific parameter (orders
) when creating the bean.
The problem is that orders
is part of another class that is implemented by `OrderTests`: OtherClass
.
I played around with it and can’t think about a way of how I could pass that into the bean. The problem is that it’s quite crucial and that there’s no way to change the way the orders
are set up in OtherClass
.
The easiest (from a vanilla point of view) would be to mark TestConfig
as inner class
, but that’s not compatible with Spring.
Do you have an idea? Thanks in advance! 👋hantsy
06/01/2023, 4:24 AM~.client.ExchangeFunctions: Cancel signal (to close connection)
....
kotlinx.coroutines.JobCancellactionException: MonoCoroutines was cancelled.
and the last exception is thrown again and again till time out, what we want is if there is an exception in one iteration(we used try/catch to handle it), and move to the next iteration. Now the result it stopped the whole scheduled task.
Any idea?
https://stackoverflow.com/questions/63472729/cancel-signal-close-connection-what-could-be-the-causeMinsoo Cheong
06/12/2023, 1:32 AMJon Senchyna
06/14/2023, 12:50 PMPihentagy
06/15/2023, 10:01 AMval params= mapOf("foo" to "bar")
, how can I pass it to an UriComponentBuilder
?alwyn
06/19/2023, 4:37 PMSpringApplication.from(xxxx::main).with(yyyy.class).run(args)
to copy the configuration of your main xxxx SpringBootApplication class and extend it with the configuration class yyyy.class
Specifying xxxx::main in Kotlin don't want to resolve in Intellij, but for Java it works. The argument for the .from
method is of type ThrowingConsumer
which neither the Java main or the Kotlin main functions match, yet it works for Java, but not Kotlin.
I guess the broader question is, can you get a function reference to fun main(..)
and how do you use it?Pihentagy
06/29/2023, 1:38 PMsmallufo
06/30/2023, 10:57 AMcontext class
work well with spring ?
Because of some context requirement , I have to mark my spring bean context
:
context(IConfig)
@Named
class MyService (...) {
val config = SomeBuilder().build() // it needs IConfig context
}
test :
internal class MyServiceTest : AbstractCoreTest() {
@Inject
private lateinit var service: MyService
// do tests
}
It compiles OK , but when executing , it throws :
java.lang.IllegalStateException: Failed to load ApplicationContext for [MergedContextConfiguration@484876a1 testClass = foo.MyServiceTest, locations = ["classpath:core.xml"], classes = [], contextInitializerClasses = [destiny.TestAppInit], activeProfiles = [], propertySourceLocations = [], propertySourceProperties = [], contextCustomizers = [], contextLoader = org.springframework.test.context.support.DelegatingSmartContextLoader, parent = null]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext
…
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myService' defined in file [.../MyService.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'IConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Is there a better way to solve this ? Thanks.
(Kotlin 1.8.21 , Spring 6.0.9)Slackbot
07/07/2023, 10:24 AM