Generic R2DBC Custom Converter - postgresql

I am using postgres database with reactive repository and R2dbc and have more than 5 json fields.
R2dbc does not directly recognize the jsonb fields and hence cannot map it to java object.
So after following various docs - I came to know a solution - custom converters.
So, I created converters for all fields. However, then I saw that the code in all the converters were same - just the class mapped were different (POJOs).
Hence, I thought of creating a generic class for the converters.
However, Spring is not recognizing the generic class but works with a separate converter for all the fields.
I would like to add more json fields in future and do not want to create a separate converter class for each.
Please help me with this issue.
Entity Class:
#Data
#Table("person")
public class Person {
#Id
private Integer id;
private String uid;
private AddressInfo address;
...
}
Working custom converter for one of field:
#ReadingConverter
#Slf4j
public class JsonToAddressInfoConverter implements Converter<Json, AddressInfo> {
#Override
public AddressInfo convert(Json json) {
try {
ObjectMapper mapper = new ObjectMapper();
AddressInfo addressInfo = mapper.readValue(json.asString(), AddressInfo.class);
return addressInfo;
} catch (IOException e) {
log.error("Problem while parsing JSON: {}", json, e);
}
return new AddressInfo();
}
}
Generic converter that I am trying to create - (not working)
#ReadingConverter
#Slf4j
public class JsonToSimplePojoConverter<S, T> implements Converter<S, T> {
final Class<T> typeParameterClass;
public JsonToSimplePojoConverter(Class<T> typeParameterClass) {
super();
this.typeParameterClass = typeParameterClass;
}
#Override
public T convert(S json) {
T object = null;
try {
ObjectMapper mapper = new ObjectMapper();
object = mapper.readValue(((Json) json).asString(), typeParameterClass);
} catch (IOException e) {
log.error("Problem while parsing JSON: {}", json, e);
}
return object;
}
}
Configuration class where converter is registered:
#Configuration
public class ReactivePostgresConfig extends AbstractR2dbcConfiguration {
#Override
public ConnectionFactory connectionFactory() {
return null;
}
#Bean
#Override
public R2dbcCustomConversions r2dbcCustomConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
// converters.add(new JsonToAddressInfoConverter());
converters.add(new JsonToSimplePojoConverter< Json, AddressInfo >( AddressInfo.class));
return R2dbcCustomConversions.of(PostgresDialect.INSTANCE, converters);
}
}
Error that I am getting on app initialization:
Caused by: java.lang.IllegalStateException: Couldn't resolve type arguments for class com.kredx.service.converters.JsonToSimplePojoConverter
at org.springframework.data.convert.CustomConversions$StoreConversions.getRegistrationFor(CustomConversions.java:805) ~[spring-data-commons-2.7.2.jar:2.7.2]
at org.springframework.data.convert.CustomConversions$StoreConversions.getRegistrationsFor(CustomConversions.java:787) ~[spring-data-commons-2.7.2.jar:2.7.2]
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197) ~[na:na]
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) ~[na:na]
at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150) ~[na:na]
at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596) ~[na:na]
at org.springframework.data.convert.CustomConversions.collectPotentialConverterRegistrations(CustomConversions.java:201) ~[spring-data-commons-2.7.2.jar:2.7.2]
at org.springframework.data.convert.CustomConversions.<init>(CustomConversions.java:112) ~[spring-data-commons-2.7.2.jar:2.7.2]
at org.springframework.data.r2dbc.convert.R2dbcCustomConversions.<init>(R2dbcCustomConversions.java:60) ~[spring-data-r2dbc-1.5.2.jar:1.5.2]
at org.springframework.data.r2dbc.convert.R2dbcCustomConversions.of(R2dbcCustomConversions.java:88) ~[spring-data-r2dbc-1.5.2.jar:1.5.2]
at com.kredx.service.config.ReactivePostgresConfig.r2dbcCustomConversions(ReactivePostgresConfig.java:39) ~[classes/:na]
at com.kredx.service.config.ReactivePostgresConfig$$EnhancerBySpringCGLIB$$b372d1fb.CGLIB$r2dbcCustomConversions$1(<generated>) ~[classes/:na]
at com.kredx.service.config.ReactivePostgresConfig$$EnhancerBySpringCGLIB$$b372d1fb$$FastClassBySpringCGLIB$$2d0d2d10.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.22.jar:5.3.22]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.22.jar:5.3.22]
at com.kredx.service.config.ReactivePostgresConfig$$EnhancerBySpringCGLIB$$b372d1fb.r2dbcCustomConversions(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.22.jar:5.3.22]
... 114 common frames omitted
I am using Spring reactive + r2dbc + postgressql
Any Help is appreciated.

