Spring not dynamic Switch DataSource - spring

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

Related

UsernameTokenValidator Can not #Autowired Dao

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);
}
}

CustomPropertyEditor is not working

I am new to Spring. I am trying implementing CustomPropertyEditor using PropertyEditorSupport and registering the CustomPropertyEditor in app-context.xml.
Please find the code below.
public class NamePropertyEditor extends PropertyEditorSupport{
#Override
public void setAsText(String text) throws IllegalArgumentException {
//String[] name = text.split(":");
System.out.println("text: "+ text);
Name result = new Name(text, "randomString");
setValue(result);
}
}
app-context file
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.property.bean.Name">
<bean class="com.property.editor.NamePropertyEditor"/>
</entry>
</map>
</property>
</bean>
<bean id="exampleBean" class="com.start.CustomEditorExample">
<property name="name">
<value>Varun Bhatia</value></property>
</bean>
Class trying to use PropertyEditor
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:/META-INF/spring/app-context.xml");
//ctx.refresh();
CustomEditorExample bean = (CustomEditorExample) ctx.getBean("exampleBean");
System.out.println(bean.getName());
}
public Name getName() {
System.out.println("getName");
return name;
}
public void setName(Name name) {
System.out.println("setName");
this.name = name;
}
Problem is control is not going to setAsText method.
Code that you have written in main() will not invoke your property editor
Try something like
CustomEditorExample bean = (CustomEditorExample) ctx.getBean("exampleBean");
BeanWrapper wrapper = new BeanWrapperImpl(bean );
wrapper.setPropertyValue("name", "Some Text");//this will invoke your property editor
System.out.println(bean.getName());
I would advise you to read this Spring Docs

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;

Create spring beans, based on a comma-separated list of classes

Is there a way in Spring to create a collection, or array, of beans, based on a comma-separated list of classes. For example:
package mypackage;
public class Bla {
private Set<MyBean> beans;
public void setBeans(Set<MyBean> beans) {
this.beans = beans;
}
}
With the application context:
<bean id="bla" class="mypackage.Bla">
<property name="beans">
<set>
<bean class="mypackage.Bean1, mypackage.Bean2" />
</set>
</property>
</bean>
Preferably the beans are all initialized and wired from the context, leaving the code as simplistic as possible, is this possible?
Use a combination of ApplicationContextAware and ApplicationListener:
public class BeanInitializer implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext context;
private List<Class<?>> beanClasses;
public void onApplicationEvent(final ContextRefreshedEvent event) {
final AutowireCapableBeanFactory beanFactory = this.context.getAutowireCapableBeanFactory();
for (final Class<?> beanClass : this.beanClasses) {
beanFactory.autowire(beanClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
}
}
public void setApplicationContext(final ApplicationContext context) throws BeansException {
this.context = context;
}
public void setBeanClasses(final List<Class<?>> beanClasses) {
this.beanClasses = beanClasses;
}
}
in your spring config, do this:
<bean class="com.yourcompany.BeanInitializer">
<property name="beanClasses">
<list>
<value>com.yourcompany.Type1</value>
<value>com.yourcompany.Type2</value>
<value>com.yourcompany.Type3</value>
</list>
</property>
</bean>
Edited: Actually, if you want comma separated, it will probably be more like this:
<bean class="com.yourcompany.BeanInitializer">
<property name="beanClasses"
value="com.yourcompany.Type1,com.yourcompany.Type2,com.yourcompany.Type3" />
</bean>
I don't know if there is a built-in property editor that converts a comma delimited string to a list of classes but if not you can either create one yourself or change your setter method to accept a string and parse the string yourself

Resources