UsernameTokenValidator Can not #Autowired Dao - spring

I have a Spring-ws and i am using Apahce-wss4j for spring-ws authentication. I want to use my Dao class in my custom TokenValidator class. But there was an exception can not #Autowired my Dao class. Here is my code
applicationContext.xml
<bean id="myWssConfig" class="tr.com.xxx.services.MyWssConfig"/>
<bean id="kepDBDAO" class="tr.com.xxx.dao.KepDBDAOImpl"/>
<bean id="ssha" class="tr.com.xxx.utils.SSHA"/>
<bean id="memberStatusService" class="tr.com.xxx.services.MemberStatusServiceImpl"/>
<bean id="myUsernameTokenValidator" class="tr.com.xxx.services.MyUsernameTokenValidator">
<property name="kepDBDAO" ref="kepDBDAO"/>
</bean>
<sws:interceptors>
<bean class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="UsernameToken"/>
<property name="validationCallbackHandler" ref="callbackHandler"/>
<property name="wssConfig">
<ref bean="myWssConfig"/>
</property>
</bean>
</sws:interceptors>
Here is MyWssConfig.java
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
public MyWssConfig() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, MyUsernameTokenValidator.class);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}
And here is MyUsernameTokenValidator.java
#Component
public class MyUsernameTokenValidator extends UsernameTokenValidator {
private static final Logger LOGGER = LoggerFactory
.getLogger(MyUsernameTokenValidator.class);
#Autowired
private KepDBDAO kepDBDAO;
#Transactional
protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException {
if (usernameToken != null && usernameToken.getPassword() != null) {
byte[] saltValue = null;
kepDBDAO.getWsUsers("basvuru");
String hashPassword = null;
try {
hashPassword = SSHA.calculateSSHA256(saltValue, usernameToken.getPassword());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e.toString(), e);
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
usernameToken.setPassword(hashPassword);
super.verifyDigestPassword(usernameToken, data);
}
}
public KepDBDAO getKepDBDAO() {
return kepDBDAO;
}
public void setKepDBDAO(KepDBDAO kepDBDAO) {
this.kepDBDAO = kepDBDAO;
}
}
Couldn't #Autowired my KepDBDAO when I call webservice in SOAPUI.
Help me please.. THank you all guys.

Try this:
1. In applicationContext:
<context:component-scan base-package="tr.com.xxx.dao"/>
<context:component-scan base-package="package for MyUsernameTokenValidator"/>
remove these beans:
kepDBDAO, myUsernameTokenValidator
2. Remove setter and getter for KepDBDAO in MyUsernameTokenValidator
3. Make sure KepDBDAOImpl is marked as #Service

I solved my problem.
#Component("myWssConfig")
public class MyWssConfig extends WSSConfig {
#Autowired
private MyUsernameTokenValidator myUsernameTokenValidator;
//
#PostConstruct
public void myInit() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, myUsernameTokenValidator);
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}

Related

Spring not roll back transaction if exception throws in the application

