designing java classes to send the message to the queue through spring - spring

I am new to the world of spring jms , prior to this i have used the core java program without spring where we have manually create the connection factories but rite now i am learning spring jms , rite now i have configured the xml but plesae advise how can i design corresponding java classes by which i can send the text message to the queue
<bean id="tibcoEMSJndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">com.tibco.tibjms.naming.TibjmsInitialContextFactory</prop>
<prop key="java.naming.provider.url">tcp://abcnet:707</prop>
<prop key="java.naming.security.principal">abc</prop>
<prop key="java.naming.security.credentials">abc</prop>
</props>
</property>
</bean>
<bean id="tibcoEMSConnFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="tibcoEMSJndiTemplate" />
</property>
<property name="jndiName">
<value>GenericConnectionFactory</value>
</property>
</bean>
<bean id="tibcosendJMSTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref local="tibcoEMSConnFactory" />
</property>
<property name="defaultDestinationName">
<value>test.data</value>
</property>
<property name="pubSubDomain">
<value>false</value>
</property>
<property name ="receiveTimeout">
<value>120000</value>
</property>
</bean>
folks as advise i have designthe java class below but my question is that there should be another class which consists of main methid and which load my xml , i have design the below java class but still i know it is not correct if you do not mind pls can you please show how to design the java classes so that i can grasp and in which the depenmdencies are injected by my above xml pls..
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jndi.JndiTemplate;
public class JmsQueueSender {
private JmsTemplate jmsTemplate;
private Queue queue;
public void setConnectionFactory(ConnectionFactory cf) {
this.jmsTemplate = new JmsTemplate(cf);
}
public void setQueue(Queue queue) {
this.queue = queue;
}
public void simpleSend() {
this.jmsTemplate.send(this.queue, new MessageCreator() {
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage("hello queue world");
}
});
}
}

Read the documentation.
The simplest use of your JmsTemplate would be...
tibcoJmsTemplate.convertAndSend("foo");
...which will convert foo to a TextMessage and send it to your default destination (test.data).
The JmsTemplate has these high level methods as well as providing more advanced features if you need access to the session, or to post process the message after conversion.

Related

Spring modular Quartz Configurations

