Using Optaplanner VRP example with optaplanner-spring-boot-starter - optaplanner

I'm trying to create an app to solve VRP problems, and I'm getting this error msg when I use the domain classes from the VRP example code. in version 8.19.0.Final
"A planning entity is an instance of a class (class com.test.vrp.domain.Vehicle) that is not configured as a planning entity class ([class com.test.vrp.domain.Customer, class com.test.vrp.domain.timewindowed.TimeWindowedCustomer]).
If that class (Vehicle) (or superclass thereof) is not a #PlanningEntity annotated class, maybe your #PlanningSolution annotated class has an incorrect #PlanningEntityCollectionProperty or #PlanningEntityProperty annotated member.
Otherwise, if you're not using the Quarkus extension or Spring Boot starter, maybe that entity class (Vehicle) is missing from your solver configuration."
The Vehicle class is not configured as planning entity class, although it implements "Standstill" which is annotated as a Planning Entity.
Any changes I make (like annotating Vehicle as a Planning Entity) just create other errors.
2022-04-04 15:49:24.464 ERROR 8264 --- [ XNIO-1 task-1] c.test.vrp.web.rest.PlannerResource : Illegal argument: [] in getSolution()
2022-04-04 15:49:24.464 ERROR 8264 --- [ XNIO-1 task-1] c.test.vrp.web.rest.PlannerResource : Exception in getSolution() with cause = 'NULL' and exception = 'A planning entity is an instance of a class (class com.test.vrp.domain.planner.Vehicle) that is not configured as a planning entity class ([class com.test.vrp.domain.planner.Customer, class com.test.vrp.domain.planner.timewindowed.TimeWindowedCustomer]).
If that class (Vehicle) (or superclass thereof) is not a #PlanningEntity annotated class, maybe your #PlanningSolution annotated class has an incorrect #PlanningEntityCollectionProperty or #PlanningEntityProperty annotated member.
Otherwise, if you're not using the Quarkus extension or Spring Boot starter, maybe that entity class (Vehicle) is missing from your solver configuration.'
java.lang.IllegalArgumentException: A planning entity is an instance of a class (class com.test.vrp.domain.planner.Vehicle) that is not configured as a planning entity class ([class com.test.vrp.domain.planner.Customer, class com.test.vrp.domain.planner.timewindowed.TimeWindowedCustomer]).
If that class (Vehicle) (or superclass thereof) is not a #PlanningEntity annotated class, maybe your #PlanningSolution annotated class has an incorrect #PlanningEntityCollectionProperty or #PlanningEntityProperty annotated member.
Otherwise, if you're not using the Quarkus extension or Spring Boot starter, maybe that entity class (Vehicle) is missing from your solver configuration.
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.findEntityDescriptorOrFail(SolutionDescriptor.java:729)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.lambda$countUninitializedVariables$16(SolutionDescriptor.java:1047)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.lambda$visitAllEntities$9(SolutionDescriptor.java:936)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.visitAllEntities(SolutionDescriptor.java:950)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.visitAllEntities(SolutionDescriptor.java:936)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.countUninitializedVariables(SolutionDescriptor.java:1046)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.lambda$countUninitialized$15(SolutionDescriptor.java:1041)
at java.base/java.util.Optional.orElseGet(Optional.java:369)
at org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor.countUninitialized(SolutionDescriptor.java:1041)
at org.optaplanner.core.impl.score.director.AbstractScoreDirector.setWorkingSolution(AbstractScoreDirector.java:178)
at org.optaplanner.constraint.drl.DrlScoreDirector.setWorkingSolution(DrlScoreDirector.java:68)
at org.optaplanner.core.impl.score.DefaultScoreManager.updateScore(DefaultScoreManager.java:53)
at com.test.vrp.web.rest.PlannerResource.getSolution(PlannerResource.java:182)
at com.test.vrp.web.rest.PlannerResource$$FastClassBySpringCGLIB$$a02fe551.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:88)
at com.test.vrp.aop.logging.LoggingAspect.logAround(LoggingAspect.java:103)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:62)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.test.vrp.web.rest.PlannerResource$$EnhancerBySpringCGLIB$$dfc6fec2.getSolution(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:503)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:155)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at com.test.vrp.security.jwt.JWTFilter.doFilter(JWTFilter.java:40)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.web.filter.CorsFilter.doFilterInternal(CorsFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.SessionRestoringHandler.handleRequest(SessionRestoringHandler.java:119)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:841)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2019)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1558)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1423)
at java.base/java.lang.Thread.run(Thread.java:834)

