Spring boot does not start when secondary datasource database connection unavailable - java

Caused by: java.lang.NullPointerException
at org.springframework.boot.actuate.endpoint.DataSourcePublicMetrics.initialize(DataSourcePublicMetrics.java:64) ~[spring-boot-actuator-1.3.2.RELEASE.jar:1.3.2.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_79]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_79]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:354) ~[spring-beans-4.2.4.RELEASE.jar:4.2.4.RELEASE]
I disabled the metrics too but no luck
endpoints.enabled=false
endpoints.autoconfig.enabled=false
endpoints.metrics.enabled=false
The DataSourcePublicMetrics bean always gets created, even when the metrics are disabled. This causes a NullPointerException when the database connection is unavailable, causing spring boot not to start.

I am using Hikari datasource and it fails to construct data source object when database is unavailable. Hence NPE from DataSourcePublicMetrics bean. I am able to circumvent the issue creating a Hikari data source that is lazy initialized with database config even when database is unavailable for later use when database becomes available. Not sure why HikariDataSource does not have a constructor for lazy init. It does have a default constructor but database config can't be set using any setter method. This is useful for applications where database is not always necessary to start them up.
public class LazyConnectionDataSource extends HikariDataSource {
public LazyConnectionDataSource(HikariConfig config) {
config.validate();
config.copyState(this);
}
}

Related

NullPointerException during bean creation in Spring

I'm receiving a NullPointerException in a method with the Annotation #Bean, but before I never got this NullPointerException there:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [dev.teamnight.command.CommandFramework]: Circular reference involving containing bean 'config' - consider declaring the factory method as static for independence from its containing instance. Factory method 'commandFramework' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
... 68 common frames omitted
Caused by: java.lang.NullPointerException: null
at dev.teamnight.nightbot.Config.commandFramework(Config.java:84) ~[classes/:na]
at dev.teamnight.nightbot.Config$$EnhancerBySpringCGLIB$$2d4937ec.CGLIB$commandFramework$3(<generated>) ~[classes/:na]
at dev.teamnight.nightbot.Config$$EnhancerBySpringCGLIB$$2d4937ec$$FastClassBySpringCGLIB$$3fbdfefd.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at dev.teamnight.nightbot.Config$$EnhancerBySpringCGLIB$$2d4937ec.commandFramework(<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:62) ~[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:566) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
... 69 common frames omitted
The code of the file causing the Exception:
#Configuration
#PropertySource("file:bot.properties")
public class Config {
#Autowired
private ShardManager shardManager;
#Autowired
private PermissionProvider permissionProvider;
#Autowired
private LanguageProvider languageProvider;
#Autowired
private PrefixProvider prefixProvider;
#Autowired
private HelpProvider helpProvider;
#Bean
public ShardManager shardManager() throws LoginException, IllegalArgumentException {
DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.createDefault(this.botToken)
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.setMemberCachePolicy(MemberCachePolicy.ALL)
.setStatus(OnlineStatus.IDLE)
.setShardsTotal(this.totalShards)
.addEventListeners(Arrays.asList(this.jdaListener()));
return builder.build();
}
#Bean
public CommandFramework commandFramework() {
Logger log = LogManager.getLogger();
//Line causing the error below!
log.error("Name of helpProvider: " + this.helpProvider.getClass().getCanonicalName());
return new FrameworkBuilder()
.addOwners(Arrays.stream(this.ownerIds).filter(ownerId -> ownerId.matches("^(\\d)+$")).map(ownerId -> Long.parseLong(ownerId)).collect(Collectors.toList()))
.setLogger(NightBot.logger())
.allowBots(false)
.allowDM(false)
.allowMention(true)
.allowRainbowColors(true)
.withPrefixProvider(this.prefixProvider)
.withLanguageProvider(this.languageProvider)
.withPermissionProvider(this.permissionProvider)
.withHelpProvider(this.helpProvider)
.withCustomArgumentProcessor(new NamedArgumentProcessor())
.registerClient(this.shardManager)
.build();
}
}
As I said, before the code fully worked, and I changed nothing on the Config.java file, so this error is confusing me as hell.
You are seeing this NullPointerException because the autowired HelperProvider not being injected in.
You are attempting to call .getClass() on a null object.
General Dependency Injection Debugging
Just want to add a quick basic mentions, since the main answer to this question has to make some assumption on your codebase. There are several things that you want to check when dependency injection fails.
Configuration files - Are these being loaded in correctly. Is your component scanning recently disabled?
Do your Components have the necessary #Component and or #Service/#Controller/#Repository annotations?
The Likely Root Problem - Circular Reference - BeanInstantiationException
There is also a mention of a circular reference in your stacktrace which is likely what is causing the problem.
Caused by: org.springframework.beans.BeanInstantiationException: Circular reference involving containing bean 'config' - consider declaring the factory method as static for independence from its containing instance. Factory method 'commandFramework' threw exception; nested exception is java.lang.NullPointerException
Since you received this error message, you have introduced a circular reference. This means... that a component relies on a component which relies on that component.
For example:
#Component
class HelperProvider {
#Autowired
Config config;
}
and
#Configuration
class Config {
#Autowired
HelperProvider helperProvider
}
This pattern will stump the spring framework because they rely on each other to load each component up. It can happen if you introduce a dependency further down the line. Say HelperProvider requires HelperHelperProvider which requires Config.
You will want to check for any new injections of Config or CommandFramework in your recent edits.
What you should do
You will want to redesign your configuration to break it's reliance on the HelperProvider. Doing this can resolve a lot of headaches in your future.
What you shouldn't do
It's possible to lazyload the component or configuration with #Lazy annotation. That way the bean is only instantiated upon invocation. It's recommended if you want to learn more nuances in booting up the Spring ApplicationContext, but it will become a nightmare to maintain down the road.
The error you are getting is most probably because you have a cyclic dependency in your project. And since you are getting it in commandFramework method as illustrated in error it is because of the HelpProvider class in which you are using the Config class again.
So when spring is creating a bean of Config it has to create a bean of HelpProvider which in terms wants to create a bean of Config(Autowired in HelpProvider) and leads to a never ending cycle giving the error. Also check if HelpProvider has the #component annotataion.
Config -> HelpProvider -> Config -> HelpProvider -> Config .............
Solution:-
Either you can remove the config from the HelpProvider and try to redesign it.
Use #Lazy on Config in HelpProvider which will load this dependency on object instantiation. Will suggest it as a last resort.

