400 Bad Request using RestTemplete and postForObject - spring

i'm building two applications using Spring 3.The first one is meant to be rest API and the second is a client.The client must create a reservation. I'm getting 400 Bad Request error,please help.
The class Reservation in the client app:
package ma.ensias.agencecentrale.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
#JsonIgnoreProperties(ignoreUnknown=true)
#Entity
#Table(name="reservations")
public class Reservation implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idReservation;
private String date;
#ManyToOne
#JoinColumn(name="id_utilisateur")
private Utilisateur utilisateur;
#JsonIgnore
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="passager_reservation", joinColumns=#JoinColumn(name="id_reservation"), inverseJoinColumns=#JoinColumn(name="id_passager"))
private Collection<Passager> passagers;
#JsonIgnore
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="vol_reservation", joinColumns=#JoinColumn(name="id_reservation"), inverseJoinColumns=#JoinColumn(name="id_vol"))
private Collection<Vol> vols;
// Contructor without fields
public Reservation() {
super();
}
// contructor with date attribute
public Reservation(String date) {
super();
this.date = date;
}
// ----------------------- Getters and setters-------------------------------
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
#JsonProperty(value="client")
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public Collection<Vol> getVols() {
return vols;
}
public void setVols(Collection<Vol> vols) {
this.vols = vols;
}
public Long getIdReservation() {
return idReservation;
}
}
the rest Client :
//-------------------Create a Reservation--------------------------------------------------------
#RequestMapping("/ajouterReservation")
private static void ajouterReservation(Reservation reservation) {
RestTemplate restTemplate = new RestTemplate();
Reservation addedRes = restTemplate.postForObject(REST_SERVICE_URI,reservation, Reservation.class);
}
And the class Reservation in provider app:
package ma.ensias.agencevoyage.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
#JsonIgnoreProperties(ignoreUnknown=true)
#Entity
#Table(name="reservations")
public class Reservation implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idReservation;
private String date;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id_client")
private Client client;
#JsonIgnore
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="passager_reservation", joinColumns=#JoinColumn(name="id_reservation"), inverseJoinColumns=#JoinColumn(name="id_passager"))
private Collection<Passager> passagers;
#JsonIgnore
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="vol_reservation", joinColumns=#JoinColumn(name="id_reservation"), inverseJoinColumns=#JoinColumn(name="id_vol"))
private Collection<Vol> vols;
// Contructor without fields
public Reservation() {
super();
}
// contructor with date attribute
public Reservation(String date) {
super();
this.date = date;
}
// ----------------------- Getters and setters-------------------------------
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Collection<Passager> getPassagers() {
return passagers;
}
public void setPassagers(Collection<Passager> passagers) {
this.passagers = passagers;
}
public Collection<Vol> getVols() {
return vols;
}
public void setVols(Collection<Vol> vols) {
this.vols = vols;
}
}
and the controller is :
//-------------------Create a Reservation--------------------------------------------------------
#RequestMapping(value = "/ajouterReservation", method = RequestMethod.POST, consumes="application/json")
public ResponseEntity<String> ajouterReservation(#RequestBody Reservation reservation) {
metier.ajouterReservation(reservation);
return new ResponseEntity(HttpStatus.CREATED);
}
I also tested the provider using post man and it is working.
The error i'm getting is below :
GRAVE: Servlet.service() for servlet [appServlet] in context with path [/agencecentrale] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 415 Type de Support Non Supporté] with root cause
org.springframework.web.client.HttpClientErrorException: 415 Type de Support Non Supporté
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:532)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:488)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:446)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:294)
at ma.ensias.agencecentrale.controllers.ReservationController.ajouterReservation(ReservationController.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:958)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1087)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

