OSGI EventAdmin can not send event - getting null point exception on Producer - osgi

I am trying to send an event to a consumer. I am getting NullPointerException
Here is my event code
public class Activator implements BundleActivator {
EventAdmin eventAdmin;
#Override
public void start(BundleContext bundleContext) throws Exception {
System.out.println("started");
Dictionary<String, String> properties = new Hashtable<>();
properties.put("test", "blah");
Event event = new Event("test/sent", properties);
System.out.println("sending");
eventAdmin.sendEvent(event);
}
#Override
public void stop(BundleContext bundleContext) throws Exception {
System.out.println("stopped ");
}
}
Here is the LOG
org.osgi.framework.BundleException: Exception in
com.aml.project.Activator.start() of bundle h. at
org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:863)
at
org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:791)
at
org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:1013)
at
org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:365)
at org.eclipse.osgi.container.Module.doStart(Module.java:598) at
org.eclipse.osgi.container.Module.start(Module.java:462) at
org.eclipse.osgi.internal.framework.EquinoxBundle.start(EquinoxBundle.java:439)
at org.apache.felix.gogo.command.Basic.start(Basic.java:739) 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:567) at
org.apache.felix.gogo.runtime.Reflective.invoke(Reflective.java:139)
at
org.apache.felix.gogo.runtime.CommandProxy.execute(CommandProxy.java:91)
at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:599)
at
org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:526)
at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:415)
at org.apache.felix.gogo.runtime.Pipe.doCall(Pipe.java:416) at
org.apache.felix.gogo.runtime.Pipe.call(Pipe.java:229) at
org.apache.felix.gogo.runtime.Pipe.call(Pipe.java:59) at
java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:835) Caused by:
java.lang.NullPointerException at
com.aml.project.Activator.start(Activator.java:21) at
org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:842)
at
org.eclipse.osgi.internal.framework.BundleContextImpl$3.run(BundleContextImpl.java:1)
at
java.base/java.security.AccessController.doPrivileged(AccessController.java:552)
at
org.eclipse.osgi.internal.framework.BundleContextImpl.startActivator(BundleContextImpl.java:834)
... 23 more java.lang.NullPointerException

You use the field eventAdmin that is never set. So you get a NullPointerException. I suggest to use declarative services instead and inject EventAdmin using #Reference.
See OSGi Event Admin – Publish & Subscribe from Vogella for all details.

Related

spring security messaging throws NullPointerException internally (Spring context is null!)

this is websocket security config:
#Configuration
public class WSSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer implements ApplicationContextAware {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.nullDestMatcher().denyAll()
.simpSubscribeDestMatchers("/topic/t01", "/topic/t99").authenticated()
.anyMessage().denyAll();
}
}
the context fails to load with this error (trimmed only to the relevant parts):
Caused by: java.lang.NullPointerException: null
at org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer.configureClientInboundChannel(AbstractSecurityWebSocketMessageBrokerConfigurer.java:106) ~[spring-security-config-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration.configureClientInboundChannel(DelegatingWebSocketMessageBrokerConfiguration.java:73) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.getClientInboundChannelRegistration(AbstractMessageBrokerConfiguration.java:153) ~[spring-messaging-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.clientInboundChannelExecutor(AbstractMessageBrokerConfiguration.java:144) ~[spring-messaging-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration$$EnhancerBySpringCGLIB$$e1380a16.CGLIB$clientInboundChannelExecutor$35(<generated>) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration$$EnhancerBySpringCGLIB$$e1380a16$$FastClassBySpringCGLIB$$1a42e7b2.invoke(<generated>) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration$$EnhancerBySpringCGLIB$$e1380a16.clientInboundChannelExecutor(<generated>) ~[spring-websocket-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_342]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_342]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_342]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_342]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
... 93 common frames omitted
I looked at the culprit class AbstractSecurityWebSocketMessageBrokerConfigurer, the exception was thrown in method configureClientInboundChannel, the context is null. after some debugging I found out that the context was set before this method get called (of course with not null value) by setApplicationContext but the object (proxy) reference was not same when these two method was called (configureClientInboundChannel and setApplicationContext)
#Override
public final void configureClientInboundChannel(ChannelRegistration registration) {
ChannelSecurityInterceptor inboundChannelSecurity = context.getBean(ChannelSecurityInterceptor.class);
.
.
.
}
more information:
spring boot version: 2.3.1.RELEASE
spring security version: 5.3.3.RELEASE

Can't commit transaction JPA Repository Spring after using GCP PubSub