Looks like the problem is a result of the code being migrated from optaplanner-examples to a new project with a different package structure.
This is the important part of the message:
A planning entity is an instance of a class (class com.test.vrp.domain.planner.Vehicle)
that is not configured as a planning entity class ([
class com.test.vrp.domain.planner.Customer,
class com.test.vrp.domain.planner.timewindowed.TimeWindowedCustomer
]).
I suspect the solverConfig.xml that you have in your project is ignored and that's not necessarily a bad thing or the cause of the issue. The reason I think so is that the FQCNs you shared in the comment are completely different from what's in the exception message. I guess that if you delete your solverConfig.xml the exception will remain the same.
The optaplanner-spring-boot-starter artifact contains an extension that will automatically discover your #PlanningSolution and your #PlanningEntity annotated classes provided that they are in a sub-package of your #SpingBootApplication. From the exception message, we can see that Customer and TimeWindowedCustomer have been discovered (despite of what you have in your solverConfig.xml) but com.test.vrp.domain.Standstill is missing. Try to fix that:
Make sure com.test.vrp.domain.Vehicle extends com.test.vrp.domain.Standstill.
Make sure com.test.vrp.domain.Standstill is in your project in the com.test.vrp.domain package.
Check that com.test.vrp.domain.Standstill has the #PlanningEntity annotation.
Also check that your #SpringBootApplication annotated class is in the com.test.vrp or com.test.vrp.domain package.

Related

Jackson MismatchedInputException : no String-argument constructor/factory method to deserialize from String value

I use RestTemplate.exchange in my Spring Boot app to GET this response:
<?xml version="1.0" encoding="UTF-8"?>
<advertisers current_page="1" per_page="10" total_pages="1" total_entries="1">
<advertiser>
<id>1057343</id>
<name>SOME ADVERTISER</name>
<status>ACTIVE</status>
<created_at>2021-10-12T09:06:12Z</created_at>
<updated_at>2022-04-08T13:36:50Z</updated_at>
</advertiser>
</advertisers>
Advertisers.java:
#Data
#FieldDefaults(level = AccessLevel.PRIVATE)
public class Advertisers {
List<Advertiser> advertiser;
}
Advertiser.java:
#Data
#FieldDefaults(level = AccessLevel.PRIVATE)
public class Advertiser {
String id;
String name;
String status;
}
But I get the following exception:
org.springframework.web.client.RestClientException: Error while extracting response for type [class fr.canalplus.tvseg.models.freewheel.entities.Advertisers] and content type [application/xml;charset=utf-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `fr.canalplus.tvseg.models.freewheel.entities.Advertiser` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1057343'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `fr.canalplus.tvseg.models.freewheel.entities.Advertiser` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1057343')
at [Source: (ByteArrayInputStream); line: 4, column: 16] (through reference chain: fr.canalplus.tvseg.models.freewheel.entities.Advertisers["advertiser"]->java.util.ArrayList[0])
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:120)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1037)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1020)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:778)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at fr.canalplus.tvseg.services.FreeWheelService.exchange(FreeWheelService.java:102)
at fr.canalplus.tvseg.services.FreeWheelService.getCreativeAdvertiser(FreeWheelService.java:154)
at fr.canalplus.tvseg.controllers.TestController.test(TestController.java:23)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:346)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:887)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1684)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `fr.canalplus.tvseg.models.freewheel.entities.Advertiser` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1057343'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `fr.canalplus.tvseg.models.freewheel.entities.Advertiser` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1057343')
at [Source: (ByteArrayInputStream); line: 4, column: 16] (through reference chain: fr.canalplus.tvseg.models.freewheel.entities.Advertisers["advertiser"]->java.util.ArrayList[0])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:387)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:342)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:105)
... 58 more
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `fr.canalplus.tvseg.models.freewheel.entities.Advertiser` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1057343')
at [Source: (ByteArrayInputStream); line: 4, column: 16] (through reference chain: fr.canalplus.tvseg.models.freewheel.entities.Advertisers["advertiser"]->java.util.ArrayList[0])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1455)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1081)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1408)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:176)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:290)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:249)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:371)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3521)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:376)
... 60 more
I don't understand why the id '1057343' can't be deserialize.
Can you help please? Thank you in advance
The exception thrown by Jackson is really quite misleading.
You need to tell Jackson that your sequence of
<advertiser> ...</advertiser> elements is not wrapped
by an additional XML element.
You do this in your Advertisers class
by annotating the List<Advertiser> property with
#JacksonXmlElementWrapper(useWrapping = false)
See also the javadoc of JacksonXmlElementWrapper.useWrapping.

How can I properly unit test a reactive response for a simple string value?

