Spring: #Valid always returns False - spring-mvc

I'm new to Spring Framework. I'm trying to get #Valid to work. Data Binding is happening properly but not the validation. hasErrors() is always returning False in the Controller class. Please see below code.
I'm utilizing Spring 4.1.3 and Hibernate validator 6.0.16.
Context xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<context:property-placeholder location="classpath:/config.properties"/>
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.personal, com.documentum" />
</beans>
Controller:
package com.personal.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.personal.search.model.SearchForm;
import com.personal.search.service.SearchService;
#Controller
public class SearchController {
private SearchService service;
#Autowired
public SearchController(SearchService service) {
this.service = service;
}
#RequestMapping(value="/", method=RequestMethod.GET)
public String searchHome(Model model) {
model.addAttribute(new SearchForm());
return "search/search";
}
#RequestMapping(value="/", method=RequestMethod.POST)
public String searchResults(#Valid SearchForm searchForm, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
System.out.println(searchForm.getObjectName());
model.addAttribute(service.getResults(searchForm));
}
return "search/search";
}
}
View:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%# page session="false" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<sf:form method="POST" commandName="searchForm">
<sf:errors path="*" />
<label>Enter Object Name:</label>
<sf:input path="objectName"/><sf:errors path="objectName" /><br>
<button type="submit" value="Submit">Submit</button>
</sf:form>
<h3>For your search term "${searchForm.objectName}" below are the results: </h3>
<c:forEach items="${searchResultList}" var="searchResult" >
<li>
<div>
<span>
(<c:out value="${searchResult.objectName}" />,
<c:out value="${searchResult.title}" />)</span>
</div>
</li>
</c:forEach>
</body>
</html>
Model:
SearchForm Model:
package com.personal.search.model;
import javax.validation.constraints.NotBlank;
public class SearchForm {
#NotBlank
private String objectName;
public SearchForm() {
}
public SearchForm(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
SearchResult Model:
package com.personal.search.model;
public class SearchResult {
private String objectName;
private String title;
public SearchResult() {
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String name) {
this.objectName = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Service:
package com.personal.search.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.personal.search.dao.SearchDAO;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Service
public class SearchService implements ISearchService {
private SearchDAO dao;
public SearchService() {
}
#Autowired
public SearchService(SearchDAO dao) {
this.dao = dao;
}
#Override
public List<SearchResult> getResults(SearchForm searchform) {
return dao.getSearchObjects(searchform);
}
}
DAO:
package com.personal.search.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import com.documentum.com.DfClientX;
import com.documentum.fc.client.DfServiceException;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;
#Repository
public class SearchDAO {
private String repository;
private String userName;
private String password;
private IDfSessionManager sessionMgr = null;
public SearchDAO() {
}
#Autowired
public SearchDAO(
#Value("${docbase.repository}") String repository,
#Value("${docbase.user}") String userName,
#Value("${docbase.password}") String password)
{
this.repository = repository;
this.userName = userName;
this.password = password;
System.out.println(repository + " " + userName + " " + password);
}
/**
* Creates a IDfSessionManager
*/
private IDfSessionManager getSessionManager()
{
// create a client object using a factory method in DfClientX
DfClientX clientx = new DfClientX();
IDfClient client;
IDfSessionManager sessionMgr = null;
try {
client = clientx.getLocalClient();
// call a factory method to create the session manager
sessionMgr = client.newSessionManager();
addIdentity(clientx, sessionMgr);
} catch (DfException e) {
e.printStackTrace();
}
return sessionMgr;
}
private void addIdentity(DfClientX clientx, IDfSessionManager sessionMgr)
{
// create an IDfLoginInfo object and set its fields
IDfLoginInfo loginInfo = clientx.getLoginInfo();
loginInfo.setUser(userName);
loginInfo.setPassword(password);
if (sessionMgr != null) {
if (sessionMgr.hasIdentity(repository))
{
sessionMgr.clearIdentity(repository);
}
}
try {
sessionMgr.setIdentity(repository, loginInfo);
} catch (DfServiceException e) {
e.printStackTrace();
}
}
public IDfSession getDBSession() {
IDfSession sess = null;
// Get a session using a factory method of session manager.
try {
sess = sessionMgr.getSession(repository);
} catch (DfServiceException e) {
System.out.println(e.getStackTraceAsString());
}
return sess;
}
public void releaseDBSession(IDfSession sess) {
sessionMgr.release(sess);
}
public List<SearchResult> getSearchObjects(SearchForm searchform) {
List<SearchResult> lst = new ArrayList<SearchResult>();
this.sessionMgr = getSessionManager();
IDfSession sess = null;
try
{
sess = getDBSession();
if (sess != null) {
IDfQuery query = new DfClientX().getQuery();
String dqlStr = "select object_name, title from dm_sysobject where object_name like '%" + searchform.getObjectName() + "%'";
System.out.println(dqlStr);
query.setDQL(dqlStr);
IDfCollection co = query.execute(sess, IDfQuery.DF_READ_QUERY);
while (co.next()) {
SearchResult searchresult = new SearchResult();
searchresult.setObjectName(co.getString("object_name"));
searchresult.setTitle(co.getString("title"));
lst.add(searchresult);
}
if (co != null)
co.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (sess != null)
releaseDBSession(sess);
}
return lst;
}
}
I expect the hasErrors() output to be True.

This could be because you have defined the validation as,
#Null
#Size(min=1, max=30)
private String objectName;
Check if when you submit the request to controller the objectName has NULL value or empty string?
For String you must use #NotBlank and not #Null

Related

spring mvc view resolution configuration fail to display jsp page

I am new to spring mvc.
When I run this url:http://localhost:8080/spring-mvc-foundation/main/
I get "hello". I was expecting to execute the hello.jsp page and get output:Hello World TEST123
DispatcherInitializer.java:
package com.oreilly.mvc;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DispatcherInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
RootConfig.java:
package com.oreilly.mvc;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan("com.oreilly.mvc.services")
public class RootConfig {
}
WebConfig.java:
package com.oreilly.mvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#ComponentScan("com.oreilly.mvc.controllers")
public class WebConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolverBean = new InternalResourceViewResolver();
viewResolverBean.setPrefix("/WEB-INF/views/");
viewResolverBean.setSuffix(".jsp");
return viewResolverBean;
}
}
MainController.java:
package com.oreilly.mvc.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.oreilly.mvc.services.GreetingService;
#Controller
#RequestMapping("/main")
public class MainController {
#Autowired
public GreetingService greetingService;
#ResponseBody
#RequestMapping("/")
public String message(Model model) {
model.addAttribute("message",this.greetingService.greet());
return "hello";
}
}
hello.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World Application</title>
</head>
<body>
<h1>${message} TEST123</h1>
</body>
</html>
location of jsp page hello.jsp:
browser output:
Remove #ResponseBody annotation.
#ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header.

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing:

I have created a Rest controller. I am trying to access it through POSTMAN in Chrome. But I get this error:
WARNING: Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity com.ukp.controller.Spring4MVCRestController.createUser(com.ukp.model.User,org.springframework.web.util.UriComponentsBuilder)
I don't know what is the reason. Please help me with the solution.
package com.ukp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.ukp.model.User;
import com.ukp.service.UserService;
#RestController
public class Spring4MVCRestController {
#Autowired
UserService userService; //Service which will do all data retrieval/manipulation work
//-------------------Retrieve All Users--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
//-------------------Retrieve Single User--------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<Void> createUser(#RequestBody User user, UriComponentsBuilder ucBuilder) {
System.out.println("Creating User " + user.getName());
if (userService.isUserExist(user)) {
System.out.println("A User with name " + user.getName() + " already exist");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
userService.saveUser(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
//------------------- Update a User --------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
public ResponseEntity<User> updateUser(#PathVariable("id") long id, #RequestBody User user) {
System.out.println("Updating User " + id);
User currentUser = userService.findById(id);
if (currentUser==null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
currentUser.setName(user.getName());
currentUser.setAge(user.getAge());
currentUser.setSalary(user.getSalary());
userService.updateUser(currentUser);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
//------------------- Delete a User --------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteUser(#PathVariable("id") long id) {
System.out.println("Fetching & Deleting User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("Unable to delete. User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
userService.deleteUserById(id);
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
//------------------- Delete All Users --------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.DELETE)
public ResponseEntity<User> deleteAllUsers() {
System.out.println("Deleting All Users");
userService.deleteAllUsers();
return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
}
}
Here is my service interface: UserService
package com.ukp.service;
import java.util.List;
import com.ukp.model.User;
public interface UserService {
User findById(long id);
User findByName(String name);
void saveUser(User user);
void updateUser(User user);
void deleteUserById(long id);
List<User> findAllUsers();
void deleteAllUsers();
public boolean isUserExist(User user);
}
Here is service implementation class UserServiceImpl:
package com.ukp.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ukp.model.User;
#Service
#Transactional
public class UserServiceImpl implements UserService {
private static final AtomicLong counter = new AtomicLong();
private static List<User> users;
static{
users= populateDummyUsers();
}
public List<User> findAllUsers() {
return users;
}
#Override
public User findById(long id) {
for(User user : users){
if(user.getId() == id){
return user;
}
}
return null;
}
#Override
public User findByName(String name) {
for(User user : users){
if(user.getName().equalsIgnoreCase(name)){
return user;
}
}
return null;
}
#Override
public void saveUser(User user) {
user.setId(counter.incrementAndGet());
users.add(user);
}
#Override
public void updateUser(User user) {
int index = users.indexOf(user);
users.set(index, user);
}
#Override
public void deleteUserById(long id) {
for (Iterator<User> iterator = users.iterator(); iterator.hasNext(); ) {
User user = iterator.next();
if (user.getId() == id) {
iterator.remove();
}
}
}
public static List<User> populateDummyUsers() {
List<User> users = new ArrayList<User>();
users.add(new User(counter.incrementAndGet(),"Sam",30, 70000));
users.add(new User(counter.incrementAndGet(),"Tom",40, 50000));
users.add(new User(counter.incrementAndGet(),"Jerome",45, 30000));
users.add(new User(counter.incrementAndGet(),"Silvia",50, 40000));
return users;
}
#Override
public void deleteAllUsers() {
users.clear();
}
#Override
public boolean isUserExist(User user) {
return findByName(user.getName())!=null;
}
}
Here is my model class:
package com.ukp.model;
public class User {
private long id;
private String name;
private int age;
private double salary;
public User() {
id = 0;
}
public User(long id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age
+ ", salary=" + salary + "]";
}
}
Here is my SpringMVC4Initializer:
package com.ukp.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMVC4Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {SpringMVC4Configuration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Here is my Spring configuration class:
package com.ukp.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages="com.ukp")
public class SpringMVC4Configuration {
}
Finally my 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.ukp</groupId>
<artifactId>Spring4MVCCRUDRestService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVC With RestFull demo</name>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
<jackson.version>2.5.3</jackson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-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</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>Spring4MVCCRUDRestService</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>Spring4MVCCRUDRestService</finalName>
</build>
</project>
error:
INFO: FrameworkServlet 'dispatcher': initialization completed in 381 ms
Apr 03, 2017 4:39:42 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/Spring4MVCCRUDRestService] is completed
Apr 03, 2017 4:41:26 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpMessageNotReadable
WARNING: Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Void> com.ukp.controller.Spring4MVCRestController.createUser(com.ukp.model.User,org.springframework.web.util.UriComponentsBuilder)
Apr 03, 2017 4:41:40 PM org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported
I am trying to access through postman for POST request: http://localhost:8282/Spring4MVCCRUDRestService/user/

Hibernate Search Error With Spring MVC

I am trying to learn Hibernate Search.
I have an existing SpringMVC+Hibernate CRUD project with Form Validations.
The project works perfectly, but after I add Hibernate Search functionality,
The following error is shown
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
My code :
/////////////////////////////SpringConfig.java///////////////////////////
package com.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.model.Person;
import com.service.PersonService;
#Configuration
#EnableWebMvc
#ComponentScan({ "com.*" })
#EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment environment;
#Autowired
private PersonService ps;
#Bean #Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean #Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
#Bean #Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
//////////////////////////////Controller/////////////////////////////
package com.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.model.Person;
import com.service.PersonService;
#Controller
public class MainController {
#Autowired
private PersonService ps;
#RequestMapping("/")
public ModelAndView listPersons(ModelAndView model) throws Exception {
ps.indexPersons();
List<Person> listper = ps.list();
model.addObject("personsList", listper);
model.setViewName("index");
return model;
}
#RequestMapping(value = "/newPerson", method = RequestMethod.GET)
public ModelAndView newPerson(ModelAndView model) throws IOException {
#SuppressWarnings("unused")
Person p = new Person();
model.addObject("person", new Person());
model.setViewName("AddPerson");
return new ModelAndView("AddPerson", "person", new Person());
}
#RequestMapping(value="/save")
public String save(/*#ModelAttribute*/ #Valid Person p, BindingResult result) {
if(result.hasErrors())
{
return "AddPerson";
}
else
{
ps.save(p);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
#RequestMapping("/removePerson")
public String remove(HttpServletRequest req) {
int id = Integer.parseInt(req.getParameter("id"));
ps.removePerson(id);
return "redirect:http://localhost:8080/MainAssignment3/";
}
#RequestMapping("/update")
public String update(/*#ModelAttribute*/ #Valid Person p1,BindingResult result,Model p) {
System.out.println(p1.getName());
int id=p1.getId();
// ps.getPersonById(p.getId());
p.addAttribute("p1", p1);
p.addAttribute("id", id);
p.addAttribute("name", p1.getName());
p.addAttribute("gender", p1.getGender());
p.addAttribute("address", p1.getAddress());
p.addAttribute("salary", p1.getSalary());
if(result.hasErrors())
{
return "redirect:http://localhost:8080/MainAssignment3/updatePerson";
}
else{
ps.save(p1);
return "redirect:http://localhost:8080/MainAssignment3/";
}
}
#RequestMapping("/updatePerson")
public ModelAndView updatePerson(HttpServletRequest req, ModelMap p1,#ModelAttribute Person p) {
p1.addAttribute("person",new Person());
int id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
String address = req.getParameter("address");
String gender = req.getParameter("gender");
String salary = req.getParameter("salary");
p1.addAttribute("id", id);
p1.addAttribute("name", name);
p1.addAttribute("gender", gender);
p1.addAttribute("address", address);
p1.addAttribute("salary", salary);
p1.addAttribute("p1",new Person());
return new ModelAndView("updatePerson", "person", new Person());
}
#RequestMapping(value = "/search", method = RequestMethod.GET)
public ModelAndView searchPage()
{
ModelAndView mav = new ModelAndView("search");
return mav;
}
#RequestMapping(value = "/doSearch", method = RequestMethod.POST)
public ModelAndView search(#RequestParam("searchText")String searchText) throws Exception
{
List<Person> allFound = ps.searchForPerson(searchText);
List<Person> bookModels = new ArrayList<Person>();
for (Person p : allFound)
{
Person pm = new Person();
pm.setName(p.getName());
pm.setAddress(p.getAddress());
pm.setGender(p.getGender());
pm.setSalary(p.getSalary());
bookModels.add(pm);
}
ModelAndView mav = new ModelAndView("foundPersons");
mav.addObject("foundPersons", bookModels);
return mav;
}
}
////////////////////////////////Repository////////////////////////
package com.dao;
import java.util.List;
import com.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
////////////////////////////////Implementation////////////////////////
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
#Transactional
#Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
#SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
#SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
#Transactional
public void indexPersons() throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
}
catch(Exception e)
{
throw e;
}
}
public List<Person> searchForPerson(String searchText) throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = qb
.keyword().onFields("name", "address", "salary","gender")
.matching(searchText)
.createQuery();
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Person.class);
List<Person> results = hibQuery.list();
return results;
}
catch(Exception e)
{
throw e;
}
}
}
//////////////////////////MODEL////////////////////////////
package com.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
#Entity
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#NotEmpty #NotNull(message="Name is required!")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String name;
#Size(min=5, max=10, message="Your address should be between 5 - 10 characters.")
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String address;
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private Integer salary;
#Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO)
private String gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
////////////////////////////////Service/////////////////////////////////
package com.service;
import java.util.List;
import com.model.Person;
public interface PersonService {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
//////////////////////////////////////Service Implementation/////////////
package com.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.dao.PersonDAO;
import com.model.Person;
#Service("PersonService")
public class PersonServiceImpl implements PersonService {
#Autowired
private PersonDAO pdao;
#Transactional
public void save(Person p) {
// TODO Auto-generated method stub
pdao.save(p);
}
public List<Person> list() {
// TODO Auto-generated method stub
return pdao.list();
}
public void updatePerson(Integer id) {
// TODO Auto-generated method stub
pdao.updatePerson(id);
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
return this.pdao.getPersonById(id);
}
public void removePerson(Integer id) {
// TODO Auto-generated method stub
pdao.removePerson(id);
}
public void indexPersons() throws Exception {
// TODO Auto-generated method stub
pdao.indexPersons();
}
public List<Person> searchForPerson(String searchText) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
//////////////////////////////index.jsp/////////////////////
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>Hello World!</h2>
<h3>Add Person</h3>
<table border="1">
<tr>
<th>id</th>
<td>name<springForm:errors path='${p.name}' /></td>
<td>address<springForm:errors path='${p.address}' /></td>
<td>gender<springForm:errors path='${p.gender}' /></td>
<td>salary<springForm:errors path='${p.salary}' /></td></tr>
<c:forEach var="p" items='${personsList}' varStatus="status">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
///////////////////////////////////search.jsp//////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search Page</title>
</head>
<body>
<springForm:form action="/MainAssignment3/doSearch" method="POST" commandName="p">
<c:forEach var="p" items='${foundPersons}' varStatus="status">
<td>${p.name}</td>
<td>${p.address}</td>
<td>${p.gender}</td>
<td>${p.salary}</td>
</c:forEach>
</springForm:form>
</body>
</html>
//////////////////////////////AddPerson.jsp/////////////////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Person</title>
</head>
<body>
<h1>Employee Registration Form</h1>
<springForm:form action="/MainAssignment3/save" method="POST"
commandName="person">
<table style="border: thin; border: ridge;">
<tr>
<td>Enter Name:</td>
<td bordercolor="#FF0000" ><springForm:input path="name"
placeholder="Enter Name" /></td>
<td><springForm:errors path="name" /></td>
</tr>
<tr>
<td>Enter address:</td>
<td><input type="text" name="address" placeholder="Enter Address" ></td>
<td><springForm:errors path="address" /></td>
</tr>
<tr>
<td>Enter gender:</td>
<td><springForm:input path="gender" id="gender" placeholder="Enter Gender" /></td>
<%-- <td><springForm:errors path="gender" /></td> --%>
</tr>
<tr>
<td>Enter salary:</td>
<td><input type="text" name="salary" placeholder="Enter Salary" ></td>
<td><springForm:errors path="salary" /></td>
<td style="padding-left: 110px;"></td>
</tr>
<tr>
<td><input type="submit"value="submit"></td>
</tr>
</table>
</springForm:form>
</body>
</html>
/////////////////////////////////////updatePerson.jsp/////////////////////
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags/form"
prefix="springForm"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update Person</title>
</head>
<body>
<springForm:form action="/MainAssignment3/update" method="POST" commandName="person">
<table style="border: thin; border: ridge;">
<tr>
<td><input type="hidden" name="id" value="${id}"></td>
</tr>
<tr>
<td>Enter Name:</td>
<td bordercolor="#FF0000" >
<springForm:input path="name" placeholder="Enter Name" value='${name}'/></td>
<%-- <td><springForm:errors path="name" /></td> --%>
</tr>
<tr>
<td>Enter address:</td>
<td><springForm:input path="address" id="address" placeholder="Enter Address" value='${address}'/></td>
<%-- <td><springForm:errors path='${p1.address}'/></td> --%>
</tr>
<tr>
<td>Enter gender:</td>
<td><springForm:input path="gender" id="gender" placeholder="Enter Gender" value='${gender}' /></td>
<%-- <td><springForm:errors path='${p1.gender}'/></td> --%>
</tr>
<tr>
<td>Enter salary:</td>
<td><springForm:input path="salary" id="salary" placeholder="Enter Salary" value='${salary}'/></td>
<%-- <td><springForm:errors path='${p1.salary}' /></td> --%>
<td style="padding-left: 110px;"></td>
</tr>
<tr>
<td><input type="submit"value="submit"></td>
</tr>
</table>
</springForm:form>
</body>
</html>

Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Fault occurred while processing

I &m trying to expose my data base using a web service , i am using a postgresql data base , ejb 3.1 and , CXF as webservice framework.
This is the entity
package persistance.model;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: ENVOI
*
*/
#Entity
#Table(name = "Envoi")
#NamedQueries({#NamedQuery(name="Envoi.getAll", query="Select e from Envoi e")})
public class Envoi implements Serializable {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column
private int Numet;
#Column
private int Numseq;
#Column
private int Valadler;
#Column
private String Typemess;
#Column
#Temporal(TemporalType.DATE)
private Date Horodatage;
#Column
private String Appli;
#Column
private String Versproto;
#Column
private String Data;
#Column
private String ACK;
private static final long serialVersionUID = 1L;
public Envoi() {
super();
}
public int getNumet() {
return this.Numet;
}
public void setNumet(int Numet) {
this.Numet = Numet;
}
public int getNumseq() {
return this.Numseq;
}
public void setNumseq(int Numseq) {
this.Numseq = Numseq;
}
public int getValadler() {
return this.Valadler;
}
public void setValadler(int Valadler) {
this.Valadler = Valadler;
}
public String getTypemess() {
return this.Typemess;
}
public void setTypemess(String Typemess) {
this.Typemess = Typemess;
}
public Date getHorodatage() {
return this.Horodatage;
}
public void setHorodatage(Date Horodatage) {
this.Horodatage = Horodatage;
}
public String getAppli() {
return this.Appli;
}
public void setAppli(String Appli) {
this.Appli = Appli;
}
public String getVersproto() {
return this.Versproto;
}
public void setVersproto(String Versproto) {
this.Versproto = Versproto;
}
public int getId() {
return this.Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getData() {
return this.Data;
}
public void setData(String Data) {
this.Data = Data;
}
public String getACK() {
return this.ACK;
}
public void setACK(String ACK) {
this.ACK = ACK;
}
}
Now here the DAO
this one is generic
package persistance.dao;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//import javax.persistence.criteria.CriteriaQuery;
public abstract class GenericDAO<T> {
private final static String UNIT_NAME = "MestaPU";
#PersistenceContext(unitName = UNIT_NAME)
private EntityManager em;
private Class<T> entityClass;
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void save(T entity) {
em.persist(entity);
}
protected void delete(Object id, Class<T> classe) {
T entityToBeRemoved = em.getReference(classe, id);
em.remove(entityToBeRemoved);
}
public T update(T entity) {
return em.merge(entity);
}
public T find(int entityID) {
return em.find(entityClass, entityID);
}
// Using the unchecked because JPA does not have a
// em.getCriteriaBuilder().createQuery()<T> method
/* #SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}*/
// Using the unchecked because JPA does not have a
// ery.getSingleResult()<T> method
/* #SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = em.createNamedQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}*/
/* private void populateQueryParameters(Query query, Map<String, Object> parameters) {
for (Entry<String, Object> entry : parameters.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}*/
}
this one is spécifique to Envoi entity
package persistance.dao;
import javax.ejb.Stateless;
import persistance.model.*;
#Stateless
public class EnvoiDAO extends GenericDAO<Envoi> {
public EnvoiDAO() {
super(Envoi.class);
}
public void delete(Envoi envoi) {
super.delete(envoi.getId(), Envoi.class);
}
}
This is the Facade to expose the ejb
package persistance.facade;
import java.util.List;
import javax.ejb.Local;
import javax.jws.WebService;
import persistance.model.Envoi;
#WebService
#Local
public interface EnvoiFacade {
public abstract void save(Envoi envoi);
public abstract Envoi update(Envoi envoi);
public abstract void delete(Envoi envoi);
public abstract Envoi find(int entityID);
public abstract List<Envoi> findAll();
}
package persistance.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import persistance.dao.EnvoiDAO;
import persistance.model.Envoi;
#WebService
#Stateless
public class EnvoiFacadeImp implements EnvoiFacade {
#EJB
private EnvoiDAO envoiDAO;
public void save(Envoi envoi) {
envoiDAO.save(envoi);
}
public Envoi update(Envoi envoi) {
return envoiDAO.update(envoi);
}
public void delete(Envoi envoi) {
envoiDAO.delete(envoi);
}
public Envoi find(int entityID) {
// TODO Auto-generated method stub
return null;
}
public List<Envoi> findAll() {
// TODO Auto-generated method stub
return null;
}
/*public Envoi find(int entityID) {
return envoiDAO.find(entityID);
}*/
/*public List<Envoi> findAll() {
return envoiDAO.findAll();
}*/
}
Now you will find the spring bean that publishes the service
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint
id="orderProcess"
implementor="demo.order.OrderProcessImpl"
address="/OrderProcess" />
<jaxws:endpoint
id="EnvoiFacade"
implementor="persistance.facade.EnvoiFacadeImp"
address="/EnvoiFacade" />
</beans>
Now you'll find the client and the bean associated to it
package demo.ejb.client;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import persistance.facade.EnvoiFacade;
import persistance.model.Envoi;
public final class Client {
public Client() {
}
public static void main(String args[]) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "demo/ejb/client/client-beans.xml" });
EnvoiFacade client = (EnvoiFacade) context.getBean("envoiClient");
Envoi p1 = new Envoi();
p1.setNumet(3690);
p1.setNumseq(9990);
client.save(p1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:client id="envoiClient" serviceClass="persistance.facade.EnvoiFacade" address="http://localhost:8080/orderapp/EnvoiFacade" >
</jaxws:client>
</beans>
Now my webservice deploy just fin in JBOSS 7.1.0 AS , i created the datasources and included the driver for postgres my sql , the problem is when a run the client i get this error
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Fault occurred while processing.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:143)
at $Proxy57.save(Unknown Source)
at demo.ejb.client.Client.main(Client.java:23)
Caused by: org.apache.cxf.binding.soap.SoapFault: Fault occurred while processing.
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.unmarshalFault(Soap11FaultInInterceptor.java:75)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:46)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:35)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:96)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:69)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:34)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:658)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2139)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2022)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1947)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:632)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:472)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:302)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:254)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:123)
... 2 more
I had a similar stack trace recently and I found out I was missing a classic setter on one of my fields.