Root cause : Problem is with content type set in the provider controller:
#RequestMapping(value = "/ajouterReservation", method = RequestMethod.POST, consumes="application/json")
public ResponseEntity<String> ajouterReservation(#RequestBody Reservation reservation)
Solution 1: remove consumes="application/json" in the handler method
Solution 2 : Set the headers accordingly before making the rest call and make use of exchange method of RestTemplate like below :
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers=new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity requestEntity=new HttpEntity(reservation, headers);
Reservation addedRes = restTemplate.exchange(REST_SERVICE_URI, HttpMethod.POST,requestEntity,Reservation.class);

Related

Spring data crud repository save method not able to save Java model in Redis cache

We are trying to save a model into the Redis cache using the spring data crud repository. This model has one property which is a map like below.
private Map<String, StudentInfo> studentData = new HashMap<String, StudentInfo>();
And this StudentInfo model has another Map as a property as below:-
private Map<String, Set<Books>> stBooks = new HashMap<String, Set<Books>>();
So overall structure is like this:-
Student.java
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#JsonRootName(value = "student")
#JsonInclude(Include.NON_NULL)
public class Student implements Serializable {
private static final long serialVersionUID = -2421290151039598746L;
private Map<String, StudentInfo> studentData = new HashMap<String, StudentInfo>();
#JsonCreator
public Student(#JsonProperty("studentData") Map<String, StudentInfo> aStudentData)
{
super();
this.setStudentData(aStudentData);
}
public void studentData(String aId, StudentInfo astudentData)
{
this.studentData.put(aId, astudentData);
}
public Map<String, StudentInfo> getStudentData()
{
return this.studentData;
}
private void setStudentData(Map<String, StudentInfo> aStudentData)
{
this.studentData = aStudentData;
}}
StudentInfo.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#JsonRootName(value = "studentInfo")
#JsonInclude(Include.NON_NULL)
public class StudentInfo implements Serializable {
private static final long serialVersionUID = 6873987079436896955L;
String stName = null;;
private Map<String, Set<Books>> stBooks = new HashMap<String, Set<Books>>();
public StudentInfo(String stName)
{
super();
this.setDealerCode(stName);
}
#JsonCreator
public StudentInfo(#JsonProperty("stName") String aStName,
#JsonProperty("stBooks") Map<String, Set<Books>> aStBooks)
{
super();
this.setDealerCode(aStName);
this.setStBooks(aStBooks);
}
private void setStBooks(Map<String, Set<Books>> aStBooks)
{
this.stBooks = aStBooks;
}
public Map<String, Set<Books>> getStBooks()
{
return this.stBooks;
}
private void setDealerCode(String astName)
{
this.stName = astName;
}
public String getStName()
{
return this.stName;
}
#Override
public String toString() {
return "Student [StudentName=" + stName + "]";
}}
Books.java
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#JsonRootName(value = "books")
#JsonInclude(Include.NON_NULL)
public class Books implements Serializable {
private static final long serialVersionUID = 1759477433483466736L;
private String bookName = null;
#JsonCreator
public Books(#JsonProperty("bookName") String aBookName)
{
super();
this.setBookName(aBookName);
}
public String getBookName() {
return bookName;
}
private void setBookName(String aBookName) {
this.bookName = aBookName;
}
public String toString()
{
return this.getBookName();
}}
StudenCacheModel.java
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#RedisHash(value = "StudentCache")
public class StudenCacheModel implements Serializable {
private static final long serialVersionUID = 9174813592532123048L;
#Id
String userId;
Student student;
}
Spring Crud Repository
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudenCacheRepository extends CrudRepository<StudenCacheModel, String> {
}
Saving the model using Crud Repo
StudenCacheModel studentCacheModel = new StudenCacheModel();
studentCacheModel.setSrudent(st); //student model set
studentCacheModel.setUserId(userId);
studentCacheRepository.save(studentCacheModel);
Exception:-
enter code hereorg.springframework.data.mapping.MappingException: Couldn't find
PersistentEntity for type class java.lang.Object!
Complete Stacktrace:-
org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type class java.lang.Object!
at org.springframework.data.mapping.context.MappingContext.getRequiredPersistentEntity(MappingContext.java:79) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeInternal(MappingRedisConverter.java:621) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeMap(MappingRedisConverter.java:867) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.lambda$writeInternal$2(MappingRedisConverter.java:640) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:360) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeInternal(MappingRedisConverter.java:624) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeMap(MappingRedisConverter.java:867) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.lambda$writeInternal$2(MappingRedisConverter.java:640) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:360) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeInternal(MappingRedisConverter.java:624) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeMap(MappingRedisConverter.java:867) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.lambda$writeInternal$2(MappingRedisConverter.java:640) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:360) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeInternal(MappingRedisConverter.java:624) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.lambda$writeInternal$2(MappingRedisConverter.java:666) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:360) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.writeInternal(MappingRedisConverter.java:624) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.write(MappingRedisConverter.java:424) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.convert.MappingRedisConverter.write(MappingRedisConverter.java:114) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.RedisKeyValueAdapter.put(RedisKeyValueAdapter.java:215) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.keyvalue.core.KeyValueTemplate.lambda$update$1(KeyValueTemplate.java:221) ~[spring-data-keyvalue-2.6.1.jar:2.6.1]
at org.springframework.data.keyvalue.core.KeyValueTemplate.execute(KeyValueTemplate.java:362) ~[spring-data-keyvalue-2.6.1.jar:2.6.1]
at org.springframework.data.keyvalue.core.KeyValueTemplate.update(KeyValueTemplate.java:221) ~[spring-data-keyvalue-2.6.1.jar:2.6.1]
at org.springframework.data.redis.core.RedisKeyValueTemplate.update(RedisKeyValueTemplate.java:178) ~[spring-data-redis-2.6.1.jar:2.6.1]
at org.springframework.data.keyvalue.repository.support.SimpleKeyValueRepository.save(SimpleKeyValueRepository.java:80) ~[spring-data-keyvalue-2.6.1.jar:2.6.1]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:529) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:639) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:163) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138) ~[spring-data-commons-2.6.1.jar:2.6.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.15.jar:5.3.15]
at com.sun.proxy.$Proxy163.save(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.15.jar:5.3.15]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.15.jar:5.3.15]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.15.jar:5.3.15]
at com.sun.proxy.$Proxy163.save(Unknown Source) ~[na:na]
Q1 - Is it the limitation of Spring data redis as we are able to save the same model using JEDIS library.
Any help/input will be highly apperciated !!
With a few small changes I got your example working:
In the POM used Spring Boot 2.6.4 and Java 11:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
Added a no-args constructor to StudentInfo
Added Lombok #ToString1 to StudenCacheModel
Modified Student to have method params that Jackson reflection could use:
#JsonRootName(value = "student")
#JsonInclude(Include.NON_NULL)
public class Student implements Serializable {
private static final long serialVersionUID = -2421290151039598746L;
private Map<String, StudentInfo> studentData = new HashMap<String, StudentInfo>();
#JsonCreator
public Student(#JsonProperty("studentData") Map<String, StudentInfo> studentData) {
super();
this.setStudentData(studentData);
}
public void studentData(String aId, StudentInfo studentData) {
this.studentData.put(aId, studentData);
}
public Map<String, StudentInfo> getStudentData() {
return this.studentData;
}
private void setStudentData(Map<String, StudentInfo> studentData) {
this.studentData = studentData;
}
}
Added a simple test with a runner on the main app:
#SpringBootApplication
public class SodemoApplication {
#Bean
CommandLineRunner testRepo(StudenCacheRepository studentCacheRepository) {
return args -> {
StudenCacheModel studentCacheModel = new StudenCacheModel();
StudentInfo si = new StudentInfo("bsb");
Student st = new Student(Map.of("bsb", si));
studentCacheModel.setStudent(st); //student model set
studentCacheRepository.save(studentCacheModel);
studentCacheRepository.findAll().forEach(System.out::println);
};
}
public static void main(String[] args) {
SpringApplication.run(SodemoApplication.class, args);
}
}
Running it you get the console output:
[2m2022-03-09 10:07:19.087[0;39m [32m INFO[0;39m [35m19669[0;39m [2m---[0;39m [2m[ main][0;39m [36mcom.example.sodemo.SodemoApplication [0;39m [2m:[0;39m Started SodemoApplication in 1.134 seconds (JVM running for 1.734)
StudenCacheModel(userId=19028f97-3e10-4776-8777-4a8cee224baf, student=com.example.sodemo.Student#24e5389c)
And on the Redis CLI you can see:
127.0.0.1:6379> keys *
1) "StudentCache"
2) "StudentCache:19028f97-3e10-4776-8777-4a8cee224baf"
127.0.0.1:6379> TYPE "StudentCache:19028f97-3e10-4776-8777-4a8cee224baf"
hash
127.0.0.1:6379> HGETALL "StudentCache:19028f97-3e10-4776-8777-4a8cee224baf"
1) "_class"
2) "com.example.sodemo.StudenCacheModel"
3) "student.studentData.[bsb].stName"
4) "bsb"
5) "userId"
6) "19028f97-3e10-4776-8777-4a8cee224baf"
127.0.0.1:6379>
I've created a repo with the full running example at https://github.com/bsbodden/sodemo
BTW Spring Data Redis uses Lettuce by default unless you configure it to use Jedis; both drivers can be used to save #RedisHash annotated entities

java.lang.NullPointerException what I'm doing wrong?

I'm working on a project in which my intention is to run a Corn job and send mail to my friends to wishing them on their birthday, I was able to get email from MySQL DB and compared it to the current date but when it comes to sending an email I'm getting NullPointerException.
I'm sure there is no problem with application properties I used them with other projects as well and they are function properly
//Imports
package dev.teja.happybirthday;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.persistence.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Email;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
//Main
#SpringBootApplication
public class HappybirthdayApplication {
public static void main(String[] args) {
SpringApplication.run(HappybirthdayApplication.class, args);
}
#Autowired
MyFriendsRepository myFriendsRepository ;
#Scheduled(cron = "*/30 * * * * *")
void WishMyFriends() {
List<MyFriends> myFriendsList = myFriendsRepository.findAll();
myFriendsList.forEach(friend -> {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
String CurrentDate= formatter.format(date);
String GivenDate = formatter.format(friend.dob);
if (GivenDate.equals(CurrentDate)){
Job job = new Job();
Map<String, Object> model = new HashMap<>();
model.put("Name",friend.name);
job.sendWish(friend.email,model);
}
});
}
}
#Configuration
#ConditionalOnProperty(name = "scheduling.enabled", matchIfMissing = true)
#EnableScheduling
class Tasks {
}
//Model
#Data
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#ToString
#Entity
class MyFriends {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
#Email
#Column(unique = true)
String email;
#JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
Date dob;
Long phoneNumber;
}
//Repository
interface MyFriendsRepository extends JpaRepository<MyFriends, Long> {
}
#RestController
#RequestMapping("/")
class FriendsController {
#Autowired
MyFriendsRepository myFriendsRepository;
#PostMapping("/friends")
ResponseEntity<MyFriends> createFriend(#RequestBody MyFriends myFriend) {
myFriendsRepository.save(myFriend);
return new ResponseEntity<MyFriends>(myFriend, HttpStatus.CREATED);
}
#GetMapping("/friends")
List<MyFriends> getFriends() {
return myFriendsRepository.findAll();
}
}
//Interface
interface wisher{
void sendWish(String email, Map<String, Object> model);
}
//Implementation
#Service
class Job implements wisher{
#Autowired
private JavaMailSender sender;
#Autowired
private freemarker.template.Configuration config;
#Override
public void sendWish(String email,Map<String, Object> model) {
System.out.println("wishes sent to "+ email);
MimeMessage message = sender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Template template = config.getTemplate("new-template.ftl");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setTo(email);
helper.setFrom("kondasaitej#gmail.com");
helper.setSubject("Happy Birthday");
helper.setText(html,true);
sender.send(message);
} catch (MessagingException | IOException | TemplateException e) {
e.printStackTrace();
}
}
}
FreeMaker file in ./resources/Templates
/**
* FREEMAKER new-template.ftl
* <html xmlns="http://www.w3.org/1999/xhtml">
* <head>
* <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
* <title>Comment Alert Mail</title>
* </head>
* <body>
* <p>happy birthday ${Name}</p>
* </body>
*/
This is the error I'm getting this following
Hibernate: select myfriends0_.id as id1_0_, myfriends0_.dob as dob2_0_, myfriends0_.email as email3_0_, myfriends0_.name as name4_0_, myfriends0_.phone_number as phone_nu5_0_ from my_friends myfriends0_
wishes sent to kondasaitej#protonmail.com
2020-09-26 21:01:52.012 ERROR 84242 --- [ scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
java.lang.NullPointerException: null
at dev.teja.happybirthday.Job.sendWish(HappybirthdayApplication.java:115) ~[classes/:na]
at dev.teja.happybirthday.HappybirthdayApplication.lambda$WishMyFriends$0(HappybirthdayApplication.java:53) ~[classes/:na]
at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_251]
at dev.teja.happybirthday.HappybirthdayApplication.WishMyFriends(HappybirthdayApplication.java:44) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_251]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) [spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_251]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_251]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_251]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_251]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_251]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_251]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_251]
Try add getting in the #Autowired private JavaMailSender sender;
I think you have not implemented your JavaMailSender bean. Define a bean like below. Then your #Autowire annotation will work.
#Bean
public JavaMailSender getJavaMailSender()
{
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(25);
mailSender.setUsername("admin#gmail.com");
mailSender.setPassword("password");
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
return mailSender;
}

