Jackson Object Mapper not working when extended configuration provided but working when providing class level/field level annotations in Spring Boot - spring-boot

The below object mapper configuration is not working when I add jjwt security to spring boot application.
#Configuration
public class CustomObjectMapper extends ObjectMapper {
/**
* Default serial version id generated.
*/
private static final long serialVersionUID = 1L;
public CustomObjectMapper() {
this.setSerializationInclusion(Include.NON_EMPTY);
this.registerModule(new ThreeTenModule());
this.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
}
Security dependencies added here
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
where as the below Jackson annotations are working on class/field levels.
#JsonInclude(Include.NON_EMPTY)
Why the bean configured custom object mapper not been used for serialization & deserialization? Any other libraries configured object mapper overriding my custom mapper?

After a long investigation, i have noticed #EnableWebMvc annotated configuration bean available in one dependent library. And got to know from here that #EnableWebMvc disables Spring Boot's MVC auto-configuration, thus giving complete control to provide customer MVC configuration. HTTP Message Convertors will also be included in Spring MVC component which in turn disables my custom jackson object mapper configuration.
PS: As jjwt imports jackson databind dependency by default, it fell in my suspect list. Feel good that i could RCA. Thanks.

Related

Hystrix - behaviour of #HystrixCommand annotation

I have inherited a Java SpringBoot application (currently SpringBoot 2.7) that uses Hystrix for fault tolerance. I am aware that this has been deprecated, and we plan to more to Resilience4J
The Hystrix dependencies are
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.10.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
<version>2.2.10.RELEASE</version>
<scope>compile</scope>
</dependency>
The main class in the application is annotated with:
#EnableCircuitBreaker
#EnableHystrixDashboard
#EnableHystrix
The following properties are specified:
hystrix.threadpool.default.coreSize=30
hystrix.threadpool.default.maxQueueSize=300
hystrix.threadpool.default.queueSizeRejectionThreshold=300
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=30000
hystrix.command.default.circuitBreaker.errorThresholdPercentage=50
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=5000
hystrix.command.default.circuitBreaker.requestVolumeThreshold=60
hystrix.shareSecurityContext=true
I have gone through the usage of Hystrix within the application to understand exactly what the application is gaining from using Hystrix. I see that there are two different usages of the annotation HystrixCommand within the application.
In some cases, there are methods that are annotated as follows:
#HystrixCommand(fallbackMethod = "executeFallback")
public ResponseClass methodName (inputs...) {
private ResponseClass executeFallback(inputs...) {
LOGGER.error("Something went wrong...");
return new ResponseClass();
}
I have simplified the code, but my understanding is if the circuit is open, then it will result in the fallback method (named "executeFallback" above) being executed until the circuit is closed again.
But there are also many instances within the application of methods that are simply annotated with #HystrixCommand but there is no fallback method specified. These methods are also trying to access some data source, that could potentially be unavailable.
For example:
#HystrixCommand
public ResponseClass methodName (inputs...) {
My question is: what does an application gain from annotating methods with #HystrixCommand if no fallback method is specified?

integrate spring security and spring MVC and and spring integration with each other

I am currently developing a web site for having control over IOT devices by spring.
The application is based on spring boot.
I have developed most of rest API s by extending from DataJpa.
Next step I had to implement TCP connection in my application and after doing some
research I adopt spring integration for doing that and simple application worked well.
Next, I decided to add spring Integration to my application for only user authentication after that I configured that I realized that there are some conflicts
in my application and I received java: cannot access javax.servlet.Filter class file for javax.servlet.Filter not found.
I did some research in I found a related topic for spring webflux and it was said that I should implement spring security for webflux (integration in this case) not for spring web.
Now about the main problem: as I said earlier the structure of application should be like this:
1- first part which is MVC based and there are some webpages and data should be stored in mySql or mariaDB, also i want to authenticate and authorize users by spring security.
2-Second part of application is implementation Tcp socket via Netty or spring integration for having an an alive connection between IOT devices and Server.
Now I am looking for a way to be able to say to spring that it should distinguish
these two different contexts from each other and not combine configurations with the other one while they must work with each other.
Is there any way for this separation and tell spring combine them with special responsible for each?
note that adding following dependency did not change anyThing
`<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>`
other dependencies :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-ip</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</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-core</artifactId>
</dependency>
security Config :
#Configuration
#EnableWebSecurity
public class securityConfig extends WebSecurityConfigurerAdapter {
#Autowired
appUserDetailService appUserDetailService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(appUserDetailService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin").hasRole("ADMIN")
.antMatchers("/user").hasAnyRole("ADMIN", "USER")
.antMatchers("/","/home").permitAll()
.and().formLogin();
}
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
error which occurs :
java: cannot access javax.servlet.Filterclass file for javax.servlet.Filter not found
and points to first line of spring security configuration.
my application properties:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.datasource.url=jdbc:mariadb://localhost:3307/testapp
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
server.port=8081
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDBDialect
/C:/Users/s.movahedi/Downloads/t1/demo/src/main/java/com/example/demo/security/securityConfig.java:[17,8] cannot access javax.servlet.Filter [ERROR] class file for javax.servlet.Filter not found
So it's your demo app that needs to be changed to use jakarta instead of javax if you want to use Boot 3, Spring 6.

What kind of view technology used in spring boot by default

What kind of view technology used in spring boot by default when I add the 'Spring Boot Web Starter'.
If I want to use the JSP, I need to include the 'tomcat-embed-jasper' or 'Spring Boot Thymeleaf Starter' for thymeleaf templates. So I would like to know the default view technology of 'Spring Boot Web Starter'
By default there is no view You need to configure and add their dependencies.If You are using Spring Boot older versions then You can refer above answer but if You are using Spring Boot 2 then add on more dependency for thymeleaf-
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
JSP is supported by Spring out-of-the-box.
It can be configured like this
#EnableWebMvc
#Configuration
public class ApplicationConfiguration implements WebMvcConfigurer {
#Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
return bean;
}
}
or in properties file
spring.mvc.view.prefix: /WEB-INF/views/
spring.mvc.view.suffix: .jsp
For Thymeleaf
Spring Boot will provide auto-configuration for Thymeleaf with below dependency in pom.xml
Please make a note of version used. Also you might need to provide view properties like above
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>

JMX on Spring Boot project

I have annotated a class as follows:
#ManagedResource(objectName="com.myproject.bean.jmx:name=JMXSolrIndexerBean",
description="Index Solr Operations")
public class JMXSolrIndexerBean {
....
}
My pom has the following dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-jmx</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
I can't find my MBean in the JConsole... are there any configuration steps I am missing?
Two things:
You don't need the spring-integrtation-jmx dependency to make that work, the actuator starter is enough
Your class needs to be a spring bean if you want Spring Boot to auto-detect JMX annotation on them. So adding #Component on your JMXSolrIndexerBean is all that's needed as long as it is located in a package that is processed by component scan
In other words, that class of yours is just a pojo that spring know nothings about. #ManagedResource is not a stereotype that turns that class in a Spring Bean.

Conflict between Spring data MongoDb and Elasticsearch

I started a project in which I use both Mongo, Elasticsearch and spring boot.
With either technologies by itself, the project works just fine. However with both together, they conflict. I saw this particular article that seemed to be similar to my issue.
https://jira.spring.io/browse/DATAES-57
So I tried it out and it the problem is still there.
I put these on the Main class
#EnableAutoConfiguration(exclude = MongoRepositoriesAutoConfiguration.class)
#EnableMongoRepositories(basePackages = "com.searchizi.mongo.repository")
#EnableElasticsearchRepositories(basePackages = "com.searchizi.elasticsearch.repository")
#ComponentScan
public class Application implements CommandLineRunner { … }
A shortened form the the exception trace is this
The class SearchiziUser is in the com.searchizi.mongo.model package. It is not on the Elasticsearch scan path.
Caused by: java.lang.IllegalArgumentException: Unable to identify index name. SearchiziUser is not a Document. Make sure the document class is annotated with #Document(indexName="foo")
at org.springframework.util.Assert.isTrue(Assert.java:65)
at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.getPersistentEntityFor(ElasticsearchTemplate.java:869)
at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.createIndexIfNotCreated(ElasticsearchTemplate.java:684)
at org.springframework.data.elasticsearch.core.ElasticsearchTemplate.createIndex(ElasticsearchTemplate.java:135)
at org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository.createIndex(AbstractElasticsearchRepository.java:80)
at org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository.<init>(AbstractElasticsearchRepository.java:72)
at org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository.<init>(SimpleElasticsearchRepository.java:36)
The scanning for each repository type should be separated but apparently it is not. Any idea what to do?
This is clearly a bug in Spring Data Elasticsearch as it seems to scan for domain types in packages it actually shouldn't. I filed DATAES-?? for you. Also, I filed a ticket so that Spring Data Elasticsearch supports the new multi-store configuration improvements so that you shouldn't have to explicitly configure separate packages.
On a side note, excluding the auto-configuration is not necessary if you set up #EnableMongoRepositories as it will automatically disable Spring Boot's auto-configuration.
I faced this exception and I resolved by change version of elasticsearch and mongodb lib versions
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.10.0.RELEASE</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
<!-- ELASTICSEARCH -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>

Resources