Specifying cursor options when returning a Stream in Spring Data MongoDB?

I'm using Spring Data MongoDB (spring-boot-starter-data-mongodb from Spring Boot 1.5.2.RELEASE) and MongoDB 3.4.9 and have defined a repository defined that looks like this:
interface MyMongoDBRepository extends CrudRepository<MyDTO, String> {
Stream<MyDTO> findAllByCategory(String category);
}
I then have a service, MyService that interacts with this repository:
#Service
class MyService {
#Autowired
MyMongoDBRepository repo;
public void doStuff() {
repo.findAllByCategory("category")
.map(..)
.filter(..)
.forEach(..)
}
}
There's quite a lot of data in the database and sometimes this error occur:
2018-01-01 18:16:56.631 ERROR 1 --- [ask-scheduler-6] o.s.integration.handler.LoggingHandler : org.springframework.dao.DataAccessResourceFailureException:
Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>;
nested exception is com.mongodb.MongoCursorNotFoundException:
Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:77)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135)
at org.springframework.data.mongodb.core.MongoTemplate.access$1100(MongoTemplate.java:147)
at org.springframework.data.mongodb.core.MongoTemplate$CloseableIterableCursorAdapter.hasNext(MongoTemplate.java:2506)
at java.util.Iterator.forEachRemaining(Iterator.java:115)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at com.mycompany.MyService.doStuff(MyService.java:108)
at com.mycompany.AnotherService.doStuff(AnotherService.java:42)
at sun.reflect.GeneratedMethodAccessor2026.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748) Caused by: com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>
at com.mongodb.operation.QueryHelper.translateCommandException(QueryHelper.java:27)
at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:213)
at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:103)
at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
at com.mongodb.DBCursor.hasNext(DBCursor.java:145)
at org.springframework.data.mongodb.core.MongoTemplate$CloseableIterableCursorAdapter.hasNext(MongoTemplate.java:2504) ... 24 more
I've read at various places that when using the vanilla MongoDB Java client you can configure the MongoDB cursor to either have no timeout or set a batch size to hopefully mitigate this.
If this is the way to go, then how can I supply cursor options when returning a Stream from Spring Data MongoDB?
Your error is occurring because you are processing the stream too slowly, so the cursor is timing out before you get to the next batch.
Batch size can be set on the Spring Data Query object, or on a Repository using the #Meta annotation. For example:
Query query = query(where("firstname").is("luke"))
.batchSize(100);
Or when using repositories:
#Meta(batchSize = 100)
List<Person> findByFirstname(String firstname);
See Spring Data MongoDB documentation for more details.
The cursor timeout can also be disabled on a per query basis using the same configuration. e.g. #Meta(flags = {CursorOption.NO_TIMEOUT}).
The cursor timeout cannot be changed on a per-query basis. That is a server configuration. You need to use the cursorTimeoutMillis server parameter to change that server-wide.
Regarding the two options you mentioned.
Batch size, You cannot set batch size using Repository class. You can do it using MongoTemplate. Something like this
final DBCursor cursor = mongoTemplate
.getCollection(collectionName)
.find(queryBuilder.get(), projection)
.batchSize(readBatchSize);
while (cursor.hasNext()) {
......
......
}
But to use MongoTemplate you need to create a Custom Repository.
Regarding Cursor timeout. You can do something like this
#Configuration
public class MongoDbSettings {
#Bean
public MongoClientOptions setmongoOptions() {
return MongoClientOptions.builder().socketTimeout(5000).build();
}
}
There are many other options(heartbeat, connectiontimeout) you can set for Mongo. You can set those properties in your application.properties file, and then bind it using #Value in the above class and set(instead of hardcoding).
Unfortunately, spring-boot doesn't provide any way to specify these in application.properties file
You don't need to supply cursor options when returning a Stream from Spring Data MongoDB. The possible reason for this exception is how your service read data from Mongo. Possible reasons:
You are sharing a single cursor across multiple threads
You are requested too many elements at once
Load balancer before Mongo server
See this Jira topic's comments for some ideas an direction applicable to your application.