jaxb, single item setter for collections

I want to make sure that an xml element-content is unmarshalled in upper case on my object.
public class SZM {
String field01;
#XmlElement(name="field01")
public void setField01(String value) {this.field01 = value.toUpperCase();}
public String getField01() {return field01;}
but how to do the same thing for every item in a collection? I want that any value read from the xml is capitalized.
#XmlElement
ArrayList<String>collection01;
Thanks in advance,
Agostino
all the class, just in case:
package test.jaxb;
import java.util.ArrayList;
import javax.xml.bind.annotation.*;
#XmlRootElement
public class SZM {
String field01;
#XmlElement(name="field01")
public void setField01(String value) {this.field01 = value.toUpperCase();}
public String getField01() {return field01;}
#XmlElement
ArrayList<String>collection01;
}
You can use an XmlAdapter to manipulate the String values:
StringCaseAdapter
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class StringCaseAdapter extends XmlAdapter<String, String> {
#Override
public String unmarshal(String v) throws Exception {
return v.toUpperCase();
}
#Override
public String marshal(String v) throws Exception {
return v.toLowerCase();
}
}
SZM
You reference the XmlAdapter as:
package test.jaxb;
import java.util.ArrayList;
import javax.xml.bind.annotation.*;
#XmlRootElement
public class SZM {
String field01;
#XmlElement(name="field01")
#XmlJavaTypeAdapter(StringCaseAdapter.class)
public void setField01(String value) {this.field01 = value;}
public String getField01() {return field01;}
#XmlElement
#XmlJavaTypeAdapter(StringCaseAdapter.class)
ArrayList<String>collection01;
}
input.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
<collection01>def</collection01>
<collection01>ghi</collection01>
<field01>abc</field01>
</szm>
Demo
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(SZM.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
SZM szm = (SZM) unmarshaller.unmarshal(new File("input.xml"));
System.out.println(szm.getField01());
for(String item : szm.collection01) {
System.out.println(item);
}
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(szm, System.out);
}
}
Output
ABC
DEF
GHI
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
<collection01>def</collection01>
<collection01>ghi</collection01>
<field01>abc</field01>
</szm>

Resources