I have a Spring Boot app that sends and receives messages on a GCP PubSub queue. Basically I try to store in the DB some of the information that I get in the message. However when I try to commit this information or saveAndFlush() I get the error RollbackException: Error while committing the transaction. If I persists any other information that it's not triggered when the app receives an inbound message it works correctly. If I try saveAndFlush instead of save I get a NullPointerException.
What am I missing?
Thanks.
Error stack
Caused by: org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:543)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:633)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:386)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
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.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy153.save(Unknown Source)
at com.sap.service.deployments.DeploymentService.lambda$saveLogs$16(DeploymentService.java:235)
at java.util.Optional.map(Optional.java:215)
at com.sap.service.deployments.DeploymentService.saveLogs(DeploymentService.java:233)
at com.sap.service.deployments.DeploymentService.processDeploymentExecutionResponse(DeploymentService.java:404)
at com.sap.service.deployments.DeploymentService.messageReceiver(DeploymentService.java:245)
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.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:171)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper$HandlerMethod.invoke(MessagingMethodInvokerHelper.java:1105)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper.invokeHandlerMethod(MessagingMethodInvokerHelper.java:583)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:478)
at org.springframework.integration.handler.support.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:356)
at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:108)
... 24 more
Caused by: javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:81)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534)
... 54 more
Caused by: java.lang.NullPointerException
at com.sap.config.AuditorAwareImpl.getCurrentAuditor(AuditorAwareImpl.java:13)
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205)
at com.sun.proxy.$Proxy164.getCurrentAuditor(Unknown Source)
at org.springframework.data.auditing.AuditingHandler.lambda$touchAuditor$6(AuditingHandler.java:193)
at java.util.Optional.map(Optional.java:215)
at org.springframework.data.auditing.AuditingHandler.touchAuditor(AuditingHandler.java:191)
at org.springframework.data.auditing.AuditingHandler.lambda$touch$0(AuditingHandler.java:165)
at java.util.Optional.map(Optional.java:215)
at org.springframework.data.auditing.AuditingHandler.touch(AuditingHandler.java:163)
at org.springframework.data.auditing.AuditingHandler.markModified(AuditingHandler.java:143)
at org.springframework.data.jpa.domain.support.AuditingEntityListener.touchForUpdate(AuditingEntityListener.java:112)
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.hibernate.jpa.event.internal.ListenerCallback.performCallback(ListenerCallback.java:35)
at org.hibernate.jpa.event.internal.CallbackRegistryImpl.callback(CallbackRegistryImpl.java:95)
at org.hibernate.jpa.event.internal.CallbackRegistryImpl.preUpdate(CallbackRegistryImpl.java:69)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.invokeInterceptor(DefaultFlushEntityEventListener.java:366)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.handleInterception(DefaultFlushEntityEventListener.java:348)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:299)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:170)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:232)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:92)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1360)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:451)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3210)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2378)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101)
... 55 more
AuditorAwareImpl
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
class AuditorAwareImpl implements AuditorAware<String> {
#Override
public Optional<String> getCurrentAuditor() {
SamlUserDetails userDetails = (SamlUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //NullPointerExc on this line
return Optional.of(userDetails.getFullname() + " (" + userDetails.getAttribute("uid") + ")");
}
}
This is the configuration of the Inbound PubSub
#Component
public class PubSubInbound {
#Autowired
private DeploymentService deploymentService;
#Bean
public MessageChannel inputMessageChannel() {
return new PublishSubscribeChannel();
}
// Create an inbound channel adapter to listen to the subscription `sub-one` and send
// messages to the input message channel.
#Bean
public PubSubInboundChannelAdapter inboundChannelAdapter(
#Qualifier("inputMessageChannel") MessageChannel messageChannel,
PubSubTemplate pubSubTemplate) {
PubSubInboundChannelAdapter adapter =
new PubSubInboundChannelAdapter(pubSubTemplate, "cerberusSubscription");
adapter.setOutputChannel(messageChannel);
adapter.setAckMode(AckMode.MANUAL);
adapter.setPayloadType(String.class);
return adapter;
}
#Bean
#ServiceActivator(inputChannel = "pubsubInputChannel")
public MessageHandler messageReceiver() {
return message -> {
System.out.println("Message arrived! Payload: " + new String((byte[]) message.getPayload()));
BasicAcknowledgeablePubsubMessage originalMessage =
message.getHeaders().get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
originalMessage.ack();
deploymentService.persistLogs(
Long.parseLong(message.getHeaders().get("deploymentId", String.class)),
new String((byte[]) message.getPayload()));
};
}
}
DeploymentService
#Service
public class DeploymentService {
#Autowired
private DeploymentRepository deploymentRepository;
....
public Optional<Deployment> persistLogs(Long deploymentId, String logs){
Optional<Deployment> deploymentOpt = deploymentRepository.findById(deploymentId);
return deploymentOpt.map(deployment -> {
deployment.setLogs(logs);
return deploymentRepository.save(deployment); //ERROR HERE
});
}
....
DeploymentRepository
#Repository
public interface DeploymentRepository extends JpaRepository<Deployment, Long> { }
Solved.
SecurityContextHolder.getContext().getAuthentication()
was null when the message is coming from the GCP PubSub. Reworking the getCurrentAuditor did the trick.
#Override
public Optional<String> getCurrentAuditor() {
if(SecurityContextHolder.getContext().getAuthentication()!=null){
SamlUserDetails userDetails = (SamlUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Optional.of(userDetails.getFullname() + " (" + userDetails.getAttribute("uid") + ")");
}else return Optional.empty();
}

Getting Kafka error- java.util.concurrent.ExecutionException: org.springframework.kafka.core.KafkaProducerException: Failed to send

I am getting the error in Kafka. While sending the message on the topic
Here is the code for sending message on topic.
#Override
public void sendMessage(User user) {
ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(user);
future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
#Override
public void onSuccess(SendResult<String, Object> result) {
}
#Override
public void onFailure(Throwable e) {
}
});
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
throw new SystemException("Error sending message to topic " + channelConfiguration.getTopic(), e);
**Getting following error here**
}
}
Here is the error I am getting while sending message on topic
Caused by: java.util.concurrent.ExecutionException: org.springframework.kafka.core.KafkaProducerException: Failed to send; nested exception is org.apache.kafka.common.errors.TimeoutException: Topic user_event not present in metadata after 60000 ms.
at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na]
at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[na:na]
at org.springframework.util.concurrent.SettableListenableFuture.get(SettableListenableFuture.java:119) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at com.test.common.messenger.kafka.sender.KafkaMessageSender.sendMessage(KafkaMessageSender.java:60) ~[classes/:na]
... 55 common frames omitted
Caused by: org.springframework.kafka.core.KafkaProducerException: Failed to send; nested exception is org.apache.kafka.common.errors.TimeoutException: Topic loyalty_event not present in metadata after 60000 ms.
at org.springframework.kafka.core.KafkaTemplate.lambda$buildCallback$4(KafkaTemplate.java:424) ~[spring-kafka-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:930) ~[kafka-clients-2.3.1.jar:na]
at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:856) ~[kafka-clients-2.3.1.jar:na]
at org.springframework.kafka.core.DefaultKafkaProducerFactory$CloseSafeProducer.send(DefaultKafkaProducerFactory.java:592) ~[spring-kafka-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.kafka.core.KafkaTemplate.doSend(KafkaTemplate.java:404) ~[spring-kafka-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at org.springframework.kafka.core.KafkaTemplate.send(KafkaTemplate.java:254) ~[spring-kafka-2.3.6.RELEASE.jar:2.3.6.RELEASE]
at com.test.common.messenger.kafka.sender.KafkaMessageSender.sendMessage(KafkaMessageSender.java:45) ~[classes/:na]
... 55 common frames omitted
Caused by: org.apache.kafka.common.errors.TimeoutException: Topic user_event not present in metadata after 60000 ms.
Does anyone knows about this?
Topic user_event not present in metadata after 60000 ms.
Do you have the topic user_event?
If not you need to create it or else configure Kafka admin to create topic automatically.

Running Cassandra in Spring Boot

I have installed Cassandra in my windows environment, I run it with cassandra.bat.
Now, I have an Spring Boot application that contains the following cassandra configuration file:
#Configuration
#EnableCassandraRepositories(
basePackages = "org.manuel.cassandra.repositories")
public class CassandraConfig extends AbstractCassandraConfiguration {
#Override
protected String getKeyspaceName() {
return "testKeySpace";
}
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints("127.0.0.1");
cluster.setPort(9142);
return cluster;
}
#Override
protected boolean getMetricsEnabled() { return false; }
#Bean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new CassandraMappingContext();
}
}
But I can't run the application because I get this:
Caused by: java.lang.NoClassDefFoundError: com/datastax/driver/core/Session
at java.base/java.lang.Class.getDeclaredMethods0(Native Method) ~[na:na]
at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3167) ~[na:na]
at java.base/java.lang.Class.getDeclaredMethods(Class.java:2310) ~[na:na]
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:489) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 27 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.datastax.driver.core.Session
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583) ~[na:na]
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[na:na]
... 31 common frames omitted
These are my cassandra related dependencies:
implementation 'org.springframework.boot:spring-boot-starter-data-cassandra'
implementation 'com.datastax.cassandra:cassandra-driver-core:4.0.0'
implementation 'io.dropwizard.metrics:metrics-jmx:4.1.0'
My application.yml file is empty and I also have declared a repository, but I think the error isn't related to that problem.
The spring-boot-starter-data-cassandra depends on the sprint-data-cassandra that uses Java driver 3.6.0, and you have specified the dependency on the 4.0.0 - this version is not binary compatible with 3.x releases, so you need to correct your dependencies.

