Using Spring RestTemplate in JAX-RS project - spring

My project consist of 5 modules. And only one of them uses JAX-RS, others use Spring. My current task is develop service, that will be send HTTP requests to some API. I wanna use Spring RestTemplate for this task, but problem is project with JAX-RS haven't RestTemplate class and other needfull dependencies. I wanna use:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
in the JAX-RS module, to avoid code duplicating for RestTemplate and for some JAX-RS client. Is it good idea? Will be RestTemplate work properly without spring-core dependency?

Using RestTemplate
To use RestTemplate you need just the spring-web dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
The spring-web dependency has spring-core as a transitive dependency.
To use RestTemplate it's as simple as:
public class ExampleWithRestTemplate {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =
restTemplate.getForEntity("http://date.jsontest.com", String.class);
System.out.println(response.getBody());
}
}
Considering JAX-RS Client API as an alternative
Instead of RestTemplate you also could consider JAX-RS 2.0 Client API to consume REST web services. Jersey is the JAX-RS reference implementation and offers a great API.
To use Jersey Client API, the following dependency is required:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
</dependency>
For more details, have a look at the documentation.
You also could consider the Jersey Client Proxy API. The basic idea of this approach is to attach the standard JAX-RS annotations to an interface, and then implement that interface by a resource class on the server side while reusing the same interface on the client side by dynamically generating an implementation of that using java.lang.reflect.Proxy calling the right low-level client API methods.
To use the Jersey Client Proxy API, the following dependency is required:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-proxy-client</artifactId>
<version>2.23.2</version>
</dependency>

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.

Jackson Object Mapper not working when extended configuration provided but working when providing class level/field level annotations in 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.

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.

Prevent XXE (External Entity Processing) Attack with JAXB + Spring RESTful Web Services

I know that we can prevent the XXE attack by setting the property IS_SUPPORTING_EXTERNAL_ENTITIES in the abstract class XMLInputFactory to false in JAXB.
I have also seen this stackoverflow answer.
My question here is,
How do I create a instance of XMLInputFactory and set this IS_SUPPORTING_EXTERNAL_ENTITIES property to false when the spring application loads up. And that particular XMLInputFactory instance should only be used for all the JAXB conversion for all the classes that uses javax.xml.bind.annotation package.
Spring uses RequestMappingHandlerAdapter which is an AbstractHandlerMethodAdapter that supports HandlerMethods with the signature -- method argument and return types, defined in #RequestMapping.
There are 7 seven HttpMessageConverters and one of them is Jaxb2RootElementHttpMessageConverter
Jaxb2RootElementHttpMessageConverter is from the spring-web package.
From 3.2.8 version of spring-web onwards Jaxb2RootElementHttpMessageConverter sets the processExternalEntities to false which in turn sets the XMLInputFactory property IS_SUPPORTING_EXTERNAL_ENTITIES to false.
Refer : Jaxb2RootElementHttpMessageConverter from Spring
Answer use
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.8.RELEASE</version>
</dependency>

Resources