Spring with MongoTemplate: java.lang.String com.mongodb.connection.ClusterSettings.getDescription() - java

I am trying to create a simple application that handles MongoDB database with MongoTemplate. However, this method:
#Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate template = new MongoTemplate(mongoClient(), this.mongodbName);
return template;
}
fails with this exception:
Error creating bean with name 'mongoTemplate' defined in class path resource [com/myapp/tryout/repository/config/MongoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is java.lang.NoSuchMethodError: 'java.lang.String com.mongodb.connection.ClusterSettings.getDescription()'
pom.xml has these dependencies:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.5</version>
</dependency>
Spring version is 5.2.6.
Documentation of this com.mongodb.connection.ClusterSettings tells that the method in question is indeed deprecated. Moreover by looking in ClusterSettings class I cannot find this method.
My question is: Is it about mismatch in current releases of Spring and mongo-java-driver? If yes, can you please point out a correct combination of packages to use?
Please ask, if you need more information. I will gladly provide it.
ADDED: Ah, irony...
I found this
private static Cluster createCluster(final MongoClientSettings settings,
#Nullable final MongoDriverInformation mongoDriverInformation) {
notNull("settings", settings);
List<MongoCredential> credentialList = settings.getCredential() != null ? singletonList(settings.getCredential())
: Collections.<MongoCredential>emptyList();
return new DefaultClusterFactory().createCluster(settings.getClusterSettings(), settings.getServerSettings(),
settings.getConnectionPoolSettings(), getStreamFactory(settings, false), getStreamFactory(settings, true), credentialList,
getCommandListener(settings.getCommandListeners()), settings.getApplicationName(), mongoDriverInformation,
settings.getCompressorList());
}
in com.mongodb.client.internal.MongoClientImpl.
And this
public Cluster createCluster(final ClusterSettings clusterSettings, final ServerSettings serverSettings,
final ConnectionPoolSettings connectionPoolSettings, final StreamFactory streamFactory,
final StreamFactory heartbeatStreamFactory, final List<MongoCredential> credentialList,
final CommandListener commandListener, final String applicationName,
final MongoDriverInformation mongoDriverInformation,
final List<MongoCompressor> compressorList) {
ClusterId clusterId = new ClusterId(clusterSettings.getDescription());
in com.mongodb.connection.DefaultClusterFactory, which is deprecated.

Spring 3.x supports mongodb java version 4.x. The mongo-java-driver and mongodb-driver “uber-jars” are no longer published as noted in the linked page. Between 3.x and 4.x mongo driver java version the uber jar dependencies have been split to core and sync/reactive streams dependencies. I was able to reproduce the issue with 3.x version. Once I updated to correct 4.x dependencies issue disappeared.
So the correct dependencies are in the below order
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-core</artifactId>
<version>4.0.4</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.0.4</version>
</dependency>
https://mongodb.github.io/mongo-java-driver/4.0/upgrading/#upgrading-from-the-3-12-java-driver
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#upgrading.2-3

Seems like I was correct about versions mismatch.
Changing versions of the mentioned packages to these ones:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.11.2</version>
</dependency>
will workaround the issue. I cannot mark this post as an answer to the issue. Seems like version 3.0.* of spring-data-mongodb is not compatible with the latest mongo-java-driver or vice versa. I can be wrong.

Related

Swagger 2 Issue spring Boot

I'm facing issue with Swagger Integration in Spring Boot. Have a look at the code and error snippet.
------------------POM--------------------
<properties>
<java.version>1.8</java.version>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>${swagger.version}</version>
</dependency>
-----------------App class--------------
#SpringBootApplication
#EnableSwagger2
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ServletPocProducerApplication.class, args);
}
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Stack Trace
org.springframework.context.ApplicationContextException: Failed to start bean
'documentationPluginsBootstrapper'; nested exception is
java.lang.NullPointerException: Cannot invoke
"org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.toString()"
because the return value of
"springfox.documentation.spi.service.contexts.Orderings.patternsCondition(springfox.docume
ntation.RequestHandler)" is null
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
How do I fix this??
I solved it by adding "spring.mvc.pathmatch.matching-strategy=ant-path-matcher" in application.properties.
For a long time I have tried to solve this problem and solution for this is:
a) adding this to application.properties:
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
b) adding this to application.yaml(or application.yml):
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
I know this does not solve your problem directly, but consider moving to springdoc. Springfox is so buggy at this point that is a pain to use. I've moved to springdoc 2 years ago because of its Spring WebFlux support and I am very happy about it. Additionally, it also supports Kotlin Coroutines, which I am not sure Springfox does.
If you decide to migrate, springdoc even has a migration guide.
For the integration between spring-boot and swagger-ui, add the library to the list of your project dependencies (No additional configuration is needed):
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.12</version>
</dependency>
The Swagger UI page will then be available at
http://server:port/context-path/swagger-ui.html and the OpenAPI
description will be available at the following url for json format:
http://server:port/context-path/v3/api-docs
server: The server name or IP
port: The server port
context-path: The context path of the application
Adding this "spring.mvc.pathmatch.matching-strategy=ant-path-matcher" to your application.properties file solves the problem.
It's what i used and i saved me alot of trouble.
My suggestion is when you are using spring-boot then it is better to use spring boot dependency for swagger. So, spring-boot will take care of your default settings.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>...</version>
</dependency>