ClassFormatError: Duplicate method name&signature from EnhancerBySpringCGLIB

I"m really stumped here. I've upgraded our Spring libraries from 4.0.6 to 4.3.2. One of our tests fail when running with 4.3.2. This is the code in question:
#Bean(name = SCHEDULER_FACTORY)
public SchedulerFactoryBean getSchedulerFactory()
{
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setConfigLocation(schedulerConfig);
schedulerFactory.setResourceLoader(null);
schedulerFactory.setDataSource(dataSource);
schedulerFactory.setJobFactory(getSchedulerJobFactory());
schedulerFactory.setAutoStartup(false);
return schedulerFactory;
}
#Bean(name = SCHEDULER)
public Scheduler getScheduler()
{
return getSchedulerFactory().getScheduler();
}
I'm getting the error java.lang.ClassFormatError: Duplicate method name&signature in class file org/springframework/scheduling/quartz/SchedulerFactoryBean$$EnhancerBySpringCGLIB$$bee87fe8$$EnhancerBySpringCGLIB$$6bb26669.
Running the test using spring 4.0.6 framework works perfectly fine, but with 4.3.2, it's failing. When using 4.0.6, I was using cglib no dependencies library. With 4.3.2, the tests fail regardless of whether or not I use cglib.
Spring embeds cglib and objensis into 4.3.* core library. "Furthermore, Spring Framework 4.3 embeds the updated ASM 5.1, CGLIB 3.2.4, and Objenesis 2.4 in spring-core.jar." SpringDocs
We were using Java 8 and cglib-no-dep 2.2 with Spring framework 4.0.6. We tried running this code with and without the standalone library and see the same results.
Stack trace:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.quartz.Scheduler]: Factory method 'getScheduler' threw exception; nested exception is org.springframework.cglib.core.CodeGenerationException:java.lang.reflect.InvocationTargetException >null
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver$3.run(ConstructorResolver.java:582)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
... 112 more
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException >null
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
at org.springframework.cglib.proxy.Enhancer.generate(Enhancer.java:492)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 188.486 sec
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:337)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.enhanceFactoryBean(ConfigurationClassEnhancer.java:452)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:338)
at com.example.SpringConfiguration$$EnhancerBySpringCGLIB$$54d3cb35.getSchedulerFactory(<generated>)
at com.example.SpringConfiguration.getScheduler(SpringConfiguration.java:242)
at com.example.SpringConfiguration$$EnhancerBySpringCGLIB$$54d3cb35.CGLIB$getScheduler$24(<generated>)
at com.example.SpringConfiguration$$EnhancerBySpringCGLIB$$54d3cb35$$FastClassBySpringCGLIB$$a2a6e004.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
at com.example.SpringConfiguration$$EnhancerBySpringCGLIB$$54d3cb35.getScheduler(<generated>)
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:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 115 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor26.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:413)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
... 140 more
Caused by: java.lang.ClassFormatError: Duplicate method name&signature in class file org/springframework/scheduling/quartz/SchedulerFactoryBean$$EnhancerBySpringCGLIB$$bee87fe8$$EnhancerBySpringCGLIB$$6bb26669
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
... 145 more
This is definetly a bug in cglib. It seems like it does not currectly determines a method in the type hierarchy to be equal to another method. Are you using Java 8 in combination with default methods in interfaces?
Cglib is not really tested for modern Java versions and experiences only little maintenance. Newer features sometimes cause trouble when using the library.

