I am trying to get the list of users from Mongodb with ajax it works without ajax. I did this with MySQL and it worked so I don't understand what is wrong with my code.
I can send the request and go to the method and return the List<User>.
But when I put it in map can't get that map as a response in the success function.
My Console Output:
free.js:31 Uncaught TypeError: Cannot read property 'action' of null
at window.onmessage (free.js:31)
window.onmessage # free.js:31
jquery.min.js:2 POST http://localhost:8080/UserManagementMongoDB/list 500
send # jquery.min.js:2
ajax # jquery.min.js:2
load # submitedform:342
onload # submitedform:25
submitedform:355 Uncaught ReferenceError: response is not defined
at Object.error (submitedform:355)
at u (jquery.min.js:2)
at Object.fireWith [as rejectWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Here is my Controller method
#RequestMapping(value="/list", method=RequestMethod.POST)
public #ResponseBody Map<String,Object> getAll(User user) {
Map<String,Object> map = new HashMap<String,Object>();
List<User> list = mainPageService.getAllUsers();
if (list != null){
map.put("status","200");
map.put("message","Data found");
map.put("data", list);
}else{
map.put("status","404");
map.put("message","Data not found");
}
return map;
}
And my ajax load function
data = "";
load = function(){
$.ajax({
url:'list',
type:'POST',
success: function(response){
alert("Hello");
data = response.data;
$('.tr').remove();
for(i=0; i<response.data.length; i++){
$("#table").append("<tr class='tr'> <td> "+response.data[i].userName+" </td> <td> "+response.data[i].userSurname+" </td> <td> <a href='#' onclick= edit("+i+");> Edit </a> </td> </td> <td> <a href='#' onclick='delete_("+response.data[i].userId+");'> Delete </a> </td> </tr>");
}
},
error: function () {
alert(response);
}
});
Here is my dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>UserManagementMongoDB</groupId>
<artifactId>UserManagementMongoDB</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>UserManagementMongoDB Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Servlet Library -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring.data.commons.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.data.mongodb.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.tanesha.recaptcha4j/recaptcha4j -->
<dependency>
<groupId>net.tanesha.recaptcha4j</groupId>
<artifactId>recaptcha4j</artifactId>
<version>0.0.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish/javax.json -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.10</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.framework.version}</version>
</dependency>
</dependencies>
<!-- Properties for the dependencies -->
<properties>
<java-version>1.7</java-version>
<!-- Spring properties -->
<spring.framework.version>5.0.9.RELEASE</spring.framework.version>
<spring.data.commons.version>1.12.1.RELEASE</spring.data.commons.version>
<spring.data.mongodb.version>1.10.6.RELEASE</spring.data.mongodb.version>
<!-- Other properties -->
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<junit.version>4.12</junit.version>
<jstl.version>1.2</jstl.version>
</properties>
<build>
<finalName>ExampleWebApplication</finalName>
</build>
</project>
I am getting 500 right now I just can't get the response everything other than that works. I can send my parameters with ajax just can't receive the map resources
My model code:
public class User {
#Id
private String userId;
private String userName;
private String userSurname;
private String phoneNo;
public User(String userId,String userName,String userSurname,String phoneNo) {
setUserId(userId);
setUserName(userName);
setUserSurname(userSurname);
setPhoneNo(phoneNo);
}
public User() {
// TODO Auto-generated constructor stub
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSurname() {
return userSurname;
}
public void setUserSurname(String userSurname) {
this.userSurname = userSurname;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
My Stacktrace:
ava.lang.Exception
at com.kaan.springmvc.controller.MainPageController.getAll(MainPageController.java:117)
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.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:891)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Blockquote
Do you separate the front end and back end?
If yes, it might be different server or port number and violate CORS. Please help to update more information.
The second point, your method require User object, but i don't any thing relative to it from ajax request?
Related
I am currently working on a FAQ Web Application in Spring Boot. My index page is working fine but if I want to open another HTML Page I get a 404 Not found Error Page in my browser and Intellij says:
WARN 8068 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound : No mapping for GET /new
How can I fix that?
IndexController:
#Controller
public class IndexController {
#Autowired
private FAQService service;
#RequestMapping("/")
public String viewHomePage(Model model) {
List<FAQ> listFaqs = service.listAll();
model.addAttribute("listFaqs", listFaqs);
return "index";
}
#RequestMapping("/home")
public String backHomePage(Model model) {
List<FAQ> listFaqs = service.listAll();
model.addAttribute("listFaqs", listFaqs);
return "index";
}
#RequestMapping("/new")
public String showNewProductForm(Model model) {
FAQ faq = new FAQ();
model.addAttribute("faq", faq);
return "new_product";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveProduct(#ModelAttribute("faq") FAQ faq) {
service.save(faq);
return "redirect:/";
}
#RequestMapping("/edit/{id}")
public ModelAndView showEditProductPage(#PathVariable(name = "id") int id) {
ModelAndView mav = new ModelAndView("edit_faq");
FAQ faq = service.get(id);
mav.addObject("faq", faq);
return mav;
}
#RequestMapping("/delete/{id}")
public String deleteProduct(#PathVariable(name = "id") int id) {
service.delete(id);
return "redirect:/";
}
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3" lang="en">
<link rel="stylesheet" type="text/css" th:href="#{/static/css/styles.css}"/>
<head>
<title>WebApp</title>
</head>
<body>
<div align="center"><h3 th:inline="text">Welcome [[${#httpServletRequest.remoteUser}]]</h3></div>
<div class="logout-btn" th:align="center">
<a th:href="#{/logout}"><button>Logout</button></a>
</div>
<div align="center">
<br>
<h1>Manage Excel Files</h1>
<th:block th:include="/_menu"></th:block>
<div class="ncontent-btn">
<button>New Entry</button>
<a th:href="#{/excel/export}"><button>Export to Excel</button></a>
</div>
<br/>
</div>
</body>
</html>
POM.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>net.sf.supercsv</groupId>
<artifactId>super-csv</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application.properties
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=10MB
spring.mvc.dispatch-options-request=true
spring.datasource.continue-on-error=true
spring.mvc.static-path-pattern=/static/**
spring.jpa.open-in-view=false
All my HTML files are in /resources/templates path.
You are returning "new_product", in the /new method.
You have to create a new_product view (new_product.jsp / new_product.html..) and do whatever you want to inside, then it will be ok and you'll get a 200 response.
If your file already exists, maybe the path is not correct and you have to configure it. Try to put the html file in static folder otherwise add your path in your application.properties
Heres code of the bean that we validate:
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.io.Serializable;
public class NewUserCompanyForm implements Serializable {
private static final long serialVersionUID = 6414340627544822204L;
#Email(groups = ValidationGroup1.class)
#NotBlank(groups = ValidationGroup1.class)
private String userName;
#NotBlank(groups = ValidationGroup1.class)
private String password;
#NotBlank(groups = ValidationGroup1.class)
private String repeatedPassword;
#NotBlank(groups = ValidationGroup1.class)
private String companyName;
#Pattern(regexp = "\\d\\d-\\d\\d\\d", groups = ValidationGroup2.class)
private String postalCode;
#Pattern(regexp = "\\p{L}*", groups = ValidationGroup2.class)
private String city;
#Pattern(regexp = "[-A-Za-z0-9 ,.]*", groups = ValidationGroup2.class)
private String addressDetails;
//didn't copied get/set methods
public interface ValidationGroup1 {
}
public interface ValidationGroup2 {
}
}
Part of configuration classes:
#Bean
public LocalValidatorFactoryBean localValidatorFactoryBean(){
LocalValidatorFactoryBean localValidatorFactoryBean=new LocalValidatorFactoryBean();
return localValidatorFactoryBean;
}
Class that I use to test validation:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {SpringWebFlowConfiguration.class, WebConfiguration.class})
public class NewUserCompanyFormValidationTest {
#Autowired
#Qualifier("localValidatorFactoryBean")
private LocalValidatorFactoryBean validator;
#Autowired
private MessageSource messageSource;
#Test
public void DependencyInjectionTest(){
Assert.assertNotNull(validator);
}
#Test
public void NewUserCompanyFormValidatingTest(){
NewUserCompanyForm form1=new NewUserCompanyForm();
form1.setPassword("");
form1.setUserName("");
form1.setRepeatedPassword("");
Set<ConstraintViolation<NewUserCompanyForm>> volations1=validator.validate(form1,NewUserCompanyForm.ValidationGroup1.class);
}
}
Sadly all I get is :
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Email' validating type 'java.lang.String'. Check configuration for 'userName'
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.throwExceptionForNullValidator(ConstraintTree.java:229)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:310)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:244)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:163)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:116)
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:620)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:583)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForNonDefaultGroup(ValidatorImpl.java:543)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:457)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:410)
at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:207)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:305)
at pwr.groupproject.vouchers.bean.form.NewUserCompanyFormValidationTest.NewUserCompanyFormValidatingTest(NewUserCompanyFormValidationTest.java:43)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
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:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
There is pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<thymeleaf.spring.version>3.0.7.RC1</thymeleaf.spring.version>
<thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>
<hibernate.validation.version>6.0.3.Final</hibernate.validation.version>
<hibernate.version>5.2.11.Final</hibernate.version>
<mysql.connector.java.version>6.0.6</mysql.connector.java.version>
<spring.version>5.0.0.RELEASE</spring.version>
<spring.session.version>1.3.1.RELEASE</spring.session.version>
<spring.security.version>4.2.3.RELEASE</spring.security.version>
<spring.webflow.version>2.4.6.RELEASE</spring.webflow.version>
<spring.boot.test.version>2.0.0.M5</spring.boot.test.version>
<common.codecs>1.10</common.codecs>
</properties>
<groupId>projectapp</groupId>
<artifactId>app</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</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-validation</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>${spring.session.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>${thymeleaf.spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.java.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${common.codecs}</version>
</dependency>
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>${spring.webflow.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>
</dependencies>
<repositories>
</repositories>
</project>
I have no idea what is going on. I tried changing some dependencies in pom.xml, but everytime I get the same result. People get this exception when they don't match annotation with data type of variable, but I feel like it's ok to validate String with #NotBlank.
I'm working on a Spring, Spring MVC and MongoDB backed application.
I'm looking add an integration test for saving and reading a document file with Fongo.
My test fixture class is the following:
#ActiveProfiles({ "test"})
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {SpringMongoConfig.class, MockDatasourceConfig.class})
#WebAppConfiguration
public class FSIntegrationFongoTest extends SpringApplicationContextTest {
private MockMvc mockMvc;
#Mock
private FileService fileService;
#Mock
private FileStoreRequest file ;
#Before
#Test
public void setUp() throws IOException {
//set up FongoDB and collection
Fongo fongo = new Fongo("FongoTest");
DB db = fongo.getDB("dbtest");
DBCollection collection = db.getCollection("filedocuments");
//test database
assertNotNull(db);
assertSame("getDB should be idempotent", db, fongo.getDB("dbtest"));
assertEquals(Arrays.asList(db), fongo.getUsedDatabases());
assertEquals(Arrays.asList("dbtest"), fongo.getDatabaseNames());
//test collection
assertNotNull(collection);
assertSame("getCollection should be idempotent", collection, db.getCollection("filedocuments"));
//import json with collection name filedocuments
importJSON("filedocuments", "src/test/resources/SampleFiles.json");
fileService = Mockito.mock(FileServiceImpl.class);
file = Mockito.mock(FileStoreRequest.class);
}
#Test
public void testInsertFileAndGetIt()throws IOException{
FileStoreRequest file = new FileStoreRequest();
file.setId("test1");
file.setFileName("test1");
file.setVersionId("1");
file.setDescription("Test file");
file.setAlias("Testing");
file.setContent(MockUtils.getMockFileContent());
Map<String,String> extraAttributes = new HashMap<>();
extraAttributes.put("parameter1", "parameter1Name");
extraAttributes.put("parameter2", "parameter2Name");
file.setExtraAttributes(extraAttributes);
fileService.storeFileGeneral(file);
System.out.println(file);
assertNotNull(file);
assertEquals("test1", file.getId());
assertEquals("test1", file.getFileName());
//this causes java.lang.NullPointerException
assertEquals(fileService.getFileById("test1").getFileName(), file.getFileName());
}
}
Here down my SpringApplicationContextTest class:
#ActiveProfiles({ "test"})
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {SpringMongoConfig.class, MockDatasourceConfig.class,})
public class SpringApplicationContextTest {
Logger log = LoggerFactory.getLogger(SpringApplicationContextTest.class);
#Autowired
private MongoTemplate mongoTemplate;
public void importJSON(String collection, String file) {
try {
for (Object line : FileUtils.readLines(new File(file), "utf8")) {
log.debug("Import Object to database:" + line);
mongoTemplate.save(line, collection);
}
} catch (IOException e) {
throw new RuntimeException("Could not import file: " + file, e);
}
}
#Test
public void testContextInitialized() {
assertNotNull(mongoTemplate);
}
}
Here down the project pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<properties>
<spring.version>4.3.3.RELEASE</spring.version>
<hibernate.version>4.1.0.Final</hibernate.version>
<spring.data.version>1.9.0.RELEASE</spring.data.version>
<spring.mongodb.version>1.9.5.RELEASE</spring.mongodb.version>
<apache.commons.io.version>2.5</apache.commons.io.version>
<apache.commons.codec.version>1.10</apache.commons.codec.version>
<apache.commons.fileupload>1.3.2</apache.commons.fileupload>
<tika.version>1.14</tika.version>
<swagger.version>2.6.1</swagger.version>
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.1.0</javax.servlet.version>
<junit.version>4.12</junit.version>
<hamcrest.version>1.3</hamcrest.version>
<servlet.api.version>2.5</servlet.api.version>
<mockito.version>2.2.15</mockito.version>
<mockwebserver.version>3.8.0</mockwebserver.version>
<jcl.slf4j.version>1.6.0</jcl.slf4j.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<retrofit.version>2.3.0</retrofit.version>
<okhttp.version>3.8.1</okhttp.version>
<slf4jVersion>1.6.1</slf4jVersion>
<nosqlunit-version>0.7.6</nosqlunit-version>
</properties>
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.mongodb.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Spring controllers -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Apache commons -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${apache.commons.codec.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${apache.commons.io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${apache.commons.fileupload}</version>
</dependency>
<!-- Apache tika -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<!-- Swagger 2.0 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- Servlet , JSP, JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- for compile only, your container should have this -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.api.version}</version>
<scope>provided</scope>
</dependency>
<!-- Testing Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>${mockwebserver.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>2.2.0</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-mongodb</artifactId>
<version>${nosqlunit-version}</version>
<scope>test</scope>
</dependency>
<!-- Jackson Dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.3</version>
</dependency>
<!-- Retrofit2 -->
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>${retrofit.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-jackson</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<!-- Bridge logging from JCL to SLF4j-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${jcl.slf4j.version}</version>
</dependency>
<!-- Binding for NOP, silently discarding all logging. -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>${slf4jVersion}</version>
</dependency>
</dependencies>
</project>
I get a NullPointerException when running my test fixture:
java.lang.NullPointerException
at com.myproject.fongodb.FSIntegrationFongoTest.testInsertFileAndGetIt(FSIntegrationFongoTest.java:97)
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:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
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:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Any clue on what is going wrong?
In your test fixture setUp hook, you are initializing the fileService with a mock object:
fileService = Mockito.mock(FileServiceImpl.class);
Then you are trying to save your file using the mocked object:
fileService.storeFileGeneral(file);
Since the fileService is nothing but a mock, it will do nothing on #storeFileGeneral call and no file will be saved as you are expecting.
Later on, you are trying to read back the persisted file to asset that it has been created using the right id, while all you get is a null reference:
assertEquals(fileService.getFileById("test1").getFileName(), file.getFileName()); // fileService.getFileById("test1") will return 'null'
The short answer would be to review your test fixture since it does not reflect an integration-test since you are testing your FileService behavior.
I was planning to migrate from Spring 4.2.1.RELEASe + Hibernate 4.2.19.Final to 4.2.1.RELEASe + Hibernate 5.0.7.Final.
I have created a simple project, available on Github, to test the new Hibernate version and have come across a problem: in my integration tests I initialize a HSQLDB with two rows from a sql file. The point is that when my Hibernate version is 4.2.19.Final all the tests from ExampleIntegrationTRTest pass. However with 5.0.7.Final the very first test (testExampleInsertWithRollback) fails:
scripts/initData.sql
INSERT INTO TFOEMPLE(FOEMPLE_ID, FOEMPLE_NAME) values(1, 'Louis');
INSERT INTO TFOEMPLE(FOEMPLE_ID, FOEMPLE_NAME) values(2, 'Maria');
ExampleIntegrationTRTest.testExampleInsertWithRollback: This test passes with 4.1, but fails due to a javax.persistence.EntityExistsException in 5.0.7.Final. Apparently it tries to create the new FooEmployee assigning it an id 1, which is already present in the DB as part of the initialization.
#ContextConfiguration({ "/spring/test/test-context.xml" })
#Test
public class ExampleIntegrationTRTest extends AbstractTransactionalTestNGSpringContextTests {
#Transactional
public void testExampleInsertWithRollback() {
FooEmployee response = null;
response = fooUserService.getEmployee(1);
//response is FooEmpleado ( BaseEntity ( FooEmployee#590013c7 id = 1 ) id = 1 nombre = Louis )
FooEmployee newFoo = new FooEmployee();
newFoo.setName("James");
createdFooWithRollback = fooUserService.createEmployee(newFoo).getId();
//The line above throws the exception
assertNotNull(createdFooWithRollback);
EntityManagerHolder holder = (EntityManagerHolder)TransactionSynchronizationManager.getResource(entityManagerFactory);
EntityManager em = holder.getEntityManager();
em.flush();
em.clear();
response = null;
response = fooUserService.getEmployee(createdFooWithRollback);
assertNotNull(response);
assertEquals(response.getId(), createdFooWithRollback);
assertEquals(response.getName(), "James");
}
Stacktrace
org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session : [com.codependent.s4h5.entity.FooEmployeeEntity#1]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.codependent.s4h5.entity.FooEmployeeEntity#1]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:410)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:223)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:131)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy52.save(Unknown Source)
at com.codependent.s4h5.service.impl.FooUserServiceImpl.createEmployee(FooUserServiceImpl.java:36)
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:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy57.createEmployee(Unknown Source)
at com.codependent.s4h5.ExampleIntegrationTRTest.testExampleInsertWithRollback(ExampleIntegrationTRTest.java:47)
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:497)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:200)
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:175)
at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:212)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:689)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:882)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1189)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:124)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:348)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:343)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:305)
at org.testng.SuiteRunner.run(SuiteRunner.java:254)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Caused by: javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [com.codependent.s4h5.entity.FooEmployeeEntity#1]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1664)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1608)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1152)
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:497)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:293)
at com.sun.proxy.$Proxy47.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:439)
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:497)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:468)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:440)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 49 more
Spring's test-context.xml
<tx:annotation-driven order="0" />
<!-- Drives transactions using datasource transaction manager -->
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="mainEntityManagerFactory" />
</bean>
<bean id="mainEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="mainPersistenceUnit"/>
<property name="dataSource" ref="mainDataSource"/>
<property name="packagesToScan" value="com.codependent.s4h5.entity"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.import_files">scripts/initData.sql</prop>
</props>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
</bean>
<import resource="classpath:com/codependent/s4h5/spring/library.xml" />
<jdbc:embedded-database id="mainDataSource" type="HSQL"/>
<jpa:repositories base-package="com.codependent.s4h5.dao" entity-manager-factory-ref="mainEntityManagerFactory"/>
<context:component-scan base-package="com.codependent.s4h5.service.impl" />
<context:component-scan base-package="com.codependent.s4h5.mapper" />
<bean id="dozerMapper" class="org.dozer.spring.DozerBeanMapperFactoryBean"/>
Project pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.codependent.s4h5</groupId>
<artifactId>spring4-hibernate5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>Test</description>
<dependencyManagement>
<dependencies>
<!-- SPRING DATA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>${spring-data-releasetrain-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- SPRING -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<!-- HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-version}</version>
</dependency>
<!-- DOZER -->
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer-spring</artifactId>
<version>5.5.1</version>
</dependency>
<!-- log system: slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-version}</version>
<optional>true</optional>
<scope>runtime</scope>
</dependency>
<!-- TEST dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng-version}</version>
<type>jar</type>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>${powermock-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb-j5</artifactId>
<version>2.2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>${jboss-logging-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.kubek2k</groupId>
<artifactId>springockito-annotations</artifactId>
<version>1.0.9</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<spring-version>4.2.1.RELEASE</spring-version>
<spring-data-releasetrain-version>Gosling-SR1</spring-data-releasetrain-version>
<hibernate-version>4.2.19.Final</hibernate-version>
<testng-version>6.8.17</testng-version>
<powermock-version>1.6.2</powermock-version>
<slf4j-version>1.7.7</slf4j-version>
<log4j-version>2.2</log4j-version>
<jboss-logging-version>3.2.1.Final</jboss-logging-version>
</properties>
</project>
BaseEntity.java
#SuppressWarnings("serial")
public abstract class BaseEntity<IdType extends Serializable> implements Serializable {
public abstract IdType getId();
public abstract void setId(IdType id);
}
FooEmployeeEntity.java
#Entity
#Table(name="TFOEMPLE")
public class FooEmployeeEntity extends BaseEntity<Integer> {
private static final long serialVersionUID = 2583160744316336577L;
#Id
#Column(name="FOEMPLE_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id ;
#Column(name="FOEMPLE_NAME")
private String name;
#ManyToOne
#JoinColumn(name="FOEMPLE_FODEPAR_ID")
private FooDepartmentEntity department;
//Getters-Setters
FooDepartmentEntity.java
#Entity
#Table(name="TFODEPAR")
public class FooDepartmentEntity extends BaseEntity<Integer> {
private static final long serialVersionUID = 2583160744316336577L;
#Id
#Column(name="FODEPAR_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id ;
#Column(name="FODEPAR_NAME")
private String name;
#OneToMany(mappedBy="department",cascade={CascadeType.MERGE,CascadeType.REFRESH, CascadeType.PERSIST, CascadeType.DETACH})
private List<FooEmployeeEntity> employees;
//Getters-Setters
Here are the table creations logs generated by 4.2.19.Final and 5.0.7.Final
4.2.19.Final
create table TFODEPAR (
FODEPAR_ID integer generated by default as identity (start with 1),
FODEPAR_NAME varchar(255),
primary key (FODEPAR_ID)
)
5.0.7.Final
create table TFODEPAR (
FODEPAR_ID integer not null,
FODEPAR_NAME varchar(255),
primary key (FODEPAR_ID)
)
In 4.2.19.Final, the id column is generated as identity column, while in 5.0.7.Final, it is generated as a normal non-nullable column. I suspect the culprit is in the way that #GeneratedValue(strategy=GenerationType.AUTO) is picking the right id generation strategy. Seems like before version 5, it is picking GenerationType.IDENTITY while in version 5 it is not.
So to solve the issue, change #GeneratedValue(strategy=GenerationType.AUTO) to #GeneratedValue(strategy=GenerationType.IDENTITY) to forcefully tell hibernate to make the id column as an identity column.
Configure pom.xml dependency are :
================================================
<properties>
<java-version>1.7</java-version>
<org.springframework-version>4.2.0.RELEASE</org.springframework-version>
<org.aspectj-version>1.7.4</org.aspectj-version>
<org.slf4j-version>1.7.5</org.slf4j-version>
<hibernate.version>4.3.5.Final</hibernate.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- <version>4.2.0.RELEASE</version> -->
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Tiles -->
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-servlet</artifactId>
<version>2.1.4</version>
</dependency>
<!-- Email -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</project>
=====================================================
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class Mail{
#RequestMapping(value = "mail.html", method = {RequestMethod.POST, RequestMethod.GET })
public ModelAndView mail(final ModelMap modelMap,final String userName, final String password,final HttpServletRequest request,
final HttpServletResponse response, final String wp,ModelMap map,String nso) {
System.out.println("debug point read");
MailThread mm = new MailThread(); // problem area
mm.sendMail("text testing", "xyz#anyemail.xyz", "subject");
return null;
}
========================================================
// We define this class same package (This class working if its run with main method)
private static final Session session = createSmtpSession();
private static Session createSmtpSession() {
final Properties props = new Properties();
props.setProperty("mail.host","IP ADDRESS");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port","25");
props.setProperty("mail.smtp.starttls.enable","true");
props.setProperty("mail.transport.protocol","MY PROTOCOL");
return Session.getDefaultInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("host email","password");
}
});
}
public void sendMail(final String text, String toMail,final String subject) {
Boolean mailSent = false;
try {
final Transport transport = session.getTransport();
final MimeMessage message = new MimeMessage(session);
message.setSubject(subject);
message.setFrom(new InternetAddress("from"));
message.setContent(text, "text/html");
message.addRecipient(Message.RecipientType.TO,new InternetAddress(toMail));
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
}
} catch (Exception e) {
}
return mailSent;
}
public static void main(String[] args) {
MailThread mm = new MailThread();
mm.sendMail("text testing", "xyz#anyemail.xyz", "subject");
}
}
=========================================================================
I got this problem when read MailThread mm = new MailThread(); this line
Aug 17, 2015 3:17:33 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/agencyv1] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: javax/mail/Address] with root cause
java.lang.ClassNotFoundException: javax.mail.Address
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
at com.superadmin.loginSAController.loginPage(loginSAController.java:23)
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:215)
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:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This problem come due to .jar not found even we define in pom. but actually it did not load. If you work with pom it works fine. you can add lib 1. activation-1.1.jar, 2.commons-logging-1.1.3, mail-1.4 in projectName\src\main\webapp\WEB-INF\lib\ folder.