I am very new to Webflux and the whole reactive context. I just can't get my head around. However I started with a - in my theory - simple example to try things out.
The following code should be used for some data exporting web endpoints. Therefore I need to fill the response with data. In my unit test I simply test this with a string foo to start easy.
internal class ExportRendererTest {
private val renderer = ExportRenderer()
private val testResponse = MockServerHttpResponse()
#Test
fun `should export word if one product is given`() {
renderer.writeResponse(testResponse, Flux.fromIterable(listOf()))
val value = testResponse.bodyAsString.block()
assertThat(value).isEqualTo("foo")
}
}
Here is the logic under test
class ExportRenderer {
fun writeResponse(response: ServerHttpResponse, products: Flux<out Product>): Mono<Void> {
response.writeAndFlushWith(
products.map { Mono.just(response.bufferFactory().wrap("foo".toByteArray(Charsets.UTF_8))) }
)
return Mono.empty()
}
}
My test results in the following exception
No content was written nor was setComplete() called on this response.
java.lang.IllegalStateException: No content was written nor was setComplete() called on this response.
at org.springframework.mock.http.server.reactive.MockServerHttpResponse.<init>(MockServerHttpResponse.java:53)
at org.springframework.mock.http.server.reactive.MockServerHttpResponse.<init>(MockServerHttpResponse.java:60)
at com.myapp.productgate.export.renderer.data.ExportRendererTest.<init>(ExportRendererTest.kt:11)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.junit.platform.commons.util.ReflectionUtils.newInstance(ReflectionUtils.java:513)
at org.junit.jupiter.engine.execution.ConstructorInvocation.proceed(ConstructorInvocation.java:56)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.api.extension.InvocationInterceptor.interceptTestClassConstructor(InvocationInterceptor.java:72)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:77)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestClassConstructor(ClassBasedTestDescriptor.java:342)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateTestClass(ClassBasedTestDescriptor.java:289)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:79)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:267)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:259)
at java.base/java.util.Optional.orElseGet(Optional.java:362)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:258)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:101)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:100)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1510)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
at com.sun.proxy.$Proxy2.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:133)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
at java.base/java.lang.Thread.run(Thread.java:832)
Suppressed: java.lang.Exception: #block terminated with an error
at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99)
at reactor.core.publisher.Mono.block(Mono.java:1703)
at com.myapp.productgate.export.renderer.data.ExportRendererTest.should export empty template if no products were given(ExportRendererTest.kt:16)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
... 59 more
I see there is an issue with the "completion" it seems but to be honest I find the whole reactive API stuff very confusing and have no idea how to inteprete the issue or what to look for exactly.
i dont really understand your code and what you are trying to accomplish with your code. You wrote that you are confused so i'll give you some basics.
If you just want to return a server response containing a string there are several ways to do it.
#GetMapping("/string")
public Mono<String> getString() {
return Mono.just("Foobar");
}
When the calling client calls this endpoint, the client will subscribe, and the Mono which is a Producer will produce the item it contains to the subscriber (here the calling client)
if you wish to "produce" a stream of items, you use a Flux. They are for multiple items, while a Mono is for zero or one item.
#GetMapping("/strings")
public Flux<String> getStrings() {
return Flux.just("Foo", "Bar");
}
In both these examples, the response will automatically be wrapped in a ServerResponse. If we wish to add custom headers, or be explicit with error codes etc. we can use the builder on the ServerResponse class to build a response, with our Producer in the body.
#GetMapping("/strings")
public Flux<String> getStrings() {
return ServerResponse.ok().body(Flux.just("Foo", "Bar")).build();
}
There is a general rule in reactive programming and that is nothing happens until you subscribe. So if we want to test our functions what to we do, well we need to either block, or subscribe to them.
Blocking is in general very bad and should never be done in a reactive application since it will hurt performance a lot. Subscribing should only be done in an application if your application is the client to something and your service is the final consumer. For instance your application calls another api to fetch data and to write it to a database.
So testing:
#Test
public void singleStringTest() {
// here i call block, i can also call subscribe,
// its a test so its fine we block here.
var string = someClass.getString().block()
assertEquals("Foobar", string);
}
But if we want to test a flow, like a Flux we can use a StepVerifier.
#Test
public void singleStringTest() {
StepVerifier
.create(source)
.expectNext("Foo")
.expectNext("Bar")
.expectComplete()
.verify();
}
A step verifier is a more advanced tool for manually feeding items, here i use it to manually ask for an item, and another item, and then check that the flow is completed. You can control time with it and do all sorts of cool funky stuff to test reactive flows.
If you have a hard time understanding i suggest you start with the reactor documentation which is the library webflux is built upon.
Since this was tagged with Kotlin, I just want to add that instead of using the StepVerifier you can use the Kotlin extensions to Reactor and just do something like:
MyClass.myFunction().test()
.assertNext{your assertions goes here}
.verifyComplete()
which produces very nice and concise testing for the reactive methods. The test() function call is the extension method which creates a StepVerifier behind the scenes.
#Toerktumlare gave me some more time to think about the whole and I figured out the implementation where I used the Mono was simply wrong.
class Exportenderer {
override fun writeResponse(response: ServerHttpResponse, products: Flux<out Product>): Mono<Void> {
return response.writeAndFlushWith(
products.map { Mono.just(response.bufferFactory().wrap("foo".toByteArray(Charsets.UTF_8))) }
)
}
}
This time I return the writeAndFlushWith return value Mono<Void> instead of returning an Mono.empty() at the bottom of the logic. Now I can access the value of the response.body in the test method properly by using .block() and finally it works as expected