Related

Use real instances in tests with webflux

Hi I try to create a tests for my projeto use only real instances but I getting a follow error:
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:43)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$8(ClassBasedTestDescriptor.java:363)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:368)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$9(ClassBasedTestDescriptor.java:363)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:362)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:283)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:282)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:272)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:271)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:102)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:101)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
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:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
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 jdk.proxy2/jdk.proxy2.$Proxy5.stop(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userQueryService': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.study.reactivecalendar.domain.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
at app//org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953)
at app//org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
at app//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
at app//org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740)
at app//org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415)
at app//org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at app//org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:136)
at app//org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at app//org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
... 86 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.study.reactivecalendar.domain.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1799)
at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1355)
at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309)
at app//org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
... 104 more
I know this error is because my test configuration not solved my repository. I want to use web client to ping in my controller
#ActiveProfiles("test")
#ContextConfiguration(classes = {ReactiveCalendarApplication.class, UserMapperImpl.class, UserQueryService.class,
UserService.class, UserRepository.class})
#WebFluxTest({UserController.class, UserRepository.class})
#AutoConfigureDataMongo
#EnableReactiveMongoRepositories
#ExtendWith(SpringExtension.class)
#EnableAutoConfiguration
public class UserControllerInsertTest {
#Autowired
private UserRepository userRepository;
#Autowired
private ApplicationContext applicationContext;
private RequestBuilder<UserSingleResponse> requestBuilder; // this class I create to build requests using WebTestClient
#BeforeEach
void setup(){
requestBuilder = userResponseRequestBuilder(applicationContext, "/users");
}
#Test
void saveTest(){
var request = UserRequestFactoryBot.builder().build();
requestBuilder.withUri(UriBuilder::build)
.withBody(request)
.generateRequestWithSimpleBody()
.doPost()
.isHttpStatusIsCreated()
.assertBody(response -> {
assertThat(response).isNotNull();
assertThat(response).hasNoNullFieldsOrProperties();
assertThat(response.getId()).containsPattern(MONGOID_REGEX);
assertThat(response.getName()).isEqualTo(request.getName());
assertThat(response.getEmail()).isEqualTo(request.getEmail());
});
}
}
to explain about my dependencies:
UserController (#Controller) needs UserMapper, UserService and UserQuery service.
UserService (#Service) needs UserMapper, UserQueryService and UserRepository.
UserQueryService (#Service) needs UserRepository.
UserRepository (#Repository) needs nothing and extends ReactiveMongoRepository
UserMapper needs noting, it is a interface used by mapstruct.
How can I configure my test to solve all dependencies and use all real instances in my test in SpringWebFlux
I solved my problem, follow my configurations:
My test class to verify controller I use a follow annotations
#ActiveProfiles("test")
#ContextConfiguration(classes = {ReactiveCalendarApplication.class, UserMapperImpl.class, UserQueryService.class,
UserService.class, UserRepository.class, EmbeddedMongoDbConfig.class})
#WebFluxTest({UserController.class, UserRepository.class})
#AutoConfigureDataMongo
#ExtendWith({SpringExtension.class})
public class UserControllerDeleteTest {
// my test code
}
My Database Embedded configuration:
#Slf4j
#TestConfiguration
#EnableReactiveMongoRepositories(basePackageClasses = UserRepository.class)
#AllArgsConstructor
public class EmbeddedMongoDbConfig extends AbstractReactiveMongoConfiguration {
private final Environment environment;
#Bean
public MongoClient mongoClient() {
return MongoClients.create();
}
#Override
protected String getDatabaseName() {
return "test";
}
#Bean
ReactiveMongoTemplate reactiveMongoTemplate() {
return new ReactiveMongoTemplate(mongoClient(), getDatabaseName());
}
//optinal configuration, I use because I have custom converters
//for to use OffsetDateTime in my project
#Override
public MongoCustomConversions customConversions() {
List<Converter<? ,?>> converters = new ArrayList<>();
converters.add(new DateToOffsetDateTimeConverter());
converters.add(new OffsetDateTimeToDateConverter());
return new MongoCustomConversions(converters);
}
#Bean
DateTimeProvider dateTimeProvider(){
return new OffsetDateTimeProvider();
}
}
and My application-test.yml
spring:
mongodb:
embedded:
version: 4.0.12
data:
mongodb:
port: 27017
host: localhost
database: test

Spring-batch exception: org.springframework.batch.core.launch.NoSuchJobException: No job configuration with the name [] was registered

I am seeing this exception when stopping a running job using jobOperator.stop(id) or when I want to restart it using jobOperator.restart(id).
I don't have any idea why the MapJobRegistry is empty ... Am I missing a step ?
I have reproduced the problem using the complete example from https://github.com/spring-guides/gs-batch-processing.git
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
// end::setup[]
#Autowired
JobRepository jobRepository;
// tag::readerwriterprocessor[]
#Bean
public FlatFileItemReader<Person> reader() {
return new FlatFileItemReaderBuilder<Person>()
.name("personItemReader")
.resource(new ClassPathResource("sample-data.csv"))
.delimited()
.names(new String[]{"firstName", "lastName"})
.fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
setTargetType(Person.class);
}})
.build();
}
#Bean
public PersonItemProcessor processor() {
return new PersonItemProcessor();
}
#Bean
public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Person>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
.dataSource(dataSource)
.build();
}
// end::readerwriterprocessor[]
// tag::jobstep[]
#Bean
public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
#Bean
public Step step1(JdbcBatchItemWriter<Person> writer) {
return stepBuilderFactory.get("step1")
.<Person, Person> chunk(10)
.reader(reader())
.processor(processor())
.writer(writer)
.build();
}
// end::jobstep[]
#Bean
public JobLauncher simpleJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
}
The rest controller
#RestController
public class BatchController {
Logger logger = LoggerFactory.getLogger(BatchController.class);
#Autowired
JobLauncher simpleJobLauncher;
#Autowired
Job importUserJob;
#Autowired
JobOperator jobOperator;
#RequestMapping("/startNewJob")
public String handle() {
try {
JobParameters jobParameters = new JobParametersBuilder().addLong("time", System.currentTimeMillis())
.toJobParameters();
JobExecution jobExecution = simpleJobLauncher.run(importUserJob, jobParameters);
return jobExecution.toString();
} catch (Exception e) {
logger.info(e.getMessage());
return ("An error has occured, please check the logs");
}
}
#RequestMapping("/stopJob/{id}")
public Boolean stopJob(#PathVariable Long id) throws Exception {
logger.info("stopJob "+id);
return jobOperator.stop(id);
}
#RequestMapping("/restartJob/{id}")
public Long restartJob(#PathVariable Long id) throws Exception {
logger.info("restartJob "+id);
return jobOperator.restart(id);
}
}
Stacktrace while restarting the job
2020-11-12 21:47:16.452 ERROR 26252 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.batch.core.launch.NoSuchJobException: No job configuration with the name [importUserJob] was registered] with root cause
org.springframework.batch.core.launch.NoSuchJobException: No job configuration with the name [importUserJob] was registered
at org.springframework.batch.core.configuration.support.MapJobRegistry.getJob(MapJobRegistry.java:68) ~[spring-batch-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at com.sun.proxy.$Proxy68.getJob(Unknown Source) ~[na:na]
at org.springframework.batch.core.launch.support.SimpleJobOperator.restart(SimpleJobOperator.java:275) ~[spring-batch-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobOperator$$FastClassBySpringCGLIB$$44ee6049.invoke() ~[spring-batch-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685) ~[spring-aop-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.batch.core.launch.support.SimpleJobOperator$$EnhancerBySpringCGLIB$$853e8727.restart() ~[spring-batch-core-4.2.1.RELEASE.jar:4.2.1.RELEASE]
at com.example.batchprocessing.BatchController.restartJob(BatchController.java:60) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_92]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_92]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_92]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_92]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
The JobOperator requires a JobLocator to locate jobs to restart, stop, etc. This JobLocator (typically a MapJobRegistry) should be populated with known jobs, and this should be done either manually or by adding a JobRegistryBeanPostProcessor to the application context.
This is explained in the reference documentation here: JobRegistry.
I simply added a JobRegistryBeanPostProcessor and set it the jobRegistry.
#Autowired
JobRegistry jobRegistry;
#Bean
public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor() {
JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcessor();
postProcessor.setJobRegistry(jobRegistry);
return postProcessor;
}
You can also trigger job using jobLauncher. Here is a blog explaining it.
In short you can refer to this code.
#Component
public class JobScheduler
{
#Autowired
JobLauncher jobLauncher;
#Qualifier("jobBeanName") // if you have multiple jobs
#Autowired
Job job;
#Scheduled(cron = "* * * * * *")
public void runJob() {
jobLauncher.run(job, new JobParameters());
}
}