I developed the application using spring transactions and insert records in the table.
I'm explicitly throwing the exception in DAO class but spring is inserting the record into the table rather than roll back the transaction.
I have created the two applications as below . In Case 1 record is inserted into table even though exception is thrown . But In Case 2 no record is inserted and spring roll back the transaction successfully. Can you explain me the difference between these two applications.
Case 1:
Item.java
public class Item {
int itemNo;
String itemName;
String itemType;
String itemSize;
public int getItemNo() {
return itemNo;
}
public void setItemNo(int itemNo) {
this.itemNo = itemNo;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemType() {
return itemType;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public String getItemSize() {
return itemSize;
}
public void setItemSize(String itemSize) {
this.itemSize = itemSize;
}
}
ItemDao
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
try{
itemDao.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ct = new ClassPathXmlApplicationContext("spring.xml");
ItemService itemService = ct.getBean("itemService", ItemService.class);
Item item = new Item();
item.setItemNo(1234);
item.setItemName("sofa");
item.setItemSize("4");
item.setItemType("furniture");
itemService.insert(item);
}
}
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Enable Annotation based Declarative Transaction Management -->
<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />
<context:component-scan base-package="com.spring.springtransaction" />
<!-- Creating TransactionManager Bean, since JDBC we are creating of type
DataSourceTransactionManager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- MySQL DB DataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#locahost:1521:xe)))" />
<property name="username" value="system" />
<property name="password" value="system" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="itemService" class="com.spring.springtransaction.ItemService" />
</beans>
Case 2:
ItemService.java
#Service
public class ItemService {
#Autowired
ItemDao itemDao;
#Autowired
ItemManger itemManger;
#Transactional
public void insert(Item item){
try{
itemManger.insert(item);
}
catch(Exception e){
e.printStackTrace();
}
}
}
ItemManger.java
#Service
public class ItemManger {
#Autowired
ItemDao itemDao;
#Transactional
public void insert(Item item){
itemDao.insert(item);
}
}
ItemDao.java
#Service
public class ItemDao {
#Autowired
JdbcTemplate jdbcTemplate ;
void insert(Item item){
jdbcTemplate.update("insert into item_test(itemno, itemtype,itemsize,itemname) values (?,?,?,?)", new Object[]{item.getItemNo(),item.getItemType(),item.getItemSize(),item.getItemName()});
int a=2/0;
}
}
Annotate you ItemDao as #Repository instead of #Service
You should execute unit test with spring Transactional context instead of main , for example using TestNG:
#ContextConfiguration(classes = {ConfigurationClass.class})
#ActiveProfiles({"test"})
public class TestItemDAO extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private ItemDao dao;
#Test
public void testItemDao() {
dao.insert(item);
}
}
Remove the try block, you are trying to handle the exception so this is reason why RollbackException is not cutting the transaction stream.

Load particular bean using Spring SPEL method

I have a requirement to load specific bean on a condition which i am reading from config properties .
I have two beans so i am trying to load it as below
public interface MediatorInt {
public void init();
}
class A implements MediatorInt {
init() { It does some task }
}
class B implements MediatorInt {
init(){ It does some task }
}
public class MasterNewGenImpl {
#Autowired
#Qualifier("config")
private Configuration config;
#Autowired
MediatorInt mediatorInt;
private final Logger logger = Logger.getLogger(getClass());
public void startService() {
mediatorInt.init();
}
}
<context:component-scan base-package="com.ca"/>
<bean id="config" class="com.ca.configuration.ConfigImplementation"/>
<bean id="masterSlave" class="com.ca.masterslave.A"/>
<bean id="systemState" class="com.ca.masterslave.B"/>
<bean id="masterSlaveNewGen" class="com.ca.masterslave.MasterNewGenImpl">
<property name = "mediatorInt" value="#{config.getMediatorMode() == 'true' ? 'systemState' : 'masterSlave'}" />
</bean>
But the bean is not getting loaded .
Can you please help if any error in the syntax or the method of using it .

JTATransactionManager Not Committing To Database

