SpringBoot test - Cannot load driver class: org.h2.Driver - spring

I have this class in my springBoot app:
#ContextConfiguration(classes={ ApplicationTestConfig.class})
#RunWith(SpringRunner.class)
public class ServiceTest {
#Autowired
private RuntimeService runtimeService;
#Autowired
private TaskService taskService;
#Autowired
private HistoryService historyService;
..
}
my application.properties:
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
my pom.xml:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
but when I run the test I got this error:
Caused by: java.lang.IllegalStateException: Cannot load driver class: org.h2.Driver
at org.springframework.util.Assert.state(Assert.java:94)
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:222)
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:174)
at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:43)
at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari.dataSource(DataSourceConfiguration.java:85)
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)
... 66 common frames omitted

Try with this if it may work for you
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

Related

org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]

I want to give permission of URL access according to user roles. I have tried to execute my program but I unable to execute my program, I am facing ExceptionTranslationFilter cannot be cast to class javax.servlet.Filter errors.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com</groupId>
<artifactId>smartcontactmanager</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>smartcontactmanager</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
MyConfig.java:
This is my configuration class.
package com.smartcontactmanager.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
#Configuration
#EnableWebSecurity
#Component
public class MyConfig extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService getUserDetailService() {
return new UserDetailsServiceImpl();
}
//To Encrypt password
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(this.getUserDetailService());
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
//Method configuration.
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/**").permitAll()
.and().formLogin().and().csrf().disable();
}
}
Errors:
I am facing this issues.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exceptio
n with message: class org.springframework.security.web.access.ExceptionTranslationFilter cannot be cast to class javax.servlet.Filter (org.springframework.security.web.
access.ExceptionTranslationFilter and javax.servlet.Filter are in unnamed module of loader 'app')
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.0.2.jar:6.0.2]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:648) ~[spring-beans-6.0.2.jar:6.0.2]
... 26 common frames omitted
Caused by: java.lang.ClassCastException: class org.springframework.security.web.access.ExceptionTranslationFilter cannot be cast to class javax.servlet.Filter (org.spri
ngframework.security.web.access.ExceptionTranslationFilter and javax.servlet.Filter are in unnamed module of loader 'app')
at org.springframework.security.config.annotation.web.builders.FilterComparator.compare(FilterComparator.java:57) ~[spring-security-config-5.1.6.RELEASE.jar:5.1
.6.RELEASE]
at java.base/java.util.TimSort.countRunAndMakeAscending(Unknown Source) ~[na:na]
at java.base/java.util.TimSort.sort(Unknown Source) ~[na:na]
at java.base/java.util.Arrays.sort(Unknown Source) ~[na:na]
at java.base/java.util.ArrayList.sort(Unknown Source) ~[na:na]
at java.base/java.util.Collections.sort(Unknown Source) ~[na:na]
at org.springframework.security.config.annotation.web.builders.HttpSecurity.performBuild(HttpSecurity.java:1108) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.
6.RELEASE]
at org.springframework.security.config.annotation.web.builders.HttpSecurity.performBuild(HttpSecurity.java:119) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.6
.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config
-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.
6.RELEASE]
at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:294) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.6.R
ELEASE]
at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:79) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.6.RE
LEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334) ~[spring-security-config
-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.1.6.RELEASE.jar:5.1.
6.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spri
ng-security-config-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$SpringCGLIB$$0.CGLIB$springSecurityFilterChain$5(<generated>) ~[sp
ring-security-config-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$SpringCGLIB$$2.invoke(<generated>) ~[spring-security-config-5.1.6.
RELEASE.jar:5.1.6.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:257) ~[spring-core-6.0.2.jar:6.0.2]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-6.0.2
.jar:6.0.2]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$SpringCGLIB$$0.springSecurityFilterChain(<generated>) ~[spring-sec
urity-config-5.1.6.RELEASE.jar:5.1.6.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139) ~[spring-beans-6.0.2.jar:6.0.2]
... 27 common frames omitted
You should remove this dependency:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
It is conflicting with the dependencies provided by spring-boot-starter-security. Additionally, Spring Boot 3 uses Spring Security 6 and the jakarta namespace instead of javax.

Error while try to start a web application teset with junit and spring

i'm trying to test a java spring web application and in particular i want to try some class that are injected in the application context. In order to do this i've found thate using the #SpringBootTest annotation i can obtain the application context. I wanted to create a simplet test to verify that i can actualy use it. I have a problem with the following test case:
#TestMethodOrder(OrderAnnotation.class)
#SpringBootTest
class ProvaContext {
#Autowired
protected ApplicationContext apt;
#Test
#Order(0)
void test1() {
assertNotNull(apt);
}
#Test
#Order(0)
void test2() {
apt=ContextLoader.getCurrentWebApplicationContext();
assertNotNull(apt);
}
}
When i start the server and try to run junit test with eclipse i get this error:
org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:111)
at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discover(EngineDiscoveryOrchestrator.java:85)
at org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:92)
at org.junit.platform.launcher.core.DefaultLauncher.discover(DefaultLauncher.java:67)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.<init>(JUnit5TestReference.java:46)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createUnfilteredTest(JUnit5TestLoader.java:76)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.createTest(JUnit5TestLoader.java:66)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.loadTests(JUnit5TestLoader.java:53)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.junit.platform.commons.JUnitException: ClassSelector [className = 'base.ProvaContext'] resolution failed
at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:45)
at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
at org.junit.platform.launcher.core.EngineDiscoveryOrchestrator.discoverEngineRoot(EngineDiscoveryOrchestrator.java:103)
... 11 more
Caused by: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724)
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getDeclaredAnnotation(Class.java:3458)
at org.junit.platform.commons.util.AnnotationUtils.findAnnotation(AnnotationUtils.java:128)
at org.junit.platform.commons.util.AnnotationUtils.findMetaAnnotation(AnnotationUtils.java:176)
at org.junit.platform.commons.util.AnnotationUtils.findAnnotation(AnnotationUtils.java:134)
at org.junit.platform.commons.util.AnnotationUtils.findAnnotation(AnnotationUtils.java:115)
at org.junit.jupiter.engine.descriptor.DisplayNameUtils.determineDisplayName(DisplayNameUtils.java:68)
at org.junit.jupiter.engine.descriptor.JupiterTestDescriptor.<init>(JupiterTestDescriptor.java:69)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.<init>(ClassBasedTestDescriptor.java:94)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.<init>(ClassTestDescriptor.java:51)
at org.junit.jupiter.engine.discovery.ClassSelectorResolver.newClassTestDescriptor(ClassSelectorResolver.java:119)
at org.junit.jupiter.engine.discovery.ClassSelectorResolver.lambda$resolve$0(ClassSelectorResolver.java:71)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution$DefaultContext.createAndAdd(EngineDiscoveryRequestResolution.java:246)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution$DefaultContext.addToParent(EngineDiscoveryRequestResolution.java:209)
at org.junit.jupiter.engine.discovery.ClassSelectorResolver.resolve(ClassSelectorResolver.java:71)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.lambda$resolve$2(EngineDiscoveryRequestResolution.java:134)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.ArrayList$ArrayListSpliterator.tryAdvance(ArrayList.java:1361)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:499)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:486)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:531)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:185)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolve(EngineDiscoveryRequestResolution.java:125)
at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:91)
... 16 more
I can't figure out the problem. The pom.xml file has the following dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.6.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Without the #SpringBootTest annotation the test run but the viriable apt is null. Thanks

After Spring Data ES migration : IllegalArgumentException: NamedWriteable is already registered for [...], cannot register [...]

I have a spring application (that's part of spring discovery cluster as discovery client). We have chosen to migrate this app from spring data elasticsearch 2.1.1.RELEASE (link to a dockerise 2.4.3-alpine elasticsearch) to SDE 3.0.14.RELEASE (that can be linked, if i'm correct, with a dockerise ES 5.5.0-alpine). My problem is that this app never achieve to start.
NOTE: It was perfectly working before the migration
First, I thought it was a trouble with maven dependencies, so I tried to find duplicate dependancies but I didn't have result.
I also tried to use a own TransportClient (with erasing app properties to prevent spring autoconfiguration), like Elasticsearch documentation describes (but apparently, spring should be able to do it itself).
Here's main class (with some, maybe useful, spring annotations):
#SpringBootApplication
#EnableDiscoveryClient
#EnableFeignClients
#EnableConfigurationProperties
#Configuration
#EnableElasticsearchRepositories(basePackages = {"com.sap.testreportservice"}, repositoryBaseClass = ApplicationRepositoryImpl.class)
public class TestreportServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TestreportServiceApplication.class, args);
}
}
Here's its maven dependancies:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.14.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
<scope>compile</scope>
</dependency>
</dependencies>
Here's some app properties:
spring:
data:
elasticsearch:
cluster-name: ${ES_CLUSTER_NAME:insights}
cluster-nodes: ${ES_CLUSTER_NODES:localhost:9300}
Here's my custom Transport Client:
#Configuration
public class ElasticsearchConfig {
#Bean
Client client() {
Settings settings = Settings.builder()
.put("cluster.name", "insights")
.build();
TransportClient client = new PreBuiltTransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
}
Here's some log extract (ask me for the complete stacktrace)
Caused by: java.lang.IllegalArgumentException: NamedWriteable [org.elasticsearch.index.query.QueryBuilder][parent_id] is already registered for [org.elasticsearch.search.SearchModule$$Lambda$942/734191650], cannot register [org.elasticsearch.join.ParentJoinPlugin$$Lambda$952/956934228]
at org.elasticsearch.common.io.stream.NamedWriteableRegistry.<init>(NamedWriteableRegistry.java:91) ~[elasticsearch-5.5.0.jar:5.5.0]
at org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:148) ~[elasticsearch-5.5.0.jar:5.5.0]
at org.elasticsearch.client.transport.TransportClient.<init>(TransportClient.java:254) ~[elasticsearch-5.5.0.jar:5.5.0]
at org.springframework.data.elasticsearch.client.TransportClientFactoryBean$SpringDataTransportClient.<init>(TransportClientFactoryBean.java:234) ~[spring-data-elasticsearch-3.0.14.RELEASE.jar:3.0.14.RELEASE]
at org.springframework.data.elasticsearch.client.TransportClientFactoryBean.buildClient(TransportClientFactoryBean.java:103) ~[spring-data-elasticsearch-3.0.14.RELEASE.jar:3.0.14.RELEASE]
at org.springframework.data.elasticsearch.client.TransportClientFactoryBean.afterPropertiesSet(TransportClientFactoryBean.java:98) ~[spring-data-elasticsearch-3.0.14.RELEASE.jar:3.0.14.RELEASE]
at org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration.elasticsearchClient(ElasticsearchAutoConfiguration.java:59) ~[spring-boot-autoconfigure-2.1.7.RELEASE.jar:2.1.7.RELEASE]
at org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration$$EnhancerBySpringCGLIB$$151bff6d.CGLIB$elasticsearchClient$0(<generated>) ~[spring-boot-autoconfigure-2.1.7.RELEASE.jar:2.1.7.RELEASE]
at org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration$$EnhancerBySpringCGLIB$$151bff6d$$FastClassBySpringCGLIB$$575694c9.invoke(<generated>) ~[spring-boot-autoconfigure-2.1.7.RELEASE.jar:2.1.7.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration$$EnhancerBySpringCGLIB$$151bff6d.elasticsearchClient(<generated>) ~[spring-boot-autoconfigure-2.1.7.RELEASE.jar:2.1.7.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 145 common frames omitted
These are pretty old versions to which you are upgrading.
Looking at the stacktrace you see that Spring Boot is still automatically creating the TransportClient, if you want to provide your bean, you should change your code to:
#Bean
TransportClient elasticsearchClient() {
Settings settings = Settings.builder()
.put("cluster.name", "insights")
.build();
TransportClient client = new PreBuiltTransportClient(settings);
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
Spring Boot autoconfiguration has a #ConditionalOnMissingBean annotation on it's factory method, and that checks for TransportClient, not Client. With this you will provide the TransportClient, but Spring Boot will do the rest of the autoconfiguration.
To disable autoconfiguration for Elasticsearch you can use #SpringBootApplication(exclude={ElasticsearchAutoConfiguration.class}).
Do you have elasticsearch plugin configuration somewhere in your config? Because the error you see comes from the fact, that the Client that the autoconfiguration tries to build wants to register the ParentJoinPlugin(that's hardcoded in the TransportClientFactoryBean of that version and there is already a conflicting entry registered.

spring boot distributed transaction error java.lang.ClassNotFoundException: javax.transaction.TransactionManager

I am trying to do distributed transaction but I have a lot of errors, so I have written this demo app to explain my problem
my pom.xml has these dependencies :
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>ch.maxant</groupId>
<artifactId>genericconnector-atomikos-api</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
</dependencies>
and my only class containing main function is :
#Configuration
public class Main {
#Autowired
#Qualifier("xaTransactionManager")
protected static UserTransactionManager tm;
#Primary
#Bean(name = "xaTransactionManager", initMethod = "init", destroyMethod = "close")
public UserTransactionManager xaTransactionManager() throws SystemException {
UserTransactionManager txManager = new UserTransactionManager();
txManager.setTransactionTimeout(300);
txManager.setForceShutdown(false);
return txManager;
}
#Bean(name = "xaTransactionService", initMethod = "init", destroyMethod = "shutdownWait")
public UserTransactionServiceImp xaTransactionService() {
return new UserTransactionServiceImp();
}
public static void main(String[] s) {
try {
tm.begin();
// here is empty
tm.commit();
} catch (Exception e) {
tm.rollback();
System.out.println(e.getMessage());
}
}
}
I have just begin a transaction
but I have faced this problem at the Line of tm.begin()
java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 19 more
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" [INFO] NETBEANS-ExecEvent:{"exc":{"msg":"Q29tbWFuZCBleGVjdXRpb24gZmFpbGVkLg=="},"mojo":{"impl":"org.codehaus.mojo.exec.ExecMojo","urls":["file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/org\/codehaus\/mojo\/exec-maven-plugin\/1.2.1\/exec-maven-plugin-1.2.1.jar","file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/org\/apache\/maven\/reporting\/maven-reporting-api\/2.0.6\/maven-reporting-api-2.0.6.jar","file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/org\/apache\/maven\/doxia\/doxia-sink-api\/1.0-alpha-7\/doxia-sink-api-1.0-alpha-7.jar","file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/commons-cli\/commons-cli\/1.0\/commons-cli-1.0.jar","file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/org\/codehaus\/plexus\/plexus-interactivity-api\/1.0-alpha-4\/plexus-interactivity-api-1.0-alpha-4.jar","file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/org\/codehaus\/plexus\/plexus-utils\/2.0.5\/plexus-utils-2.0.5.jar","file:\/C:\/Users\/NOSIRAT\/.m2\/repository\/org\/apache\/commons\/commons-exec\/1.1\/commons-exec-1.1.jar"],"goal":"exec","id":"org.codehaus.mojo:exec-maven-plugin:1.2.1","source":"CLI","execId":"default-cli"},"type":"MojoFailed"}
any help please?
The javax.transaction.TransactionManager is a class inside the J2EE SDK library javaee.jar, and probably you are missing this jar file in your project's classpath.
You can follow this article to add the needed dependency to your project!
For the impatient, here is the dependency that needs to be added to your pom.xml
<repository>
<id>Java.Net</id>
<url>http://download.java.net/maven/2/</url>
</repository>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
Hope this helps!

Spring boot + MongoDB

I'm working with Spring boot + MongoDB, and I've tried to deploy this application, but I have this exception:
Caused by: java.lang.ClassNotFoundException: org.springframework.data.mongodb.repository.MongoRepository
at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_111]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_111]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_111]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_111]
... 63 common frames omitted
this is my code:
POM:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
AddressDAOImpl:
package pe.com.microexample.daoimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import pe.com.microexample.bean.Address;
import pe.com.microexample.dao.AddressDAO;
import pe.com.microexample.repository.AddressRepository;
#Repository
public class AddressDAOImpl implements AddressDAO{
#Autowired
private AddressRepository addressRepository;
}
AddressRepository:
package pe.com.microexample.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import pe.com.microexample.bean.Address;
public interface AddressRepository extends MongoRepository<Address, Integer>{
Address getAddress();
}
Any idea about this exception?
maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
=======================================================================
application.properties
server.port = 8080
spring.data.mongodb.database=user_db
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
=======================================================================
Repository
public interface UserRepository extends MongoRepository{
}
for reference use below link:(step by step explanation)
https://www.youtube.com/watch?v=2Tq2Q7EzhSA&t=7s

Resources