Error when trying to connect to Azure Eventhub: AzureTokenCredentials / IllegalArgumentException: name

I am following a tutorial on how to setup a connection to Azure EventHub in Spring Boot: [1]
When starting the spring boot app, I get the following error:
2021-01-07 13:37:25.447 WARN 16444 --- [ main] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'resourceManagerProvider' defined in class path resource
[com/microsoft/azure/spring/cloud/autoconfigure/context/AzureContextAutoConfiguration.class]: Unsatisfied
dependency expressed through method 'resourceManagerProvider' parameter 0; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'azure'
defined in class path resource
[com/microsoft/azure/spring/cloud/autoconfigure/context/AzureContextAutoConfiguration.class]: Unsatisfied
dependency expressed through method 'azure' parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'credentials'
defined in class path resource
[com/microsoft/azure/spring/cloud/autoconfigure/context/AzureContextAutoConfiguration.class]: Bean
instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.microsoft.azure.credentials.AzureTokenCredentials]: Factory method 'credentials' threw exception;
nested exception is java.lang.IllegalArgumentException: name
my.azureauth looks like analogous to the on in [1].
I am using Java 11. Here is the relevant part of my pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>spring-cloud-azure-eventhubs-stream-binder</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-servicebus-jms-spring-boot-starter</artifactId>
<version>2.3.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Workaround. -->
<!-- Apparently com.microsoft.azure:spring-cloud-azure-eventhubs-stream-binder:1.2.7 has a transitive -->
<!-- dependency to the following package. However, it seems that the version is not pinned correctly, so -->
<!-- we have to pin the version to a compatible one as a workaround. -->
<!-- 7.5 is apparently the latest version in which com.nimbusds.oauth2.sdk.http.CommonContentTypes is available. -->
<!-- For a similar (but different) issue see also https://github.com/microsoft/azure-spring-boot/issues/650 -->
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>oauth2-oidc-sdk</artifactId>
<version>7.5</version>
</dependency>
Note the workaround regarding the dependency com.nimbusds.
I tried navigating to the relevant code. However, for some reason the code of AzureContextAutoConfiguration.credentials
is not available in the disassembled code of my IDE.
Is the version I used in the workaround in my pom.xml appropriate?
Does anyone have an idea what the error means and how to fix it?
Can anyone report, that this tutorial still works?
[1] https://learn.microsoft.com/en-us/azure/developer/java/spring-framework/configure-spring-cloud-stream-binder-java-app-azure-event-hub
So here the root issue is
"Failed to instantiate
[com.microsoft.azure.credentials.AzureTokenCredentials]: Factory method 'credentials' threw exception;
nested exception is java.lang.IllegalArgumentException: name"
I would suggest you to verify your my.azureauth and application.properties files again against the guide.
Also, as the guide suggests, if you're using JDK version 9 or greater (you are using 11 here), add the following dependencies
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.1</version>
<scope>runtime</scope>
</dependency>

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