spring boot data cassandra reactive JmxReporter problem

I updated my project to spring-boot Version 2.1.0.RELEASE.
Now i get the following error:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.ReactiveSession]: Factory method 'reactiveSession' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
at org.springframework.beans.factory.support.ConstructorResolver.lambda$instantiate$2(ConstructorResolver.java:615)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:614)
... 120 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in class path resource [ch/sbb/kat/fc/config/CassandraConfig.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:339)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.session(<generated>)
at org.springframework.data.cassandra.config.AbstractCassandraConfiguration.getRequiredSession(AbstractCassandraConfiguration.java:66)
at org.springframework.data.cassandra.config.AbstractReactiveCassandraConfiguration.reactiveSession(AbstractReactiveCassandraConfiguration.java:47)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.CGLIB$reactiveSession$7(<generated>)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7$$FastClassBySpringCGLIB$$7973a63.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at ch.sbb.kat.fc.config.CassandraConfig$$EnhancerBySpringCGLIB$$a22674d7.reactiveSession(<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:154)
... 123 more
Caused by: java.lang.NoClassDefFoundError: com/codahale/metrics/JmxReporter
at com.datastax.driver.core.Metrics.<init>(Metrics.java:146)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1501)
at com.datastax.driver.core.Cluster.init(Cluster.java:208)
at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:376)
at com.datastax.driver.core.Cluster.connect(Cluster.java:332)
at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.connect(CassandraCqlSessionFactoryBean.java:89)
at org.springframework.data.cassandra.config.CassandraCqlSessionFactoryBean.afterPropertiesSet(CassandraCqlSessionFactoryBean.java:82)
at org.springframework.data.cassandra.config.CassandraSessionFactoryBean.afterPropertiesSet(CassandraSessionFactoryBean.java:59)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.lambda$invokeInitMethods$5(AbstractAutowireCapableBeanFactory.java:1795)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1794)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
... 143 more
Caused by: java.lang.ClassNotFoundException: com.codahale.metrics.JmxReporter
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 155 more
Using the property introduced in this issue https://github.com/spring-projects/spring-boot/issues/14778 seems to have no effect to solve my issue.
How can i disable jmx for cassandra?
My current cassandra config looks like this:
#Configuration
#EnableReactiveCassandraRepositories({"repository"})
public class CassandraConfig extends AbstractReactiveCassandraConfiguration {
#Value("${cassandra.host}")
private String host;
#Override
protected String getKeyspaceName() {
return "keyspace";
}
#Override
public String[] getEntityBasePackages() {
return new String[]{"model"};
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override
public String getContactPoints() {
return host;
}
}
The spring.data.cassandra.jmx-enabled property is used when Spring Boot is auto-configuring a Cassandra Cluster bean. By extending AbstractReactiveCassandraConfiguration, you are switching off this auto-configuration in favour of the Cluster bean that's created by AbstractClusterConfiguration which is a super-class of AbstractReactiveCassandraConfiguration. As a result, the property has no effect.
There are two ways that you can fix your problem:
Remove your AbstractReactiveCassandraConfiguration sub-class and use the various spring.data.cassandra.* properties to configure things instead.
Override cluster on AbstractClusterConfiguration in CassandraConfig, call super.cluster() to get the CassandraClusterFactoryBean and then call setJmxReportingEnabled(false) on the factory bean before returning it.
Alternatively, if you are not using Dropwizard elsewhere in your application, you may be able to downgrade to an older version that is compatible with Cassandra's JMX reporting by overriding the dropwizard-metrics.version property in your pom.xml or build.gradle.
instead of overriding cluster as mentionned by Andy Wilkinson, you could alternatively override getMetricsEnabled so that always returns false.
#Override
protected boolean getMetricsEnabled() { return false; }
I tried the the answers here, I don't know how but error still persisted.
I read this from docs.datastax.com , where they talked about Moving JMX reporting in Metrics 4 to a separate module, metrics-jmx. Which they made clear that it might cause issues/errors.
To fix this, I just had to call this method .withoutJMXReporting() as in the below.
Cluster cluster = Cluster.builder()
.withoutJMXReporting()
.build();
You can follow quietly here
Including old version of library also fixes problem:
implementation("io.dropwizard.metrics:metrics-core:3.2.2")
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("spring.data.cassandra.contact-points"));
cluster.setPort(Integer.parseInt(environment.getProperty("spring.data.cassandra.port")));
cluster.setJmxReportingEnabled(false);
return cluster;
}
cluster.setJmxReportingEnabled(false) is the answer seems.

Resources