Multile Ignite Client with Cluser Singleton Service Connect to Remote Ignite Server Failed to marshal discovery data

I have 2 Ignite server, and when I create a ignite client,
it will connect to the two server and it works fine with no error.
In the ignite client java code, it create a cluster singleton service
But if i create a second ignite client with the same code, the
client will also call the function to create the cluster singleton service(i think ignite may know this service has one already, and will not create again, correct me if i am wrong), and in the one of the server, it dumps the following errors(another is fine):
[02:05:30,912][SEVERE][tcp-disco-msg-worker-#2][TcpDiscoverySpi] Failed to marshal discovery data
[comp=0, data=DiscoveryData [nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c, items=[DiscoveryDataItem
[routineId=6be10471-bdfb-47e0-881a-aa9cf285cead, prjPred=IgniteAllNodesPredicate [],
hnd=CacheContinuousQueryHandlerV2 [rmtFilterFactory=com.test.simple.IgniteMatchClusterSingletonService$3#39812ce8,
rmtFilterFactoryDep=null, types=0], bufSize=1, interval=0, autoUnsubscribe=true], DiscoveryDataItem
[routineId=c0582fdc-0539-4c41-8238-f15d426af475, prjPred=IgniteAllNodesPredicate [],
hnd=CacheContinuousQueryHandler [cacheName=datastructures_ATOMIC_PARTITIONED_0#default-ds-group,
rmtFilter=o.a.i.i.processors.cache.datastructures.CacheDataStructuresManager$QueueHeaderPredicate#4e5687a1,
rmtFilterDep=null, internal=true, notifyExisting=true, oldValRequired=true, sync=false, ignoreExpired=true,
taskHash=0, skipPrimaryCheck=false, locCache=false, keepBinary=false, ackBuf=CacheContinuousQueryAcknowledgeBuffer
[size=0, updateCntrs={}, topVers=[]], cacheId=474336146, initTopVer=AffinityTopologyVersion [topVer=5, minorTopVer=10],
nodeLeft=false, ignoreClsNotFound=false, asyncCb=false, nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c,
routineId=c0582fdc-0539-4c41-8238-f15d426af475], bufSize=1, interval=0, autoUnsubscribe=true], DiscoveryDataItem
[routineId=a2ad72c7-cd07-4fd5-bb51-adf33d344238, prjPred=EqualsClusterNodeIdPredicate
[nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c], hnd=CacheContinuousQueryHandler [cacheName=ignite-sys-cache,
rmtFilter=null, rmtFilterDep=null, internal=true, notifyExisting=true, oldValRequired=true, sync=false,
ignoreExpired=true, taskHash=0, skipPrimaryCheck=true, locCache=false, keepBinary=false,
ackBuf=CacheContinuousQueryAcknowledgeBuffer [size=0, updateCntrs={}, topVers=[]], cacheId=-2100569601,
initTopVer=null, nodeLeft=false, ignoreClsNotFound=false, asyncCb=false, nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c,
routineId=a2ad72c7-cd07-4fd5-bb51-adf33d344238], bufSize=1, interval=0, autoUnsubscribe=true]]]]
class org.apache.ignite.IgniteCheckedException: Failed to serialize object: DiscoveryData [nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c,
items=[DiscoveryDataItem [routineId=6be10471-bdfb-47e0-881a-aa9cf285cead, prjPred=IgniteAllNodesPredicate [],
hnd=CacheContinuousQueryHandlerV2 [rmtFilterFactory=com.test.simple.IgniteMatchClusterSingletonService$3#39812ce8,
rmtFilterFactoryDep=null, types=0], bufSize=1, interval=0, autoUnsubscribe=true], DiscoveryDataItem
[routineId=c0582fdc-0539-4c41-8238-f15d426af475, prjPred=IgniteAllNodesPredicate [], hnd=CacheContinuousQueryHandler
[cacheName=datastructures_ATOMIC_PARTITIONED_0#default-ds-group,
rmtFilter=org.apache.ignite.internal.processors.cache.datastructures.CacheDataStructuresManager$QueueHeaderPredicate#4e5687a1,
rmtFilterDep=null, internal=true, notifyExisting=true, oldValRequired=true, sync=false, ignoreExpired=true,
taskHash=0, skipPrimaryCheck=false, locCache=false, keepBinary=false, ackBuf=CacheContinuousQueryAcknowledgeBuffer
[size=0, updateCntrs={}, topVers=[]], cacheId=474336146, initTopVer=AffinityTopologyVersion [topVer=5, minorTopVer=10],
nodeLeft=false, ignoreClsNotFound=false, asyncCb=false, nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c,
routineId=c0582fdc-0539-4c41-8238-f15d426af475], bufSize=1, interval=0, autoUnsubscribe=true], DiscoveryDataItem
[routineId=a2ad72c7-cd07-4fd5-bb51-adf33d344238, prjPred=EqualsClusterNodeIdPredicate [nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c],
hnd=CacheContinuousQueryHandler [cacheName=ignite-sys-cache, rmtFilter=null, rmtFilterDep=null, internal=true, notifyExisting=true,
oldValRequired=true, sync=false, ignoreExpired=true, taskHash=0, skipPrimaryCheck=true, locCache=false, keepBinary=false,
ackBuf=CacheContinuousQueryAcknowledgeBuffer [size=0, updateCntrs={}, topVers=[]], cacheId=-2100569601, initTopVer=null,
nodeLeft=false, ignoreClsNotFound=false, asyncCb=false, nodeId=bb2beed3-38e9-4134-a898-b4aab8705c8c,
routineId=a2ad72c7-cd07-4fd5-bb51-adf33d344238], bufSize=1, interval=0, autoUnsubscribe=true]]]
at org.apache.ignite.marshaller.jdk.JdkMarshaller.marshal0(JdkMarshaller.java:103)
at org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller.marshal(AbstractNodeNameAwareMarshaller.java:70)
at org.apache.ignite.marshaller.jdk.JdkMarshaller.marshal0(JdkMarshaller.java:117)
at org.apache.ignite.marshaller.AbstractNodeNameAwareMarshaller.marshal(AbstractNodeNameAwareMarshaller.java:58)
at org.apache.ignite.spi.discovery.tcp.internal.DiscoveryDataPacket.marshalData(DiscoveryDataPacket.java:311)
at org.apache.ignite.spi.discovery.tcp.internal.DiscoveryDataPacket.marshalGridNodeData(DiscoveryDataPacket.java:87)
at org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi.collectExchangeData(TcpDiscoverySpi.java:1897)
at org.apache.ignite.spi.discovery.tcp.ServerImpl$RingMessageWorker.processNodeAddedMessage(ServerImpl.java:4173)
at org.apache.ignite.spi.discovery.tcp.ServerImpl$RingMessageWorker.processMessage(ServerImpl.java:2706)
at org.apache.ignite.spi.discovery.tcp.ServerImpl$RingMessageWorker.processMessage(ServerImpl.java:2519)
at org.apache.ignite.spi.discovery.tcp.ServerImpl$MessageWorkerAdapter.body(ServerImpl.java:6707)
at org.apache.ignite.spi.discovery.tcp.ServerImpl$RingMessageWorker.body(ServerImpl.java:2602)
at org.apache.ignite.spi.IgniteSpiThread.run(IgniteSpiThread.java:62)
Caused by: java.io.NotSerializableException: com.test.simple.IgniteMatchClusterSingletonService$2
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryHandlerV2.writeExternal(CacheContinuousQueryHandlerV2.java:157)
at java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java:1459)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1430)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at org.apache.ignite.internal.processors.continuous.GridContinuousProcessor$DiscoveryDataItem.writeExternal(GridContinuousProcessor.java:1853)
at java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java:1459)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1430)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at org.apache.ignite.internal.util.IgniteUtils.writeCollection(IgniteUtils.java:1754)
at org.apache.ignite.internal.processors.continuous.GridContinuousProcessor$DiscoveryData.writeExternal(GridContinuousProcessor.java:1772)
at java.io.ObjectOutputStream.writeExternalData(ObjectOutputStream.java:1459)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1430)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at org.apache.ignite.marshaller.jdk.JdkMarshaller.marshal0(JdkMarshaller.java:98)
... 12 more
The root cause is clearly shown in the stack trace:
Caused by: java.io.NotSerializableException: com.test.simple.IgniteMatchClusterSingletonService$2
There is an anonymous class (com.test.simple.IgniteMatchClusterSingletonService$2) that is not Serializable, but gets serialized along with the service instance.
If this is expected, then you need to make sure this class does implement Serializable. Otherwise, change the code so that instance of this class is not sent across network.
In general, I would recommend to avoid using anonymous classes or lambdas for anything that can be serialized. They typically contain a link to enclosing class which makes it more difficult to understand what is serialized and what is not. Switch to inner static classes to avoid that.