Getting exception while refreshing Spring ApplicationContext in Spring Boot application

We are using Spring Boot for our application.
After starting the application, in the runtime we are adding(loading) a new Bean to the existing Applicationcontext.
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.register(NewBean.class);
appContext.refresh();
after adding the bean we are doing a refresh of applicationContext
During the refresh the MBean is trying to reregister some endpoints and we are getting the following error
(getting error for all these endpoints - requestMappingEndpoint, environmentEndpoint, healthEndpoint, beansEndpoint, infoEndpoint, metricsEndpoint, traceEndpoint, dumpEndpoint,
autoConfigurationAuditEndpoint, shutdownEndpoint, configurationPropertiesReportEndpoint)
Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint
at com.sun.jmx.mbeanserver.Repository.addMBean(Unknown Source)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(Unknown Source)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(Unknown Source)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(Unknown Source)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(Unknown Source)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(Unknown Source)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:662)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:605)
Can anyone please tell how to skip this exception?
I have tried the following too
#EnableIntegrationMBeanExport(registration = RegistrationPolicy.REPLACE_EXISTING)
but getting the below exception
Caused by: org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.springframework.integration.monitor.IntegrationMBeanExporter#16c5464] with key 'integrationMbeanExporter'; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.integration.monitor:name=integrationMbeanExporter,type=IntegrationMBeanExporter
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:609)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:534)
at org.springframework.jmx.export.MBeanExporter.afterPropertiesSet(MBeanExporter.java:416)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 22 more
Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.integration.monitor:name=integrationMbeanExporter,type=IntegrationMBeanExporter
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:662)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:599)
... 26 more
Before you call refresh on an existing ApplicationContext, you should first destroy it else beans keep running.
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext();
appContext.register(NewBean.class);
appContext.refresh();
What you show here is that you are constructing a new context instead of reusing an existing one. The register method is also intended for #Configuration classes not arbitrary beans. If you want to add those just use one of the methods on the ApplicationContext like, registerSingleton. But in general adding beans at runtime should be a bad thing (imho).
Some applicationContext can refresh times, but not AnnotationConfigApplicationContext.
when you construct AnnotationConfigApplicationContext, which had run the refresh method, so it will be reported exception, you can destroy it first, and then refresh

problem with using JPA

