25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11 ■ Integrating Your <strong>Spring</strong> Application with External Systems<br />

import com.apress.isf.java.model.Document;<br />

import com.apress.isf.java.utils.XmlUtils;<br />

import com.apress.isf.spring.data.DocumentDAO;<br />

@Component<br />

public class JMSConsumer implements MessageListener{<br />

}<br />

@Autowired<br />

DocumentDAO documentDAO;<br />

@Override<br />

public void onMessage(Message message) {<br />

TextMessage textMessage = (TextMessage)message;<br />

try{<br />

Document document = XmlUtils.fromXML(textMessage.getText(), Document.class);<br />

documentDAO.save(document);<br />

}catch(JMSException ex){<br />

ex.printStackTrace();<br />

}<br />

}<br />

Let’s analyze what you are doing in Listing 11-2. First, you are implementing the javax.jms.MessageListener.<br />

The JMS API exposes this interface where you need to implement the onMessage method; this method accepts a<br />

javax.jms.Message that will contain the message. Also, you are using a small Utility class, which will help to convert<br />

the XML into a document object and be saved into the database using the DocumentDAO implementation. Next, take a<br />

look at Listing 11-3, which shows the Utility class that is used in the consumer.<br />

Listing 11-3. XmlUtils.java<br />

package com.apress.isf.java.utils;<br />

import com.thoughtworks.xstream.XStream;<br />

public class XmlUtils {<br />

public static String toXML(T object){<br />

XStream xstream = new XStream();<br />

xstream.alias(object.getClass().getSimpleName().toLowerCase(), object.getClass());<br />

return xstream.toXML(object);<br />

}<br />

}<br />

@SuppressWarnings({ "unchecked"})<br />

public static T fromXML(String xml, Class _class){<br />

XStream xstream = new XStream();<br />

xstream.alias(_class.getSimpleName().toLowerCase(), _class);<br />

return (T)xstream.fromXML(xml);<br />

}<br />

151

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!