I will be working with a database and with a JMS queue so I decided to use JTATransactionManager (multiple resources).
I am using Spring Framework 3.2.3.RELEASE
Hibernate 4.2.1.Final
Glassfish 3.1.2.2
With JTATransactionManager nothing is committed to db.I tried JPATransactionManager it works fine.I don't get any exceptions with JTATransactionManager.Any idea what I am doing wrong?Thanks.
This is a piece of jpa config file
<jee:jndi-lookup id="dataSource" jndi-name="Test" />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.pinkshield.jpaTest.domain"
p:dataSource-ref="dataSource"
p:jpaPropertyMap-ref="jpaPropertyMap"
p:jpaVendorAdapter-ref="hibernateVendor" />
<util:map id="jpaPropertyMap">
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
<entry key="transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
<entry key="transaction.manager_lookup_class"
value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</util:map>
<bean id="hibernateVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="true" />
<tx:jta-transaction-manager />
<context:component-scan base-package="com.pinkshield.jpaTest" />
This is my Generic Dao for JPA
package com.pinkshield.jpaTest;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class GenericDaoJpa<T> implements GenericDao<T>
{
private Class<T> queryClass;
protected EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager)
{
this.entityManager = entityManager;
}
public GenericDaoJpa(Class<T> queryClass)
{
super();
this.queryClass = queryClass;
}
public T getNewInstance()
{
try
{
return getQueryClass().newInstance();
}
catch (InstantiationException e)
{
throw new RuntimeException("Error creating new instance of : " + getQueryClass().getName(), e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("Error creating new instance of : " + getQueryClass().getName(), e);
}
}
public Class<T> getQueryClass()
{
return queryClass;
}
public T get(Long id)
{
if (id == null)
{
return null;
}
else
{
return entityManager.find(queryClass, id);
}
}
#SuppressWarnings("unchecked")
public List<T> getAll()
{
return entityManager.createQuery("select o from " + queryClass.getName() + " o").getResultList();
}
public void save(T object)
{
entityManager.persist(object);
}
public void update(T object)
{
entityManager.merge(object);
}
public void delete(T object)
{
entityManager.remove(entityManager.merge(object));
}
}
This is UserDao
#Repository
public class UserDao extends GenericDaoJpa<User>
{
public UserDao()
{
super(User.class);
}
}
And this is my service code
#Service
public class UserServiceImpl implements IUserService{
#Autowired UserDao userDao;
#Override
#Transactional
public void saveUser(String name, String lastName)
{
User user=new User();
user.setLastName(lastName);
user.setName(name);
userDao.save(user);
}
}
I think you need to add <tx:annotation-driven/> to the context xml. That will run a context post processor that will wrap methods with #Transactional with an AOP method interceptor that provides the transaction behavior you're looking for.

Can't get view scope working for my ManagedBeans