I am getting following error while executing a unti test case(JUNIT).I am using it to understand the part of the project.Project is a web based project.Project is using OPENJPA
<openjpa-1.2.1-SNAPSHOT-r422266:686069 fatal store error> org.apache.openjpa.persistence.RollbackException: Unable to obtain a TransactionManager using null.
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:523)
at com.XYZ.cloud.admin.loadCatalog.LoadCatalogTest.populateOffering(LoadCatalogTest.java:253)
at com.XYZ.cloud.admin.loadCatalog.LoadCatalogTest.CatalogUploadTest(LoadCatalogTest.java:160)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: <openjpa-1.2.1-SNAPSHOT-r422266:686069 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: Unable to obtain a TransactionManager using null.
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4231)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4196)
at org.apache.openjpa.jdbc.sql.DB2Dictionary.newStoreException(DB2Dictionary.java:503)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:102)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:88)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:64)
at org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:65)
at org.apache.openjpa.util.ImplHelper.generateValue(ImplHelper.java:160)
at org.apache.openjpa.util.ImplHelper.generateFieldValue(ImplHelper.java:144)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignField(JDBCStoreManager.java:698)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:487)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:463)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignObjectId(JDBCStoreManager.java:682)
at org.apache.openjpa.kernel.DelegatingStoreManager.assignObjectId(DelegatingStoreManager.java:134)
at org.apache.openjpa.kernel.StateManagerImpl.assignObjectId(StateManagerImpl.java:519)
at org.apache.openjpa.kernel.StateManagerImpl.preFlush(StateManagerImpl.java:2823)
at org.apache.openjpa.kernel.PNewState.beforeFlush(PNewState.java:39)
at org.apache.openjpa.kernel.StateManagerImpl.beforeFlush(StateManagerImpl.java:959)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1948)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:1908)
at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:1826)
at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1350)
at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:877)
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:512)
... 26 more
Caused by: java.sql.SQLException: Unable to obtain a TransactionManager using null.
at org.apache.openjpa.jdbc.kernel.TableJDBCSeq.allocateSequence(TableJDBCSeq.java:419)
at org.apache.openjpa.jdbc.kernel.TableJDBCSeq.nextInternal(TableJDBCSeq.java:290)
at org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:60)
... 44 more
Caused by: javax.transaction.NotSupportedException: Unable to obtain a TransactionManager using null.
at org.apache.openjpa.ee.AutomaticManagedRuntime.doNonTransactionalWork(AutomaticManagedRuntime.java:306)
at org.apache.openjpa.jdbc.kernel.TableJDBCSeq.allocateSequence(TableJDBCSeq.java:415)
... 46 more
Caused by: <openjpa-1.2.1-SNAPSHOT-r422266:686069 fatal user error> org.apache.openjpa.util.InvalidStateException: Could not perform automatic lookup of EJB container's javax.transaction.TransactionManager implementation. Please ensure that you are running the application from within an EJB 1.1 compliant EJB container, and then set the org.apache.openjpa.ManagedRuntime property to
at org.apache.openjpa.ee.AutomaticManagedRuntime.getTransactionManager(AutomaticManagedRuntime.java:250)
at org.apache.openjpa.ee.AutomaticManagedRuntime.doNonTransactionalWork(AutomaticManagedRuntime.java:304)
... 47 more
Caused by: javax.naming.ConfigurationException: Name space accessor for the java: name space has not been set. Possible cause is that the user is specifying a java: URL name in a JNDI Context method call but is not running in a J2EE client or server environment.
at com.XYZ.ws.naming.java.javaURLContextFactory.isNameSpaceAccessable(javaURLContextFactory.java:93)
at com.XYZ.ws.naming.urlbase.UrlContextFactory.getObjectInstance(UrlContextFactory.java:82)
at javax.naming.spi.NamingManager.getURLContext(NamingManager.java:655)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:434)
at javax.naming.InitialContext.lookup(InitialContext.java:450)
at org.apache.openjpa.ee.RegistryManagedRuntime.getTransactionManager(RegistryManagedRuntime.java:61)
at org.apache.openjpa.ee.AutomaticManagedRuntime.getTransactionManager(AutomaticManagedRuntime.java:154)
... 48 more
My guess is that you are trying to use a persistence.xml declaring a jta-data-source in a unit test context (i.e. in a Java SE context).
In other words, you're not using an appropriate persistence.xml for a testing context. You need a specific persistence.xml using a RESOURCE_LOCAL transaction type and configure it to use a built-in connection pool (instead of a datasource).
Show your persistence.xml if you need more guidance.
Like the error message suggests: You need to make sure that you are running the application from within an EJB 1.1 compliant EJB container.
I wasted nearly an hour o fix this. The issue was very basic. The #Id and #GeneratedValue was not annotated on the id field.
As we are using JPA Tools in RAD, Eclipse to generate the entity classes, it does not annotate id field.
So, this can be fixed by placing the #Id field.
#Id
#GeneratedValue(strategy=GenerationType.Identity)
#Column(name="some_name")
private long someNameId;

Categories