Weld encounters NoClassDefFoundError while loading custom context class

I am writing a CDI custom scope that is added via an extension:
public class SliceScopeExtension
implements Extension, Serializable {
public void addScope(#Observes final BeforeBeanDiscovery event) {
event.addScope(SliceScoped.class, true, true);
}
public void registerContext(#Observes final AfterBeanDiscovery event) {
event.addContext(new SliceScopeContext());
}
}
The corresponding context class uses a custom bean store implementation that is derived from org.jboss.weld.context.beanstore.AttributeBeanStore:
public class SliceScopeContext implements Context, Serializable {
private static final Logger log = Logger.getLogger(SliceScopeContext.class.getName());
private final ThreadLocal<HttpServletRequest> request;
private final ThreadLocal<SliceScopeBeanStore> beanStore;
public SliceScopeContext() {
this.request = new ThreadLocal<>();
this.beanStore = new ThreadLocal<>();
}
...
}
If I now deploy this web application glassfish/weld are throwing a org.jboss.weld.resources.spi.ResourceLoadingException with a nested NoClassDefFoundError saying that the class org/jboss/weld/context/beanstore/AttributeBeanStore could not be found. If I use the NamingScheme interface or SimpleNamingScheme the error is thrown for these class names:
org.jboss.weld.resources.spi.ResourceLoadingException: Error loading class my.package.SliceScopeContext
at org.jboss.weld.resources.ClassTransformer.getBackedAnnotatedType(ClassTransformer.java:179)
at org.jboss.weld.resources.ClassTransformer.getBackedAnnotatedType(ClassTransformer.java:188)
at org.jboss.weld.bootstrap.BeanDeployer.loadAnnotatedType(BeanDeployer.java:122)
at org.jboss.weld.bootstrap.BeanDeployer.addClass(BeanDeployer.java:100)
at org.jboss.weld.bootstrap.BeanDeployer.addClasses(BeanDeployer.java:159)
at org.jboss.weld.bootstrap.BeanDeployment.createClasses(BeanDeployment.java:214)
at org.jboss.weld.bootstrap.WeldBootstrap.startInitialization(WeldBootstrap.java:470)
at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:211)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:328)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:493)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NoClassDefFoundError: org/jboss/weld/context/beanstore/AttributeBeanStore
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.glassfish.web.loader.WebappClassLoader.findClass(WebappClassLoader.java:1183)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1728)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1611)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:266)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.visitor.Reifier.reifyTypeArguments(Reifier.java:68)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:138)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.generics.repository.FieldRepository.getGenericType(FieldRepository.java:85)
at java.lang.reflect.Field.getGenericType(Field.java:236)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedField.of(BackedAnnotatedField.java:28)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedFields.computeValue(BackedAnnotatedType.java:178)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedFields.computeValue(BackedAnnotatedType.java:171)
at org.jboss.weld.util.LazyValueHolder.get(LazyValueHolder.java:35)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$EagerlyInitializedLazyValueHolder.<init>(BackedAnnotatedType.java:154)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedFields.<init>(BackedAnnotatedType.java:171)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType$BackedAnnotatedFields.<init>(BackedAnnotatedType.java:171)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.<init>(BackedAnnotatedType.java:65)
at org.jboss.weld.annotated.slim.backed.BackedAnnotatedType.of(BackedAnnotatedType.java:47)
at org.jboss.weld.resources.ClassTransformer$TransformClassToBackedAnnotatedType.apply(ClassTransformer.java:85)
at org.jboss.weld.resources.ClassTransformer$TransformClassToBackedAnnotatedType.apply(ClassTransformer.java:82)
at com.google.common.collect.ComputingConcurrentHashMap$ComputingValueReference.compute(ComputingConcurrentHashMap.java:358)
at com.google.common.collect.ComputingConcurrentHashMap$ComputingSegment.compute(ComputingConcurrentHashMap.java:184)
at com.google.common.collect.ComputingConcurrentHashMap$ComputingSegment.getOrCompute(ComputingConcurrentHashMap.java:153)
at com.google.common.collect.ComputingConcurrentHashMap.getOrCompute(ComputingConcurrentHashMap.java:69)
at com.google.common.collect.ComputingConcurrentHashMap$ComputingMapAdapter.get(ComputingConcurrentHashMap.java:396)
at org.jboss.weld.resources.ClassTransformer.getBackedAnnotatedType(ClassTransformer.java:174)
... 43 more
Caused by: java.lang.ClassNotFoundException: org.jboss.weld.context.beanstore.AttributeBeanStore
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1761)
at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1611)
... 76 more
I verified if these classes are present in the weld-osgi-bundle.jar inside the glassfish modules directory and they are. This SO post I have checked and my project does not include any library that already contains these WELD classes.
What's going or what am I doing wrong here?
Opening weld-osgi-bundle.jar you can see that in META-INF/MANIFEST.MF file, the Export-Package section doesn't mention org.jboss.weld.context.beanstore; package, so it is private to weld.
You probably have to create your own context by copying this weld code or by using Apache Deltaspike and the tools in org.apache.deltaspike.core.util.context to create a portable context across Weld and OpenWebBeans.
The last (dirty) solution would be to modify the MANIFEST.MF file in weld-osgi-bundle.jar