javax.ejb.EJBException java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName

I'm working on a JavaEE application with EJB.
I have an Entity called Medico which code is:
#Entity
public class Medico implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public Medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) { //construtor parametrico
super();
this.nome_medico = nome_medico;
this.morada_medico = morada_medico;
this.esp = esp;
this.dnasc_medico = dnasc_medico;
this.tel_medico = tel_medico;
}
#Id
#GeneratedValue
private int cod_medico; //bi
private String nome_medico;
private String morada_medico;
private String esp;
#Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_medico;
private int tel_medico;
private ArrayList<GregorianCalendar> agenda_consultas;
private ArrayList<GregorianCalendar> agenda_atos;
private int total_atos;
private int total_presc;
public int getTotal_presc() {
return total_presc;
}
public void setTotal_presc(int total_presc) {
this.total_presc = total_presc;
}
public Medico(){ //construtor vazio
super();
}
public int getTotal_atos() {
return total_atos;
}
public void setTotal_atos(int total_atos) {
this.total_atos = total_atos;
}
public ArrayList<GregorianCalendar> getAgenda_consultas() {
return agenda_consultas;
}
public void setAgenda_consultas(ArrayList<GregorianCalendar> agenda_consultas) {
this.agenda_consultas = agenda_consultas;
}
public ArrayList<GregorianCalendar> getAgenda_atos() {
return agenda_atos;
}
public void setAgenda_atos(ArrayList<GregorianCalendar> agenda_atos) {
this.agenda_atos = agenda_atos;
}
public int getCod_medico() {
return cod_medico;
}
public void setCod_medico(int cod_medico) {
this.cod_medico = cod_medico;
}
public String getNome_medico() {
return nome_medico;
}
public void setNome_medico(String nome_medico) {
this.nome_medico = nome_medico;
}
public String getMorada_medico() {
return morada_medico;
}
public void setMorada_medico(String morada_medico) {
this.morada_medico = morada_medico;
}
public String getEsp() {
return esp;
}
public void setEsp(String esp) {
this.esp = esp;
}
public GregorianCalendar getDnasc_medico() {
return dnasc_medico;
}
public void setDnasc_medico(GregorianCalendar dnasc_medico) {
this.dnasc_medico = dnasc_medico;
}
public int getTel_medico() {
return tel_medico;
}
public void setTel_medico(int tel_medico) {
this.tel_medico = tel_medico;
}
#Override
public String toString() {
return "Medico [cod_medico=" + cod_medico + ", nome_medico="
+ nome_medico + ", morada_medico=" + morada_medico + ", esp="
+ esp + ", dnasc_medico=" + dnasc_medico + ", tel_medico="
+ tel_medico + "]";
}
}
Then I created a session bean implementation class:
#Stateless
public class HospitalManagement implements AdministradorSessionRemote,GestorSessionRemote {
/**
* Default constructor.
*/
#PersistenceContext(unitName="Hospital")
private EntityManager em;
public HospitalManagement() {
// TODO Auto-generated constructor stub
}
#Override
public String cria_medico(String nome_medico, String morada_medico,
String esp, GregorianCalendar dnasc_medico, int tel_medico) {
Medico md = new Medico (nome_medico, morada_medico, esp, dnasc_medico,tel_medico);
em.persist(md);
return "Medico "+Integer.toString(md.getCod_medico())+" criado!";
}
This class implements two interfaces, but the method above is only used in the following one:
#Remote
public interface GestorSessionRemote {
public String cria_medico(String nome_medico,String morada_medico,String esp,GregorianCalendar dnasc_medico, int tel_medico);
public String procura_nome_medico(String nome);
public String procura_cod_medico(int cod);
public String altera_morada_med(int cod, String morada);
public String altera_telemovel_med(int cod, int tel);
Then I created a client:
public class GestorClient {
public static void main(String[] args){
InitialContext ctx =new InitialContext();
GestorSessionRemote g=(GestorSessionRemote)ctx.lookup("java:global/HospitalEAR/Hospital/HospitalManagement!Sessions.GestorSessionRemote");
System.out.println(g.cria_medico(nomem, moradam, esp,cal,telm));
where the parameters of the method are obtained by scannig from the keyboard.
I've also created the following persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Hospital">
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
When I try to deploy the application, an error occurs. Here is the complete stacktrace:
Exception in thread "main" javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:698)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy236.cria_medico(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName Hospital
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.init(EntityManagerWrapper.java:138)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:158)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:151)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:281)
at Sessions.HospitalManagement.cria_medico(HospitalManagement.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:55)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Could someone help me understand the reason why this is happening?
The obvious problem is that you didn't specify a jta-data-source and the transaction-type in your persistence.xml.
A jta-data-source is specified like this:
<persistence-unit name="Hospital">
<jta-data-source>jdbc/sample</jta-data-source>
</persistence-unit>
You have to create the JDBC resource in your Glassfish instance. To do this open the Glassfish Admin GUI under http://localhost:4848 and create a Connection Pool under Resources -> JDBC Connection Pools. Then create a JDBC resource under Resources -> JDBC Resources named jdbc/sample and make it reference the new connection pool.
Further, it looks like the server somehow thinks that you want to use transaction-type RESOURCE_LOCAL which requires that you specify an EntityManagerFactory to get an instance of the EntityManager.
JTA should be the default transaction-type in a Java EE environment but you may have to explicitly specifiy the transaction-type in the persistence.xml like this:
<persistence-unit name="Hospital" transaction-type="JTA">
See also:
persistence.xml different transaction-type attributes

CORBA exception in EJB application

I've got a problem with EJB/Glassfish. I'm working on a client-server application in which the client creates an entity object and must send it to the server application, which must persist the entity in its database. I've choose to use session beans to communicate with the server.
I've implemented some simple cases in which a method in the session bean takes as input a string or an int and it works fine. The problem arises when I try to give an entity object as input.
I report my entity class:
#Entity
public class Example implements Serializable {
private static final long serialVersionUID = 1L;
#Id
String nome;
public void setNome(String nome) {
this.nome = nome;
}
public String getNome() {
return nome;
}
Here my session bean:
#Stateless
public class GestoreLibreriaRemoto implements GestoreLibreriaRemotoRemote {
#Override
public String getProva(Example prova) {
return prova.getNome();
}
Here my client application:
public class GestoreLibreriaLocale {
public static void assegnaCategoriaACopia(CopiaUtente copia, Categoria categoria) throws
public void prova() {
GestoreLibreriaRemotoRemote gestore = lookupGestoreLibreriaRemotoRemote();
Example example = new Example();
prova.setNome("hodor");
System.out.println(gestore.getProva(example));
}
private GestoreLibreriaRemotoRemote lookupGestoreLibreriaRemotoRemote() {
try {
Context c = new InitialContext();
return (GestoreLibreriaRemotoRemote) c.lookup("java:global/ServerMDB/ServerMDB-ejb/GestoreLibreriaRemoto");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
In my main class I simply call GestoreLibreriaLocale.prova() and i get the following error:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException: java.rmi.MarshalException: CORBA MARSHAL 1330446346 Maybe; nested exception is:
org.omg.CORBA.MARSHAL: ----------BEGIN server-side stack trace----------
org.omg.CORBA.MARSHAL: AVVERTENZA: 00810010: Error from readValue on ValueHandler in CDRInputStream vmcid: OMG minor code: 10 completed: Maybe
at com.sun.proxy.$Proxy139.valuehandlerReadError(Unknown Source)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:912)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.read_value(CDRInputStream_1_0.java:1005)
at com.sun.corba.ee.impl.encoding.CDRInputObject.read_value(CDRInputObject.java:518)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl$14.read(DynamicMethodMarshallerImpl.java:383)
at com.sun.corba.ee.impl.presentation.rmi.DynamicMethodMarshallerImpl.readArguments(DynamicMethodMarshallerImpl.java:450)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:171)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.corba.ee.impl.io.IIOPInputStream
at com.sun.corba.ee.impl.io.ValueHandlerImpl.createInputStream(ValueHandlerImpl.java:820)
at com.sun.corba.ee.impl.io.ValueHandlerImpl.readValue(ValueHandlerImpl.java:263)
at com.sun.corba.ee.impl.encoding.CDRInputStream_1_0.readRMIIIOPValueType(CDRInputStream_1_0.java:903)
... 16 more
The error log continues, I don't report the whole log but if you need it I can post it.
Please help me, I'm working on it from days without resolving it.
Thanks for the attention,
Francesco
This seems to be a bug in the current Java versions (e.g. 1.7.0_55 and 1.8.0_05), have a look at this issue: GLASSFISH-21047
To make it work, install either an older or a newer Java version (e.g. 1.7.0_051 or 1.8.0_020).
See also:
Exception inside CORBA when accessing a remote bean

Static method call from Eclipse Plugin: InjectionException

I have 2 plugin projects - generator.ui and generator.core.
The generator.ui depends on generator.core plugin for processes and data manipulation. However wherever there is an API call on generator.core (through static method invocation), I get an exception mentioned below:
org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: de/upb/crc901/serge/generator/Generator
at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:63)
at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:243)
at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:224)
at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:132)
at org.eclipse.e4.core.commands.internal.HandlerServiceHandler.execute(HandlerServiceHandler.java:167)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:213)
at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:850).........
Caused by: java.lang.ClassNotFoundException: de.upb.crc901.serge.generator.Generator cannot be found by de.upb.crc901.serge.ui_1.0.0.qualifier
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:501)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:421)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:412)
at org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader.loadClass(DefaultClassLoader.java:107)
at java.lang.ClassLoader.loadClass(Unknown Source)
Now this NoClassDefFoundError always comes for the class which contains static method for object creation as the design pattern followed is "Singleton".
Any help would be greatly appreciated.
Here is the code, From the UI plugin; the configuration hub class:
public class ConfigurationHub implements IConfigurationHub {
private IGenerator generator;
private static IConfigurationHub configurationHub;
/*
* Constructor private to make Singleton
*/
private ConfigurationHub() {
generator = GeneratorFactory.createGenerator(Generator.class);
}
public static synchronized IConfigurationHub getInstance() {
if(null == configurationHub) {
configurationHub = new ConfigurationHub();
}
return configurationHub;
}
}
The GeneratorFactory class is in Generator plugin:
public class GeneratorFactory {
private GeneratorFactory() {}
public static <T extends IGenerator> T createGenerator(Class<T> type) {
try {
return (T) type.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
Regards,
Sid