Memory leak , tomcat 7 - java

When you start tomcat,
it consumes 70mbs of memory,
when I make requests then it consumes 80mbs,
never back to 70mbs
Crud code
package br.com.controlevendas.recurso;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import br.com.controlevendas.controle.ClienteControle;
import br.com.controlevendas.modelo.Cliente;
#Component
#Path("/cliente")
public class ClienteRecurso {
#Autowired
private ClienteControle clienteControle;
#GET
#Path("/lista")
#Produces(MediaType.APPLICATION_JSON)
public List<Cliente> listar() {
List<Cliente> clienteList = this.clienteControle.listar();
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clienteList;
}
#POST
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Cliente inserir(Cliente cliente) {
cliente = this.clienteControle.salvar(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cliente;
}
#PUT
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Cliente alterar(Cliente cliente) {
cliente = this.clienteControle.alterar(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cliente;
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Cliente buscar(#PathParam("id") Integer id) {
Cliente cliente = new Cliente();
cliente.setIdcliente(id);
cliente = this.clienteControle.buscar(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cliente;
}
#DELETE
#Path("/{id}")
public void remover(#PathParam("id") Integer id) {
Cliente cliente = new Cliente();
cliente.setIdcliente(id);
cliente = this.clienteControle.remover(cliente);
try {
this.clienteControle.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ClienteControle
package br.com.controlevendas.controle;
import java.io.Closeable;
import java.util.List;
import br.com.controlevendas.modelo.Cliente;
public interface ClienteControle extends Closeable {
Cliente salvar(Cliente cliente);
Cliente alterar(Cliente cliente);
Cliente remover(Cliente cliente);
Cliente buscar(Cliente cliente);
List<Cliente> listar();
}
ClienteControleImplementacao
package br.com.controlevendas.controle.implementacao;
import java.io.IOException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import br.com.controlevendas.controle.ClienteControle;
import br.com.controlevendas.dao.ClienteDAO;
import br.com.controlevendas.modelo.Cliente;
#Service
public class ClienteControleImplementacao implements ClienteControle {
#Autowired
private ClienteDAO clienteDAO;
#Override
public void close() throws IOException {
this.clienteDAO.close();
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public Cliente salvar(Cliente cliente) {
return this.clienteDAO.salvar(cliente);
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public Cliente alterar(Cliente cliente) {
return this.clienteDAO.alterar(cliente);
}
#Override
public Cliente buscar(Cliente cliente) {
return this.clienteDAO.buscar(cliente);
}
#Override
public List<Cliente> listar() {
return this.clienteDAO.listar();
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public Cliente remover(Cliente cliente) {
return this.clienteDAO.remover(cliente);
}
}
ClienteDAO
package br.com.controlevendas.dao;
import java.io.Closeable;
import java.util.List;
import br.com.controlevendas.modelo.Cliente;
public interface ClienteDAO extends Closeable {
Cliente salvar(Cliente cliente);
Cliente alterar(Cliente cliente);
Cliente remover(Cliente cliente);
Cliente buscar(Cliente cliente);
List<Cliente> listar();
}
ClienteDAOImplementacao
package br.com.controlevendas.dao.implementacao;
import java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import br.com.controlevendas.dao.ClienteDAO;
import br.com.controlevendas.modelo.Cliente;
#Repository
public class ClienteDAOImplementacao implements ClienteDAO {
#PersistenceContext
private EntityManager entityManager;
#Override
public Cliente salvar(Cliente cliente) {
this.entityManager.persist(cliente);
return cliente;
}
#Override
public Cliente alterar(Cliente cliente) {
return this.entityManager.merge(cliente);
}
#Override
public Cliente buscar(Cliente cliente) {
Query query = this.entityManager.createQuery("from Cliente where idcliente = ?");
query.setParameter(1, cliente.getIdcliente());
return (Cliente) query.getSingleResult();
}
#SuppressWarnings("unchecked")
#Override
public List<Cliente> listar() {
Query query = this.entityManager.createQuery("from Cliente");
return query.getResultList();
}
#Override
public void close() throws IOException {
this.entityManager.close();
}
#Override
public Cliente remover(Cliente cliente) {
cliente = this.entityManager.getReference(Cliente.class, cliente.getIdcliente());
this.entityManager.remove(cliente);
return cliente;
}
}
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="controlevendas">
<!-- provedor/implementacao do JPA -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
</persistence-unit>
</persistence>
WebContent/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context reladable="true">
<Resource
name="jdbc/vendas"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="60"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/controlevendas"/>
</Context>
applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="br.com.controlevendas.controle.implementacao" />
<context:component-scan base-package="br.com.controlevendas.dao.implementacao" />
<context:component-scan base-package="br.com.controlevendas.recurso" />
<!-- <bean id="dataSourceMySQL" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> -->
<!-- <property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost/controlevendas" />
<property name="user" value="root" />
<property name="password" value="root" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxStatements" value="50" />
<property name="checkoutTimeout" value="3000" />
<property name="idleConnectionTestPeriod" value="3000" />
<property name="maxIdleTime" value="180" />
<property name="numHelperThreads" value="5" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="5" /> -->
<!-- </bean> -->
<bean id="dataSource.jndi" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton" lazy-init="true">
<property name="jndiName" value="java:comp/env/jdbc/vendas" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- <property name="dataSource" ref="dataSourceMySQL" /> -->
<property name="dataSource" ref="dataSource.jndi" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.jdbc.use_streams_for_binary">true</prop>
<prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
<prop key="hibernate.jdbc.batch_size">0</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.jdbc.use_get_generated_keys">true</prop>
<prop key="hibernate.statement_cache.size">0</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>ControleVendas</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>jersey-spring</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>br.com.controlevendas.recurso</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DataSource Vendas</description>
<res-ref-name>jdbc/vendas</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
</web-app>
hibernate 4.3.8
spring 4.14
jersey 1.18
jackson 1.9.13
Someone help with any tips?

Related

J2ee and java: i have prob with my function java he didn't work with DB (mysql)

Hey my Friends I have some problem with my code he didn't work
I think this problem in my Class UserService but I'm not sure please help me
When I run my programme
my console affiche :
On train de detecter
UtlisateurAction.java
package com.web.actions;
import java.util.List;
import com.app.business.bo.security.Role;
import com.app.business.bo.security.Utlisateur;
import com.app.business.services.UtlisateurService;
import com.app.exceptions.DuplicateLoginException;
import com.web.BaseAction;
public class UtlisateurAction extends BaseAction {
private UtlisateurService userService;
private List<Utlisateur> listUsers;
private Utlisateur utilisateur;
private List<Role> listRoles;
private Long selectedRole;
public String passage(){
System.out.println("Passage");
return SUCCESS;
}
public String showMenu(){
System.out.println("User Access");
return SUCCESS;
}
public String initFormAddUser() {
listRoles = userService.getAllRoles();
return SUCCESS;
}
public String addUser() {
try {
utilisateur.setRole(userService.getRoleById(selectedRole));
userService.addUtilisateur(utilisateur);
} catch (DuplicateLoginException ex) {
addActionError("Operation non effectuee a  cause d'une erreur");
ex.printStackTrace();
return "error";
} catch (Exception ex) {
addActionError("Operation non effectuee à cause d'une erreur");
ex.printStackTrace();
return "error";
}
// on affiche une page d'erreur
addActionMessage("Utilisateur ajoutée avec succées");
return SUCCESS;
}
public String listUsers() {
System.out.println("On train de detecter");
listUsers = userService.getAllUsers();
System.out.println("GET ALL USERS");
return SUCCESS;
}
public List<Utlisateur> getListUsers() {
return listUsers;
}
public void setListUsers(List<Utlisateur> listUsers) {
this.listUsers = listUsers;
}
public UtlisateurService getUserService() {
return userService;
}
public void setUserService(UtlisateurService userService) {
this.userService = userService;
}
public Utlisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utlisateur utilisateur) {
this.utilisateur = utilisateur;
}
public List<Role> getListRoles() {
return listRoles;
}
public void setListRoles(List<Role> listRoles) {
this.listRoles = listRoles;
}
public Long getSelectedRole() {
return selectedRole;
}
public void setSelectedRole(Long selectedRole) {
this.selectedRole = selectedRole;
}
}
my function :
public String listUsers() {
System.out.println("On train de detecter");
listUsers = userService.getAllUsers();
System.out.println("GET ALL USERS");
return SUCCESS;
}
UtlisateurServiceImpl.java
package com.services.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.bo.security.Role;
import com.bo.security.Utilisateur;
import com.boudaa.dao.exceptions.EntityNotFoundException;
import com.dao.RoleDao;
import com.dao.UtilisateurDao;
import com.exceptions.DuplicateLoginException;
import com.services.UtilisateurService;
public class UtilisateurServiceImpl implements UtilisateurService, UserDetailsService {
private UtilisateurDao userDao;
private RoleDao roleDao;
protected final Log log = LogFactory.getLog(getClass());
public UserDetails loadUserByUsername(String pLogin) throws UsernameNotFoundException {
Utilisateur lUser = null;
Collection<GrantedAuthority> arrayAuths = new ArrayList<GrantedAuthority>();
// On récupère un objet de domaine de type User ayant comme login pLogin
try {
lUser = userDao.getUserByLogin(pLogin);
} catch (ObjectRetrievalFailureException ex) {
ex.printStackTrace();
// nous relançons une UsernameNotFoundException si aucun utilisateur
// ne correspond à cet login
log.debug("Erreur d'authentification avec le login : " + pLogin);
throw new UsernameNotFoundException("User " + pLogin + " not exists", ex);
}
// Si un utilisateur correspond à cet identifiant, nous en profitons
// pour mettre à jour sa date de dernière connexion
lUser.setLastAccessDate(Calendar.getInstance().getTime());
userDao.update(lUser);
// Il faut ensuite récupérer les rôles de l’utilisateur et les
// mettre
// sous la forme de SimpleGrantedAuthority, une interface propre à
// Spring
// Security*
Role role = lUser.getRole();
arrayAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
// /un User (classe Spring Security) est créé
System.out.println("oui");
return new User(pLogin, lUser.getPassword(), lUser.isEnabled(), lUser.isAccountNotExpired(), true,
lUser.isAccountNotLocked(), arrayAuths);
}
public Utilisateur getUserByLogin(String pLogin) throws EntityNotFoundException {
List<Utilisateur> users;
try {
users = userDao.getEntityByColumn("Utilisateur", "login", pLogin);
} catch (ObjectRetrievalFailureException ex) {
throw new EntityNotFoundException("Aucun utilisateur avec le login : " + pLogin);
}
if (users.size() != 1) {
// TODO : Ecrire le code pour ajouter des log fatal
// TODO : ecrire le code envoyant un mail d'erreur fatal à
// l'administrateur
throw new RuntimeException("Erreur inconnue dans le systeme");
}
return users.get(0);
}
public void addUtilisateur(Utilisateur user) throws DuplicateLoginException {
// pour hacher avec SHA1
ShaPasswordEncoder encoder = new ShaPasswordEncoder();
// Hachage du mot de passe avec un gain de sel variable = login
String cryptedPassword = encoder.encodePassword(user.getPassword(),
user.getLogin());
// affecter le mot de passe haché
user.setPassword(cryptedPassword);
// stockage de l'utilisateur dans la base de données
try {
userDao.create(user);
} catch (DataIntegrityViolationException ex) {
log.error("erreur d'ajout d'un utilisateur à cause de l'exception " + ex
+ " . un utilisateur avec le login " + user.getLogin() + " existe déjà dans la base de données");
throw new DuplicateLoginException("Erreur d'inscription, login existe déjà", ex);
}
}
public Role getRoleByName(String roleName) {
return roleDao.getRoleByName(roleName);
}
public Role getRoleById(Long pRoleId) throws EntityNotFoundException {
return roleDao.findById(pRoleId);
}
public List<Utilisateur> getAllUsers() {
return userDao.getAll();
}
public List<Role> getAllRoles() {
return roleDao.getAll();
}
public void deleteUser(Utilisateur u) throws EntityNotFoundException {
userDao.delete(u.getIdUtilisateur());
}
public UtilisateurDao getUserDao() {
return userDao;
}
public void setUserDao(UtilisateurDao userDao) {
this.userDao = userDao;
}
public RoleDao getRoleDao() {
return roleDao;
}
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost/services</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>azertyui</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource">
</property>
<property name="mappingResources">
<list>
<value>com/app/business/dao/hbm/Utlisateur.hbm.xml</value>
<value>com/app/business/dao/hbm/Filiere.hbm.xml</value>
<value>com/app/business/dao/hbm/Matiere.hbm.xml</value>
<value>com/app/business/dao/hbm/Niveau.hbm.xml</value>
<value>com/app/business/dao/hbm/Document.hbm.xml</value>
<value>com/app/business/dao/hbm/Role.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:advice id="defaultTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="loadUserByUsername" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="defaultServiceOperation"
expression="execution(* com.app.business.services.Impl.*Service*.*(..))" />
<aop:advisor pointcut-ref="defaultServiceOperation"
advice-ref="defaultTxAdvice" />
</aop:config>
<bean id="NiveauDao"
class="com.app.business.dao.Impl.NiveauDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="DocumentDao"
class="com.app.business.dao.Impl.DocumentDaoImp">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="FiliereDao"
class="com.app.business.dao.Impl.FiliereDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="MatiereDao"
class="com.app.business.dao.Impl.MatiereDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="DocumentService"
class="com.app.business.services.Impl.DocumentServiceImpl">
<property name="documentdao" ref="DocumentDao"></property>
</bean>
<bean id="UtlisateurDao"
class="com.app.business.dao.Impl.UtlisateurDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="RoleDao" class="com.app.business.dao.Impl.RoleDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="UtlisateurService"
class="com.app.business.services.Impl.UtlisateurServiceImpl">
<property name="userDao" ref="UtlisateurDao"></property>
<property name="roleDao" ref="RoleDao"></property>
</bean>
<bean id="UtlisateurAction"
class="com.web.actions.UtlisateurAction" scope="prototype">
<property name="userService" ref="UtlisateurService"></property>
</bean>
<bean id="SecurityAction" class="com.web.actions.SecurityAction" scope="prototype">
<property name="utilisateurService" ref="UtlisateurService"></property>
</bean>
</beans>

Spring #Autowired annotation doesn't work in Java TimerTask

How to change my code to make it work?
public class GetDataFromTheWarehouse implements ServletContextListener {
#Autowired
ScheduledTask scheduledTask;
private ScheduledExecutorService scheduler = null;
public GetDataFromTheWarehouse() {
}
public void contextDestroyed(ServletContextEvent arg0) {
try {
System.out.println("Scheduler Shutting down successfully " + new Date());
scheduler.shutdown();
} catch (Exception ex) {
}
}
public void contextInitialized(ServletContextEvent arg0) {
if ((scheduler == null) || (!scheduler.isTerminated())) {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(scheduledTask, 0, 60*60, TimeUnit.SECONDS);
}
}
}
Following is the ScheduledTask class, in which productService is null, so will fail every time calling productService.save():
#Component
public class ScheduledTask extends TimerTask {
#Autowired
ProductService productService;
public void run() {
try {
parse();
} catch (IOException e) {
e.printStackTrace();
}
}
public void parse() throws IOException {
...
productService.save(product);
...
}
}
}
My applicationContext.xml:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Enable autowire -->
<context:component-scan base-package="com" />
<context:annotation-config />
<bean id="usersUpdateTask" class="com.demo.task.ScheduledTask">
</bean>
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/views/**" location="/views/" />
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/fonts/**" location="/fonts/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/js/**" location="/js/" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/demo" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Session Factory Declaration -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.demo.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.default_schema">demo</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My demo structure:
Why do you have ScheduledTask initialized in appilcationConfig.xml when you are already using #Component for that bean class. Remove this from your applicationContext.xml file.
<bean id="usersUpdateTask" class="com.demo.task.ScheduledTask">
</bean>
EDIT : Adding Spring Boot Sample.
Here is the sample code for #Scheduled with #Autowired in Spring Boot.
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>springboot-scheduler</groupId>
<artifactId>springboot-scheduler-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
</project>
MySpringBootApp.java
package my.spring.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class MySpringBootApp {
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}
MyService.java
package my.spring.app;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.stereotype.Component;
#Component
public class MyService {
public String getNextMessage(){
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
}
}
ScheduledTask.java
package my.spring.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class ScheduledTask {
#Autowired
MyService service;
#Scheduled(fixedRate = 5000)
public void process() {
System.out.println("Processing at " + service.getNextMessage());
}
}
Sample output
Processing at 2016-08-24T14:01:48
Processing at 2016-08-24T14:01:53
Processing at 2016-08-24T14:01:58
Hope this helps.
EDIT-2 : Adding Spring Boot Sample war file version. Tested with Tomcat 8.
Following two files are changed. Others are same as above.
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>springboot-scheduler</groupId>
<artifactId>springboot-scheduler-app</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/>
</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-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
MySpringBootApp.java
package my.spring.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
#SpringBootApplication
#EnableScheduling
public class MySpringBootApp extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MySpringBootApp.class);
}
public static void main(String[] args) {
SpringApplication.run(new Object[] { MySpringBootApp.class }, args);
}
}

Java NoSuchMethodException In Spring (While I have created a constructor)

I would like to ask about where did I go wrong in this. I just started up a simple login feature using Spring and Hibernate 4, but it seems that I always seem to get NoSuchMethodException. Tried looking up everywhere about where I go wrong, but it's like I never did get it right. Any help will be most appreciated. Below are the Codes.
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="try*">PROPAGATION_REQUIRED,ISOLATION_READ_UNCOMMITTED,-Exception</prop>
<!-- <prop key="try*">PROPAGATION_REQUIRED,ISOLATION_SERIALIZABLE,-Exception</prop> -->
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:#db01.aprdev.com:1521:aprdev" />
<property name="username" value="training" />
<property name="password" value="training" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url"
value="jdbc:sqlserver://localhost:1433;databaseName=test" />
<property name="username" value="sa" />
<property name="password" value="pass123" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>com/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> -->
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
</bean>
<bean id="userDAO" class="com.dao.impl.UserDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="serviceProxyTemplate" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
<bean id="userServiceProxy" parent="serviceProxyTemplate">
<property name="target">
<bean id="userService" class="com.services.impl.UserServiceImpl">
<property name="userDAO" ref="userDAO" />
</bean>
</property>
</bean>
User.java
package com.model;
public class User {
private String id;
private String name;
private String password;
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserServiceImpl.java
package com.services.impl;
import java.util.List;
import com.dao.UserDAO;
import com.model.User;
import com.services.UserService;
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
public List validate(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return this.userDAO.validate(user);
}
}
UserDAOImpl.java
package com.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.dao.UserDAO;
import com.model.User;
public class UserDAOImpl implements UserDAO{
private SessionFactory sessionFactory;
public UserDAOImpl(SessionFactory session) {
this.sessionFactory = session;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public List validate(User user) throws HibernateException {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where name = :name and password = :pass ");
query.setParameter("name", user.getName());
query.setParameter("pass", user.getPassword());
return query.list();
}
}
Test.java
package com.factory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.services.UserService;
public class SpringUtil {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext(){
if(applicationContext==null){
applicationContext = new ClassPathXmlApplicationContext("com/factory/bean.xml");
}
return applicationContext;
}
public static UserService getUserService(){
return (UserService) getApplicationContext().getBean("userServiceProxy");
}
}
Help will be much appreciated. Thank you very much!
Not sure if I've answered the problem.
Here is my test
package com.services.impl;
import static org.junit.Assert.assertEquals;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.model.User;
import com.model.UserDAO;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext-test.xml")
public class StudyPointRepositoryTest {
#Autowired
private UserServiceImpl userService;
#Autowired
private UserDAO dao;
#Test
#Transactional
public void test1() {
dao.save(makeUser("Fred", "pass1"));
dao.save(makeUser("Bill", "pass2"));
dao.save(makeUser("Nobby", "pass3"));
List<User> validate = userService.validate("Fred", "pass1");
assertEquals(1, validate.size());
validate = userService.validate("Fred", "wrongpass");
assertEquals(0, validate.size());
}
private User makeUser(String name, String password) {
User user = new User();
user.setName(name);
user.setPassword(password);
return user;
}
}
Here is my config for test
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com" />
<jdbc:embedded-database id="dataSource" type="H2" />
<tx:annotation-driven />
<jpa:repositories base-package="com.model" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
Here is my DAO
package com.model;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserDAO extends CrudRepository<User, Integer> {
List<User> findByNameAndPassword(String name, String password);
}
Here is my Service
package com.services.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.User;
import com.model.UserDAO;
#Service
public class UserServiceImpl {
#Autowired
private UserDAO userDAO;
public List<User> validate(String name, String password) {
return userDAO.findByNameAndPassword(name, password);
}
}
And here is my pom, probable stuff that not needed
<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>com.greg</groupId>
<artifactId>jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>fmis Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<spring.data.version>1.9.2.RELEASE</spring.data.version>
<hibernate.version>5.0.6.Final</hibernate.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.190</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<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>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>jpaTest</finalName>
</build>
</project>

How to secure a Spring soap service with certificates

I managed to create a soap server and client that requires a username and password to call functions. The following code shows how i've done this
Client:
package hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SpringUsernamePasswordCallbackHandler;
#Configuration
public class SoftlayerConfiguration {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("be.elision.soap.cloud");
return marshaller;
}
#Bean
public SoftlayerClient softlayerClient(Jaxb2Marshaller marshaller) {
SoftlayerClient client = new SoftlayerClient();
client.setDefaultUri("http://192.168.137.107:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
client.setInterceptors(new ClientInterceptor[]{securityInterceptor()});
return client;
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setSecureRequest(true);
securityInterceptor.setValidateRequest(true);
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SpringUsernamePasswordCallbackHandler callbackHandler() {
SecurityContextHolder.setContext(new SecurityContextImpl());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));
return new SpringUsernamePasswordCallbackHandler();
}
}
Server:
package be.elision.main;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.server.EndpointInterceptor;
import org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SimplePasswordValidationCallbackHandler;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "devices")
public DefaultWsdl11Definition defaultWsdl11Definition(
XsdSchema devicesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("DevicesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://elision.be/soap/cloud");
wsdl11Definition.setSchema(devicesSchema);
return wsdl11Definition;
}
// toevoegen van xsd aan bean
#Bean
public XsdSchema devicesSchema() {
return new SimpleXsdSchema(new ClassPathResource("devices.xsd"));
}
#Bean
XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource(
"securityPolicy.xml"));
return securityInterceptor;
}
#Bean
SimplePasswordValidationCallbackHandler callbackHandler() {
SimplePasswordValidationCallbackHandler callbackHandler = new SimplePasswordValidationCallbackHandler();
callbackHandler.setUsersMap(Collections
.singletonMap("user", "password"));
return callbackHandler;
}
#Bean
PayloadLoggingInterceptor payloadLoggingInterceptor() {
return new PayloadLoggingInterceptor();
}
#Bean
PayloadValidatingInterceptor payloadValidatingInterceptor() {
final PayloadValidatingInterceptor payloadValidatingInterceptor = new PayloadValidatingInterceptor();
payloadValidatingInterceptor.setSchema(new ClassPathResource(
"devices.xsd"));
return payloadValidatingInterceptor;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(payloadLoggingInterceptor());
interceptors.add(payloadValidatingInterceptor());
interceptors.add(securityInterceptor());
}
}
Security policy:
<xwss:SecurityConfiguration xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:UsernameToken digestPassword="false" useNonce="false" />
</xwss:SecurityConfiguration>
But now i want to replace this username and password authentication with a certificate. I prefere not to do this in xml, but rather implement this in my existing code as shown above.
We finaly figured this out some months ago, from what I remember our configuration looked like this.
add this to your web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
this needs to be present in your mvc-dispatcher-servlet.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
<context:component-scan base-package="com.yourpackage" />
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="defaultUri"
value="${backend.ip}devices" />
<property name="interceptors">
<list>
<ref local="xwsSecurityInterceptor" />
</list>
</property>
</bean>
<bean id="xwsSecurityInterceptor"
class="org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor">
<property name="policyConfiguration" value="/WEB-INF/securityPolicy.xml" />
<property name="callbackHandlers">
<list>
<ref bean="keyStoreHandler" />
</list>
</property>
</bean>
<bean id="keyStore"
class="org.springframework.ws.soap.security.support.KeyStoreFactoryBean">
<property name="password" value="yourpassword" />
<property name="location" value="/WEB-INF/yourkeystore.jks" />
</bean>
<bean id="keyStoreHandler"
class="org.springframework.ws.soap.security.xwss.callback.KeyStoreCallbackHandler">
<property name="keyStore" ref="keyStore" />
<property name="privateKeyPassword" value="yourpassword" />
<property name="defaultAlias" value="client" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- LOAD PROPERTIES -->
<context:property-placeholder
location="WEB-INF/config.properties"
ignore-unresolvable="true" />
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
</beans>
The jks file is a java keystore file wich holds your certificate.
SecurityPolicy.xml
<xwss:SecurityConfiguration dumpMessages="true" xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:Sign includeTimestamp="true">
<xwss:X509Token certificateAlias="yourcertificatealias" />
</xwss:Sign>
</xwss:SecurityConfiguration>
This is all done using the xws-security library from oracle, you need the following dependency for this.
<dependency>
<groupId>com.sun.xml.wss</groupId>
<artifactId>xws-security</artifactId>
<version>3.0</version>
<exclusions>
<exclusion>
<groupId>javax.xml.crypto</groupId>
<artifactId>xmldsig</artifactId>
</exclusion>
</exclusions>
</dependency>
We finnaly got this working after we found some good explanation about certificate authentication in this awesome book!
'Spring Web Services 2 Cookbook by Hamidreza Sattari'
If you have any further questions regarding this implementation then just ask away! :d

Spring-Hibernate - No Session found for current thread

I have a java stuts2 web application using spring and hibernate.
Im getting org.hibernate.HibernateException: No Session found for current thread.
SpringBean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="org.rohith" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/company" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>hibernate.cfg.xml</value>
</list>
</property>
</bean>
<!-- <tx:annotation-driven/> -->
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory" />
</bean>
<bean id="customerDaoImpl" class="org.rohith.dao.impl.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="customerServiceImpl" class="org.rohith.service.impl.CustomerServiceImpl">
<property name="customerDaoImpl" ref="customerDaoImpl"/>
</bean>
</beans>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Names the annotated entity class -->
<mapping class="org.rohith.model.Customer"/>
</session-factory>
</hibernate-configuration>
CustomerServiceImpl.java
package org.rohith.service.impl;
import org.rohith.dao.impl.CustomerDaoImpl;
import org.rohith.model.Customer;
import org.rohith.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerDaoImpl customerDaoImpl;
#Override
public void saveCustomer(Customer customer) {
customerDaoImpl.saveCustomer(customer);
}
public CustomerDaoImpl getCustomerDaoImpl() {
return customerDaoImpl;
}
public void setCustomerDaoImpl(CustomerDaoImpl customerDaoImpl) {
this.customerDaoImpl = customerDaoImpl;
}
}
CustomerDaoImpl.java
package org.rohith.dao.impl;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.rohith.dao.CustomerDao;
import org.rohith.model.Customer;
public class CustomerDaoImpl implements CustomerDao {
private SessionFactory sessionFactory;
#Override
public void saveCustomer(Customer customer) {
Session session = getSession();
session.clear();
try {
session.saveOrUpdate(customer);
session.flush();
} catch (Throwable e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
public Session getSession() throws HibernateException {
Session sess = getSessionFactory().getCurrentSession();
if (sess == null) {
sess = getSessionFactory().openSession();
}
// Session sess = getSessionFactory().openSession();
return sess;
}
}
CustomerAction.java
public class CustomerAction extends ActionSupport{
private String name;
private String addr1;
private String addr2;
private String city;
private String state;
private CustomerServiceImpl customerServiceImpl;
//Getters and setters
public String execute(){
Customer cust= new Customer();
cust.setName(name);
cust.setAddress1(addr1);
cust.setAddress2(addr2);
cust.setCity(city);
cust.setState(state);
System.out.println(name);
WebApplicationContext webApplicationContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(getRequest().getSession()
.getServletContext());
customerServiceImpl = (CustomerServiceImpl) webApplicationContext.getBean("customerServiceImpl");
customerServiceImpl.saveCustomer(cust);
//saveCust(cust);
return "success";
}
protected HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
}
protected HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
}
}
The Exception I am getting
org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978)
org.rohith.dao.impl.CustomerDaoImpl.getSession(CustomerDaoImpl.java:33)
org.rohith.dao.impl.CustomerDaoImpl.saveCustomer(CustomerDaoImpl.java:16)
org.rohith.service.impl.CustomerServiceImpl.saveCustomer(CustomerServiceImpl.java:18)
org.rohith.CustomerAction.execute(CustomerAction.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
You have a transaction manager specified in your Spring config, but no configuration on when or where to apply transactions.
In your SpringBean.xml you should uncomment <tx:annotation-driven/>:
<tx:annotation-driven transaction-manager="transactionManager"/>
And then you should annotate the CustomerServiceImpl.saveCustomer method as #Transactional:
#Service
public class CustomerServiceImpl implements CustomerService {
...
#Override
#Transactional
public void saveCustomer(Customer customer) {
customerDaoImpl.saveCustomer(customer);
}
...
}
Add the following property in your hibernate.cfg.xml file for Hibernate 4.
<property name="hibernate.current_session_context_class">thread</property>
Add #EnableTransactionManagement annotation in your java configuration file if your configuration based on annotation without xml.
This may help someone
You can add in hibernate.proerties below value. It's worked for me.
hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
or
hibernate.current_session_context_class=thread

Categories

Resources