Conditional JSON response creation using Java POJO for rest service - java

I am creating a rest service and providing json to our consumer.
I have two fields cardType, cardDetails ( i have more fields but these are what relevant).
If cardType is credit card then only I want to send another field cardDetails in json.
If cardtype is something else, Then I don't want to send card details(not even empty data) .
I am not getting how can i achieve solution for this.

Which language do you use?
In spring framework you can do it very easy.
You can add if condition in your controller.
#RestController
public class YourController {
#Autowired
YourRepository yourRepository;
#RequestMapping("/creaditCardsInfo")
public String sendCreditCardToCustomer(#RequestParam(value = "creditCardType", defaultValue = "none") String cardType,#RequestParam(value = "cardDetails", default = "someInfo") String cardDetails) {
if("credit".equals(cardType.trim()) && !(cardDetails.isEmpty())){
return new RequredCreditInfoObject();
}
if you use maven your pom.xml should contain required libs
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data (if We are going to use Repositories, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<!-- for JSon marshaling -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
Good luck,

Related

I want to display different html in Spring Boot

I need to test different client against each other. for that i need to be able to open different html pages with spring boot.
i tried to do this:
Multiple index.html in spring boot
but it does only return a string "thick_client" on the webpage.
my controller looks like this:
#RestController
public class ApiController {
#Autowired
private StockRepository stockRepository;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "thick_client";
}
#RequestMapping(value = "/anotherIndex", method = RequestMethod.GET)
public String anotherIndex() {
return "thin_client";
}
application.properties:
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
My Folder Structure looks like this:
pom.xml:
<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-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
cheers!
Try returning the string without the extension.
For e.g return "thin_client";

Using Spring data with PagingAndSortingRepository and IgniteRepository is throwing error

I am working on a spring data project and tying to integrate Ignite cache with it.
I was using already using PagingAndSortingRepository<Entity, String>
#Repository public interface UserRepository extends PagingAndSortingRepository<User, String> {
Page<User> findByUserId(final String userId, final Pageable pageable);
Page<User> findByFirstName(final String firstName, final Pageable pageable);
Page<User> findByEmailAddress(final String emailAddress, final Pageable pageable);
Page<User> findAllBy(final Pageable pageable);
}
and I added a new Repository IgniteRepository<Entity, String>
#RepositoryConfig(cacheName = "UserCache")
public interface UserCacheRepository extends IgniteRepository<UserCacheDto, String> {
#Query("select UserCacheDto FROM UserCacheDto WHERE userId = ?")
List<UserCacheDto> findByUserId(final String userId);
#Query("select UserCacheDto FROM UserCacheDto WHERE firstName = ?")
List<UserCacheDto> findByFirstName(final String firstName);
#Query("select UserCacheDto FROM UserCacheDto WHERE emailAddress = ?")
List<UserCacheDto> findByEmailAddress(final String emailAddress);
}
The idea behind this setup was to fetch from the database only when the data is not found in cache
Below are my project dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.src.portal</groupId>
<artifactId>portalDataBaseCacheModule</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>portalDataBaseCacheModule</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring.version>2.5.4</spring.version>
<ignite.version>2.9.0</ignite.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-spring-data_2.2</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-core</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-spring-boot-autoconfigure-ext</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-zookeeper</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-log4j2</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-log4j</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.2</version>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3.0.0</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
Upon doing this integration I am getting the below compilation error,
java: name clash: deleteAllById(java.lang.Iterable) in
org.apache.ignite.springdata22.repository.IgniteRepository and
deleteAllById(java.lang.Iterable<? extends ID>) in
org.springframework.data.repository.CrudRepository have the same
erasure, yet neither overrides the other
From the error it appears that somehow since both the repository are internally extending CrudRepository its causing an issue, I am not able to Figure out why and how to solve this issue.
Please help here.
According to your error UserCacheRepository inherits IgniteRepository.deleteAllById(Iterable<K> ids) and CrudRepository.deleteAllById(Iterable<? extends ID> ids), but erasures for Iterable<K> and Iterable<? extends ID> would be the same (just Iterable), so we get into situation when class has two methods with absolutely same signatures and this lead to name clash error.
Root cause for this error is that IgniteRepository originally was written when CrudRepository didn't have deleteAllById() method, meanwhile CrudRepository that comes with modern versions of spring-boot-starter-data-jpa has this method.
You may try to use older version for spring data if it possible for rest of your application.
Also you mey try to explicitly override deleteAllById(Iterable iterable) method, but I'm not sure if it helps.
The best option is to update apache-ignite-extensions to work with latest spring data, so you can create a Jira ticket in Apache Ignite project for this.

Spring #valid annotation cannot be resolved

I am trying to create a simple JPA framework that performs simple CRUD operations like save employees, delete employees or get a simple employee.
When i am using the valid annotation
#PostMapping("/employees")
public Employee createEmployee(#Valid #RequestBody Employee emp)
return empdao.save(emp);
Its saying that Valid cannot be resolved to a type
I am using these starter dependencies listed below, I dont know if there is a conflict somewhere
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Please provide a solution to this, or should i skip the Valid annotation all together,will it work without the valid annotation.
You need validation dependency, this should fix your problem :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Spring Boot framework Pageable actual and formal arument lists different in length

I am writing a Java Spring REST server using Spring Boot.
This is the dependency list:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
</dependencies>
This is a part of my a controller class:
#RequestMapping(path = "/", method = RequestMethod.GET)
public GenericResponse<List<Trip>> getUserTrips(Pageable pageable , #RequestParam("owner") String owner) {
List<Trip> trips = tripRepository.findByOwner(owner , pageable);
for (Trip trip : trips) {
Link link = linkTo(methodOn(TripController.class).getTripInfo(trip.getTripId())).withSelfRel();
trip.add(link);
}
return new GenericResponse<List<Trip>>(200, "Success", trips);
}
When compiled, I got the following error:
method getUserTrips in class com... cannot be applied to given types
required org.sptringframework.data.domain.Pageable, java.lang.String
found: java.lang.String
reason: actual and formal argument lists differ in length
I don't understand. I thought Pageable automatically parse the ?page=x&pageSize=y to the pageable var.
Do I forget to add any dependencies? What is wrong?
I do not use WebMv (it's not in my dependency list) Is it why this does not work?

Why do I have ambiguous handler methods mapped for HTTP path in my Spring Boot Rest Data Application?

I have done nothing special until now, but got this annoying Exception:
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/directoryWatches': {public org.springframework.http.ResponseEntity org.springframework.data.rest.webmvc.RepositoryEntityController.headCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable) throws org.springframework.web.HttpRequestMethodNotSupportedException, public org.springframework.hateoas.Resources org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(org.springframework.data.rest.webmvc.RootResourceInformation,org.springframework.data.rest.webmvc.support.DefaultedPageable,org.springframework.data.domain.Sort,org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler) throws org.springframework.data.rest.webmvc.ResourceNotFoundException,org.springframework.web.HttpRequestMethodNotSupportedException}
Here is my entity:
#Entity
public class DirectoryWatch {
#Id
#GeneratedValue
private long id;
#Column(unique = true)
private String name;
//setters, getters and default constructor...
}
And my DirectoryWatchRepository:
#RepositoryRestResource
public interface DirectoryWatchRepository extends PagingAndSortingRepository<DirectoryWatch, Long> {
}
The exception occurs, when I open the HAL Browser and try to open the NON-GET HTTP Methods:
Snippets of my pom file:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.M2</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
Dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-docs</artifactId>
</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-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-remote-shell</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</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.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>
</dependencies>
Has anyone a helping idea?
Thank you,
Christian
This suspiciously looks like the regression in Spring Framework 4.3 RC1 that I've reported here. The issue is already fixed and the upcoming Spring Boot 1.4 M3 is going to include the fixed version.
The release Boot should be available in a couple of days. Until that has happened you could just manually upgrade to Spring Framework 4.3 RC2.

Categories