I try to write very simple application with hibernate validator:
my steps:
Added following dependency in pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
Wrote following code:
class Configuration {
Range(min=1,max=100)
int threadNumber;
//...
public static void main(String[] args) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Configuration configuration = new Configuration();
configuration.threadNumber = 12;
//...
Set<ConstraintViolation<Configuration>> constraintViolations = validator.validate(configuration);
System.out.println(constraintViolations);
}
}
And I get following stacktrace:
Exception in thread "main" javax.validation.ValidationException: Unable to instantiate Configuration.
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:279)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110)
...
at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:110)
at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:86)
at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:276)
... 2 more
What do I wrong?
It is working after adding to pom.xml following dependencies:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
Getting started with Hibernate Validator:
Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages. When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container. In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance you can add the following two dependencies to use the JSR 341 reference implementation:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
do just
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
In case you don't need javax.el (for example in a JavaSE application), use ParameterMessageInterpolator from Hibernate validator.
Hibernate validator is a standalone component, which can be used without Hibernate itself.
Depend on hibernate-validator
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
Use ParameterMessageInterpolator
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
private static final Validator VALIDATOR =
Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator())
.buildValidatorFactory()
.getValidator();
If you are using tomcat as your server runtime and you get this error in tests (because tomcat runtime is not available during tests) than it makes make sense to include tomcat el runtime instead of the one from glassfish). This would be:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-el-api</artifactId>
<version>8.5.14</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper-el</artifactId>
<version>8.5.14</version>
<scope>test</scope>
</dependency>
If you're using spring boot with starters - this dependency adds both tomcat-embed-el and hibernate-validator dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Regarding the Hibernate validator documentation page, you have to define a dependency to a JSR-341 implementation:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b11</version>
</dependency>
The Hibernate Validator requires — but does not include — an Expression Language (EL) implementation. Adding a dependency on one will will fix the issue.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>3.0.3</version>
</dependency>
This requirement is documented in the Getting started with Hibernate Validator documentation. In a Java EE environment, it would be provided by the container. In a standalone application such as yours, it needs to be provided.
Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages.
When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container.
In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance, you can add the following dependency to use the JSR 341 reference implementation:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>${version.jakarta.el-api}</version>
</dependency>
Expression Language Implementation
Several EL implementations exist. One is the Jakarta EE Glassfish reference implementation mentioned in the documentation. Another is embedded Tomcat, which is used by default by the current version of Spring Boot. That version of EL can be used as follows:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>9.0.48</version>
</dependency>
As noted in this comment, a compatible version of the Expression Language must be chosen. The Glassfish implementation is specified as a provided-scope dependency of Hibernate Validator, so the version specified there should work without issue. In particular, Hibernate Validator 7 uses version 4 of the Glassfish EL implementation and Hibernate 6 uses version 3.
Spring Boot
In a Spring Boot project, the spring-boot-starter-validation dependency would typically be used rather than specifying the Hibernate validator & EL libraries directly. That dependency includes both org.hibernate.validator:hibernate-validator and tomcat-embed-el.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.4.3.RELEASE</version>
</dependency>
Jakarta namespace
As part of the handover from Oracle to the Eclipse Foundation, Java EE is being renamed to Jakarta EE. With Jakarta EE 9, the Java package names were changed from javax.* to jakarta.*.
The Answer by M. Justin is correct with regard to Jakarta. I added this Answer to provide more explanation and specific examples.
Interface versus Implementation
Jakarta Bean Validation is a specification of an API in Java. The binary library for this spec contains only interfaces, not executable code. So we also need an implementation of these interfaces.
I know of only one implementation of Jakarta Bean Validation versions 2 & 3 specifications: Hibernate Validator versions 6 and 7 (respectively).
Desktop & console apps
For web apps, a Jakarta-compliant web container will provide both the interface and the implementation needed to perform Bean Validation.
For desktop and console apps, we have no such Jakarta-compliant web container. So you must bundle both the interface jar and the implementation jar with your app.
You can use a dependency-management tool such as Maven, Gradle, or Ivy to download and bundle the interface & implementation jars.
Jakarta Expression Language
To run Jakarta Bean Validation, we need another Jakarta tool as well: Jakarta Expression Language, a special purpose programming language for embedding and evaluating expressions. Jakarta Expression Language is also known simply as EL.
Jakarta Expression Language is defined by Jakarta EE as a specification for which you must download a jar of interfaces. And you also need to obtain an implementation of these interfaces in another jar.
You may have choice of implementations. As of 2021-03, I know of Eclipse Glassfish by Eclipse Foundation providing an implementation as a separate library we can download free-of-cost. There may be other implementations, such as Open Liberty by IBM Corporation. Shop around for an implementation that suits your needs.
Maven POM dependencies
Pulling all this info together, you need four jars: A pair of interface and implementation jars for each of two projects, Jakarta Bean Validation and Jakarta Expression Language.
Jakarta Bean Validation
Interface
Implementation
Jakarta Expression Language
Interface
Implementation
The following are the four dependencies you need to add to your Maven POM file, if Maven is your tool of choice.
As mentioned above, you may be able to find another implementation of EL to substitute for the Glassfish library I use here.
<!--********| Jakarta Bean Validation |********-->
<!-- Interface -->
<!-- https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.0</version>
</dependency>
<!-- Implementation -->
<!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.1.Final</version>
</dependency>
<!-- Jakarta Expression Language -->
<!-- Interface -->
<!-- https://mvnrepository.com/artifact/jakarta.el/jakarta.el-api -->
<dependency>
<groupId>jakarta.el</groupId>
<artifactId>jakarta.el-api</artifactId>
<version>4.0.0</version>
</dependency>
<!-- Implementation -->
<!-- https://mvnrepository.com/artifact/org.glassfish/jakarta.el -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>4.0.1</version>
</dependency>
That should eliminate the javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory' error.
Example usage
You can test your setup with the following simple class, Car. We have validations on each of the three member fields.
package work.basil.example.beanval;
import jakarta.validation.constraints.*;
public class Car
{
// ---------------| Member fields |----------------------------
#NotNull
private String manufacturer;
#NotNull
#Size ( min = 2, max = 14 )
private String licensePlate;
#Min ( 2 )
private int seatCount;
// ---------------| Constructors |----------------------------
public Car ( String manufacturer , String licensePlate , int seatCount )
{
this.manufacturer = manufacturer;
this.licensePlate = licensePlate;
this.seatCount = seatCount;
}
// ---------------| Object overrides |----------------------------
#Override
public String toString ( )
{
return "Car{ " +
"manufacturer='" + manufacturer + '\'' +
" | licensePlate='" + licensePlate + '\'' +
" | seatCount=" + seatCount +
" }";
}
}
Or, if using Java 16 and later, use a more brief record instead.
package work.basil.example.beanval;
import jakarta.validation.constraints.*;
public record Car (
#NotNull
String manufacturer ,
#NotNull
#Size ( min = 2, max = 14 )
String licensePlate ,
#Min ( 2 )
int seatCount
)
{
}
Run the validation. First we run with a successfully configured Car object. Then we instantiate a second Car object that is faulty, violating one constraint on each of the three fields.
package work.basil.example.beanval;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;
public class App
{
public static void main ( String[] args )
{
App app = new App();
app.demo();
}
private void demo ( )
{
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
// No violations.
{
Car car = new Car( "Honda" , "ABC-789" , 4 );
System.out.println( "car = " + car );
Set < ConstraintViolation < Car > > violations = validator.validate( car );
System.out.format( "INFO - Found %d violations.\n" , violations.size() );
}
// 3 violations.
{
Car car = new Car( null , "X" , 1 );
System.out.println( "car = " + car );
Set < ConstraintViolation < Car > > violations = validator.validate( car );
System.out.format( "INFO - Found %d violations.\n" , violations.size() );
violations.forEach( carConstraintViolation -> System.out.println( carConstraintViolation.getMessage() ) );
}
}
}
When run.
car = Car{ manufacturer='Honda' | licensePlate='ABC-789' | seatCount=4 }
INFO - Found 0 violations.
car = Car{ manufacturer='null' | licensePlate='X' | seatCount=1 }
INFO - Found 3 violations.
must be greater than or equal to 2
must not be null
size must be between 2 and 14
If using Spring Boot this works well. Even with Spring Reactive Mongo.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
and validation config:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
#Configuration
public class MongoValidationConfig {
#Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
for sbt, use below versions
val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"
val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"
val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"
I ran into the same issue and the above answers didn't help. I need to debug and find it.
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.6.0-cdh5.13.1</version>
<exclusions>
<exclusion>
<artifactId>jsp-api</artifactId>
<groupId>javax.servlet.jsp</groupId>
</exclusion>
</exclusions>
</dependency>
After excluding the jsp-api, it worked for me.
for gradle :
compile 'javax.el:javax.el-api:2.2.4'
For anyone using Hibernate Validator 7 (org.hibernate.validator:hibernate-validator:7.0.0.Final) as Jakarta Bean Validation 3.0 implementation should use the dependency:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>4.0.0</version>
</dependency>
as stated in Hibernate Validator documentation
I am stranded on old technologies, so I had to add the following:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>
Other answers report the same dependencies, I only updated the versions.
If your server is websphere and you used spring-boot-starter-validation , exclude tomcat-embed-el.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
</exclusion>
</exclusions>
</dependency>

Trouble starting Hibernate Validator due to Bean Validation API

I'm trying to use Hibernate Validator in my project, but it isn't working. On the following line:
SessionFactory sessions = config.buildSessionFactory(builder.build());
I get the following exception:
org.hibernate.cfg.beanvalidation.IntegrationException: Error activating Bean Validation integration
at org.hibernate.cfg.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:154)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:311)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at net.myProject.server.util.HibernateUtil.<clinit>(HibernateUtil.java:32)
... 36 more
Caused by: java.lang.NoSuchMethodError: javax.validation.spi.ConfigurationState.getParameterNameProvider()Ljavax/validation/ParameterNameProvider;
at org.hibernate.validator.internal.engine.ValidatorFactoryImpl.<init>(ValidatorFactoryImpl.java:119)
at org.hibernate.validator.HibernateValidator.buildValidatorFactory(HibernateValidator.java:45)
at org.hibernate.validator.internal.engine.ConfigurationImpl.buildValidatorFactory(ConfigurationImpl.java:217)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)
I found this question which seems quite similar to my problem. He describes his solution as
I had yet another bean validator jar in the class path. But not from
maven, so i didn't realize it. Removing that solved the problem.
I think my problem is the same. On http://hibernate.org/validator/documentation/getting-started/ it says:
This transitively pulls in the dependency to the Bean Validation API
(javax.validation:validation-api:1.1.0.Final)
That must be causing this issue, since reverting to an older version (4.3.1.Final) fixes the issue. Is there a way to force Hibernate to not pull in the Bean Validation API?
Edit: I've tried to exclude the javax-validation api:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.3.Final</version>
<exclusions>
<exclusion>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</exclusion>
</exclusions>
</dependency>
But it didn't seem to have any effect.
Try adding this dependency to your pom.xml
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
If not consider using hibernate-validator4.2.0.Final I have that one in my config and it is working fine.
For me, the 1.1.0.Final version javax.validation.validation-api had worked. Because, the javax.validation.spi.ConfigurationState interface of 1.1.0.Final has getParameterNameProvider method, which was absent in 1.0.0.GA.
I added the below dependency in pom.xml
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
<scope>test</scope>
</dependency>
I had the problem again. Thats how I've fixed that:
1-Exclude spring.validator from the 'web' dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</exclusion>
</exclusions>
</dependency>
2-After insert the dependecy with a previous version:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
in my case i just deleted the hibernate-validator and it worked .(i also had a combo of both validation api and hibernate-validator and tried everything) or you can go to your maven repository-->org and then delete the hibernate folder and rebuild your project again..
hope it helps..
I thought it would be useful to explain what is going on here.
Hibernate is calling ConfigurationState.getParameterNameProvider:
ValidatorFactoryImpl.java:
public ValidatorFactoryImpl(ConfigurationState configurationState) {
...
configurationState.getParameterNameProvider()
...
}
You can find the documentation of getParameterNameProvider:
getParameterNameProvider
ParameterNameProvider getParameterNameProvider()
Returns the parameter name provider for this configuration.
Returns:
parameter name provider instance or null if not defined
Since:
1.1
So what's the problem? The problem is that the method didn't always exist. It was added at some point in the future.
And the rule when creating interfaces is that they are set in concrete: you shall not change an interface ever. Instead the JavaX validator changed the ConfigurationState interface, and added a few new methods over the years.
The java validation code is passing the Hiberate an outdated ConfiguationState interface; one that doesn't implement the required interfaces.
You need to ensure that javax.validation.Validation.buildDefaultValidatorFactory is updated to to support version 1.1.
Removing this jar javax.validation:validation-api:1.1.0.Final solved my problem.
Make sure you have only one validation jar. If we have two jars then they may conflict resulting in error.
Go to the dependecies project and delete, hibernate.validator, and reinstall that in the most recent version. It has solved the problem for me.

Problems with instantiating of HttpServletRequest with Mockito

The following line fails with an exception:
HttpServletRequest req = mock(HttpServletRequest.class);
Exception:
java.lang.ClassFormatError: Absent Code attribute in method
that is not native or abstract in class file
javax/servlet/http/Cookie
Has anyone faced this problem?
UPD
Solution was found here.
You should add implementation of Servlet API to your test/runtime classpath. I would suggest to use this dependency:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.servlet</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>

Categories