23.07.2013 Views

O'Reilly - Java Message Service

O'Reilly - Java Message Service

O'Reilly - Java Message Service

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4.1.2 The B2B Source Code<br />

Figure 4.1. Producers and consumers in the B2B example<br />

<strong>Java</strong> <strong>Message</strong> <strong>Service</strong><br />

The rest of this chapter examines the source code for the Wholesaler and Retailer classes,<br />

and covers several advanced subjects related to the pub/sub messaging model.<br />

4.1.2.1 The Wholesaler class<br />

After the listing, we will take a brief tour of the methods in this class, and discuss their<br />

responsibilities. We will go into detail about the implementation later in this chapter. Now,<br />

here is the complete definition of the Wholesaler class, which is responsible for publishing<br />

items to the "Hot Deals" topic and receiving "Buy Orders" on those deals from retailers:<br />

public class Wholesaler implements javax.jms.<strong>Message</strong>Listener{<br />

private javax.jms.TopicConnection connect = null;<br />

private javax.jms.TopicSession pubSession = null;<br />

private javax.jms.TopicSession subSession = null;<br />

private javax.jms.TopicPublisher publisher = null;<br />

private javax.jms.TopicSubscriber subscriber = null;<br />

private javax.jms.Topic hotDealsTopic = null;<br />

private javax.jms.TemporaryTopic buyOrdersTopic = null;<br />

public Wholesaler(String broker, String username, String password){<br />

try {<br />

Properties env = new Properties( );<br />

// ... specify the JNDI properties specific to the vendor<br />

InitialContext jndi = new InitialContext(env);<br />

TopicConnectionFactory factory =<br />

(TopicConnectionFactory)jndi.lookup(broker);<br />

connect = factory.createTopicConnection (username, password);<br />

pubSession =<br />

connect.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);<br />

subSession =<br />

connect.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);<br />

hotDealsTopic = (Topic)jndi.lookup("Hot Deals");<br />

publisher = pubSession.createPublisher(hotDealsTopic);<br />

buyOrdersTopic = subSession.createTemporaryTopic( );<br />

subscriber = subSession.createSubscriber(buyOrdersTopic);<br />

subscriber.set<strong>Message</strong>Listener(this);<br />

connect.start( );<br />

} catch (javax.jms.JMSException jmse){<br />

jmse.printStackTrace( ); System.exit(1);<br />

} catch (javax.naming.NamingException jne){<br />

55

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

Saved successfully!

Ooh no, something went wrong!