Why is Glassfish 3.1.1 unable to create my Stateless Session Bean?

Glassfish 3.1.1 (build 12)
Application deployed as a WAR using JAX-RS, EJB3, JPA
There are no deployment errors in the logs. This is a very clean glassfish 3.1.1 install, with only this application deployed. This application works in Glassfish 3.0.1 I am getting the following exception when web service method is invoked.
EJB5070: Exception creating stateless session bean : [VehicleManagementService]|#]
Here is some info from the logs during deployment regarding the creation of the EJBs:
[#|2011-08-26T11:03:26.928-0500|INFO|glassfish3.1.1|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=23;_ThreadName=Thread-2;|Portable JNDI names for EJB VehicleAliases : [java:global/vehicle/VehicleAliases!com.realcomp.vehicle.ejb.VehicleAliases, java:global/vehicle/VehicleAliases]|#]
[#|2011-08-26T11:03:26.937-0500|INFO|glassfish3.1.1|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=23;_ThreadName=Thread-2;|Portable JNDI names for EJB VehicleManagementService : [java:global/vehicle/VehicleManagementService!com.realcomp.vehicle.web.service.VehicleManagementService, java:global/vehicle/VehicleManagementService]|#]
[#|2011-08-26T11:03:27.002-0500|INFO|glassfish3.1.1|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=23;_ThreadName=Thread-2;|Portable JNDI names for EJB VehicleManagementBean : [java:global/vehicle/VehicleManagementBean!com.realcomp.vehicle.ejb.VehicleManagementBean, java:global/vehicle/VehicleManagementBean!com.realcomp.vehicle.ejb.VehicleManagement]|#]
[#|2011-08-26T11:03:27.003-0500|INFO|glassfish3.1.1|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=23;_ThreadName=Thread-2;|Glassfish-specific (Non-portable) JNDI names for EJB VehicleManagementBean : [com.realcomp.vehicle.ejb.VehicleManagement, com.realcomp.vehicle.ejb.VehicleManagement#com.realcomp.vehicle.ejb.VehicleManagement]|#]
[#|2011-08-26T11:03:27.218-0500|INFO|glassfish3.1.1|org.hibernate.validator.engine.resolver.DefaultTraversableResolver|_ThreadID=23;_ThreadName=Thread-2;|Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.|#]
[#|2011-08-26T11:03:27.602-0500|INFO|glassfish3.1.1|javax.enterprise.resource.webcontainer.jsf.config|_ThreadID=23;_ThreadName=Thread-2;|Initializing Mojarra 2.1.3 (FCS b02) for context '/vehicle'|#]
[#|2011-08-26T11:03:27.660-0500|INFO|glassfish3.1.1|org.hibernate.validator.engine.resolver.DefaultTraversableResolver|_ThreadID=23;_ThreadName=Thread-2;|Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.|#]
[#|2011-08-26T11:03:27.771-0500|INFO|glassfish3.1.1|com.sun.jersey.api.core.WebAppResourceConfig|_ThreadID=23;_ThreadName=Thread-2;|Scanning for root resource and provider classes in the Web app resource paths:
/WEB-INF/lib
/WEB-INF/classes|#]
[#|2011-08-26T11:03:28.072-0500|INFO|glassfish3.1.1|com.sun.jersey.api.core.ScanningResourceConfig|_ThreadID=23;_ThreadName=Thread-2;|Root resource classes found:
class com.realcomp.vehicle.web.service.VehicleManagementService|#]
[#|2011-08-26T11:03:28.073-0500|INFO|glassfish3.1.1|com.sun.jersey.api.core.ScanningResourceConfig|_ThreadID=23;_ThreadName=Thread-2;|Provider classes found:
class org.codehaus.jackson.jaxrs.JsonMappingExceptionMapper
class com.realcomp.vehicle.web.service.NoResultMapper
class com.realcomp.vehicle.web.service.EntityNotFoundMapper
class org.codehaus.jackson.jaxrs.JacksonJsonProvider
class com.realcomp.vehicle.web.service.NonUniqueResultMapper
class org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider
class org.codehaus.jackson.jaxrs.JsonParseExceptionMapper|#]
[#|2011-08-26T11:03:28.078-0500|INFO|glassfish3.1.1|com.sun.jersey.server.impl.cdi.CDIComponentProviderFactoryInitializer|_ThreadID=23;_ThreadName=Thread-2;|CDI support is enabled|#]
[#|2011-08-26T11:03:28.079-0500|INFO|glassfish3.1.1|com.sun.jersey.server.impl.application.WebApplicationImpl|_ThreadID=23;_ThreadName=Thread-2;|Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:17 PM'|#]
[#|2011-08-26T11:03:28.172-0500|INFO|glassfish3.1.1|com.sun.jersey.server.impl.ejb.EJBComponentProviderFactory|_ThreadID=23;_ThreadName=Thread-2;|Binding the EJB class com.realcomp.vehicle.web.service.VehicleManagementService to EJBManagedComponentProvider|#]
Here is some of the VehicleManagementService:
#Stateless
#LocalBean
#Path("/")
#DeclareRoles({"production"})
public class VehicleManagementService implements Serializable{
private static final Logger logger = Logger.getLogger(VehicleManagementService.class.getName());
#Context
private UriInfo uriInfo;
#EJB
private VehicleManagementBean vehicles;
#EJB
private VehicleAliases aliases;
...
Here is full stack trace:
[#|2011-08-26T11:03:33.537-0500|SEVERE|glassfish3.1.1|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=27;_ThreadName=Thread-2;|EJB5070: Exception creating stateless session bean : [VehicleManagementService]|#]
[#|2011-08-26T11:03:33.538-0500|WARNING|glassfish3.1.1|javax.enterprise.system.container.ejb.com.sun.ejb.containers|_ThreadID=27;_ThreadName=Thread-2;|A system exception occurred during an invocation on EJB VehicleManagementService method public javax.ws.rs.core.Response com.realcomp.vehicle.web.service.VehicleManagementService.getVehicle(java.lang.String)
javax.ejb.EJBException: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:454)
at com.sun.ejb.containers.BaseContainer.getContext(BaseContainer.java:2528)
at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1895)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at $Proxy307.getVehicle(Unknown Source)
at com.realcomp.vehicle.web.service.__EJB31_Generated__VehicleManagementService__Intf____Bean__.getVehicle(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:327)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:679)
Caused by: javax.ejb.EJBException: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:726)
at com.sun.ejb.containers.util.pool.NonBlockingPool.getObject(NonBlockingPool.java:247)
at com.sun.ejb.containers.StatelessSessionContainer._getContext(StatelessSessionContainer.java:449)
... 53 more
Caused by: javax.ejb.CreateException: Could not create stateless EJB
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:534)
at com.sun.ejb.containers.StatelessSessionContainer.access$000(StatelessSessionContainer.java:95)
at com.sun.ejb.containers.StatelessSessionContainer$SessionContextFactory.create(StatelessSessionContainer.java:724)
... 55 more
Caused by: java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:796)
at org.jboss.weld.manager.BeanManagerImpl.getBean(BeanManagerImpl.java:1209)
at org.jboss.weld.manager.BeanManagerImpl.getBean(BeanManagerImpl.java:144)
at org.glassfish.weld.services.JCDIServiceImpl._createJCDIInjectionContext(JCDIServiceImpl.java:169)
at org.glassfish.weld.services.JCDIServiceImpl.createJCDIInjectionContext(JCDIServiceImpl.java:146)
at com.sun.ejb.containers.BaseContainer.createEjbInstanceAndContext(BaseContainer.java:1636)
at com.sun.ejb.containers.StatelessSessionContainer.createStatelessEJB(StatelessSessionContainer.java:475)
... 57 more
And here is getVehicle()
#GET
#Path("vin/{vin}")
#Produces(MediaType.APPLICATION_JSON)
#RolesAllowed("production")
public Response getVehicle(#PathParam("vin") String vin) {
Vehicle vehicle = vehicles.find(vin);
Response response = null;
if (vehicle == null)
response = Response.status(Status.NOT_FOUND).build();
else
response = Response.ok(vehicle).build();
return response;
}
The following changes fixed my problem. Unfortunately, I have changed too many things trying to fix this to be able to point to any one item.
I repackaged the application from WAR to EAR.
I changed the configuration of jersey from using the com.sun.jersey.spi.container.servlet.ServletContainer configuration in web.xml to a proper class that extends Application.
#ApplicationPath("/")
public class VehicleService extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> retVal = new HashSet<Class<?>>();
retVal.add(VehicleResource.class);
retVal.add(EntityNotFoundMapper.class);
retVal.add(NoResultMapper.class);
retVal.add(NonUniqueResultMapper.class);
return retVal;
}
#Override
public Set<Object> getSingletons() {
Set<Object> singletons = new HashSet<Object>();
singletons.add(new org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider());
return singletons;
}
Thanks to JamesBoyZ for the link to EJB 3.1 in war package in WEB-INF/classes - javax.ejb.CreateException: Could not create stateless EJB that got me going in the right direction.
In the 2nd line of the stack trace, I saw:
A system exception occurred during an invocation on EJB VehicleManagementService getVehicle(java.lang.String)
It seems there is a problem with your getVehicle method?
Double-check that there's a(n empty) beans.xml in your bundled project.