Spring CRUD App: Servlet.service() for servlet [dispatcherServlet] : java.lang.NullPointerException]

I've a problem to get employees data from mySQL db. According to logs there is a problem at line: 36 in my EmployeeServiceImpl.listEmployess metod.
Logs:
2018-10-18 16:07:42.871 ERROR 1504 --- [nio-8090-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.project.service.EmployeeServiceImpl.listEmployess(EmployeeServiceImpl.java:36) ~[classes/:na]
com.project.service.EmployeeServiceImpl$$FastClassBySpringCGLIB$$c7d76ecc.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at com.project.service.EmployeeServiceImpl$$EnhancerBySpringCGLIB$$1390ca06.listEmployess() ~[classes/:na]
at com.project.controller.EmployeeController.listEmployess(EmployeeController.java:34) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
EmployeeServiceImpl:
package com.project.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.project.dao.EmployeeDAO;
import com.project.entity.TEmployee;
#Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO employeeDAO;
public void setEmployeeDAO(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
#Override
#Transactional
public void addEmployee(TEmployee p) {
this.employeeDAO.addEmployee(p);
}
#Override
#Transactional
public void updateEmployee(TEmployee p) {
this.employeeDAO.updateEmployee(p);
}
#Override
#Transactional
public List<TEmployee> listEmployess() {
return this.employeeDAO.listEmployess();
}
#Override
#Transactional
public TEmployee getEmployeeById(int employee_id) {
return this.employeeDAO.getEmployeeById(employee_id);
}
#Override
#Transactional
public void removeEmployee(int employee_id) {
this.employeeDAO.removeEmployee(employee_id);
}
}
EmployeeService:
package com.project.service;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import com.project.entity.TEmployee;
#ComponentScan(basePackages= {"com.project.*"})
public interface EmployeeService {
public void addEmployee(TEmployee p);
public void updateEmployee(TEmployee p);
public List<TEmployee> listEmployess();
public TEmployee getEmployeeById(int id);
public void removeEmployee(int id);
}
EmployeeDAO:
package com.project.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import com.project.entity.TEmployee;
#ComponentScan(basePackages= {"com.project.*"})
public interface EmployeeDAO {
public void addEmployee(TEmployee p);
public void updateEmployee(TEmployee p);
public List<TEmployee> listEmployess();
public TEmployee getEmployeeById(int employee_id);
public void removeEmployee(int employee_id);
}
EmployeeDAOImpl:
package com.project.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.project.entity.TEmployee;
#Repository
public class EmployeeDAOImpl implements EmployeeDAO {
private static final Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addEmployee(TEmployee p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("TEmployee saved successfully, TEmployee Details="+p);
}
#Override
public void updateEmployee(TEmployee p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("TEmployee updated successfully, TEmployee Details="+p);
}
#SuppressWarnings("unchecked")
#Override
public List<TEmployee> listEmployess() {
Session session = this.sessionFactory.getCurrentSession();
List<TEmployee> EmployessList = session.createQuery("from TEmployee").list();
for(TEmployee p : EmployessList){
logger.info("TEmployee List::"+p);
}
return EmployessList;
}
#Override
public TEmployee getEmployeeById(int employee_id) {
Session session = this.sessionFactory.getCurrentSession();
TEmployee p = (TEmployee) session.load(TEmployee.class, new Integer(employee_id));
logger.info("TEmployee loaded successfully, TEmployee details="+p);
return p;
}
#Override
public void removeEmployee(int employee_id) {
Session session = this.sessionFactory.getCurrentSession();
TEmployee p = (TEmployee) session.load(TEmployee.class, new Integer(employee_id));
if(null != p){
session.delete(p);
}
logger.info("TEmployee deleted successfully, TEmployee details="+p);
}
}
And EmployeeController:
package com.project.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.project.entity.TEmployee;
import com.project.service.EmployeeService;
#ComponentScan(basePackages= {"com.project.*"})
#Controller
public class EmployeeController {
#Resource(name = "employeeService")
private EmployeeService employeeService;
#Autowired(required=true)
#Qualifier(value="employeeService")
public void setEmployeeService(EmployeeService ps){
this.employeeService = ps;
}
#RequestMapping(value = "/employess", method = RequestMethod.GET)
public String listEmployess(Model model) {
model.addAttribute("employee", new TEmployee());
model.addAttribute("listEmployess", this.employeeService.listEmployess());
return "employee";
}
//For add and update person both
#RequestMapping(value= "/employee/add", method = RequestMethod.POST)
public String addEmployee(#ModelAttribute("employee") TEmployee p){
if(p.getEmployeeID() == 0){
//new person, add it
this.employeeService.addEmployee(p);
}else{
//existing person, call update
this.employeeService.updateEmployee(p);
}
return "redirect:/employess";
}
#RequestMapping("/remove/{employee_id}")
public String removeEmployee(#PathVariable("employee_id") int employee_id){
this.employeeService.removeEmployee(employee_id);
return "redirect:/employess";
}
#RequestMapping("/edit/{employee_id}")
public String editEmployee(#PathVariable("employee_id") int employee_id, Model model){
model.addAttribute("employee", this.employeeService.getEmployeeById(employee_id));
model.addAttribute("listEmployess", this.employeeService.listEmployess());
return "employee";
}
}
So, according to logs there is a NPE returning from this line:
return this.employeeDAO.listEmployess();
Do you have any idea what could be wrong here?
Thanks in advance!
Hi instead of setter method use Autowired annotation on dependency private EmployeeDAO employeeDAO;
like
#Autowired
private EmployeeDAO employeeDAO;

Testing Spring Boot REST json result

I have some problem with checking json result
UserControllerTest class
package com.serwis.controller;
import com.serwis.PraktykiApplication;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(PraktykiApplication.class)
#WebIntegrationTest
public class UserControllerTests {
#Autowired
private UserRepository userRepository;
User user;
private MockMvc mockMvc;
#Before
public void setUp(){
user = new User("login1","password","email");
userRepository.deleteAll();
userRepository.save(user);
this.mockMvc = standaloneSetup(new UserController()).build();
}
#Test
public void createUser() throws Exception {
this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.login", is("login1")));
System.out.println(userRepository.findAll());
}
}
User class
package com.serwis.model;
import javax.persistence.*;
import java.util.Arrays;
import java.util.Set;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private long id;
#Column(name="login")
private String login;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#Column(name="avatar")
private byte[] avatar;
public User(){}
public User(String login, String password, String email) {
this.login = login;
this.password = password;
this.email = email;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", avatar=" + Arrays.toString(avatar) +
'}';
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
}
UserRepository class
package com.serwis.repository;
import com.serwis.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public interface UserRepository extends CrudRepository<User, Long>{
}
userController class
package com.serwis.controller;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Jodanpotasu on 2016-07-24.
*/
#Controller
public class UserController {
#Autowired
private UserRepository userRepository;
#RequestMapping("/user/create")
#ResponseBody
public String create(String email, String login, String password) {
String userId = "";
try {
User user = new User(email, login, password);
userRepository.save(user);
userId = String.valueOf(user.getId());
} catch (Exception ex) {
return "Error creating the user: " + ex.toString();
}
return "User succesfully created with id = " + userId;
}
#RequestMapping("/user/findall/")
#ResponseBody
public Iterable<User> findAll() {
return userRepository.findAll();
}
#RequestMapping("/user/delete")
#ResponseBody
public String delete(long id) {
User deleted = userRepository.findOne(id);
userRepository.delete(id);
return "USER DELETED: " + deleted;
}
#RequestMapping("/user/update")
#ResponseBody
public String update(long id, String login, String password, String email) {
User beforeUpdate = userRepository.findOne(id);
User afterUpdate = userRepository.findOne(id);
afterUpdate.setLogin(login);
afterUpdate.setEmail(email);
afterUpdate.setPassword(password);
return "BEFORE UPDATE: \n" + beforeUpdate + " <br> AFTER UPDATE: " + afterUpdate;
}
}
it should be like
[{"id":1,"login":"login1","password":"password","email":"email","avatar":null}]
But i still have error output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
and that is full output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.serwis.controller.UserControllerTests.createUser(UserControllerTests.java:56)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
at com.serwis.controller.UserController.findAll(UserController.java:37)
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.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
... 43 more
Spring boot version: 1.3.6 is there another better way to test json?
Here is my working class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(PraktykiApplication.class)
#WebIntegrationTest
public class UserControllerTests {
#Autowired
private UserRepository userRepository;
User user;
private MockMvc mockMvc;
#Autowired
UserController userController;
#Before
public void setUp(){
user = new User("login1","password","email");
userRepository.deleteAll();
userRepository.save(user);
this.mockMvc = standaloneSetup(userController).build();
}
#Test
public void createUser() throws Exception {
this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$[0].login", is("login1")));
System.out.println(userRepository.findAll());
}
}
it seems that spring boot did not see
this.mockMvc = standaloneSetup(new UserController()).build();

Acessing Remote/Local Session Beans

I'm trying to connect to a session bean. I tried many different ways that I found with Google, but I always get the same error because my JNDI lookup always returns NULL.
Here's the error:
java.lang.NullPointerException
at org.apache.jsp.index_jsp._jspService(index_jsp.java:85)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
So, I'm probably missing some configuration, but I'm newbie in this stuff. A little help?
Here's my Entity Bean:
package beans;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
#Entity
public class Album {
#Id
#Column(name="idalbum")
#GeneratedValue(generator="album_idalbum_seq")
#GenericGenerator(name="album_idalbum_seq", strategy = "increment")
private int id;
#Column(name="nomealbum")
private String nome;
#ManyToMany
#JoinTable(name = "albumfaixas",
joinColumns = {
#JoinColumn(name = "idalbum")
},
inverseJoinColumns = {
#JoinColumn(name="idfaixas")
}
)
private Set<Faixas> faixas = new HashSet<Faixas>();
public Album() {}
//gets and sets
}
My Session Bean:
package DAO;
import org.hibernate.*;
import sFactory.*;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import beans.*;
#Stateless
public class AlbumDAO implements AlbumRemote {
#PersistenceContext
private EntityManager entityManager;
public List<Album> listaAlbuns() { ... code ... }
public void createAlbum(Album f) { ... code ... }
public void updateAlbum(Album f) { ... code ... }
public void deleteAlbum(Album f) { ... code ... }
}
My Remote Interface:
package DAO;
import javax.ejb.Remote;
import java.util.List;
import beans.Album;
#Remote
public interface AlbumRemote {
public List<Album> listaAlbuns();
public void createAlbum(Album f);
public void updateAlbum(Album f);
public void deleteAlbum(Album f);
}
My Local Interface:
package DAO;
import javax.ejb.Local;
import java.util.List;
import beans.Album;
#Local
public interface AlbumLocal {
public List<Album> listaAlbuns();
public void createAlbum(Album f);
public void updateAlbum(Album f);
public void deleteAlbum(Album f);
}
The reference in web.xml:
<ejb-ref>
<ejb-ref-name>ejb/AlbumRemote</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home>DAO.AlbumLocal</home>
<remote>DAO.AlbumRemote</remote>
</ejb-ref>
My JSP Client code:
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
Object x = ctx.lookup("ejb/AlbumRemote");
AlbumRemote fr = (AlbumRemote)PortableRemoteObject.narrow(x, AlbumRemote.class);
fr.createAlbum(fx1);
I'm using myeclipse for developing and Tomcat for server
You're really close. Drop in the openejb.war file and this code should work.
Tomcat doesn't natively support EJBs, but it can easily be made to do so with OpenEJB. In fact we are now calling this combo Apache TomEE and are in the process of Java EE 6 Web Profile certifying it. So it will be in the ranks of Glassfish, JBoss, Geronimo, etc.
In case you don't already have one, make sure there is a WEB-INF/classes/META-INF/persistence.xml file in your app that defines your persistence unit.

Resources