I am working on Spring MVC web application which is using JDBC Quartz Scheduler to execute jobs. This web application has multiple services each of which is packaged as an jar and has associated jobs. I have one quartz configuration which is in web project, under which I have created beans for jobs, triggers and scheduler. Under scheduler configuration, i specify a list of triggers. This was good when we started our project. As we started adding features, number of jobs increased and its now around 100+. It has become difficult to maintain this file. Is there any approach available make it modular so that the jobs/trigger/associating trigger to scheduler are not defined in the one single file.
<bean name="incidentAutoClosure" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="itsm.scheduler.task.IncidentAutoClosureTask"/>
</bean>
<bean id="incidentAutoClosureTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="incidentAutoClosure" />
<property name="cronExpression" value="0 0 12 1/1 * ? *" />
</bean>
<bean id="quartzJdbcScheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
p:waitForJobsToCompleteOnShutdown="true">
<property name="autoStartup" value="true" />
<property name="startupDelay" value="0" />
<property name="overwriteExistingJobs" value="false" />
<property name="quartzProperties">
<props>
<prop key="org.quartz.scheduler.instanceName">mvcJdbcScheduler</prop>
<prop key="org.quartz.jobStore.class">org.quartz.impl.jdbcjobstore.JobStoreTX</prop>
<prop key="org.quartz.jobStore.driverDelegateClass">org.quartz.impl.jdbcjobstore.PostgreSQLDelegate</prop>
<prop key="org.quartz.jobStore.tablePrefix">QRTZ_</prop>
<prop key="org.quartz.threadPool.class">org.quartz.simpl.SimpleThreadPool</prop>
<prop key="org.quartz.threadPool.threadCount">${quartz.async.threadCount}</prop>
<prop key="org.quartz.threadPool.threadPriority">${quartz.async.threadPriority}</prop>
<prop key="org.quartz.jobStore.misfireThreshold">${quartz.async.misfireThreshold}</prop>
<prop key="org.quartz.jobStore.isClustered">true</prop>
<prop key="org.quartz.scheduler.threadsInheritContextClassLoaderOfInitializer">true</prop>
<prop key="org.quartz.plugin.jobHistory.class">org.quartz.plugins.history.LoggingJobHistoryPlugin</prop>
<prop key="org.quartz.plugin.jobHistory.jobToBeFiredMessage">${quartz.async.initTriggerFormat}</prop>
<prop key="org.quartz.plugin.jobHistory.jobSuccessMessage">${quartz.async.endTriggerFormat}</prop>
</props>
</property>
<property name="triggers">
<list>
<ref bean="incidentAutoClosureTrigger" />
<!-- List of 100 Jobs -->
</list>
</property>
</bean>
Few things, Are you using spring boot? A good approach to this problem would be to create auto configuration class where you can have a list of combinations. Here is a sample:
#Configuration
#ConditionalOnBean(SomeClassDependency.class)
public class JobConfig {
#Bean
#ConditionalOnProperty(....)
public SchedulerFactoryBean config1() {
....
}
#Bean
#ConditionalOnProperty(....)
public SchedulerFactoryBean config2() {
....
}
#Bean
#ConditionalOnProperty(....)
public SchedulerFactoryBean config3() {
....
}
}
public class MyDependency {
private final SchedulerFactoryBean schedulerFactoryBean;
public MyDependency(#Qualifier("config2") SchedulerFactoryBean schedulerFactoryBean) {
this.schedulerFactoryBean = schedulerFactoryBean
}
}
you can do it programmatically through a configuration class that will automatically configure your bean instead of using an xml file;
here is what I used. Note: having the applicationContext added to the jobFactory allows Quartz schedule jobs to be aware of spring autowired classes when the job executes otherwise you'll get a null autowire
#Configuration
public class PortalQuartzSchedulerConfiguration {
#Autowired
private ApplicationContext applicationContext;
#Bean
public JobFactory jobFactory() {
ApplicationContextHolder jobFactory = new ApplicationContextHolder();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
#Bean
public SchedulerFactoryBean schedulerFactory() {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setAutoStartup(true);
factory.setSchedulerName("Portal scheduler");
factory.setOverwriteExistingJobs(true);
factory.setJobFactory(jobFactory());
return factory;
}
}

Spring Transaction configuration programmatically with Spring 4.3.4 version

We are currently migrating from xml configuration to complete annotation with java configuration based Spring application. With the annotation approach #Transactional we can achieve but the we need to write for each and every method.
In XML we configured (OLD).
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="delete*">PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED</prop>
<prop key="update*">PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED</prop>
<prop key="save*">PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED</prop>
<prop key="get*">PROPAGATION_SUPPORTS,ISOLATION_READ_COMMITTED,readOnly</prop>
<prop key="is*">PROPAGATION_SUPPORTS,ISOLATION_READ_COMMITTED,readOnly</prop>
<!--<prop key="*">PROPAGATION_REQUIRED</prop> -->
</props>
</property>
</bean>
transactionManager is org.springframework.orm.hibernate3.HibernateTransactionManager
<bean id="xxxxSVC" parent="txProxyTemplate">
<property name="target">
<bean class="XXX.XXX.XXX.SVCImpl">
<property name="xxxxDao" ref="xxxDao"></property>
</bean>
</property>
</bean>
txProxyTemplate is parent class of each service class.
So, please suggest how to configure similar code in java configuration. Thanks for your valuable time spent and support us.
#Barath Comment
Bean
#Bean
public TransactionProxyFactoryBean setTransactionProperties() throws IOException {
TransactionProxyFactoryBean transactionProxyFactoryBean = new TransactionProxyFactoryBean();
transactionProxyFactoryBean.setTransactionManager(transactionManager(sessionFactory()));
Properties transactionAttributesProps = new Properties();
transactionAttributesProps.setProperty("delete*", "PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED");
transactionAttributesProps.setProperty("update*", "PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED");
transactionAttributesProps.setProperty("save*", "PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED");
transactionAttributesProps.setProperty("get*", "PROPAGATION_SUPPORTS,ISOLATION_READ_COMMITTED,readOnly");
transactionAttributesProps.setProperty("is*", "PROPAGATION_SUPPORTS,ISOLATION_READ_COMMITTED,readOnly");
transactionProxyFactoryBean.setTransactionAttributes(transactionAttributesProps);
transactionProxyFactoryBean.afterPropertiesSet();
return transactionProxyFactoryBean;
}
How to configure with each service implementation class, we can use it for single as a service layer may contain N classes. There is a method setTarget(Object target). Now how can we configure all the N classes. Please sugggest how can we configure.
A sample configuration for this case :
#Bean
public TransactionProxyFactoryBean txProxyTemplate(){
TransactionProxyFactoryBean txFactory=new TransactionProxyFactoryBean();
txFactory.setTransactionManager(new JpaTransactionManager()); // any transcation manager
txFactory.setTransactionAttributes(properties());
return txFactory;
}
#Bean
Properties properties(){
Properties properties=new Properties();
properties.put("delete*", "PROPAGATION_REQUIRED,ISOLATION_READ_COMMITTED");
//set al lthe properties
return properties;
}
#Bean
public TransactionProxyFactoryBean xxxxSVC(TransactionProxyFactoryBean txFactory){
txFactory.setTarget(testEntity());
return txFactory;
}
#Bean
TestEntity testEntity(){
return new TestEntity();
}

How to use HibernateTemplate?

I am performing retrieval operation to get list of students from database. But I am getting 'empty' data from database. Used HibernateTemplate in
Spring with Hibernate integration,
domain class:-
#Entity
#Table(name="student")
public class StdBO {
#Id
private int sno;
private String sname,sadd;
//setters and getters
}
How can I use HibernateCallBack() interface for search operation? This is my first time that integrating spring with hibernate, is the below way correct? I tried many ways to perform search operations using HibernateTemplate but failing to get the details
DAO
#Repository
public class StdDAO {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public List<StdBO> select(){
List<StdBO> list = ht.executeFind(new HibernateCallback() {
public Object doInHibernate(Session ses)
throws HibernateException, SQLException {
Criteria criteria=ses.createCriteria(StdBO.class);
System.out.println("before printing sutdents");
List<StdBO> bos = criteria.list();
System.out.println("students are"+bos);//here getting empty list
return bos;
}
});
return list;
}
xml
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.nt.dao.StdDAO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dao" class="com.nt.dao.StdDAO">
<property name="ht" ref="template" />
</bean>
You need begin (and commit) a transaction to query data. You can do it manually by session.beginTransaction() or using #Transactional annotation. For using #Transactional annotation you will need to do some additional spring configuration:
Hibernate Transaction Annotation Configuration.

Null Pointer with Spring #Autowired

I am new to Spring & Hibernate and I have spent a couple of weeks trying to get to grips with it. Most of my experience is with Oracle development so this is a departure for me. Hibernate is working but Spring is giving me a headache.
I tried following this tutorial but using an Oracle db and my Address table.
http://www.codejava.net/frameworks/spring/spring-4-and-hibernate-4-integration-tutorial-part-1-xml-configuration
The web page wasn't working so I tried a test case on the HomeController.java That didn't work so but I believe I have narrowed it down to a null pointer in addressDao and so I wrote a test case for that to try to pin it down.
java.lang.NullPointerException: null
springexp.unittest.AddressDaoTest.testListAddr(AddressDaoTest.java:29)
package springexp.unittest;
import bussys.model.Address;
import springexp.dao.AddressDao;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
public class AddressDaoTest
{
#Autowired
private AddressDao addressDao;
#RequestMapping(value="/")
/**
* #see springexp.dao.AddressDao#listAddr()
*/
#Test
public void testListAddr()
{
List<Address> listAddresses = addressDao.listAddr(); << error thrown here
System.out.println(listAddresses.get(1).getFirstname());
fail("Unimplemented");
}
}
I have also spent a long time reading stackoverflow and others to try to fix the null pointer issue but there seems to be lots of ways of writing this and it has changed in various versions.
In servlet-context.xml I have this:
<!-- Hibernate Session Factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>springexp.dao.AddressDao</value>
</list>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="addressDao" class="springexp.dao.AddressDaoImpl">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
<!-- added this recently based on one suggestion -->
<bean id="addressDaoTest" class="springexp.unittest.AddressDaoTest">
<constructor-arg>
<ref bean="sessionFactory" />
</constructor-arg>
</bean>
AddressDaoImpl.java
package springexp.dao;
import bussys.model.Address;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
public class AddressDaoImpl
implements AddressDao
{
private SessionFactory sessionFactory;
public AddressDaoImpl(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Address> listAddr()
{
#SuppressWarnings("unchecked")
List<Address> listAddress = (List<Address>)
sessionFactory.getCurrentSession().createCriteria(Address.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return listAddress;
}
}
I hope this is enough to give a clue to my mistake(s).

Sharing Spring Security Configuration Between Applications

I'm brand spanking new at Spring and have gotten a majority of the knowledge I do have from the Spring Recipes book from Apress.
I've got LDAP authentication working with Spring Security within one webapp. I would like to rip out my application context beans and properties files from this one webapp, however, and somehow externalize them so that all of our webapps can reference the same beans. So when we need to change something (like the ldapuser or the ldap urls), we change it in one place and the rest of the apps just know.
UPDATE
I've implemented Reloadable Spring Properties which is reloading properties when the files they come from are touched. I am using encrypted properties, however, so below is class I created on top of the Reloadable Spring Properties ones.
ReloadingEncryptablePropertyPlaceholderConfigurer.java
package;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.util.text.TextEncryptor;
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
public class ReloadingEncryptablePropertyPlaceholderConfigurer extends ReloadingPropertyPlaceholderConfigurer {
protected final Log logger = LogFactory.getLog(getClass());
private final StringEncryptor stringEncryptor;
private final TextEncryptor textEncryptor;
public ReloadingEncryptablePropertyPlaceholderConfigurer(TextEncryptor textEncryptor) {
super();
logger.info("Creating configurer with TextEncryptor");
Validate.notNull(textEncryptor, "Encryptor cannot be null");
this.stringEncryptor = null;
this.textEncryptor = textEncryptor;
}
public ReloadingEncryptablePropertyPlaceholderConfigurer(StringEncryptor stringEncryptor) {
super();
logger.info("Creating configurer with StringEncryptor");
Validate.notNull(stringEncryptor, "Encryptor cannot be null");
this.stringEncryptor = stringEncryptor;
this.textEncryptor = null;
}
#Override
protected String convertPropertyValue(String originalValue) {
if (!PropertyValueEncryptionUtils.isEncryptedValue(originalValue)) {
return originalValue;
}
if (this.stringEncryptor != null) {
return PropertyValueEncryptionUtils.decrypt(originalValue, this.stringEncryptor);
}
return PropertyValueEncryptionUtils.decrypt(originalValue, this.textEncryptor);
}
#Override
protected String parseStringValue(String strVal, Properties props, Set visitedPlaceholders) throws BeanDefinitionStoreException {
return convertPropertyValue(super.parseStringValue(strVal, props, visitedPlaceholders));
}
}
And here's how I use it in my securityContext.xml:
<bean id="securityContextSource" class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">
<constructor-arg value="ldaps://ldapserver" />
<property name="urls" value="#{ldap.urls}" />
</bean>
<bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<bean id="reloadProperties" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="period" value="1000"/>
<property name="runnable">
<bean class="ReloadConfiguration">
<property name="reconfigurableBeans">
<list>
<ref bean="configproperties"/>
</list>
</property>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="configproperties" class="ReloadablePropertiesFactoryBean">
<property name="location" value="classpath:ldap.properties"/>
</bean>
<bean id="ldapPropertyConfigurer" class="ReloadingEncryptablePropertyPlaceholderConfigurer">
<constructor-arg ref="configurationEncryptor" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="properties" ref="configproperties"/>
</bean>
<bean id="jasyptConfig" class="org.jasypt.encryption.pbe.config.SimpleStringPBEConfig">
<property name="algorithm" value="PBEWithMD5AndTripleDES" />
<property name="password" value="########" />
</bean>
<bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
<property name="config" ref="jasyptConfig" />
</bean>
How about:
Writing a method that returns a list
of LDAP servers - reading from a
database table or property files
expose this wethod via jndi and use it to inject a list of the servers into your spring config
If you need the ldap servers to be refreshed dynamically you could have a job poll for changes periodically or else have an admin webpage or jmx bean to trigger the update. Be careful of concurrency isses for both these methods (something reading the list while you are updating)
Wouldn't that be Spring Security? It can deal with LDAPs. And if you make it one security service that everyone uses, wouldn't that be the way to manage it?

Resources