I'm using JSF 2 with Spring 3 in my project and until now, I'm just using request and session scopes. I want to use view scope for some of my JSF beans (for multiple reasons).
The problem is that the JSF ManagedBean have to implement Serializable interface, and all of its properties.
I have some difficulty to get the Spring beans Serializables (ex. : VilleService...) because it continue to ask for more classes to be serializable even if it's not possible (hibernate classes or mysql ...).
Here is an example :
public class VilleBean extends BaseBean implements Serializable {
private Ville ville;
private List<Ville> villes;
private VilleService villeService;
private PaysService paysService;
private Pays pays;
private List<Pays> payss;
private PojoConverter<Pays> paysConverter = null;
public VilleBean() {
ville = new Ville();
pays = new Pays();
}
public void setVilleService(VilleService villeService) {
this.villeService = villeService;
}
public void setPaysService(PaysService paysService) {
this.paysService = paysService;
}
// getters and setters for attributes : ville, pays, villes, payss
public void addVilleAction() {
ville.setPays(pays);
villeService.create(ville);
}
public void deleteVilleAction(Ville ville) {
villeService.delete(ville);
villes = villeService.readAll();
}
public void updateVilleAction() {
ville.setPays(pays);
villeService.update(ville);
}
public PojoConverter<Pays> getPaysConverter() {
this.paysConverter = new PojoConverter<Pays>(getPayss());
return this.paysConverter;
}
}
public abstract class BaseBean {
protected FacesContext context = FacesContext.getCurrentInstance();
protected MessageFactory msg;
protected static final Logger log = Logger.getLogger(BaseBean.class);
}
POJO :
public class Ville implements Serializable {
private int id;
private String intitule;
private Pays pays;
// setters and getters
}
public class Pays implements Serializable {
private int id;
private String intitule;
// setters and getters
}
Service interface :
public interface VilleService extends ICrud<Ville> {
}
Service Impl :
public class VilleServiceBase implements VilleService {
private IDao<Ville> dao;
// getter and setter for dao
#Override
public List<Ville> readAll() throws Exception {
return dao.readAll();
}
#Override
public void create(Ville entity) throws Exception {
dao.create(entity);
}
//****
Util :
public interface ICrud<T> {
public java.util.List readAll() throws Exception;
public void create(T entity) throws Exception;
public void update(T entity) throws Exception;
//****
public interface IDao<T> {
public java.util.List<T> readAll();
public T create(T entity);
//****
public class DaoBase<T> extends org.springframework.orm.hibernate3.support.HibernateDaoSupport implements IDao<T> {
private final Class<T> type;
public DaoBase(Class<T> type) {
this.type = type;
}
#Override
public T load(int id) {
return (T) this.getHibernateTemplate().get(this.type, new Integer(id));
}
#Override
public T create(T entity) {
//****
this.getHibernateTemplate().save(entity);
return entity;
}
Spring beans : spring.xml :
<!-- Ville Service Implementation -->
<bean id="villeServiceBase" class="commun.ref.crud.VilleServiceBase">
<property name="dao">
<ref bean="villeDao"/>
</property>
</bean>
<!-- Ville Service Proxy -->
<bean id="villeService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="villeServiceBase"/>
</property>
<property name="proxyInterfaces">
<value>commun.ref.crud.VilleService</value>
</property>
<property name="interceptorNames">
<list>
<value>manageableServiceTransactionInterceptor</value>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<bean id="villeDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<bean class="smile.util.DaoBase">
<constructor-arg>
<value>commun.ref.Ville</value>
</constructor-arg>
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</property>
<property name="proxyInterfaces">
<value>smile.util.IDao</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
JSF configuration : faces-config.xml :
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
******
<managed-bean>
<managed-bean-name>villeBean</managed-bean-name>
<managed-bean-class>commun.ref.ui.VilleBean</managed-bean-class>
<managed-bean-scope>view</managed-bean-scope>
<managed-property>
<property-name>villeService</property-name>
<value>#{villeService}</value>
</managed-property>
<managed-property>
<property-name>paysService</property-name>
<value>#{paysService}</value>
</managed-property>
</managed-bean>
Can you tell me please, what to do to get this to work.
On fields which you don't want to be serialized or they can't be serialized use transient modifier. For example:
private transient VilleService villeService;
As you are using MyFaces add this parameter to web.xml:
<context-param>
<param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</param-name>
<param-value>false</param-value>
</context-param>
As I know this parameter is default false in Mojarra. This will disable serialization of state in session.
If you don't use session passivation you may use transient attribute for non-serializable fields.
For example:
private transient Connection connection;

Spring not dynamic Switch DataSource

Why use AbstractRoutingDataSource can not dynamic switch DataSource
This is the configuration information
public class DynamicSwitch {
public static final ThreadLocal<String> local=new ThreadLocal<String>();
public static void setDB(String id){
local.set(id);
}
public static String getDB(){
return local.get();
}
public static void removeDB(){
local.remove();
}
}
public class DynamicSource extends AbstractRoutingDataSource implements InitializingBean{
#Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return DynamicSwitch.getDB();
}
}
<bean id="dynamic" class="com.aware.DynamicSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="1" value-ref="dataSource"></entry>
<entry key="2" value-ref="localdataSource"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSource"></property>
</bean>
<bean id="methodService" class="com.test.service.MethodServiceImpl">
<property name="sqlMapClient" ref="sqlMapClient"></property>
</bean>
<bean id="test" class="com.test.Test" scope="prototype"></bean>
public class Test2 extends ActionSupport{
public String execute() throws Exception {
// TODO Auto-generated method stub
DynamicSwitch.setDB("2");
MethodService methodService=(MethodService)ApplicationAware.getBean("methodService");
Map<String, String> map=new HashMap<String, String>();
List list=methodService.testList("Service_ks_missionSpace.getService_ks_missionList", map);
System.out.println(list.size());
return SUCCESS;
}
Invoke DynamicSwitch.setDB("2") find can not Switch DataSource.
DataSource or to default dataSource
Why

Resources